text stringlengths 10 2.72M |
|---|
package com.example.g0294.tutorial.ui;
import android.app.Activity;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
public class MyWebChromeClient extends WebChromeClient {
private Activity mAct;
public MyWebChromeClient(Activity activity) {
super();
this.mAct = activity;
}
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
mAct.setProgress(newProgress * 100);
}
@Override
public boolean onJsAlert(WebView view, String url, String message,
final JsResult result) {
Log.i("WebChromeClient", "onJsAlert url=" + url + ";message=" + message);
AlertDialog.Builder builder = new AlertDialog.Builder(mAct);
builder.setTitle("AlertDialog");
builder.setMessage(message);
builder.setPositiveButton(android.R.string.ok,
new AlertDialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
builder.setCancelable(false);
builder.create();
builder.show();
return true;
}
}
|
/*
* Copyright 2002-2019 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.web.filter.reactive;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilterChain;
import org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest;
import org.springframework.web.testfixture.server.MockServerWebExchange;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link HiddenHttpMethodFilter}.
* @author Greg Turnquist
* @author Rossen Stoyanchev
*/
public class HiddenHttpMethodFilterTests {
private final HiddenHttpMethodFilter filter = new HiddenHttpMethodFilter();
private final TestWebFilterChain filterChain = new TestWebFilterChain();
@Test
public void filterWithParameter() {
postForm("_method=DELETE").block(Duration.ZERO);
assertThat(this.filterChain.getHttpMethod()).isEqualTo(HttpMethod.DELETE);
}
@Test
public void filterWithParameterMethodNotAllowed() {
postForm("_method=TRACE").block(Duration.ZERO);
assertThat(this.filterChain.getHttpMethod()).isEqualTo(HttpMethod.POST);
}
@Test
public void filterWithNoParameter() {
postForm("").block(Duration.ZERO);
assertThat(this.filterChain.getHttpMethod()).isEqualTo(HttpMethod.POST);
}
@Test
public void filterWithEmptyStringParameter() {
postForm("_method=").block(Duration.ZERO);
assertThat(this.filterChain.getHttpMethod()).isEqualTo(HttpMethod.POST);
}
@Test
public void filterWithDifferentMethodParam() {
this.filter.setMethodParamName("_foo");
postForm("_foo=DELETE").block(Duration.ZERO);
assertThat(this.filterChain.getHttpMethod()).isEqualTo(HttpMethod.DELETE);
}
@Test
public void filterWithHttpPut() {
ServerWebExchange exchange = MockServerWebExchange.from(
MockServerHttpRequest.put("/")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.body("_method=DELETE"));
this.filter.filter(exchange, this.filterChain).block(Duration.ZERO);
assertThat(this.filterChain.getHttpMethod()).isEqualTo(HttpMethod.PUT);
}
private Mono<Void> postForm(String body) {
MockServerWebExchange exchange = MockServerWebExchange.from(
MockServerHttpRequest.post("/")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.body(body));
return this.filter.filter(exchange, this.filterChain);
}
private static class TestWebFilterChain implements WebFilterChain {
private HttpMethod httpMethod;
public HttpMethod getHttpMethod() {
return this.httpMethod;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange) {
this.httpMethod = exchange.getRequest().getMethod();
return Mono.empty();
}
}
}
|
/*
* 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 PA165.language_school_manager.service;
import PA165.language_school_manager.Entities.Person;
import java.util.List;
import org.springframework.stereotype.Service;
/**
*
* @author Matúš
*/
@Service
public interface PersonService {
/**
* Find all persons
* @return List of all persons.
*/
List<Person> findAll();
/**
* Find person with ID
* @param personId ID f person
* @return Person by Id
*/
Person findPersonById(Long personId);
/**
* Find person with Username
* @param userName username of person
* @return person with username
*/
Person findPersonByUserName(String userName);
/**
* Find all persons with fullname
* @param fullName fullname of persons
* @return all persons with fullname
*/
List<Person> findPersonsByLastName(String fullName);
/**
* Create person
* @param person person to create
*/
void createPerson(Person person);
/**
* Update person
* @param person to update
*/
void updatePerson(Person person);
/**
* Delete person
* @param person to delete
*/
void deletePerson(Person person);
/**
* Find if person is admin
* @param person if he is admin
* @return boolean if person is admin
*/
boolean isAdmin(Person person);
/**
* Authenticate person
* @param findPersonById person with id
* @param password password of person
* @return validate password of person
*/
boolean authenticate(Person findPersonById, String password);
/**
* Register person.
* @param person person to register
* @param unencryptedPassword unencrypted password to person
*/
void registerPerson(Person person, String unencryptedPassword);
}
|
package p0500;
import java.awt.Color;
public class HueRenderer extends PointRenderer {
/**
* Génère un PointRenderer affichant des points de couleur
* en se basant sur le cercle chromatique
*/
public HueRenderer() {
super();
}
/**
* Génère un PointRenderer en se basant sur le cercle chromatique
* Les valeurs vont de 0.0 (rouge vers l'orange) à 1.0 (rouge vers le magenta)
* @param range plage de valeur, 1.0 correspond au spectre complet du cercle chromatique
* @param delta couleur de départ
*/
public HueRenderer(float range, float delta) {
this.range = range;
this.delta = delta;
}
public HueRenderer(float range, float delta, boolean sens) {
this.range = range;
this.delta = delta;
this.sens = sens;
}
@Override
public Color getColor(int level) {
if(level == -1) {
return background;
} else {
//float l = sens ? 200 - level : level;
float l = (level % COLOR_CYCLE) / COLOR_CYCLE * range * (sens ? 1 : -1);
return Color.getHSBColor(l+delta, 1.0f, 1.0f);
}
}
} |
package by.belotserkovsky.controllers;
import by.belotserkovsky.excepsions.ResourceNotFoundException;
import by.belotserkovsky.pojos.History;
import by.belotserkovsky.pojos.User;
import by.belotserkovsky.services.ICalcService;
import by.belotserkovsky.services.IHistoryService;
import by.belotserkovsky.services.IUserService;
import by.belotserkovsky.services.exceptions.CalculationFailsException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
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.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.security.Principal;
import java.util.List;
/**
* Created by K.Belotserkovsky
*/
@Controller
@RequestMapping(value = "/calc/user")
public class UserController {
private static Logger log = Logger.getLogger(UserController.class);
@Autowired
private IUserService userService;
@Autowired
private ICalcService calcService;
@Autowired
private IHistoryService historyService;
/**
* @param model
* @param principal
* @param session
* mapping "/user/main"
* @return page "main"
*/
@RequestMapping(value = "/main", method = RequestMethod.GET)
public String mainPage(ModelMap model, HttpSession session, Principal principal){
if(session.getAttribute("sessionUserName") == null){
User user = userService.getUserByUserName(principal.getName());
session.setAttribute("sessionUserName", user.getName());
log.info("user login, username: " + user.getUserName());
}
String result = "";
model.addAttribute("result", result);
return "main";
}
/**
* if user entered incorrect expression
* @param model
* mapping "/user/main?fail"
* @return page "main" with error
*/
@RequestMapping(value = "/main", method = RequestMethod.GET, params = "fail")
public String mainPage(ModelMap model){
String result = model.get("expression").toString();
model.addAttribute("result", result);
return "main";
}
/**
* calculate process
* @param model
* @param redirectAttributes
* @param principal
* @param original
* mapping "/user/main?calc"
* @return page "main" with result
*/
@RequestMapping(value = "/main", method = RequestMethod.POST, params = "calc")
public String calculate(ModelMap model, @RequestParam(value = "input") String original,
Principal principal,
RedirectAttributes redirectAttributes){
String sIn = calcService.transformToRpn(original);
String result="";
try {
result = calcService.calculateRpn(sIn);
}catch (CalculationFailsException e){
redirectAttributes.addFlashAttribute("expression", original);
log.error("Incorrect expression: " + original);
return "redirect:/calc/user/main?fail";
}
historyService.saveHistory(original, result, principal.getName());
model.addAttribute("expression", result);
return "main";
}
/**
* jump to page "registration"
* @param model
* mapping "/user/new"
* @return page "registration"
*/
@RequestMapping(value = "/new", method = RequestMethod.GET)
public String register(ModelMap model){
User user = new User();
model.addAttribute("user", user);
return "registration";
}
/**
* redirect to page "registration" if user already exists
* @param model
* mapping "/user/new?fail"
* @return page "registration"
*/
@RequestMapping(value = "/new", method = RequestMethod.GET, params = "fail")
public String registerFail(ModelMap model){
User user = new User();
model.addAttribute("user", user);
return "registration";
}
/**
* jump to page "registration" for edit user info
* @param model
* @param principal
* mapping "/user/update"
* @return page "registration"
*/
@RequestMapping(value = "/update", method = RequestMethod.GET)
public String editUserInfo(ModelMap model, Principal principal){
User user = userService.getUserByUserName(principal.getName());
model.addAttribute("user", user);
return "registration";
}
/**
* create or update user
* @param br
* @param principal
* @param user
* mapping "/user/add"
* @return page "registration"
*/
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addUser(@Valid User user, BindingResult br, Principal principal) {
if(br.hasErrors()){
//If the user is authorized, add a name to the model again
//because if there is an error username field will be empty
if(principal != null){
user.setUserName(principal.getName());
}
return "registration";
}
User userTemp = userService.getUserByUserName(user.getUserName());
if(userTemp != null){
return "redirect:/calc/user/new?fail";
}
userService.createOrUpdateUser(user);
return "redirect:/calc/welcome?login";
}
/**
* jump to calculation history page with pagination
* @param model
* @param principal
* @param page
* mapping "/user/history"
* @return page "history"
*/
@RequestMapping(value = "/history", method = RequestMethod.GET, params = "page")
public String showHistory(ModelMap model, @RequestParam (value = "page") String page, Principal principal){
int currentPage = 1;
int recordsPerPage = 3;
if(page.length() != 0) {
currentPage = Integer.parseInt(page);
}
List<History> listHistory = historyService.getUserHistory((currentPage-1)*recordsPerPage, recordsPerPage, principal.getName());
if(listHistory.isEmpty()){
throw new ResourceNotFoundException();
}
int allRecords = historyService.getRowsUserHistory(principal.getName());
int numberOfPages = (int) Math.ceil((double)allRecords / recordsPerPage);
model.addAttribute("listHistory", listHistory);
model.addAttribute("numberOfPages", numberOfPages);
model.addAttribute("currentPage", currentPage);
return "history";
}
/**
* logout
* @param response
* @param request
* mapping "/user/main?logout"
* @return page "welcome"
*/
@RequestMapping(value = "/main", method = RequestMethod.GET, params = "logout")
public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
new SecurityContextLogoutHandler().logout(request, response, auth);
}
return "redirect:/calc/welcome?logout";
}
}
|
package com.example.demo.controller;
import com.example.demo.dao.*;
import com.example.demo.models.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RequestMapping("api/v1/")
@RestController
@CrossOrigin(origins = "*")
public class NewsController {
@Autowired
private NewsDataAccessService newsDataAccessService;
@Autowired
private ClassifiedNewsDataAccessService classifiedNewsDataAccessService;
@Autowired
private TestNewsDataAccessService testNewsDataAccessService;
@Autowired
private RecommendedNewsDataAccessService recommendedNewsDataAccessService;
@Autowired
private SummarizedNewsDataAccessService summarizedNewsDataAccessService;
@Autowired
private CategoricalNewsDataAccessService categoricalNewsDataAccessService;
@Autowired
private NewsAllDataAccessService newsAllDataAccessService;
// all news
@GetMapping("news")
public List<News> getAllNews() {
return newsDataAccessService.findAll();
}
// One news
@GetMapping("news/{id}")
public Optional<News> getOneNews(@PathVariable("id") Integer id) {
return newsDataAccessService.findById(id);
}
// all classified news
@GetMapping("classified")
public List<ClassifiedNews> getClassifiedNews() {
return classifiedNewsDataAccessService.findAll();
}
// one classified news
@GetMapping("classified/{id}")
public Optional<ClassifiedNews> getClassifiedNewsById(@PathVariable("id") Integer id) {
return classifiedNewsDataAccessService.findById(id);
}
// testnews by joining tables
@GetMapping("testnews")
public List<TestNews> getTestNews() {
return testNewsDataAccessService.findNews();
}
@GetMapping("summerizedbyid/{id}")
public List<TestNews> getTestNewsById(@PathVariable("id") Integer id) {
return testNewsDataAccessService.findSummarizedNewsById(id);
}
// all recommended news
@GetMapping("recommended")
public List<RecommendedNews> getRecommendedNews() {
return recommendedNewsDataAccessService.findAll();
}
// one recommended news
@GetMapping("recommended/{id}")
public Optional<RecommendedNews> getRecommendedNewsById (@PathVariable("id") Integer id) {
return recommendedNewsDataAccessService.findById(id);
}
// all summarized news
@GetMapping("summarized")
public List<SummarizedNews> geSummarizedNews() {
return summarizedNewsDataAccessService.findAll();
}
// one summarized news
@GetMapping("summarized/{id}")
public Optional<SummarizedNews> getSummarizedNewsById(@PathVariable("id") Integer id) {
return summarizedNewsDataAccessService.findById(id);
}
@GetMapping("categorical/{id}")
public List<CategoricalNews> getNewsByCategory(@PathVariable("id") String id) {
return categoricalNewsDataAccessService.findComplainsById(id);
}
@GetMapping("subcategory/{id}")
public List<CategoricalNews> getNewsBySubCategory(@PathVariable("id") String id) {
return categoricalNewsDataAccessService.findNewsBySubCategory(id);
}
@GetMapping("allnews")
public List<NewsAll> getNewsWithCat() {
return newsAllDataAccessService.findNews();
}
}
|
package practica10.ejemplo3_herenciaEntreClases;
public interface IPersona {
void mostrarNombre(String nombre);
void mostrarDni(String dni);
}
|
package com.zantong.mobilecttx.common;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebView;
import com.zantong.mobilecttx.R;
import com.zantong.mobilecttx.utils.StateBarSetting;
import org.apache.cordova.ConfigXmlParser;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaInterfaceImpl;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewImpl;
import org.apache.cordova.engine.SystemWebView;
import org.apache.cordova.engine.SystemWebViewEngine;
import java.util.concurrent.ExecutorService;
import butterknife.Bind;
/**
* Created by Administrator on 2016/5/1.
*/
public class Demo extends AppCompatActivity implements CordovaInterface {
@Bind(R.id.cordovaWebView)
SystemWebView cordovaWebView;
public static String START_URL = "file:///android_asset/www/discount_index.html";
private CordovaWebView cordovaWebViewReal;
protected CordovaInterfaceImpl cordovaInterface;
private SystemWebViewEngine mSystemWebViewEngine;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo_activity);
// ButterKnife.bind(this);
cordovaWebView = (SystemWebView) findViewById(R.id.cordovaWebView);
StateBarSetting.settingBar(this);
//
START_URL = (String) PublicData.getInstance().mHashMap.get("htmlUrl");
cordovaInterface = new CordovaInterfaceImpl(Demo.this);
ConfigXmlParser parser = new ConfigXmlParser();
parser.parse(this);//这里会解析res/xml/config.xml配置文件
mSystemWebViewEngine = new SystemWebViewEngine(cordovaWebView);
cordovaWebViewReal = new CordovaWebViewImpl(mSystemWebViewEngine);//创建一个cordovawebview
cordovaWebViewReal.init(cordovaInterface, parser.getPluginEntries(), parser.getPreferences());//初始化
// cordovaWebViewSys.setOverScrollMode(View.OVER_SCROLL_IF_CONTENT_SCROLLS);
cordovaWebView.getSettings().setJavaScriptEnabled(true);
cordovaWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
cordovaWebView.loadUrl(START_URL);
//Set up the webview
// ConfigXmlParser parser = new ConfigXmlParser();
// parser.parse(this);
//// cordovaWebView.setScrollbarFadingEnabled(false);
//// cordovaWebView.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
// cordovaWebViewReal = new CordovaWebViewImpl(new SystemWebViewEngine(cordovaWebView));
//// cordovaWebViewReal.init(new MyCordovaImpl(this,webView), parser.getPluginEntries(),
// cordovaWebViewReal.init(cordovaInterface, parser.getPluginEntries(), parser.getPreferences());
// cordovaWebViewReal.loadUrl(START_URL);
// mUserPresenterImp = new UserPresenterImp(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
if(cordovaWebView != null){
cordovaWebViewReal.handleDestroy();
}
}
@Override
public void startActivityForResult(CordovaPlugin command, Intent intent, int requestCode) {
}
@Override
public void setActivityResultCallback(CordovaPlugin plugin) {
}
@Override
public Activity getActivity() {
return this;
}
@Override
public Object onMessage(String id, Object data) {
return null;
}
@Override
public ExecutorService getThreadPool() {
return null;
}
@Override
public void requestPermission(CordovaPlugin plugin, int requestCode, String permission) {
}
@Override
public void requestPermissions(CordovaPlugin plugin, int requestCode, String[] permissions) {
}
@Override
public boolean hasPermission(String permission) {
return false;
}
}
|
package com.arthur.leetcode;
import java.util.LinkedList;
/**
* @title: No206_2
* @Author ArthurJi
* @Date: 2021/3/19 11:10
* @Version 1.0
*/
public class No206_2 {
public static void main(String[] args) {
}
public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode last = reverseList(head.next);
head.next.next = head;
head.next = null;
return last;
}
public ListNode reverseList_2(ListNode head) {
ListNode slow = null;
ListNode fast = head;
while (fast != null) {
ListNode temp = fast.next;
fast.next = slow;
slow = fast;
fast = temp;
}
return slow;
}
}
/*206. 反转链表
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?*/
|
//fail to solve the problem
//because cannot find a easy way to judge "egg" with "ooo"
//the answer is pretty instructive:
//1. use a map.put(sList[i], tList[i]) to form a hashmap to judge
//2. By new HashSet<>(map.values()).size()) to slove "egg" with "ooo"
//(because HashSet<> will be built with a Collection of map.value(), same value will be neglected in hash -> cause different size)
public class Solution {
public boolean isIsomorphic(String s, String t) {
Map<String, String> map = new HashMap<>();
//two way to convert string into array:
//1. char[] ch = str.tocharArray;
//2. String[] strArray = str.split("XXX")
String[] sList = s.split("");
String[] tList = t.split("");
if (s.length() != t.length()) return false;
for (int i = 0; i < sList.length; i++) {
if (!map.containsKey(sList[i])) {
map.put(sList[i], tList[i]);
} else {
if (!map.get(sList[i]).equals(tList[i])) return false;
}
}
System.out.println("!!!" + map.values().size() + "//" + new HashSet<>(map.values()).size());
return map.values().size() == new HashSet<>(map.values()).size();
}
}
//The second solution is even genious, which beat 98% of submission
//The main idea is to Use ASSIC to store the characters and use two int[] to store each other
// public class Solution {
// public boolean isIsomorphic(String s, String t) {
// if(s.length() != t.length()) return false;
// int N = s.length();
// int[] mst = new int[256];
// int[] mts = new int[256];
// for(int i = 0; i < N; i++) {
// char cs = s.charAt(i);
// char ct = t.charAt(i);
// if((mst[cs] == 0) && (mts[ct] == 0)) {
// mst[cs] = ct;
// mts[ct] = cs;
// }
// if((mst[cs] != ct) || (mts[ct] != cs))
// return false;
// }
// return true;
// }
// } |
package com.miyatu.tianshixiaobai.entity;
import java.util.List;
public class XiaoBaiRecommendFragmentEntity {
private List<ListBean> list;
public List<ListBean> getList() {
return list;
}
public void setList(List<ListBean> list) {
this.list = list;
}
public static class ListBean {
/**
* cate_id : 0
* class_name : 全部排行
* xiaobai : [{"cate_id":"3","shop_name":"大圣杂货铺","shop_icon":"/uploads/topic/20200313/445a0ead569931a695e9c56c627c0795.jpg","score":"9.0","truename":"孙大圣","recommend":"1","business_id":1},{"cate_id":"2","shop_name":"123123","shop_icon":"/uploads/topic/20200303/d1d5c308cf9c28f9bcd0c0495ad108f7.png","score":"10.0","truename":"12312","recommend":"0"},{"cate_id":"3","shop_name":"幸福启航","shop_icon":"/uploads/topic/20200303/ac06397eb1bf6344bc7524e6b7ed1422.jpg","score":"10.0","truename":"徐桂洲","recommend":"0"},{"cate_id":"4","shop_name":"幸福启航","shop_icon":"/uploads/topic/20200304/c52f16cef8d4f4838f8450863187cdf0.jpg","score":"10.0","truename":"幸福小XU","recommend":"0"},{"cate_id":"3","shop_name":"店铺名称","shop_icon":"","score":"10.0","truename":"王","recommend":"0"},{"cate_id":"2","shop_name":"按时大大所","shop_icon":"/uploads/topic/20200226/57859a2f71dfb1c2d1b16cacaaa33d22.png","score":"8.0","truename":"21212","recommend":"0"}]
*/
private String cate_id;
private String class_name;
private boolean isSelected;
private List<XiaobaiBean> xiaobai;
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
public String getCate_id() {
return cate_id;
}
public void setCate_id(String cate_id) {
this.cate_id = cate_id;
}
public String getClass_name() {
return class_name;
}
public void setClass_name(String class_name) {
this.class_name = class_name;
}
public List<XiaobaiBean> getXiaobai() {
return xiaobai;
}
public void setXiaobai(List<XiaobaiBean> xiaobai) {
this.xiaobai = xiaobai;
}
public static class XiaobaiBean {
/**
* cate_id : 3
* shop_name : 大圣杂货铺
* shop_icon : /uploads/topic/20200313/445a0ead569931a695e9c56c627c0795.jpg
* score : 9.0
* truename : 孙大圣
* recommend : 1
* business_id : 1
*/
private String cate_id;
private String shop_name;
private String shop_icon;
private String score;
private String truename;
private String recommend;
private int business_id;
private boolean isSelected;
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
public String getCate_id() {
return cate_id;
}
public void setCate_id(String cate_id) {
this.cate_id = cate_id;
}
public String getShop_name() {
return shop_name;
}
public void setShop_name(String shop_name) {
this.shop_name = shop_name;
}
public String getShop_icon() {
return shop_icon;
}
public void setShop_icon(String shop_icon) {
this.shop_icon = shop_icon;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
public String getTruename() {
return truename;
}
public void setTruename(String truename) {
this.truename = truename;
}
public String getRecommend() {
return recommend;
}
public void setRecommend(String recommend) {
this.recommend = recommend;
}
public int getBusiness_id() {
return business_id;
}
public void setBusiness_id(int business_id) {
this.business_id = business_id;
}
}
}
}
|
/*
* Copyright (c) 2013-2014, Neuro4j.org
*
* 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 org.neuro4j.studio.properties.sources.providers;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.ui.views.properties.IPropertySource;
import org.eclipse.ui.views.properties.IPropertySourceProvider;
import org.neuro4j.studio.core.ActionNode;
import org.neuro4j.studio.core.DecisionNode;
import org.neuro4j.studio.core.LogicNode;
import org.neuro4j.studio.core.MapperNode;
import org.neuro4j.studio.core.Network;
import org.neuro4j.studio.core.Node;
import org.neuro4j.studio.core.OperatorOutput;
import org.neuro4j.studio.core.StartNode;
import org.neuro4j.studio.core.ViewNode;
import org.neuro4j.studio.core.impl.FollowByRelationNodeImpl;
import org.neuro4j.studio.core.impl.JoinNodeImpl;
import org.neuro4j.studio.core.impl.StandardNodeImpl;
import org.neuro4j.studio.properties.sources.DecisionNodePropertySource;
import org.neuro4j.studio.properties.sources.JoinNodePropertySource;
import org.neuro4j.studio.properties.sources.LogicNodePropertySource;
import org.neuro4j.studio.properties.sources.MapperNodePropertySource;
import org.neuro4j.studio.properties.sources.NetworkPropertySource;
import org.neuro4j.studio.properties.sources.Neuro4jPropertySource;
import org.neuro4j.studio.properties.sources.OutputPropertySource;
import org.neuro4j.studio.properties.sources.StandardListPropertySource;
import org.neuro4j.studio.properties.sources.StartNodePropertySource;
import org.neuro4j.studio.properties.sources.SwitchNodePropertySource;
import org.neuro4j.studio.properties.sources.ViewNodePropertySource;
public class Nuero4jPropertySourceProvider implements IPropertySourceProvider {
private AdapterFactory adapterFactory;
// Map<Object, IPropertySource> map = new HashMap<Object, IPropertySource>();
public Nuero4jPropertySourceProvider(AdapterFactory adapterFactory) {
super();
this.adapterFactory = adapterFactory;
}
@Override
public IPropertySource getPropertySource(Object object) {
if (object instanceof IPropertySource) {
return (IPropertySource) object;
} else {
IItemPropertySource itemPropertySource = (IItemPropertySource) (object instanceof EObject
&& ((EObject) object).eClass() == null ? null
: adapterFactory.adapt(object, IItemPropertySource.class));
return itemPropertySource != null ? createPropertySource(object,
itemPropertySource) : null;
}
}
private IPropertySource createPropertySource(Object object,
IItemPropertySource itemPropertySource) {
if (object instanceof ActionNode)
{
ActionNode actionNode = (ActionNode) object;
if (actionNode.getPropertySource() != null)
{
return actionNode.getPropertySource();
} else {
if (object instanceof MapperNode)
{
MapperNodePropertySource mnpSource = new MapperNodePropertySource(object, itemPropertySource, this.adapterFactory);
actionNode.setPropertySource(mnpSource);
return actionNode.getPropertySource();
} else if (object instanceof LogicNode)
{
LogicNodePropertySource mnpSource = new LogicNodePropertySource(object, itemPropertySource, this.adapterFactory);
actionNode.setPropertySource(mnpSource);
return actionNode.getPropertySource();
} else if (object instanceof DecisionNode) {
DecisionNodePropertySource mnpSource = new DecisionNodePropertySource(
object, itemPropertySource, this.adapterFactory);
actionNode.setPropertySource(mnpSource);
return actionNode.getPropertySource();
} else if (object instanceof StartNode) {
StartNodePropertySource mnpSource = new StartNodePropertySource(
object, itemPropertySource, this.adapterFactory);
actionNode.setPropertySource(mnpSource);
return actionNode.getPropertySource();
} else if (object instanceof ViewNode) {
ViewNodePropertySource mnpSource = new ViewNodePropertySource(
object, itemPropertySource, this.adapterFactory);
actionNode.setPropertySource(mnpSource);
return actionNode.getPropertySource();
} else if (object instanceof StandardNodeImpl) {
StandardListPropertySource sSource = new StandardListPropertySource((StandardNodeImpl) object);
actionNode.setPropertySource(sSource);
return actionNode.getPropertySource();
} else if (object instanceof FollowByRelationNodeImpl) {
SwitchNodePropertySource mnpSource = new SwitchNodePropertySource(
object, itemPropertySource, this.adapterFactory);
actionNode.setPropertySource(mnpSource);
return actionNode.getPropertySource();
} else if (object instanceof JoinNodeImpl) {
JoinNodePropertySource mnpSource = new JoinNodePropertySource(
object, itemPropertySource, this.adapterFactory);
actionNode.setPropertySource(mnpSource);
return actionNode.getPropertySource();
}
else {
Neuro4jPropertySource mnpSource = new Neuro4jPropertySource(
object, itemPropertySource, this.adapterFactory);
actionNode.setPropertySource(mnpSource);
return actionNode.getPropertySource();
}
}
} else if (object instanceof OperatorOutput)
{
return getOutputPropertySource(object, itemPropertySource);
} else if (object instanceof Network)
{
// Network output = (Network)object;
// if (map.containsKey(output.getId())){
// return map.get(output.getId());
// } else {
NetworkPropertySource networkSource = new NetworkPropertySource(object, itemPropertySource, this.adapterFactory);
// map.put(output.getId(), mnpSource);
return networkSource;
// }
}
return new Neuro4jPropertySource(object, itemPropertySource, this.adapterFactory);
// Returns the custom property source
// return null;
}
private IPropertySource getOutputPropertySource(Object object,
IItemPropertySource itemPropertySource) {
OperatorOutput output = (OperatorOutput) object;
if (output.getPropertySource() != null) {
return output.getPropertySource();
} else {
Node candidate = getStandardRelation(output);
if (candidate != null) {
StandardListPropertySource sSource = new StandardListPropertySource(candidate);
candidate.setPropertySource(sSource);
return candidate.getPropertySource();
} else {
OutputPropertySource mnpSource = new OutputPropertySource(object, itemPropertySource, this.adapterFactory);
output.setPropertySource(mnpSource);
return output.getPropertySource();
}
}
}
private Node getStandardRelation(OperatorOutput output)
{
if (output.eContainer() instanceof StandardNodeImpl || output.getTarget() instanceof StandardNodeImpl) {
if (output.eContainer() != null && output.eContainer() instanceof StandardNodeImpl)
{
StandardNodeImpl v1 = (StandardNodeImpl) output.eContainer();
if (v1.isCircleRelation())
{
return v1;
}
}
if (output.getTarget() != null)
{
StandardNodeImpl v1 = (StandardNodeImpl) output.getTarget();
if (v1.isCircleRelation())
{
return v1;
}
}
return output;
}
return null;
}
}
|
package info.zhiqing.tinypiratebay.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import info.zhiqing.tinypiratebay.R;
import info.zhiqing.tinypiratebay.ui.SearchActivity;
import info.zhiqing.tinypiratebay.entities.Category;
import info.zhiqing.tinypiratebay.util.CategoryUtil;
import info.zhiqing.tinypiratebay.util.ConfigUtil;
/**
* Created by zhiqing on 18-1-7.
*/
public class CategoryListAdapter extends RecyclerView.Adapter<CategoryListAdapter.CateListItemViewHolder> {
private Context context;
private List<SubCategoryRecyclerAdapter> adapters;
public CategoryListAdapter(Context context) {
this.context = context;
adapters = new ArrayList<>();
for (Category category : CategoryUtil.CATEGORIES) {
adapters.add(new SubCategoryRecyclerAdapter(context, CategoryUtil.SUB_CATEGORIES.get(category.getCode())));
}
}
@Override
public CateListItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
return new CateListItemViewHolder(inflater.inflate(R.layout.category_item, parent, false));
}
@Override
public void onBindViewHolder(CateListItemViewHolder holder, int position) {
final Category category = CategoryUtil.CATEGORIES.get(position);
holder.icon.setImageResource(
CategoryUtil.codeToIconRes(category.getCode()));
holder.title.setText(category.getTitle());
holder.cateListBar.setBackgroundColor(
CategoryUtil.codeToColor(category.getCode()));
holder.list.setLayoutManager(
new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
holder.list.setAdapter(adapters.get(position));
holder.item.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SearchActivity.actionStart(context, ConfigUtil.BASE_URL + "/browse/" + category.getCode(), category.getTitle());
}
});
}
@Override
public int getItemCount() {
return CategoryUtil.CATEGORIES.size();
}
class CateListItemViewHolder extends RecyclerView.ViewHolder {
View item;
ImageView icon;
TextView title;
RecyclerView list;
View cateListBar;
public CateListItemViewHolder(View itemView) {
super(itemView);
item = itemView.findViewById(R.id.category_item);
icon = itemView.findViewById(R.id.cate_title_bar_icon);
title = itemView.findViewById(R.id.cate_title_bar_title);
list = itemView.findViewById(R.id.sub_category_list);
cateListBar = itemView.findViewById(R.id.cate_list_bar);
}
}
}
|
public class BasicArcher {
public BasicArcher() {
}
public String archerAttacks() {
return "Archer Attacks!";
}
}
|
package com.wrathOfLoD.Models.Items.EquippableItems;
import com.wrathOfLoD.Models.Commands.EntityActionCommands.EquipItemCommands.EquipGreavesCommand;
import com.wrathOfLoD.Models.Commands.EntityActionCommands.EquipItemCommands.EquipItemCommand;
import com.wrathOfLoD.Models.Commands.EntityActionCommands.UnequipItemCommands.UnequipGreavesCommand;
import com.wrathOfLoD.Models.Commands.EntityActionCommands.UnequipItemCommands.UnequipItemCommand;
import com.wrathOfLoD.Models.Entity.Character.Character;
import com.wrathOfLoD.Models.Stats.StatsModifiable;
import com.wrathOfLoD.Utility.Position;
/**
* Created by matthewdiaz on 4/9/16.
*/
public class Greaves extends EquippableItem{
public Greaves(String name, StatsModifiable stats){
super( name, stats);
}
@Override
protected void equip(Character character){
EquipItemCommand equipGreavesCommand = new EquipGreavesCommand(character, this);
equipGreavesCommand.execute();
}
@Override
public void unequip(Character character){
UnequipItemCommand unequipGreavesCommand = new UnequipGreavesCommand(character, this);
unequipGreavesCommand.execute();
}
} |
package croissonrouge.darelbeida.competitions;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import croissonrouge.darelbeida.competitions.SQLite.SQL;
import croissonrouge.darelbeida.competitions.SQLite.SQLSharing;
import static android.view.View.GONE;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
variables();
fonts();
images();
sql();
if(SQLSharing.mycursor.getCount()<=6){
SQLSharing.mydb.insertData("");
SQLSharing.mydb.insertData("");
SQLSharing.mydb.insertData("");
SQLSharing.mydb.insertData("");
SQLSharing.mydb.insertData("");
SQLSharing.mydb.insertData("");
SQLSharing.mydb.insertData(""); // used for drawingmainfragment display version
SQLSharing.mydb.insertData(""); // used for readingmainfragment display version
SQLSharing.mydb.insertData(""); // used for cookingmainfragment display version
}
close_sql();
}
@Override
protected void onResume() {
super.onResume();
netcheck();
}
private void close_sql() {
if(SQLSharing.mycursor!=null)
SQLSharing.mycursor.close();
if(SQLSharing.mydb!=null)
SQLSharing.mydb.close();
}
private void sql() {
SQLSharing.mydb = SQL.getInstance(getApplicationContext());
SQLSharing.mycursor = SQLSharing.mydb.getData();
}
private void netcheck() {
FirebaseAuth mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
mAuth.getCurrentUser().reload();
if (mAuth.getCurrentUser() != null) {
final String uid = mAuth.getCurrentUser().getUid();
final FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference userRef = database.getReference("users").child(uid);
userRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
loadingscreen.setVisibility(GONE);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
print(getResources().getString(R.string.doyouhaveinternet));
}
});
}
} else {
mAuth.signInAnonymously()
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>()
{
@Override
public void onComplete(@NonNull Task<AuthResult> task)
{
if (!task.isSuccessful()) {
print(getResources().getString(R.string.doyouhaveinternet));
netcheck();
} else {
loadingscreen.setVisibility(GONE);
}
}
});
}
}
private void print(Object log){
Toast.makeText(this, String.valueOf(log), Toast.LENGTH_SHORT).show();
}
private void fonts() {
Typeface font = Typeface.createFromAsset(getAssets(), "Tajawal-Regular.ttf");
tofolaa.setTypeface(font);
parental.setTypeface(font);
drawing.setTypeface(font);
connecting.setTypeface(font);
reading.setTypeface(font);
cooking.setTypeface(font);
organization.setTypeface(font);
creditter.setTypeface(font);
}
private TextView connecting, organization, creditter, parental, tofolaa;
private Button drawing, reading, cooking;
private ImageView logo, logo2;
private FrameLayout loadingscreen;
private void variables() {
tofolaa = findViewById(R.id.tofolaa);
parental = findViewById(R.id.parental);
cooking = findViewById(R.id.cooking);
reading = findViewById(R.id.reading);
drawing = findViewById(R.id.drawing);
logo = findViewById(R.id.logo);
organization = findViewById(R.id.organization);
logo2 = findViewById(R.id.logo2);
loadingscreen = findViewById(R.id.loadingscreen);
connecting = findViewById(R.id.connecting);
creditter = findViewById(R.id.creditter);
}
private long backPressedTime;
private Toast backToast;
@Override
public void onBackPressed() {
if (backPressedTime + 2000 > System.currentTimeMillis()) {
backToast.cancel();
super.onBackPressed();
return;
} else {
backToast = Toast.makeText(getBaseContext(), getApplicationContext().getString(R.string.areyousure), Toast.LENGTH_SHORT);
backToast.show();
}
backPressedTime = System.currentTimeMillis();
}
private void images() {
try {
Glide.with(this).load(R.drawable.logo).into(logo);
} catch (Exception ignored) {
logo.setImageDrawable(getResources().getDrawable(R.drawable.logo));
}
/*try {
Glide.with(this).load(R.drawable.logogg).into(logo2);
} catch (Exception ignored) {
logo2.setImageDrawable(getResources().getDrawable(R.drawable.logogg));
}*/
}
public void drawingsClicked(View view) {
Intent opendrawingsMain = new Intent(this, DrawingsMain.class);
startActivity(opendrawingsMain);
finish();
}
public void readingClicked(View view) {
Intent opendrawingsMain = new Intent(this, ReadingMain.class);
startActivity(opendrawingsMain);
finish();
}
public void cookingClicked(View view) {
Intent opendrawingsMain = new Intent(this, CookingMain.class);
startActivity(opendrawingsMain);
finish();
}
}
|
import java.io.*;
public class Main {
static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main (String[] args) throws IOException {
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
char[] nums = line.toCharArray();
int exp = 0;
int ret = 0;
for(int i = nums.length - 1; i >= 0; i--) {
ret += hexToDig(nums[i]) * Math.pow(16, exp);
exp++;
}
System.out.println(ret);
}
}
static int hexToDig(char hex) {
if(hex >= 'a' && hex <= 'f')
return hex - 'a' + 10;
else if(hex >= '0' && hex <= '9')
return hex - '0';
return -1;
}
}
|
/*
* Created on Jan 12, 2007
*
*
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.citibank.ods.common.taglib;
import javax.servlet.jsp.tagext.TagSupport;
/**
* @author User
*
*
* Window - Preferences - Java - Code Style - Code Templates
*/
public abstract class BaseTag extends TagSupport
{
}
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
StringBuilder stringBuilder = new StringBuilder(100000);
Scanner scanner = new Scanner(System.in);
String error = scanner.nextLine();
String correct = scanner.nextLine();
// 1.分割字符串
// String[] errorChar = error.split("|");
String[] correctChar = correct.split("|");
// E.判断上档键是否坏掉
boolean upIsError = error.contains("+");
// 2.判断这个字符是否在坏键中,是则不输出,不是则下一步
for (String string:correctChar)
{
char c = string.charAt(0);
// System.out.println(string);
// if (c>='A')
if (error.contains(string.toUpperCase()))
{
// if (!(c>='A' && c<='Z'&& upIsError))
// System.out.println(c+"在错误字符串内");
continue;
}
if ((c>='A' && c<='Z'&& upIsError))
{
// System.out.println(c+";上档键已坏,且该字符为大写");
continue;
}
stringBuilder.append(string);
}
// 3.判断这个字符是否是大写,是则查看上档键
System.out.println(stringBuilder.toString());
}
}
|
package com.zain;
public class Main {
public static void main(String[] args) {
PassChecker checker=new PassChecker();
checker.start();
}
}
|
/**
* Copyright 2010 The European Bioinformatics Institute, and others.
*
* 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 uk.ac.ebi.intact.view.webapp.scope;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.context.request.SessionScope;
import uk.ac.ebi.intact.view.webapp.controller.search.UserQuery;
/**
* @author Bruno Aranda (baranda@ebi.ac.uk)
* @version $Id$
*/
public class CurrentSearchScope extends SessionScope implements ApplicationContextAware {
private ApplicationContext applicationContext;
public CurrentSearchScope() {
}
public Object get(String name, ObjectFactory objectFactory) {
String searchQuery = getSearchQuery();
final String uniqueName = name + "::" + simplify(searchQuery);
return super.get(uniqueName, objectFactory);
}
private String simplify(String searchQuery) {
if ("*".equals(searchQuery)) {
return "";
}
return searchQuery;
}
public Object remove(String name) {
String searchQuery = getSearchQuery();
return super.remove(name+"::"+searchQuery);
}
private String getSearchQuery() {
String searchQuery = getUserQuery().getSearchQuery();
if (searchQuery == null) {
searchQuery = "*";
}
return searchQuery;
}
public String getConversationId() {
String searchQuery = getUserQuery().getSearchQuery();
if (searchQuery != null) {
return super.getConversationId()+"::"+searchQuery;
}
return null;
}
public UserQuery getUserQuery() {
return (UserQuery) applicationContext.getBean("userQuery");
}
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
}
|
/*
MusicalInstrument -- a class within the Cellular Automaton Explorer.
Copyright (C) 2005 David B. Bahr (http://academic.regis.edu/dbahr/)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package cellularAutomata.util.music;
import javax.sound.midi.*;
import javax.sound.midi.MidiUnavailableException;
/**
* Plays musical notes that correspond to the notes on a piano. A piano has keys
* numbered from 1 (lowest "A") to 88 ("highest "C"). By selecting a number from
* 1 to 88, the play method will reproduce the corresponding piano's note.
* Values larger than 88 and less than 1 will throw an
* <code>IllegalArgumentException</code>.
* <p>
* Silent notes or "rests" can be played by specifying any key with a volume of
* 0 and a nonzero duration.
* <p>
* The duration of each note can be specified in milliseconds. The volume is a
* number between 0 and 127 with 0 being inaudible and 127 being the loudest.
* Default values for duration and volume are 150 milliseconds and 60 unless
* reset after the class is instantiated.
* <p>
* A synthesizer or midi is used to reproduce the notes. The synthesizer must be
* opened prior to use (<code>openSynthesizer</code>) and closed after use (<code>closeSynthesizer</code>).
* <p>
* An example of use:
*
* <pre>
* MusicalInstrument piano = new MusicalInstrument();
*
* try
* {
* piano.openSynthesizer();
*
* //play chromatic scale
* for(int i = 0; i <= 88; i++)
* {
* piano.play(i);
* }
* }
* catch(javax.sound.midi.MidiUnavailableException e)
* {
* System.out.println("Could not open midi. " + e.toString());
* }
* finally
* {
* //a finally clause is always executed at the end of a
* //try-catch clause, even if a failure made the code
* //enter the catch clause. So this is a very safe way
* //to close the synthesizer. Will always happen!
* piano.closeSynthesizer();
* }
* </pre>
*
* This code was authored by David Bahr and is only intended for use with Regis
* University computer science classes.
*
* @author David Bahr
* @version 1.3 11/1/05
*/
public class MusicalInstrument
{
// -------------------------------------------------
// constants
/**
* Message generated when there is an error because no instruments are
* available for the synthesizer.
*/
public final static String NO_INSTRUMENTS_MESSAGE = "No instruments are "
+ "available.";
/**
* Message generated when there is an error because no sound bank is
* available for the synthesizer.
*/
public final static String NO_SOUND_BANK_MESSAGE = "No soundbank is "
+ "available.";
/**
* Message generated when there is an error because there is no synthesizer
* available.
*/
public final static String NO_SYNTHESIZER_MESSAGE = "No synthesizer is "
+ "available.";
// The number of notes on a piano.
private final static int NOTENUM = 88;
// -------------------------------------------------
// keeps track of which notes are currently playing (on). There are 0-127
// available midi notes.
private boolean[] notesOn = new boolean[128];
// Default duration in milliseconds
private int defaultDuration = 150;
// Default volume (number between 1 and 127)
private int defaultVolume = 60;
// The default midi channel
private MidiChannel[] channels = null;
// The synthesizer used to play a note
private Synthesizer synth = null;
// -------------------------------------------------
// constructors
/**
* Create a piano synthesizer.
*/
public MusicalInstrument()
{
// indicate that no notes are currently playing
for(int i = 0; i < notesOn.length; i++)
{
notesOn[i] = false;
}
}
// -------------------------------------------------
// methods
/**
* Maps the piano key's number to a value recognized by the midi. Piano
* notes range from 0 to 87 with 39 being "middle C", but the midi can
* handle notes from 0 to 127 with 60 being "middle C".
*/
private int mapPianoNoteToMidiNote(int note)
throws IllegalArgumentException
{
if(note < 0 || note > NOTENUM - 1)
{
throw new IllegalArgumentException("Note must be between 0 and "
+ (NOTENUM - 1) + " (the notes on a piano).");
}
int midiNote = note + 21;
// just in case
if(midiNote < 0)
{
midiNote = 0;
}
// just in case
if(midiNote > 127)
{
midiNote = 127;
}
return midiNote;
}
/**
* Turns off all notes currently being played.
*
* @exception MidiUnavailableException
* if Midi Synthesizer has not been opened.
*/
public void allNotesOff()
{
if(synth.isOpen())
{
channels[0].allNotesOff();
}
// keep track that all notes are now off
for(int i = 0; i < notesOn.length; i++)
{
notesOn[i] = false;
}
}
/**
* Closes the synthesizer properly so that it does not interfere with other
* applications. If the synthesizer is not open, then this method will not
* close the synthesizer.
*/
public void closeSynthesizer()
{
if((synth != null) && synth.isOpen())
{
synth.close();
}
synth = null;
}
/**
* An array of instruments loaded into the synthesizer;
*
* @return An array of instruments.
*/
public Instrument[] getLoadedInstruments()
{
return synth.getLoadedInstruments();
}
/**
* The default duration in milliseconds. 150 milliseconds unless reset with
* setDefaultDuration.
*
* @return default duration of note
*/
public int getDefaultDuration()
{
return defaultDuration;
}
/**
* The default volume as a number between 0 (inaudible) and 127 (loudest).
* Default is 60 unless reset with setDefaultVolume.
*
* @return default volume of note
*/
public int getDefaultVolume()
{
return defaultVolume;
}
/**
* The number of keys that are on a piano (the number of tones that can be
* played by this synthesizer).
*
* @return the number of keys on a piano
*/
public int getNumberOfPianoKeys()
{
return NOTENUM;
}
/**
* Checks if the given piano key is already playing.
*
* @param keyNumber
* The piano key (note) that will be checked to see if it is
* currently playing.
*
* @return true if the specified note is playing
*/
public boolean isNoteOn(int keyNumber)
{
int midiNote = mapPianoNoteToMidiNote(keyNumber);
return notesOn[midiNote];
}
/**
* Tests for presence of the sythensizer.
*
* @return <code>true</code> if synthesizer is open
*/
public boolean isOpen()
{
boolean open = false;
if(synth != null)
{
open = synth.isOpen();
}
return open;
}
/**
* Turns off the note corresponding to the key number on the piano (0 to
* 87). A piano has 88 keys and this method starts counting from 0.
* Therefore a 0 is the lowest "A" on the piano and a 39 is "middle C".
*
* @param keyNumber
* A piano key's number between 0 and 87.
* @exception MidiUnavailableException
* if Midi Synthesizer has not been opened.
*/
public void noteOff(int keyNumber) throws MidiUnavailableException
{
int midiNote = mapPianoNoteToMidiNote(keyNumber);
if(synth.isOpen())
{
channels[0].noteOff(midiNote);
// keep track that this note is currently off
notesOn[midiNote] = false;
}
else
{
throw new MidiUnavailableException(
"You did not open the Midi Synthesizer.");
}
}
/**
* Plays the note corresponding to the key number on the piano (0 to 87)
* with the given volume. The note's duration is infinite and will continue
* sounding until it is turned off (see method noteOff()). A piano has 88
* keys and this method starts counting from 0. Therefore a 0 is the lowest
* "A" on the piano and a 39 is "middle C".
*
* @param keyNumber
* A piano key's number between 0 and 87.
* @exception MidiUnavailableException
* if Midi Synthesizer has not been opened.
*/
public void noteOn(int keyNumber) throws MidiUnavailableException
{
noteOn(keyNumber, defaultVolume);
}
/**
* Plays the note corresponding to the key number on the piano (0 to 87)
* with the given volume. The note's duration is infinite and will continue
* sounding until it is turned off (see method noteOff()). A piano has 88
* keys and this method starts counting from 0. Therefore a 0 is the lowest
* "A" on the piano and a 39 is "middle C".
*
* @param keyNumber
* A piano key's number between 0 and 87.
* @param volume
* Number between 0 and 127.
* @exception MidiUnavailableException
* if Midi Synthesizer has not been opened.
*/
public void noteOn(int keyNumber, int volume)
throws MidiUnavailableException
{
int midiNote = mapPianoNoteToMidiNote(keyNumber);
if(synth.isOpen())
{
channels[0].noteOn(midiNote, volume);
// keep track that this note is currently on
notesOn[midiNote] = true;
}
else
{
throw new MidiUnavailableException(
"You did not open the Midi Synthesizer.");
}
}
/**
* Request the default synthesizer (used to play music).
*
* @exception MidiUnavailableException
* if Midi Synthesizer is unavailable
*/
public void openSynthesizer() throws MidiUnavailableException
{
if(synth == null)
{
synth = MidiSystem.getSynthesizer();
if(synth != null)
{
synth.open();
Soundbank soundbank = synth.getDefaultSoundbank();
if(soundbank != null)
{
synth.loadAllInstruments(soundbank);
}
else
{
throw new MidiUnavailableException(NO_SOUND_BANK_MESSAGE);
}
channels = synth.getChannels();
Instrument[] inst = synth.getAvailableInstruments();
if(inst == null || (inst.length == 0))
{
throw new MidiUnavailableException(NO_INSTRUMENTS_MESSAGE);
}
}
else
{
throw new MidiUnavailableException(NO_SYNTHESIZER_MESSAGE);
}
}
}
/**
* Plays the note corresponding to the key number on the piano (0 to 87). A
* piano has 88 keys and this method starts counting from 0. Therefore a 0
* is the lowest "A" on the piano and a 39 is "middle C". The default
* duration and volume are used.
*
* @param keyNumber
* A piano key's number between 0 and 87.
* @exception MidiUnavailableException
* if Midi Synthesizer has not been opened.
*/
public void play(int keyNumber) throws MidiUnavailableException
{
play(keyNumber, defaultDuration, defaultVolume);
}
/**
* Plays the note corresponding to the key number on the piano (0 to 87)
* with the given duration. A piano has 88 keys and this method starts
* counting from 0. Therefore a 0 is the lowest "A" on the piano and a 39 is
* "middle C". The default volume is used.
*
* @param keyNumber
* A piano key's number between 0 and 87.
* @param duration
* In milliseconds.
* @exception MidiUnavailableException
* if Midi Synthesizer has not been opened.
*/
public void play(int keyNumber, int duration)
throws MidiUnavailableException
{
play(keyNumber, duration, defaultVolume);
}
/**
* Plays the note corresponding to the key number on the piano (0 to 87)
* with the given duration and volume. A piano has 88 keys and this method
* starts counting from 0. Therefore a 0 is the lowest "A" on the piano and
* a 39 is "middle C".
*
* @param keyNumber
* A piano key's number between 0 and 87.
* @param volume
* Number between 0 and 127.
* @param duration
* In milliseconds.
* @exception MidiUnavailableException
* if Midi Synthesizer has not been opened.
*/
public void play(int keyNumber, int duration, int volume)
throws MidiUnavailableException
{
int midiNote = mapPianoNoteToMidiNote(keyNumber);
if(synth.isOpen())
{
channels[0].noteOn(midiNote, volume);
// keep track that this note is currently on
notesOn[midiNote] = true;
try
{
Thread.sleep(duration);
}
catch(InterruptedException e)
{
// ignored -- not fatal
}
channels[0].noteOff(midiNote);
// keep track that this note is currently off
notesOn[midiNote] = false;
}
else
{
throw new MidiUnavailableException(
"You did not open the Midi Synthesizer.");
}
}
/**
* Sets default duration in milliseconds.
*
* @param duration
* In milliseconds.
* @throws IllegalArgumentException
* if less than 0.
*/
public void setDefaultDuration(int duration)
{
if(duration < 0)
{
throw new IllegalArgumentException(
"Duration must be between greater than or " + "equal to 0.");
}
defaultDuration = duration;
}
/**
* Sets the default volume as a number between 0 (inaudible) and 127
* (loudest).
*
* @param volume
* Between 0 and 127.
* @throws IllegalArgumentException
* if not between 0 and 127.
*/
public void setDefaultVolume(int volume) throws IllegalArgumentException
{
if(volume < 0 || volume > 127)
{
throw new IllegalArgumentException(
"Volume must be between 0 and 127.");
}
defaultVolume = volume;
}
/**
* Changes the instrument to the one specified, assuming that the instrument
* is available.
*
* @param instrumentName
* The instrument that will be played.
*/
public void setInstrument(String instrumentName)
{
// find the instrument
Instrument[] inst = synth.getLoadedInstruments();
if((inst != null) && (inst.length > 0))
{
int i = 0;
boolean notFound = true;
while(notFound)
{
if(inst[i].getName().equals(instrumentName))
{
// found that instrument
notFound = false;
// change the instrument
channels[0].programChange(inst[i].getPatch().getBank(),
inst[i].getPatch().getProgram());
}
// try the next instrument
i++;
}
}
}
}
|
package com.nepshop.dao;
import com.nepshop.model.Customer;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.ArrayList;
import org.apache.commons.codec.binary.Base64;
import java.util.List;
public class CustomerDAO {
static Connection conn = DBConnectionUtil.getConnection();
public static List<Customer> getCustomers() {
List<Customer> customers = new ArrayList<>();
String query = "select * from customer";
try (PreparedStatement ps = conn.prepareStatement(query)) {
ResultSet rs = ps.executeQuery();
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
String password = rs.getString("password");
String address = rs.getString("address");
String phone = rs.getString("phone");
Blob blob = rs.getBlob("photo");
Customer customer = null;
if (blob != null) {
InputStream inputStream = blob.getBinaryStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
byte[] imageBytes = outputStream.toByteArray();
String base64String = new String(Base64.encodeBase64(imageBytes));
String photo = "data:image/jpg;base64," + base64String;
customer = new Customer(id, name, email, password, address, phone, photo);
} else {
customer = new Customer(id, name, email, password, address, phone);
}
customers.add(customer);
}
} catch (SQLException | IOException ex) {
ex.printStackTrace();
}
return customers;
}
public static boolean createCustomer(String name, String email, String password, String address, String phone) {
String query = "insert into customer(name, email, password, address, phone) values(?, ? ,?, ?, ?)";
try (PreparedStatement ps = conn.prepareStatement(query)) {
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, password);
ps.setString(4, address);
ps.setString(5, phone);
int rs = ps.executeUpdate();
if (rs > 0)
return true;
else
return false;
} catch (SQLException ex) {
ex.printStackTrace();
}
return false;
}
public static boolean createCustomer(String name, String email, String password, String address, String phone,
InputStream inputStream) {
String query = "insert into customer(name, email, password, address, phone, photo) values(?, ? ,?, ?, ?, ?)";
try (PreparedStatement ps = conn.prepareStatement(query)) {
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, password);
ps.setString(4, address);
ps.setString(5, phone);
ps.setBlob(6, inputStream);
int rs = ps.executeUpdate();
if (rs > 0)
return true;
else
return false;
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
public static boolean updateCustomer(int id, String name, String email, String password, String address,
String phone) {
String query = "update customer set name = ?, email = ? , password = ?, address = ?, phone = ? where id = ?";
try (PreparedStatement ps = conn.prepareStatement(query)) {
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, password);
ps.setString(4, address);
ps.setString(5, phone);
ps.setInt(6, id);
int rs = ps.executeUpdate();
if (rs > 0)
return true;
else
return false;
} catch (SQLException ex) {
ex.printStackTrace();
}
return false;
}
public static boolean updateCustomer(int id, String name, String email, String password, String address,
String phone, InputStream inputStream) {
String query = "update customer set name = ?, email = ? , password = ?, address = ?, phone = ?, photo = ? where id = ?";
try (PreparedStatement ps = conn.prepareStatement(query)) {
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, password);
ps.setString(4, address);
ps.setString(5, phone);
ps.setBlob(6, inputStream);
ps.setInt(7, id);
int rs = ps.executeUpdate();
if (rs > 0)
return true;
else
return false;
} catch (SQLException ex) {
ex.printStackTrace();
}
return false;
}
public static boolean deleteCustomer(int id) {
String query = "delete from customer where id = ?";
try (PreparedStatement ps = conn.prepareStatement(query)) {
ps.setInt(1, id);
int rs = ps.executeUpdate();
if (rs > 0)
return true;
else
return false;
} catch (SQLException ex) {
ex.printStackTrace();
}
return false;
}
public static Customer getCustomer(int id) {
String query = "select * from customer where id=?";
try (PreparedStatement ps = conn.prepareStatement(query)) {
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String name = rs.getString("name");
String email = rs.getString("email");
String password = rs.getString("password");
String address = rs.getString("address");
String phone = rs.getString("phone");
return new Customer(id, name, email, password, address, phone);
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return null;
}
public static boolean checkPassword(int id, String password) {
String query = "select * from customer where id = ? and password = ?";
try (PreparedStatement ps = conn.prepareStatement(query)) {
ps.setInt(1, id);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
return true;
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return false;
}
public static boolean updateAcInfo(int id, String name, String email, String address, String phone,
InputStream inputStream) {
String query = "update customer set name = ?, email = ?, address = ?, phone = ?, photo = ? where id = ?";
try (PreparedStatement ps = conn.prepareStatement(query)) {
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, address);
ps.setString(4, phone);
ps.setBlob(5, inputStream);
ps.setInt(6, id);
int rs = ps.executeUpdate();
if (rs > 0)
return true;
else
return false;
} catch (SQLException ex) {
ex.printStackTrace();
}
return false;
}
public static boolean updateAcInfo(int id, String name, String email, String address, String phone) {
String query = "update customer set name = ?, email = ?, address = ? where id = ?";
try (PreparedStatement ps = conn.prepareStatement(query)) {
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, address);
ps.setString(5, phone);
ps.setInt(6, id);
int rs = ps.executeUpdate();
if (rs > 0)
return true;
else
return false;
} catch (SQLException ex) {
ex.printStackTrace();
}
return false;
}
public static boolean updateAcPassword(int id, String oldPassword, String newPassword) {
String queryCheck = "select * from customer where id = ? and password = ?";
String queryUpdate = "update customer set password = ? where id = ?";
try (PreparedStatement psCheck = conn.prepareStatement(queryCheck)) {
psCheck.setInt(1, id);
psCheck.setString(2, oldPassword);
ResultSet rsCheck = psCheck.executeQuery();
while (rsCheck.next()) {
try (PreparedStatement psUpdate = conn.prepareStatement(queryUpdate)) {
psUpdate.setString(1, newPassword);
psUpdate.setInt(2, id);
int rsUpdate = psUpdate.executeUpdate();
if (rsUpdate > 0)
return true;
else
return false;
} catch (SQLException ex) {
ex.printStackTrace();
}
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return false;
}
public static boolean deleteAc(int id, String password) {
String queryCheck = "select * from customer where id = ? and password = ?";
String queryDelete = "delete from customer where id = ?";
try (PreparedStatement psCheck = conn.prepareStatement(queryCheck)) {
psCheck.setInt(1, id);
psCheck.setString(2, password);
ResultSet rsCheck = psCheck.executeQuery();
while (rsCheck.next()) {
try (PreparedStatement psDelete = conn.prepareStatement(queryDelete)) {
psDelete.setInt(1, id);
int rsDelete = psDelete.executeUpdate();
if (rsDelete > 0)
return true;
else
return false;
} catch (SQLException ex) {
ex.printStackTrace();
}
}
return false;
} catch (SQLException ex) {
ex.printStackTrace();
}
return false;
}
public static String getPhoto(int id) {
String query = "select * from customer where id=?";
try (PreparedStatement ps = conn.prepareStatement(query)) {
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Blob blob = rs.getBlob("photo");
if (blob != null) {
InputStream inputStream = blob.getBinaryStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
byte[] imageBytes = outputStream.toByteArray();
String base64String = new String(Base64.encodeBase64(imageBytes));
String photo = "data:image/jpg;base64," + base64String;
return photo;
}
}
} catch (SQLException | IOException ex) {
ex.printStackTrace();
}
return null;
}
public static String getPassword(int id) {
String query = "select * from customer where id=?";
try (PreparedStatement ps = conn.prepareStatement(query)) {
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String password = rs.getString("password");
return password;
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return null;
}
}
|
package DataStructures.trees;
/** Tree
6
/ \
4 10
/ \ / \
2 5 9 12
/ \ / / \
1 3 7 11 13
*/
public class DeleteNodeBST {
TreeNode root;
//tc: o(n)
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) return null;
int cmp = Integer.compare(key, root.val);
if (cmp < 0) root.left = deleteNode(root.left, key);
else if (cmp > 0) root.right = deleteNode(root.right, key);
else {
if (root.left == null)
return root.right;
if (root.right == null)
return root.left;
TreeNode t = root;
root = findMin(t.right);
root.right = deleteMin(t.right);
root.left = t.left;
}
return root;
}
private TreeNode deleteMin(TreeNode x) {
if (x.left == null) return x.right;
x.left = deleteMin(x.left);
return x;
}
public TreeNode findMin(TreeNode node) {
if (node.left == null) return node;
return findMin(node.left);
}
public static void main(String a[]) {
DeleteNodeBST d = new DeleteNodeBST();
int[] ar = new int[]{1, 3, 5, 7, 9, 14, 18, 21};
//TreeNode root = new BSTBasicOperations().buildTreeSortedArray(new TreeNode(), ar, 0, ar.length - 1);
TreeNode root = new TreeNode(6,
new TreeNode(4,
new TreeNode(2,
new TreeNode(1, null, null),
new TreeNode(3, null, null)),
new TreeNode(5, null, null)),
new TreeNode(10,
new TreeNode(9,
new TreeNode(7, null, null),
null),
new TreeNode(12,
new TreeNode(11, null, null),
new TreeNode(13, null, null))));
root = d.deleteNode(root, 6);
System.out.println(root);
}
}
|
package com.gestion.servlet;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
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 org.hibernate.Session;
import com.gestion.entity.Client;
import com.gestion.entity.Fournisseur;
import com.gestion.entity.MaterielCortex2i;
import com.gestion.service.ServiceClientCortex2i;
import com.gestion.service.ServiceMaterielCortex2i;
import fr.cortex2i.utils.HibernateUtils;
/**
* Servlet implementation class ServletRechercheClient
*/
@WebServlet("/ServletRechercheClient")
public class ServletRechercheClient extends HttpServlet {
private static final long serialVersionUID = 1L;
Session s = null;
/**
* @see HttpServlet#HttpServlet()
*/
public ServletRechercheClient() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
}
/**
* @see Servlet#destroy()
*/
public void destroy()
{
// TODO Auto-generated method stub
}
@SuppressWarnings("unused")
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Session s = HibernateUtils.getSession();
String page = null ;
String nom = null;
String message = null ;
HttpSession s1 = request.getSession();
Client cl = new Client();
Enumeration<String> id = request.getParameterNames();
String attr = id.nextElement();
cl.setNom(request.getParameter(attr));
nom = cl.getNom();
cl = (Client) ServiceClientCortex2i.rechercheClientCortex2iByName(s, cl);
if(cl!=null)
{
if(("nomCl1").equals(attr))
{
page = "/modifierClient.jsp";
}
else
if(("nomCl2").equals(attr))
{
page = "/GestionSiteClient.jsp";
}
else
{
page = "/ServletGestionClient";
message = "oui";
}
request.setAttribute("cl", cl);
}
else
{
message = "Ce client n'existe pas!";
page = "/ServletGestionClient";
}
request.setAttribute("messageCL", message);
request.getServletContext().getRequestDispatcher(page).forward(request, response);
s.close();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
|
package annotation.getterCheck;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by DELL on 2018/10/17.
* 因为起到语法检查/约束,仅仅在编译器起租用就行了,将Retention设置为SOURCE即可。
*/
@Target({ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.SOURCE)
public @interface CheckGetter {
}
|
package com.suven.frame.server.data.model;
import org.springframework.stereotype.Component;
/**
* Created by lipingfa on 2017/6/15.
*/
@Component
public class HelloWorld {
public String hello() {
return "Hello Wddddodsdadarld!";
}
}
|
package mao.action;
import mao.view.login.LoginView;
/**
* @author 豪
* @date 2018/6/19 22:31
*/
public class run {
public static void main(String[] agrs){
new LoginView();
}
}
|
package hu.cehessteg.vizeromu.Stage;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.viewport.Viewport;
import hu.cehessteg.vizeromu.Actor.Gomb;
import hu.cehessteg.vizeromu.GlobalClasses.Assets;
import hu.csanyzeg.master.MyBaseClasses.Game.MyGame;
import hu.csanyzeg.master.MyBaseClasses.Scene2D.MyStage;
import hu.csanyzeg.master.MyBaseClasses.Scene2D.OneSpriteStaticActor;
import hu.cehessteg.vizeromu.Vizeromu;
public class OptionsStage extends MyStage {
Gomb menu;
boolean mehetVissza;
public static boolean muted = false;
OneSpriteStaticActor background;
Gomb mute;
public OptionsStage(Viewport viewport, MyGame game) {
super(viewport, game);
assignment();
setPositions();
addActors();
addListeners();
}
void assignment()
{
menu = new Gomb("Vissza",this);
mute = new Gomb("",this);
background = new OneSpriteStaticActor(Assets.manager.get(Assets.BLUE_TEXTURE));
background.setColor(0,0,0,0.85f);
}
void setPositions()
{
menu.setPosition(getViewport().getWorldWidth()-menu.getWidth()-getViewport().getWorldHeight()*0.045f,getViewport().getWorldHeight()*0.045f);
mute.setSize(mute.getWidth()*1.5f,mute.getHeight()*1.5f);
mute.setPosition(getViewport().getWorldWidth()/2-mute.getWidth()/2,getViewport().getWorldHeight()/2);
background.setPosition(0,0);
background.setSize(getViewport().getWorldWidth(),getViewport().getWorldHeight());
}
void addActors()
{
background.setDebug(false);
addActor(background);
addActor(menu);
addActor(mute);
menu.myLabel.setPosition(menu.getX()+menu.getWidth()/2-menu.myLabel.getWidth()/2,menu.getY()+menu.getHeight()/2-menu.myLabel.getHeight()/2);
menu.myLabel.setZIndex(30);
mute.myLabel.setPosition(mute.getX()+mute.getWidth()/2-mute.myLabel.getWidth()/2,mute.getY()+mute.getHeight()/2-mute.myLabel.getHeight()/2);
mute.myLabel.setZIndex(30);
}
void addListeners()
{
menu.addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y) {
super.clicked(event, x, y);
Vizeromu.gameSave.putBoolean("muted", muted);
Vizeromu.gameSave.flush();
setMehetVissza(true);
}
});
mute.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
super.clicked(event, x, y);
if(!muted) {
muted = true;
MenuStage.menuMusic.stop();
}
else {
muted = false;
MenuStage.menuMusic.play();
}
}
});
}
@Override
public void init() {
}
@Override
public void act(float delta) {
super.act(delta);
if(muted)
{
if (!mute.myLabel.getText().equals("Némítva")) mute.myLabel.setText("Némítva");
}
else
{
if (!mute.myLabel.getText().equals("Nincs némítva")) mute.myLabel.setText("Nincs némítva");
}
}
public boolean isMehetVissza() {
return mehetVissza;
}
public void setMehetVissza(boolean mehetVissza) {
this.mehetVissza = mehetVissza;
}
public static boolean isMuted() {
return muted;
}
public static void setMuted(boolean muted) {
OptionsStage.muted = muted;
}
}
|
package im.compIII.exghdecore.testes.funcional;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import org.dbunit.DatabaseTestCase;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.operation.DatabaseOperation;
import org.junit.Test;
import im.compIII.exghdecore.banco.AmbienteDB;
import im.compIII.exghdecore.entidades.Ambiente;
public class TesteAmbienteDB extends DatabaseTestCase{
@Override
protected IDatabaseConnection getConnection() throws Exception {
Connection conn = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/exghDecoreDBTeste", "admin", "admin123");
return new DatabaseConnection(conn);
}
@Override
protected IDataSet getDataSet() throws Exception {
return new FlatXmlDataSet(
new FileInputStream("WebContent/META-INF/datasetContrato.xml")
);
}
protected DatabaseOperation getSetUpOperation(){
return DatabaseOperation.CLEAN_INSERT;
}
protected DatabaseOperation getTearDownOperation(){
return DatabaseOperation.NONE;
}
@Test
public void testaCadastrarAmbient() throws Exception{
Ambiente amb = new Ambiente(10, 5, 2);
AmbienteDB ambd = new AmbienteDB();
String str []= {"1", "2"};
int quant[] = {1, 2};
long contratoId = 1;
//amb.adicionar(contratoId, str, quant);
IDataSet dsAtual = getConnection().createDataSet();
ITable tabelaAtual = dsAtual.getTable("Ambiente");
assertEquals(1, tabelaAtual.getRowCount());
}
}
|
package jp.ac.kyushu_u.csce.modeltool.base.utility;
/**
* ファイルアクセス例外クラス
*
* @author KBK yoshimura
*/
public class FileAccessException extends Exception {
private static final long serialVersionUID = 1L;
public FileAccessException() {
super();
}
public FileAccessException(String message) {
super(message);
}
public FileAccessException(Throwable cause) {
super(cause);
// setStackTrace(cause.getStackTrace());
}
public FileAccessException(String message, Throwable cause) {
super(message, cause);
// setStackTrace(cause.getStackTrace());
}
}
|
/*
这个程序在编译的时候会报错:
编码gbk的不可映射字符
这是因为有中文注释的原因;
解决方法:
这样编译 javac -encoding utf-8 ArrayListMagnet.java
@author 《head first Java》
@version “1.8.1_131”
*/
import java.util.*;//ArrayList这个类包含在java.util这个包中
//此程序的类名叫ArrayListMagnet
public class ArrayListMagnet{
public static void main (String[] args){
//创建ArrayList类,类型 String,对象是 a,
ArrayList<String> a = new ArrayList<String>();
//加入元素
a.add(0,"zero");
a.add(1,"one");
a.add(2,"two");
a.add(3,"three");
printAL(a);
if(a.contains("three")){
a.add("four");
}
a.remove(2);
printAL(a);
if(a.indexOf("four") != 4){
a.add(4,"4.2");
}
printAL(a);
if(a.contains("two")){
a.add("2.2");
}
printAL(a);
}
public static void printAL(ArrayList<String> al){
//利用超级for循环,打印ArrayList的所有元素
for(String element : al){
System.out.println(element + " ");
}
System.out.println(" ");
}
}
|
/*
* Copyright 2002-2023 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.beans.factory.config;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.beans.support.ArgumentConvertingMethodInvoker;
import org.springframework.util.MethodInvoker;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Unit tests for {@link MethodInvokingFactoryBean} and {@link MethodInvokingBean}.
*
* @author Colin Sampaleanu
* @author Juergen Hoeller
* @author Chris Beams
* @since 21.11.2003
*/
public class MethodInvokingFactoryBeanTests {
@Test
public void testParameterValidation() throws Exception {
// assert that only static OR non-static are set, but not both or none
MethodInvokingFactoryBean mcfb = new MethodInvokingFactoryBean();
assertThatIllegalArgumentException().isThrownBy(mcfb::afterPropertiesSet);
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetObject(this);
mcfb.setTargetMethod("whatever");
assertThatExceptionOfType(NoSuchMethodException.class).isThrownBy(mcfb::afterPropertiesSet);
// bogus static method
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("some.bogus.Method.name");
assertThatExceptionOfType(NoSuchMethodException.class).isThrownBy(mcfb::afterPropertiesSet);
// bogus static method
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("method1");
assertThatIllegalArgumentException().isThrownBy(mcfb::afterPropertiesSet);
// missing method
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetObject(this);
assertThatIllegalArgumentException().isThrownBy(mcfb::afterPropertiesSet);
// bogus method
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetObject(this);
mcfb.setTargetMethod("bogus");
assertThatExceptionOfType(NoSuchMethodException.class).isThrownBy(mcfb::afterPropertiesSet);
// static method
TestClass1._staticField1 = 0;
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("staticMethod1");
mcfb.afterPropertiesSet();
// non-static method
TestClass1 tc1 = new TestClass1();
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetObject(tc1);
mcfb.setTargetMethod("method1");
mcfb.afterPropertiesSet();
}
@Test
public void testGetObjectType() throws Exception {
TestClass1 tc1 = new TestClass1();
MethodInvokingFactoryBean mcfb = new MethodInvokingFactoryBean();
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetObject(tc1);
mcfb.setTargetMethod("method1");
mcfb.afterPropertiesSet();
assertThat(int.class.equals(mcfb.getObjectType())).isTrue();
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("voidRetvalMethod");
mcfb.afterPropertiesSet();
Class<?> objType = mcfb.getObjectType();
assertThat(void.class).isSameAs(objType);
// verify that we can call a method with args that are subtypes of the
// target method arg types
TestClass1._staticField1 = 0;
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes");
mcfb.setArguments(new ArrayList<>(), new ArrayList<>(), "hello");
mcfb.afterPropertiesSet();
mcfb.getObjectType();
// fail on improper argument types at afterPropertiesSet
mcfb = new MethodInvokingFactoryBean();
mcfb.registerCustomEditor(String.class, new StringTrimmerEditor(false));
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes");
mcfb.setArguments("1", new Object());
assertThatExceptionOfType(NoSuchMethodException.class).isThrownBy(mcfb::afterPropertiesSet);
}
@Test
public void testGetObject() throws Exception {
// singleton, non-static
TestClass1 tc1 = new TestClass1();
MethodInvokingFactoryBean mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetObject(tc1);
mcfb.setTargetMethod("method1");
mcfb.afterPropertiesSet();
Integer i = (Integer) mcfb.getObject();
assertThat(i).isEqualTo(1);
i = (Integer) mcfb.getObject();
assertThat(i).isEqualTo(1);
// non-singleton, non-static
tc1 = new TestClass1();
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetObject(tc1);
mcfb.setTargetMethod("method1");
mcfb.setSingleton(false);
mcfb.afterPropertiesSet();
i = (Integer) mcfb.getObject();
assertThat(i).isEqualTo(1);
i = (Integer) mcfb.getObject();
assertThat(i).isEqualTo(2);
// singleton, static
TestClass1._staticField1 = 0;
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("staticMethod1");
mcfb.afterPropertiesSet();
i = (Integer) mcfb.getObject();
assertThat(i).isEqualTo(1);
i = (Integer) mcfb.getObject();
assertThat(i).isEqualTo(1);
// non-singleton, static
TestClass1._staticField1 = 0;
mcfb = new MethodInvokingFactoryBean();
mcfb.setStaticMethod("org.springframework.beans.factory.config.MethodInvokingFactoryBeanTests$TestClass1.staticMethod1");
mcfb.setSingleton(false);
mcfb.afterPropertiesSet();
i = (Integer) mcfb.getObject();
assertThat(i).isEqualTo(1);
i = (Integer) mcfb.getObject();
assertThat(i).isEqualTo(2);
// void return value
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("voidRetvalMethod");
mcfb.afterPropertiesSet();
assertThat(mcfb.getObject()).isNull();
// now see if we can match methods with arguments that have supertype arguments
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes");
mcfb.setArguments(new ArrayList<>(), new ArrayList<>(), "hello");
// should pass
mcfb.afterPropertiesSet();
}
@Test
public void testArgumentConversion() throws Exception {
MethodInvokingFactoryBean mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes");
mcfb.setArguments(new ArrayList<>(), new ArrayList<>(), "hello", "bogus");
assertThatExceptionOfType(NoSuchMethodException.class).as(
"Matched method with wrong number of args").isThrownBy(
mcfb::afterPropertiesSet);
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes");
mcfb.setArguments(1, new Object());
assertThatExceptionOfType(NoSuchMethodException.class).as(
"Should have failed on getObject with mismatched argument types").isThrownBy(
mcfb::afterPropertiesSet);
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes2");
mcfb.setArguments(new ArrayList<>(), new ArrayList<>(), "hello", "bogus");
mcfb.afterPropertiesSet();
assertThat(mcfb.getObject()).isEqualTo("hello");
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes2");
mcfb.setArguments(new ArrayList<>(), new ArrayList<>(), new Object());
assertThatExceptionOfType(NoSuchMethodException.class).as(
"Matched method when shouldn't have matched").isThrownBy(
mcfb::afterPropertiesSet);
}
@Test
public void testInvokeWithNullArgument() throws Exception {
MethodInvoker methodInvoker = new MethodInvoker();
methodInvoker.setTargetClass(TestClass1.class);
methodInvoker.setTargetMethod("nullArgument");
methodInvoker.setArguments(new Object[] {null});
methodInvoker.prepare();
methodInvoker.invoke();
}
@Test
public void testInvokeWithIntArgument() throws Exception {
ArgumentConvertingMethodInvoker methodInvoker = new ArgumentConvertingMethodInvoker();
methodInvoker.setTargetClass(TestClass1.class);
methodInvoker.setTargetMethod("intArgument");
methodInvoker.setArguments(5);
methodInvoker.prepare();
methodInvoker.invoke();
methodInvoker = new ArgumentConvertingMethodInvoker();
methodInvoker.setTargetClass(TestClass1.class);
methodInvoker.setTargetMethod("intArgument");
methodInvoker.setArguments(5);
methodInvoker.prepare();
methodInvoker.invoke();
}
@Test
public void testInvokeWithIntArguments() throws Exception {
MethodInvokingBean methodInvoker = new MethodInvokingBean();
methodInvoker.setTargetClass(TestClass1.class);
methodInvoker.setTargetMethod("intArguments");
methodInvoker.setArguments(new Object[] {new Integer[] {5, 10}});
methodInvoker.afterPropertiesSet();
methodInvoker = new MethodInvokingBean();
methodInvoker.setTargetClass(TestClass1.class);
methodInvoker.setTargetMethod("intArguments");
methodInvoker.setArguments(new Object[] {new String[] {"5", "10"}});
methodInvoker.afterPropertiesSet();
methodInvoker = new MethodInvokingBean();
methodInvoker.setTargetClass(TestClass1.class);
methodInvoker.setTargetMethod("intArguments");
methodInvoker.setArguments(new Object[] {new Integer[] {5, 10}});
methodInvoker.afterPropertiesSet();
methodInvoker = new MethodInvokingBean();
methodInvoker.setTargetClass(TestClass1.class);
methodInvoker.setTargetMethod("intArguments");
methodInvoker.setArguments("5", "10");
methodInvoker.afterPropertiesSet();
methodInvoker = new MethodInvokingBean();
methodInvoker.setTargetClass(TestClass1.class);
methodInvoker.setTargetMethod("intArguments");
methodInvoker.setArguments(new Object[] {new Integer[] {5, 10}});
methodInvoker.afterPropertiesSet();
methodInvoker = new MethodInvokingBean();
methodInvoker.setTargetClass(TestClass1.class);
methodInvoker.setTargetMethod("intArguments");
methodInvoker.setArguments("5", "10");
methodInvoker.afterPropertiesSet();
}
public static class TestClass1 {
public static int _staticField1;
public int _field1 = 0;
public int method1() {
return ++_field1;
}
public static int staticMethod1() {
return ++TestClass1._staticField1;
}
public static void voidRetvalMethod() {
}
public static void nullArgument(Object arg) {
}
public static void intArgument(int arg) {
}
public static void intArguments(int[] arg) {
}
public static String supertypes(Collection<?> c, Integer i) {
return i.toString();
}
public static String supertypes(Collection<?> c, List<?> l, String s) {
return s;
}
public static String supertypes2(Collection<?> c, List<?> l, Integer i) {
return i.toString();
}
public static String supertypes2(Collection<?> c, List<?> l, String s, Integer i) {
return s;
}
public static String supertypes2(Collection<?> c, List<?> l, String s, String s2) {
return s;
}
}
}
|
package maze;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import javax.swing.JOptionPane;
public class MyKeyEventDispatcher implements KeyEventDispatcher {
public MyKeyEventDispatcher(MyPanel myPanel) {
this.myPanel = myPanel;
}
// private MyKeyEventDispatcher dispatcher;
private MyPanel myPanel;
@Override
public boolean dispatchKeyEvent(KeyEvent e) {
// TODO Auto-generated method stub
if (e.getID() == KeyEvent.KEY_PRESSED) {
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
if (myPanel.isMovable(myPanel.getCurX(), myPanel.getCurY() + 1)) {
myPanel.setCurY(myPanel.getCurY() + 1);
System.out.println(myPanel.getCurY());
checkSuccess();
}
}
if (e.getKeyCode() == KeyEvent.VK_UP) {
if (myPanel.isMovable(myPanel.getCurX(), myPanel.getCurY() - 1)) {
myPanel.setCurY(myPanel.getCurY() - 1);
checkSuccess();
}
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
if (myPanel.isMovable(myPanel.getCurX() - 1, myPanel.getCurY())) {
myPanel.setCurX(myPanel.getCurX() - 1);
checkSuccess();
}
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {// System.out.println(myPanel.getCurX());
// System.out.println(myPanel.isMovable(myPanel.getCurX(),
// myPanel.getCurY()));
if (myPanel.isMovable(myPanel.getCurX() + 1, myPanel.getCurY())) {
System.out.println(myPanel.getCurX());
myPanel.setCurX(myPanel.getCurX() + 1);
checkSuccess();
}
}
myPanel.repaint();
}
return true;
}
private void checkSuccess() {
if (myPanel.getCurX() == (myPanel.getMyWidth() - 1)
&& myPanel.getCurY() == 0) {
JOptionPane.showMessageDialog(myPanel, "success!");
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.removeKeyEventDispatcher(this);
}
}
}
|
package ir.madreseplus.ui.view.message;
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 androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import java.text.ParseException;
import java.util.List;
import ir.madreseplus.R;
import ir.madreseplus.data.model.enums.EventStateEnum;
import ir.madreseplus.data.model.req.Event;
import ir.madreseplus.data.model.req._Content;
import ir.madreseplus.data.model.res.TicketRes;
import ir.madreseplus.ui.base.RvAdapter;
import ir.madreseplus.ui.base.RvViewHolder;
import ir.madreseplus.utilities.DateParser;
import ir.madreseplus.utilities.StringUtil;
import saman.zamani.persiandate.PersianDate;
public class SupportAdapter extends RvAdapter<TicketRes, SupportAdapter.TaskViewHolder> {
@NonNull
@Override
public TaskViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new TaskViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_support_layout, parent, false));
}
public class TaskViewHolder extends RvViewHolder<TicketRes> {
private TextView titleTextView, statusTextView, dateTextView;
public TaskViewHolder(@NonNull View itemView) {
super(itemView);
titleTextView = itemView.findViewById(R.id.txtView_title);
statusTextView = itemView.findViewById(R.id.txtView_status);
dateTextView = itemView.findViewById(R.id.txtView_date);
}
@Override
public void bind(TicketRes item) {
try {
titleTextView.setText(item.getTitle());
statusTextView.setText(item.getGetStatusDisplay());
int intValue = item.getStatus().intValue();
if (intValue == 4) {
this.statusTextView.setTextColor(this.itemView.getContext().getResources().getColor(R.color.green));
} else if (intValue == 6) {
this.statusTextView.setTextColor(this.itemView.getContext().getResources().getColor(R.color.red));
}
PersianDate persianDate = new PersianDate(DateParser.parse(item.getCreatedOn()));
TextView textView = this.dateTextView;
textView.setText(persianDate.getShYear() + StringUtil.SLASH + persianDate.getShMonth() + StringUtil.SLASH + persianDate.getShDay());
} catch (ParseException | NullPointerException e) {
Log.i("TAG", "bind: " + e.getMessage());
}
}
}
} |
package com.Hellel.PSoloid.homework6;
import com.Hellel.PSoloid.homework6.observable.Observable;
import com.Hellel.PSoloid.homework6.observable.Observer;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by Morozov on 08.07.2015.
*/
public class Animal implements Observable {
protected int id;
protected int age;
protected double weight;
protected String color;
protected boolean isHungry;
protected boolean isSick;
List<Observer> observers = new ArrayList<Observer>();
public void bark(){
System.out.print("Hello, ");
}
public void print(){
System.out.println("My id is " + id);
System.out.println("My age is " + age);
System.out.println("My weight is " + weight);
System.out.println("My color is " + color);
}
public Animal(int id, int age, double weight, String color, boolean isHungry, boolean isSick) {
this.id = id;
this.age = age;
this.weight = weight;
this.color = color;
this.isHungry = isHungry;
this.isSick = isSick;
}
public Animal() {
}
@Override
public void addObserver(Observer observer) {
observers.add(observer);
}
@Override
public void notifyObservers() {
String state;
Date currentDate = new Date();
if (isSick) {
state = "is sick";
observers.get(0).handle(id, currentDate, state);
observers.get(3).handle(id, currentDate, state);
}
if (isHungry) {
state = "is hungry";
observers.get(0).handle(id, currentDate, state);
observers.get(3).handle(id, currentDate, state);
}
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getWeight() {
return weight;
}
public void setWeight(float weight) {
this.weight = weight;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
|
package mobi.app.redis;
import java.util.concurrent.TimeUnit;
/**
* User: thor
* Date: 13-1-4
* Time: 下午2:09
*/
public class RedisConnection {
public final String address;
public final int db;
public final String password ;
public final int timeout;
public final TimeUnit timeUnit;
public final int weight;
public final int connectionNumber;
public RedisConnection(String address, int db, String password, int timeout, TimeUnit timeUnit) {
this.address = address;
this.db = db;
this.password = password;
this.timeout = timeout;
this.timeUnit = timeUnit;
this.weight = 1;
this.connectionNumber = 1;
}
public RedisConnection(String address, int db, String password, int timeout, TimeUnit timeUnit, int weight, int connectionNumber) {
this.address = address;
this.db = db;
this.password = password;
this.timeout = timeout;
this.timeUnit = timeUnit;
this.weight = weight;
this.connectionNumber = connectionNumber;
}
}
|
package com.software3.servlet;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.software3.pojo.User;
import com.software3.service.UserService;
import com.software3.service.impl.UserServiceImpl;
@WebServlet("/login")
/**
*
* @author CaiBin
* 登录
*/
public class LoginServlet extends HttpServlet
{
/**
*
*/
private static final long serialVersionUID = 1L;
UserService us = new UserServiceImpl();
User user = null;
protected void doPost(HttpServletRequest request ,HttpServletResponse response) throws IOException{
String username = request.getParameter("user_name");
String password = request.getParameter("user_password");
int type = 2;
if(us.userLogin(username, password, type)){
response.getWriter().write("success");
user = new User();
user = us.getUser(username);
request.getSession(true).setAttribute("studentid",user.getStudentid());
request.getSession(true).setAttribute("name", user.getName());
}else{
response.getWriter().write("failure");
}
}
}
|
package ru.job4j.loop;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Class MaxTest тестирует метод класса Counter.
* @author Goureev Ilya (mailto:ill-jah@yandex.ru)
* @version 1
* @since 2017-04-08
*/
public class CounterTest {
/**
* Тестирует метод add().
*/
@Test
public void testAdd() {
int start = 0, finish = 10, expected = 30;
Counter counter = new Counter();
int result = counter.add(start, finish);
assertThat(result, is(expected));
}
}
|
/*
* Copyright (C) 2015 The Tesla OS
*
* 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.tesla.setupwizard.setup;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ThemeUtils;
import android.content.res.ThemeConfig;
import android.content.res.ThemeManager;
import android.hardware.CmHardwareManager;
import android.os.Bundle;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.IWindowManager;
import android.view.View;
import android.view.WindowManagerGlobal;
import android.widget.CheckBox;
import android.widget.TextView;
import com.tesla.setupwizard.R;
import com.tesla.setupwizard.ui.SetupPageFragment;
import com.tesla.setupwizard.ui.WebViewDialogFragment;
import com.tesla.setupwizard.util.SetupWizardUtils;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
public class TeslaSettingsPage extends SetupPage {
public static final String TAG = "TeslaSettingsPage";
public static final String KEY_ENABLE_NAV_KEYS = "enable_nav_keys";
public static final String KEY_APPLY_DEFAULT_THEME = "apply_default_theme";
public TeslaSettingsPage(Context context, SetupDataCallbacks callbacks) {
super(context, callbacks);
}
@Override
public Fragment getFragment(FragmentManager fragmentManager, int action) {
Fragment fragment = fragmentManager.findFragmentByTag(getKey());
if (fragment == null) {
Bundle args = new Bundle();
args.putString(Page.KEY_PAGE_ARGUMENT, getKey());
args.putInt(Page.KEY_PAGE_ACTION, action);
fragment = new TeslaSettingsFragment();
fragment.setArguments(args);
}
return fragment;
}
@Override
public String getKey() {
return TAG;
}
@Override
public int getTitleResId() {
return R.string.setup_services;
}
private static void writeDisableNavkeysOption(Context context, boolean enabled) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final int defaultBrightness = context.getResources().getInteger(
com.android.internal.R.integer.config_buttonBrightnessSettingDefault);
Settings.Secure.putInt(context.getContentResolver(),
Settings.Secure.DEV_FORCE_SHOW_NAVBAR, enabled ? 1 : 0);
final CmHardwareManager cmHardwareManager =
(CmHardwareManager) context.getSystemService(Context.CMHW_SERVICE);
cmHardwareManager.set(CmHardwareManager.FEATURE_KEY_DISABLE, enabled);
/* Save/restore button timeouts to disable them in softkey mode */
SharedPreferences.Editor editor = prefs.edit();
if (enabled) {
int currentBrightness = Settings.Secure.getInt(context.getContentResolver(),
Settings.Secure.BUTTON_BRIGHTNESS, defaultBrightness);
if (!prefs.contains("pre_navbar_button_backlight")) {
editor.putInt("pre_navbar_button_backlight", currentBrightness);
}
Settings.Secure.putInt(context.getContentResolver(),
Settings.Secure.BUTTON_BRIGHTNESS, 0);
} else {
int oldBright = prefs.getInt("pre_navbar_button_backlight", -1);
if (oldBright != -1) {
Settings.Secure.putInt(context.getContentResolver(),
Settings.Secure.BUTTON_BRIGHTNESS, oldBright);
editor.remove("pre_navbar_button_backlight");
}
}
editor.commit();
}
@Override
public void onFinishSetup() {
getCallbacks().addFinishRunnable(new Runnable() {
@Override
public void run() {
if (getData().containsKey(KEY_ENABLE_NAV_KEYS)) {
writeDisableNavkeysOption(mContext, getData().getBoolean(KEY_ENABLE_NAV_KEYS));
}
}
});
handleDefaultThemeSetup();
}
private void handleDefaultThemeSetup() {
Bundle privacyData = getData();
if (!ThemeUtils.getDefaultThemePackageName(mContext).equals(ThemeConfig.SYSTEM_DEFAULT) &&
privacyData != null && privacyData.getBoolean(KEY_APPLY_DEFAULT_THEME)) {
Log.i(TAG, "Applying default theme");
final ThemeManager tm = (ThemeManager) mContext.getSystemService(Context.THEME_SERVICE);
tm.applyDefaultTheme();
} else {
getCallbacks().finishSetup();
}
}
private static boolean hideKeyDisabler(Context ctx) {
final CmHardwareManager cmHardwareManager =
(CmHardwareManager) ctx.getSystemService(Context.CMHW_SERVICE);
return !cmHardwareManager.isSupported(CmHardwareManager.FEATURE_KEY_DISABLE);
}
private static boolean isKeyDisablerActive(Context ctx) {
final CmHardwareManager cmHardwareManager =
(CmHardwareManager) ctx.getSystemService(Context.CMHW_SERVICE);
return cmHardwareManager.get(CmHardwareManager.FEATURE_KEY_DISABLE);
}
private static boolean hideThemeSwitch(Context context) {
return ThemeUtils.getDefaultThemePackageName(context).equals(ThemeConfig.SYSTEM_DEFAULT);
}
public static class TeslaSettingsFragment extends SetupPageFragment {
private View mDefaultThemeRow;
private View mNavKeysRow;
private CheckBox mDefaultTheme;
private CheckBox mNavKeys;
private boolean mHideNavKeysRow = false;
private boolean mHideThemeRow = false;
private View.OnClickListener mDefaultThemeClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
boolean checked = !mDefaultTheme.isChecked();
mDefaultTheme.setChecked(checked);
mPage.getData().putBoolean(KEY_APPLY_DEFAULT_THEME, checked);
}
};
private View.OnClickListener mNavKeysClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
boolean checked = !mNavKeys.isChecked();
mNavKeys.setChecked(checked);
mPage.getData().putBoolean(KEY_ENABLE_NAV_KEYS, checked);
}
};
@Override
protected void initializePage() {
mDefaultThemeRow = mRootView.findViewById(R.id.theme);
mHideThemeRow = hideThemeSwitch(getActivity());
if (mHideThemeRow) {
mDefaultThemeRow.setVisibility(View.GONE);
} else {
mDefaultThemeRow.setOnClickListener(mDefaultThemeClickListener);
String defaultTheme =
getString(R.string.services_apply_theme,
getString(R.string.default_theme_name));
String defaultThemeSummary = getString(R.string.services_apply_theme_label,
defaultTheme);
final SpannableStringBuilder themeSpan =
new SpannableStringBuilder(defaultThemeSummary);
themeSpan.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD),
0, defaultTheme.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView theme = (TextView) mRootView.findViewById(R.id.enable_theme_summary);
theme.setText(themeSpan);
mDefaultTheme = (CheckBox) mRootView.findViewById(R.id.enable_theme_checkbox);
}
mNavKeysRow = mRootView.findViewById(R.id.nav_keys);
mNavKeysRow.setOnClickListener(mNavKeysClickListener);
mNavKeys = (CheckBox) mRootView.findViewById(R.id.nav_keys_checkbox);
boolean needsNavBar = true;
try {
IWindowManager windowManager = WindowManagerGlobal.getWindowManagerService();
needsNavBar = windowManager.needsNavigationBar();
} catch (RemoteException e) {
}
mHideNavKeysRow = hideKeyDisabler(getActivity());
if (mHideNavKeysRow || needsNavBar) {
mNavKeysRow.setVisibility(View.GONE);
} else {
boolean navKeysDisabled =
isKeyDisablerActive(getActivity());
mNavKeys.setChecked(navKeysDisabled);
}
}
@Override
protected int getLayoutResource() {
return R.layout.setup_tesla_services;
}
@Override
public void onResume() {
super.onResume();
updateDisableNavkeysOption();
updateThemeOption();
}
private void updateThemeOption() {
if (!mHideThemeRow) {
final Bundle myPageBundle = mPage.getData();
boolean themesChecked =
!myPageBundle.containsKey(KEY_APPLY_DEFAULT_THEME) || myPageBundle
.getBoolean(KEY_APPLY_DEFAULT_THEME);
mDefaultTheme.setChecked(themesChecked);
myPageBundle.putBoolean(KEY_APPLY_DEFAULT_THEME, themesChecked);
}
}
private void updateDisableNavkeysOption() {
if (!mHideNavKeysRow) {
final Bundle myPageBundle = mPage.getData();
boolean enabled = Settings.Secure.getInt(getActivity().getContentResolver(),
Settings.Secure.DEV_FORCE_SHOW_NAVBAR, 0) != 0;
boolean checked = myPageBundle.containsKey(KEY_ENABLE_NAV_KEYS) ?
myPageBundle.getBoolean(KEY_ENABLE_NAV_KEYS) :
enabled;
mNavKeys.setChecked(checked);
myPageBundle.putBoolean(KEY_ENABLE_NAV_KEYS, checked);
}
}
}
}
|
package com.comp3717.comp3717;
import java.util.ArrayList;
/**
* Created by Josh-ROG on 11/13/2016.
*/
public class Recipe {
private String name;
private ArrayList<String> ingredientList;
// private String instructions; add later on
public Recipe(String name, ArrayList<String> ingredientList) {
this.name = name;
this.ingredientList = ingredientList;
}
public ArrayList<String> getIngredientList() {
return ingredientList;
}
public String getName() {
return name;
}
}
|
package com.app.coinally.in.Utils;
/**
* Created by Vishal on 4/25/2016.
*/
public class Webservices {
/*this is host url from where all webservice call*/
public static String WEB_HOST_URL = "http://crypto.capitally.in/api";
public static String CRYPT_WEBSERVICE = WEB_HOST_URL + "/currency_api_app.php";
public static String HANDBOOK_WEBSERVICE = WEB_HOST_URL + "/get_loop_content.php";
}//http://crypto.capitally.in/api/currency_api_app.php |
package factory;
/**
* Created by max.lu on 2016/2/2.
*/
public class Blue extends Color {
public Blue() {
System.out.println("blue");
}
}
|
package com.longfellow.tree;
/*
* 从给定的后序和中序遍历恢复二叉搜索树
*/
public class PostInBuildTree {
public static TreeNode buildTree(int[] inorder, int[] postorder) {
if (inorder == null || inorder.length ==0 || postorder ==null || postorder.length ==0) {
return null;
}
return helper(inorder, 0 , inorder.length -1, postorder, 0 , postorder.length -1);
}
private static TreeNode helper(int[] inorder, int inL, int inR, int[] postorder, int pL, int pR) {
//System.out.println(inL + ":" + inR +":" + pL + ":" +pR );
if (inL > inR || pL > pR) {
//System.out.println("1");
return null;
}
int rootVal = postorder[pR];
int index = 0;
while (index <= inR && inorder[index] != rootVal) {
index++;
}
TreeNode root = new TreeNode(rootVal);
root.left = helper(inorder, inL, index, postorder, pL, pL - inL + index -1);
root.right = helper(inorder, index + 1, inR, postorder, pL - inL + index, pR - 1);
return root;
}
public static void main(String[] args) {
int[] mid = {9,3,15,20,7};
int[] post = {9,15,7,20,3};
TreeNode root = buildTree(mid, post);
System.out.println(root);
}
}
|
package com.lagardien.interfaces;
/**
* Ijaaz Lagardien
* Group 3A
* Dr B. Kabaso
* Date: 12/03/2016
*/
public class CalculatorImpl implements Calculator
{
public float add(float a, float b) {
// TODO Auto-generated method stub
return a + b;
}
public float multiply(float a, float b) {
// TODO Auto-generated method stub
return a * b;
}
public float divide(float a, float b) {
// TODO Auto-generated method stub
return a/b;
}
public float subtract(float a, float b) {
// TODO Auto-generated method stub
return a - b;
}
}
|
package au.gov.nsw.records.digitalarchive.service;
import java.util.Date;
import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import au.gov.nsw.records.digitalarchive.ORM.Archivist;
import au.gov.nsw.records.digitalarchive.ORM.HibernateUtil;
import au.gov.nsw.records.digitalarchive.ORM.Member;
import au.gov.nsw.records.digitalarchive.base.BaseLog;
public class ArchivistServiceImpl extends BaseLog implements ArchivistService
{
@Override
public boolean addArchivist(Archivist archivist) throws Exception {
Session session = HibernateUtil.getSession();
Transaction tx = null;
boolean result = false;
try {
tx = session.beginTransaction();
session.save(archivist);
tx.commit();
result = true;
} catch (Exception e) {
if (tx != null)tx.rollback();
logger.info("In class ArchivistServiceImpl:addArchivist()\n");
e.printStackTrace();
} finally
{
HibernateUtil.closeSession();
}
return result;
}
@Override
public Archivist archivistLogin(String login, String password)
throws Exception {
Session session = HibernateUtil.getSession();
Transaction tx = null;
Archivist archivist = null;
try
{
String hql = "SELECT a FROM Archivist AS a WHERE a.loginName=:login AND a.loginPassword=:password";
Query query = session.createQuery(hql);
query.setString("login", login);
query.setString("password", password);
query.setMaxResults(1);
tx = session.beginTransaction();
archivist = (Archivist)query.uniqueResult();
if (archivist != null)
{
archivist.setLoginTimes(Integer.valueOf(archivist.getLoginTimes()) + 1);
archivist.setLastLogin(new Date());
session.update(archivist);
}
tx.commit();
} catch (Exception ex) {
if(tx!=null)tx.rollback();
logger.info("In class ArchivistServiceImpl:archivistLogin()\n");
ex.printStackTrace();
}finally{
HibernateUtil.closeSession();
}
return archivist;
}
@Override
public boolean updateArchivist(Archivist archivist) throws Exception {
Session session = HibernateUtil.getSession();
Transaction tx = null;
boolean result = false;
try{
tx = session.beginTransaction();
session.update(archivist);
tx.commit();
result=true;
}catch(Exception ex){
if(tx!=null)tx.rollback();
logger.info("In class ArchivistServiceImpl:updateArchivist()\n");
ex.printStackTrace();
}finally{
HibernateUtil.closeSession();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
public List<Archivist> browseArchivist() throws Exception {
Session session = HibernateUtil.getSession();
Transaction tx = null;
List<Archivist> list = null;
try{
Query query = session.createQuery("from Archivist as a order by a.archivistId");
tx = session.beginTransaction();
list = query.list();
tx.commit();
if (!Hibernate.isInitialized(list))Hibernate.initialize(list);
}catch(Exception ex){
if(tx!=null)tx.rollback();
logger.info("In class ArchivistServiceImpl:browseArchivist()\n");
ex.printStackTrace();
}finally{
HibernateUtil.closeSession();
}
return list;
}
@Override
public boolean delArchivist(Integer id) throws Exception {
Session session = HibernateUtil.getSession();
Transaction tx = null;
boolean status = false;
try{
tx = session.beginTransaction();
Archivist archivist = (Archivist)session.load(Archivist.class, id);
session.delete(archivist);
tx.commit();
status = true;
}catch(Exception ex){
if(tx!=null)tx.rollback();
logger.info("In class ArchivistServiceImpl:delArchivist()\n");
ex.printStackTrace();
}finally{
HibernateUtil.closeSession();
}
return status;
}
@Override
public Archivist loadArchivist(Integer id) throws Exception {
Session session = HibernateUtil.getSession();
Transaction tx = null;
Archivist archivist = null;
try{
tx = session.beginTransaction();
archivist = (Archivist)session.get(Archivist.class, id);
tx.commit();
}catch(Exception ex){
if(tx!=null)tx.rollback();
logger.info("In class ArchivistServiceImpl:loadArchivist()\n");
ex.printStackTrace();
}finally{
HibernateUtil.closeSession();
}
return archivist;
}
} |
package toasty.messageinabottle;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import toasty.messageinabottle.exception.ErrorAdapter;
public class ErrorActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_error);
RecyclerView errors = findViewById(R.id.error_recycler_view);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
errors.setLayoutManager(linearLayoutManager);
ErrorAdapter errorAdapter = new ErrorAdapter();
errors.setAdapter(errorAdapter);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(errors.getContext(), linearLayoutManager.getOrientation());
errors.addItemDecoration(dividerItemDecoration);
}
}
|
package com.nfet.icare.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.nfet.icare.dao.EvaluateMapper;
import com.nfet.icare.pojo.Evaluate;
@Service
public class EvaluateServiceImpl implements EvaluateService {
@Autowired
private EvaluateMapper evaluateMapper;
@Override
public void insertEvaluate(Evaluate evaluate) {
// TODO Auto-generated method stub
evaluateMapper.insertEvaluate(evaluate);
}
@Override
public Evaluate queryEvaluate(String fixNo) {
// TODO Auto-generated method stub
return evaluateMapper.queryEvaluate(fixNo);
}
@Override
public Integer getMaxEvaluateNo() {
// TODO Auto-generated method stub
return evaluateMapper.getMaxEvaluateNo();
}
}
|
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.ow2.proactive.scheduler.common.job;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.objectweb.proactive.annotation.PublicAPI;
import org.ow2.proactive.scheduler.common.SchedulerConstants;
import org.ow2.proactive.scheduler.common.exception.UserException;
import org.ow2.proactive.scheduler.common.task.Task;
/**
* Use this class to create your job if you want to define a task flow job.<br>
* A task flow job or data flow job, is a job that can contain
* one or more task(s) with the dependencies you want.<br>
* To make this type of job, just use the default no arg constructor,
* and set the properties you want to set.<br>
* Then add tasks with the given method {@link #addTask(Task)} in order to fill the job with your own tasks.
*
* @author The ProActive Team
* @since ProActive Scheduling 0.9
*/
@PublicAPI
public class TaskFlowJob extends Job {
/** */
private static final long serialVersionUID = 31L;
/** Task count for unset task name */
private int taskCountForUnSetTaskName = 1;
/** List of task for the task flow job */
private Map<String, Task> tasks = new HashMap<String, Task>();
/** ProActive Empty Constructor */
public TaskFlowJob() {
}
/**
* @see org.ow2.proactive.scheduler.common.job.Job#getType()
*/
@Override
public JobType getType() {
return JobType.TASKSFLOW;
}
/**
* Add a task to this task flow job.<br>
* The task name must not be null as it is not by default.<br>
* The task name must also be different for each task as it is used to identify each task result.<br>
* <br>
* If not set, the task name will be a generated one : 'task_X' (where X is the Xth added task number)
*
* @param task the task to add.
* @throws UserException if a problem occurred while the task is being added.
*/
public void addTask(Task task) throws UserException {
if (task.getName() == null) {
throw new UserException("The name of the task must not be null !");
}
if (task.getName().equals(SchedulerConstants.TASK_DEFAULT_NAME)) {
task.setName(SchedulerConstants.TASK_NAME_IFNOTSET + taskCountForUnSetTaskName);
taskCountForUnSetTaskName++;
}
if (tasks.containsKey(task.getName())) {
throw new UserException("The name of the task is already used : " + task.getName());
}
tasks.put(task.getName(), task);
}
/**
* Add a list of tasks to this task flow job.
* The task names must not be null as it is not by default.<br>
* The task names must also be different for each task as it is used to identify each task result.<br>
* <br>
* If not set, the task names will be generated : 'task_X' (where X is the Xth added task number)
*
* @param tasks the list of tasks to add.
* @throws UserException if a problem occurred while the task is being added.
*/
public void addTasks(List<Task> tasks) throws UserException {
for (Task task : tasks) {
addTask(task);
}
}
/**
* To get the list of tasks.
*
* @return the list of tasks.
*/
public ArrayList<Task> getTasks() {
return new ArrayList<Task>(tasks.values());
}
/**
* Get the task corresponding to the given name.
*
* @param name the name of the task to look for.
* @return the task corresponding to the given name.
*/
public Task getTask(String name) {
return tasks.get(name);
}
/**
* @see org.ow2.proactive.scheduler.common.job.Job#getId()
*/
@Override
public JobId getId() {
// Not yet assigned
return null;
}
}
|
/**
* RoomFactoryBuilder.java
* @author guochenshen
*
* creates rooms
*/
package object.graph;
import java.io.Serializable;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class RoomFactoryBuilder implements Serializable {
private Room room;
private static int roomID = 0;
// ********** DEFAULT VARIABLES **********
private static final double DEFAULT_X_COOR = 0.0; // [m]
private static final double DEFAULT_Y_COOR = 0.0; // [m]
private static final double DEFAULT_LENGTH = 20.0; // [m]
private static final double DEFAULT_WIDTH = 20.0; // [m]
private static final double DEFAULT_HEIGHT = 2.5; // [m]
private static final double DEFAULT_TEMP = 22.0;
private static final double DEFAULT_HUMIDITY = 0.0;
private static final double DEFAULT_AIRFLOW = 0.0;
private static final Cardinality DEFAULT_AIRFLOW_CARDINALITY = Cardinality.NORTH;
// ********** CONSTRUCTOR **********
/**
* constructor
*/
public RoomFactoryBuilder() {
return;
}
// ********** CREATE FUNCTION **********
/**
* creates a new room for customization; call get_room to return the room
*/
public Room create_room() {
this.room = new Room();
this.room.setName("room" + Integer.toString(this.room.get_id()));
this.set_x_coor(DEFAULT_X_COOR);
this.set_y_coor(DEFAULT_Y_COOR);
this.set_length(DEFAULT_LENGTH);
this.set_width(DEFAULT_WIDTH);
this.set_height(DEFAULT_HEIGHT);
this.set_temp(DEFAULT_TEMP);
this.set_humidity(DEFAULT_HUMIDITY);
this.set_airflow(DEFAULT_AIRFLOW);
this.set_airflow_direction(DEFAULT_AIRFLOW_CARDINALITY);
return this.room;
}
// ********** PARSER FUNCTION **********
public Room new_room() {
this.room = new Room();
return this.room;
}
/**
* creates a room using a parser
* @param room
* @return customized room
*/
public Room create_room(Node room) {
NodeList configuration = room.getChildNodes();
this.new_room();
for (int i = 0; i < configuration.getLength(); i++) {
Node setting = configuration.item(i);
String val = setting.getTextContent();
switch(setting.getNodeName()) {
case "name": set_name(val);
break;
case "x": this.set_x_coor(Double.parseDouble(val));
break;
case "y": this.set_y_coor(Double.parseDouble(val));
break;
case "length": this.set_length(Double.parseDouble(val));
break;
case "width": this.set_width(Double.parseDouble(val));
break;
case "height": this.set_height(Double.parseDouble(val));
break;
case "temp": this.set_temp(Double.parseDouble(val));
break;
case "humidity": this.set_humidity(Double.parseDouble(val));
break;
case "airflow": this.set_airflow(Double.parseDouble(val));
break;
default: break;
}
}
return this.get_room();
}
// ********** GET FUNCTION **********
/**
* @return the room after finishing customization
*/
public Room get_room() {
return this.room;
}
// ********** SET FUNCTIONS **********
/**
* sets the name of the room
*
* @param name
* the name of the room
*/
public Room set_name(String name) {
this.room.setName(name);
return this.room;
}
/**
* sets the x-coordinate of the top left corner
*
* @param x
* x-coordinate
*/
public Room set_x_coor(double x) {
this.room.set_x(x);
return this.room;
}
/**
* sets the y-coordinate of the top left corner
*
* @param y
* y-coordinate
*/
public Room set_y_coor(double y) {
this.room.set_y(y);
return this.room;
}
/**
* sets the length of the room
*
* @param length
* length of the room
*/
public Room set_length(double length) {
this.room.set_length(length);
return this.room;
}
/**
* sets the width of the room
*
* @param width
* width of the room
*/
public Room set_width(double width) {
this.room.set_width(width);
return this.room;
}
/**
* sets the height of the room
*
* @param height
* height of the room
*/
public Room set_height(double height) {
this.room.set_height(height);
return this.room;
}
// ********** SET ROOM PROPERTY FUNCTIONS **********
/**
* sets the temperature of the room
*
* @param temp
* temperature of the room
*/
public void set_temp(double temp) {
this.room.set_temp(temp);
}
/**
* sets the humidity of the room
*
* @param humidity
* humidity of the room
*/
public void set_humidity(double humidity) {
this.room.set_humidity(humidity);
}
/**
* sets the airflow speed of the room
*
* @param airflow
* airflow of the room
*/
public void set_airflow(double airflow) {
this.room.set_airflow(airflow);
}
/**
* sets the airflow direction
*
* @param direction
* airflow direction
*/
public void set_airflow_direction(Cardinality direction) {
this.room.set_airflow_direction(direction);
}
public void set_room_graph(RoomGraph r) {
this.room.set_room_graph(r);
}
}
|
package org.softRoad.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.softRoad.models.query.QueryUtils;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "categories")
public class Category extends SoftRoadModel {
@Transient
public final static String ID = "id";
@Transient
public final static String NAME = "name";
@Transient
public final static String TYPE = "type";
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer id;
@NotNull
public String name;
@NotNull
@Enumerated(EnumType.STRING)
public Type type;
@OneToMany(mappedBy = "category")
@JsonIgnore
public Set<Fee> fees = new HashSet<>();
@ManyToMany(mappedBy = "categories")
@JsonIgnore
public Set<Procedure> procedures = new HashSet<>();
@ManyToMany(mappedBy = "categories")
@JsonIgnore
public Set<ConsultantProfile> consultants = new HashSet<>();
public void setId(Integer id) {
this.id = id;
presentFields.add("id");
}
public void setName(String name) {
this.name = name;
presentFields.add("name");
}
public void setType(Type type) {
this.type = type;
presentFields.add("type");
}
public static String fields(String fieldName, String... fieldNames) {
return QueryUtils.fields(Category.class, fieldName, fieldNames);
}
public enum Type {
VERIFIED
}
}
|
package com.hamatus.web.rest.dto;
import java.time.ZonedDateTime;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.util.Objects;
import com.hamatus.domain.enumeration.ContentStatus;
/**
* A DTO for the Area entity.
*/
public class AreaViewDTO implements Serializable {
private Long id;
private String name;
private String photoSetId;
private Integer routeCount;
private Integer routeBeginnerCount;
private Integer routeExperiencedCount;
private Integer routeKeenCount;
private Integer routeHardCount;
private Integer routeSuperHardCount;
private Integer sectorCount;
private Integer minAccessTimePublicTransport;
private Integer minAccessTimeParkingPlace;
private Integer maxAccessTimePublicTransport;
private Integer maxAccessTimeParkingPlace;
private Integer ratingAverage;
private String description;
private String approach;
private String conditions;
private String langKey;
private BreadcrumbDTO breadcrumbDTO;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhotoSetId() {
return photoSetId;
}
public void setPhotoSetId(String photoSetId) {
this.photoSetId = photoSetId;
}
public Integer getRouteCount() {
return routeCount;
}
public void setRouteCount(Integer routeCount) {
this.routeCount = routeCount;
}
public Integer getRouteBeginnerCount() {
return routeBeginnerCount;
}
public void setRouteBeginnerCount(Integer routeBeginnerCount) {
this.routeBeginnerCount = routeBeginnerCount;
}
public Integer getRouteExperiencedCount() {
return routeExperiencedCount;
}
public void setRouteExperiencedCount(Integer routeExperiencedCount) {
this.routeExperiencedCount = routeExperiencedCount;
}
public Integer getRouteKeenCount() {
return routeKeenCount;
}
public void setRouteKeenCount(Integer routeKeenCount) {
this.routeKeenCount = routeKeenCount;
}
public Integer getRouteHardCount() {
return routeHardCount;
}
public void setRouteHardCount(Integer routeHardCount) {
this.routeHardCount = routeHardCount;
}
public Integer getRouteSuperHardCount() {
return routeSuperHardCount;
}
public void setRouteSuperHardCount(Integer routeSuperHardCount) {
this.routeSuperHardCount = routeSuperHardCount;
}
public Integer getSectorCount() {
return sectorCount;
}
public void setSectorCount(Integer sectorCount) {
this.sectorCount = sectorCount;
}
public Integer getMinAccessTimePublicTransport() {
return minAccessTimePublicTransport;
}
public void setMinAccessTimePublicTransport(Integer minAccessTimePublicTransport) {
this.minAccessTimePublicTransport = minAccessTimePublicTransport;
}
public Integer getMinAccessTimeParkingPlace() {
return minAccessTimeParkingPlace;
}
public void setMinAccessTimeParkingPlace(Integer minAccessTimeParkingPlace) {
this.minAccessTimeParkingPlace = minAccessTimeParkingPlace;
}
public Integer getMaxAccessTimePublicTransport() {
return maxAccessTimePublicTransport;
}
public void setMaxAccessTimePublicTransport(Integer maxAccessTimePublicTransport) {
this.maxAccessTimePublicTransport = maxAccessTimePublicTransport;
}
public Integer getMaxAccessTimeParkingPlace() {
return maxAccessTimeParkingPlace;
}
public void setMaxAccessTimeParkingPlace(Integer maxAccessTimeParkingPlace) {
this.maxAccessTimeParkingPlace = maxAccessTimeParkingPlace;
}
public Integer getRatingAverage() {
return ratingAverage;
}
public void setRatingAverage(Integer ratingAverage) {
this.ratingAverage = ratingAverage;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getApproach() {
return approach;
}
public void setApproach(String approach) {
this.approach = approach;
}
public String getConditions() {
return conditions;
}
public void setConditions(String conditions) {
this.conditions = conditions;
}
public BreadcrumbDTO getBreadcrumbDTO() {
return breadcrumbDTO;
}
public void setBreadcrumbDTO(BreadcrumbDTO breadcrumbDTO) {
this.breadcrumbDTO = breadcrumbDTO;
}
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
}
|
//source: https://leetcode.com/problems/move-zeroes/solution/
//Easy
//Array
//Date: May 15 2019
/*
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
*/
//runtime 12ms, beats 14%
public class Solution {
public void moveZeroes(int[] nums) {
int n = nums.length;
for(int i = 0; i < n; i++){
if(nums[i] == 0){
for(int j = i+1; j < n; j++){
if(nums[j] != 0){
nums[i] = nums[j];
nums[j] = 0;
break;
}
}
}
}
}
}
//solution 2 0ms, beats 100%
public class Solution {
public void moveZeroes(int[] nums) {
int n = nums.length;
int index = 0;
for(int i = 0; i < n; i++){
if(nums[i] != 0){
nums[index] = nums[i];
index++;
}
}
for(int i = index; i < n; i++){
nums[i] = 0;
}
}
}
|
import java.util.*;
public class CheckFibonacciNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long input = sc.nextLong();
long[] f = new long[94];
f[0] = 0;
f[1] = 1;
f[2] = 1;
if(input==0 || input==1){
System.out.println("This number is the Fibonacci number");
} else {
boolean checkFibonacci = false;
for(int i = 3; i <= 93; i++){
f[i] = f[i-1] + f[i-2];
if(f[i]==input){
System.out.println("This number is the Fibonacci number");
checkFibonacci = true;
break;
}
}
if(!checkFibonacci){
System.out.println("This number is not a Fibonacci number");
}
}
}
}
|
package com.ut.base.push;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import com.ut.base.AppManager;
import com.ut.base.BaseActivity;
import com.ut.jpushlib.CLJPushReceiver;
public class UTCLReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (CLJPushReceiver.REMOTELOGIN_ACTION.equals(intent.getAction())) {
BaseActivity baseActivity = AppManager.getAppManager().currentActivity();
if (baseActivity != null) {
baseActivity.remoteLogin();
}
}
}
}
|
package main;
import java.math.BigDecimal;
import dao.CategoriaDao;
import dao.ProdutoDao;
import model.Categoria;
import model.Produto;
public class Principal {
public static void main(String[] args) {
ProdutoDao dao = new ProdutoDao();
CategoriaDao daoCategoria = new CategoriaDao();
Categoria categoria = new Categoria("Telefonia");
Produto produto = new Produto("LG K11", "Bateria dura pouco", new BigDecimal(800), categoria);
daoCategoria.insertCategoria(categoria);
dao.insertProduto(produto);
System.out.println("Produto incluido: " + produto);
}
}
|
public class DeleteX{
public static void main(String[] args){
char charToDel = args[0].charAt(0);
String text = "";
while(!StdIn.isEmpty()){
char charact = StdIn.readChar();
if(charact != charToDel){
System.out.print(charact);
}
}
/*int textLength = text.length;
for(int i=0; i < textLength; i++){
char charact = text.charAt(i);
if(charact != charToDel){
System.out.print(charact + " ");
}
}*/
}
} |
package com.lagardien.dipviolation;
/**
* Ijaaz Lagardien
* Group 3A
* Dr B. Kabaso
* Date: 13 March 2016
*/
public class SuperWorker
{
public void work()
{
System.out.println("Working harder than other workers");
}
}
|
package com.jrz.bettingsite.player;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public interface PlayerService {
public Iterable<Player> findAll();
public Optional<Player> findById(Long id);
public void savePlayer(Player player);
void updatePlayer(Player player, Long id);
void deleteTeam(Player player);
}
|
/**
* 二叉树的最近公共祖先 https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/
*/
public class 二叉树的最近公共祖先 {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/solution/236-er-cha-shu-de-zui-jin-gong-gong-zu-xian-hou-xu/
if(root==null||root==p||root==q){//这里很巧妙,因为p或q一定都在树里,若pq有一个是祖先节点,那即使只遍历到祖先节点返回,另一个遍历不到,那也就证明返回到这个是祖先节点
return root;
}
TreeNode left=lowestCommonAncestor(root.left,p,q);
TreeNode right=lowestCommonAncestor(root.right,p,q);
if (left==null){
return right;
}
if (right==null){
return left;
}
return root;
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
}
|
package com.example.md23_bai1_qlnv;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import static java.lang.String.valueOf;
public class DataNhanVien extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "nhanvien_list";
private static final String TABLE_NAME = "nhanvien";
private static final String ID = "id";
private static final String NAME = "name";
private static final String GT = "gt";
private Context context;
public DataNhanVien( Context context) {
super(context, DATABASE_NAME, null, 1);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String SQLquery ="create table "+TABLE_NAME+" ("+
ID + " integer primary key, " +
NAME + " text, " +
GT + " integer)";
sqLiteDatabase.execSQL(SQLquery);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("drop table if exists " + TABLE_NAME);
onCreate(sqLiteDatabase);
Toast.makeText(context, "Xoa thanh cong table " + TABLE_NAME, Toast.LENGTH_SHORT).show();
}
public void addNhanVien(NhanVien nv){
SQLiteDatabase db = this.getWritableDatabase();//ghi du lieu vao db
ContentValues values = new ContentValues();//khoi tao gia tri
values.put(ID, nv.getId());
values.put(NAME, nv.getName());
values.put(GT,nv.getGender());
db.insert(TABLE_NAME,null,values);
db.close();
}
//delete NhanVien theo id
public void deleteNhanVien(NhanVien nv){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, ID +" =?",new String[]{valueOf(nv.getId())});
db.close();
}
//update nhanvien
public int updateNhanVien(NhanVien nv){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ID, nv.getId());
values.put(NAME, nv.getName());
values.put(GT, nv.getGender());
return db.update(TABLE_NAME, values,ID+ "=?", new String[]{String.valueOf(nv.getId())});
}
// lay tat ca nhan vien
public List<NhanVien> getAllNhanVie() {
List<NhanVien> nhanVienList = new ArrayList<>();
String query = "select * from " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst()){
do{
NhanVien nv = new NhanVien();
nv.setId(cursor.getString(0));
nv.setName(cursor.getString(1));
nv.setGender(cursor.getInt(2));
nhanVienList.add(nv);
}while (cursor.moveToNext());
}
cursor.close();
db.close();
return nhanVienList;
}
}
|
package com.bship.games;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Ship {
@JsonProperty("type")
private Harbor shipType;
private Point start;
private Point end;
public Ship() {}
public Ship(Harbor shipType, Point start, Point end) {
this.shipType = shipType;
this.start = start;
this.end = end;
}
public void setShipType(Harbor shipType) {
this.shipType = shipType;
}
public Harbor getShipType() {
return shipType;
}
public void setStart(Point start) {
this.start = start;
}
public Point getStart() {
return start;
}
public void setEnd(Point end) {
this.end = end;
}
public Point getEnd() {
return end;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Ship ship = (Ship) o;
if (getShipType() != ship.getShipType()) return false;
if (getStart() != null ? !getStart().equals(ship.getStart()) : ship.getStart() != null) return false;
return getEnd() != null ? getEnd().equals(ship.getEnd()) : ship.getEnd() == null;
}
@Override
public int hashCode() {
int result = getShipType() != null ? getShipType().hashCode() : 0;
result = 31 * result + (getStart() != null ? getStart().hashCode() : 0);
result = 31 * result + (getEnd() != null ? getEnd().hashCode() : 0);
return result;
}
}
|
package org.springframework.samples.mvc.basic.account.dao;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.samples.mvc.basic.account.Page;
import org.springframework.samples.mvc.basic.account.PageRequest;
import org.springframework.samples.mvc.basic.account.model.User;
import org.springframework.stereotype.Component;
@Component
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
public User getById(Long primaryKey) {
return (User) getSqlSession().selectOne(
"org.springframework.samples.mvc.basic.account.model.mapper.UserMapper.getUserById", primaryKey);
}
public int deleteById(Long id) {
return getSqlSession().delete(
"org.springframework.samples.mvc.basic.account.model.mapper.UserMapper.deleteUserById", id);
}
public int save(User entity) {
//prepareObjectForSaveOrUpdate(entity);
return getSqlSession().insert(
"org.springframework.samples.mvc.basic.account.model.mapper.UserMapper.insertUser", entity);
}
public int update(User entity) {
//prepareObjectForSaveOrUpdate(entity);
return getSqlSession().update(
"org.springframework.samples.mvc.basic.account.model.mapper.UserMapper.updateUser", entity);
}
public int saveOrUpdate(User entity) {
//prepareObjectForSaveOrUpdate(entity);
return getSqlSession().insert("User", entity);
}
public List<User> findAll() {
throw new UnsupportedOperationException();
}
public boolean isUnique(User entity, String uniquePropertyNames) {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.cssweb.common.dao.IBaseDAO#getObject(java.lang.Class, java.lang.Object)
*/
public User findUniqueBy(String parameterName, Object parameterValue) {
//return
SqlSession ss = getSqlSession();
User u = (User) ss.selectOne(
"org.springframework.samples.mvc.basic.account.model.mapper.UserMapper.findUniqueByLoginname",
parameterValue);
return u;
}
/**
* 判断对象的属性值在数据库内是否唯一.
*
* 在修改对象的情景下,如果属性新修改的值(value)等于属性原来的值(orgValue)则不作比较.
*/
public boolean isPropertyUnique(final String propertyName, final Object newValue, final Object oldValue) {
if (newValue == null || newValue.equals(oldValue)) {
return true;
}
Object object = findUniqueBy(propertyName, newValue);
return (object == null);
}
public String getCountStatementForPaging(String statementName) {
return statementName + ".count";
}
protected Page<User> pageQuery(String statementName, PageRequest<User> pageRequest) {
return pageQuery(getSqlSession(), statementName,
"org.springframework.samples.mvc.basic.account.model.mapper.UserMapper.count", pageRequest);
}
public Page<User> pageQuery(SqlSession sqlSession, String statementName, String countStatementName,
PageRequest<User> pageRequest) {
Number totalCount = (Number) sqlSession.selectOne(countStatementName, pageRequest);
if (totalCount == null || totalCount.longValue() <= 0) {
return new Page<User>(pageRequest, 0);
}
Page<User> page = new Page<User>(pageRequest, totalCount.intValue());
//其它分页参数,用于不喜欢或是因为兼容性而不使用方言(Dialect)的分页用户使用. 与getSqlMapClientTemplate().queryForList(statementName, parameterObject)配合使用
Map filters = new HashMap();
filters.put("offset", page.getFirstResult());
filters.put("pageSize", page.getPageSize());
filters.put("lastRows", page.getFirstResult() + page.getPageSize());
filters.put("sortColumns", pageRequest.getSortColumns());
Map parameterObject = null;
try {
parameterObject = PropertyUtils.describe(pageRequest);
} catch (Exception e) {
e.printStackTrace();
}
filters.putAll(parameterObject);
//List list = sqlSessionTemplate.selectList(statementName, filters, page.getFirstResult(), page.getPageSize());
List list = getSqlSession().selectList(statementName, filters,
new RowBounds(page.getFirstResult(), page.getPageSize()));
page.setResult(list);
return page;
}
public Page<User> findPage(UserQuery query) {
return pageQuery("org.springframework.samples.mvc.basic.account.model.mapper.UserMapper.findPage", query);
}
}
|
package com.swm.common.util;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* 该类主要负责过滤请求,验证用户是否登录。
* JLEcgWeb
* @author fanyuanyang
* @开发日期: 2012-9-29 上午10:54:15
* @version 1.0
* @description 登录过滤器
* @see
*/
public class SystemUserFilter implements Filter{
/**
* 销毁
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* 过滤
*/
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)arg0;
HttpServletResponse response = (HttpServletResponse)arg1;
String urlPath = request.getRequestURI().split("/")[(request.getRequestURI().split("/").length-1)];
System.out.println(urlPath);
if("oauth.do".equals(urlPath) || "callback.do".equals(urlPath)){//如果url请求路径是login,则继续下发
arg2.doFilter(request,response);
return;
}
else{//验证用户是否登录,如果没有,则要求用户登录后,继续下发
if(request.getSession().getAttribute("user") == null){
String url = request.getContextPath()+"/weChat/oauth.do";
response.setContentType("text/html;charset=utf-8");
response.sendRedirect(url);
}else{
arg2.doFilter(request,response);
}
}
}
/**
* 初始化
*/
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
|
package ObjectDemoProduct;
public class abstract Sample {
public abstract demo();
} |
package com.pce.BookMeTutor.Model.Dto.Requests;
public class CompletionRequest {
private String secret;
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public CompletionRequest(String secret) {
super();
this.secret = secret;
}
public CompletionRequest() {
// TODO Auto-generated constructor stub
}
}
|
package com.pan.Concurrent.t5;
public class ThreadBt5 extends Thread{
private MyObjectt5 myObjectt5;
public ThreadBt5(MyObjectt5 myObjectt5)
{
super();
this.myObjectt5=myObjectt5;
}
@Override
public void run() {
super.run();
myObjectt5.speedPrintString();
}
}
|
package verification;
import org.opt4j.satdecoding.Constraint;
import org.opt4j.satdecoding.Literal;
import org.opt4j.satdecoding.Constraint.Operator;
/**
* Class offering static methods to generate constraints.
*
* @author Fedor Smirnov
*
*/
public class ConstraintGeneration {
private ConstraintGeneration(){
}
/**
* Generate a constraint setting the given variable to 1.
*
* @param variable : the variable to set
* @return The constraint setting the variable.
*/
public static Constraint activateVariable(Object variable) {
return setVariable(variable, true);
}
/**
* Generate a constraint setting the given variable to 1.
*
* @param variable : the variable to set
* @return The constraint setting the variable.
*/
public static Constraint deactivateVariable(Object variable) {
return setVariable(variable, false);
}
/**
* Generate a constraint that sets the given variable to the given value.
*
* @param variable : The variable to set
* @param active : TRUE => variable set to 1; FALSE => variable set to 0
* @return : The constraint setting the variable
*/
public static Constraint setVariable(Object variable, boolean active) {
Constraint result = new Constraint(Operator.EQ, active ? 1 : 0);
result.add(new Literal(variable, true));
return result;
}
}
|
/*
* Copyright 2002-2023 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.util;
import java.io.File;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Rob Harrop
*/
class FileSystemUtilsTests {
@Test
void deleteRecursively() throws Exception {
File root = new File("./tmp/root");
File child = new File(root, "child");
File grandchild = new File(child, "grandchild");
grandchild.mkdirs();
File bar = new File(child, "bar.txt");
bar.createNewFile();
assertThat(root).exists();
assertThat(child).exists();
assertThat(grandchild).exists();
assertThat(bar).exists();
FileSystemUtils.deleteRecursively(root);
assertThat(root).doesNotExist();
assertThat(child).doesNotExist();
assertThat(grandchild).doesNotExist();
assertThat(bar).doesNotExist();
}
@Test
void copyRecursively() throws Exception {
File src = new File("./tmp/src");
File child = new File(src, "child");
File grandchild = new File(child, "grandchild");
grandchild.mkdirs();
File bar = new File(child, "bar.txt");
bar.createNewFile();
assertThat(src).exists();
assertThat(child).exists();
assertThat(grandchild).exists();
assertThat(bar).exists();
File dest = new File("./dest");
FileSystemUtils.copyRecursively(src, dest);
assertThat(dest).exists();
assertThat(new File(dest, child.getName())).exists();
FileSystemUtils.deleteRecursively(src);
assertThat(src).doesNotExist();
}
@AfterEach
void tearDown() throws Exception {
File tmp = new File("./tmp");
if (tmp.exists()) {
FileSystemUtils.deleteRecursively(tmp);
}
File dest = new File("./dest");
if (dest.exists()) {
FileSystemUtils.deleteRecursively(dest);
}
}
}
|
package foo.service;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.*;
@ComponentScan(basePackageClasses = RootPackage.class)
@SpringBootApplication
public class FooServiceApplication {
public static void main(String[] args) {
SpringApplication.run(FooServiceApplication.class, args);
}
@RestController
@RequestMapping("foo")
static class Endpoint {
@GetMapping
public String foo() {
return "foo is alive";
}
@GetMapping("bar")
public String bar() {
return "bar is alive";
}
@PostMapping("submit")
public Dto submit(@RequestBody Dto dto) {
return dto;
}
}
@Getter
@Setter
class Dto {
private String name;
}
}
|
package com.stackroute.movieservice.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import com.stackroute.movieservice.domain.Movie;
import com.stackroute.movieservice.repository.MovieRepository;
@Configuration
public class BootstrapData implements CommandLineRunner {
MovieRepository movieRepository;
@Autowired
public BootstrapData(MovieRepository movieRepository) {
this.movieRepository = movieRepository;
}
@Override
public void run(String... args) throws Exception {
Movie movie = new Movie();
movie.setMovieId(1);
movie.setMovieTitle("batman");
movieRepository.save(movie);
}
}
|
package com.sunbinqiang.iconcountview;
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
/**
* Created by sunbinqiang on 15/10/2017.
*/
public class CountView extends View implements CountConstract.View {
private static final int PADDING_WIDTH = 12;
private static final int PADDING_HEIGHT = 60;
private static final int PADDING_SPACE = 3;
private final int DEFAULT_TEXT_SIZE = getResources().getDimensionPixelSize(R.dimen.text_normal_size);
private CountConstract.Presenter mPresenter;
private ValueAnimator mObjectAnimator;
private float mCurAniValue; //当前属性动画数值
private Rect mRect = new Rect(); // 当前文字的区域
private Rect mDigitalRect = new Rect(); // 单个数字的区域
private Paint mTextNormalPaint;
private Paint mTextSelectedPaint;
public CountView(Context context) {
this(context, null);
}
public CountView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public CountView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mTextNormalPaint = new Paint();
mTextSelectedPaint = new Paint();
mTextNormalPaint.setColor(getResources().getColor(R.color.text_gray));
mTextNormalPaint.setTextSize(DEFAULT_TEXT_SIZE);
mTextNormalPaint.setStyle(Paint.Style.FILL);
mTextNormalPaint.setAntiAlias(true);
mTextSelectedPaint.setColor(getResources().getColor(R.color.text_gray));
mTextSelectedPaint.setTextSize(DEFAULT_TEXT_SIZE);
mTextSelectedPaint.setStyle(Paint.Style.FILL);
mTextSelectedPaint.setAntiAlias(true);
mTextNormalPaint.getTextBounds("0", 0, 1, mDigitalRect);
new CountPresenter(this);
mPresenter.start();
}
@Override
public void setPresenter(CountConstract.Presenter presenter) {
mPresenter = presenter;
}
@Override
public void initView() {
requestLayout();
}
@Override
public void initAnimator() {
mObjectAnimator = ValueAnimator.ofFloat(0.0f, 1.0f);
mObjectAnimator.setDuration(500);
mObjectAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
mCurAniValue = (float) valueAnimator.getAnimatedValue();
invalidate();
}
});
mObjectAnimator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
}
@Override
public void onAnimationEnd(Animator animator) {
//动画结束, 数值更新
mPresenter.updateCount();
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
});
}
@Override
public void startAnimator() {
if (mObjectAnimator != null) {
mObjectAnimator.start();
}
}
@Override
public void endAnimator() {
if (mObjectAnimator != null && mObjectAnimator.isRunning()) {
mObjectAnimator.end();
}
}
@Override
public void drawText(Canvas canvas, String strDigital, float x, float y, boolean isSelected) {
canvas.drawText(strDigital, x, y, getCurPaint(isSelected));
}
/**
* initial mCurCount
*
* @param count
*/
public void setCount(long count) {
mPresenter.initCount(count);
}
/**
* 设置数字为0时的文本
* @param zeroText
*/
public void setZeroText(String zeroText) {
mPresenter.setZeroText(zeroText);
}
public void setTextNormalColor(int normalColor) {
mTextNormalPaint.setColor(normalColor);
}
public void setTextSelectedColor(int selectedColor) {
mTextSelectedPaint.setColor(selectedColor);
}
public void setTextSize(int textSize) {
mTextNormalPaint.setTextSize(textSize);
mTextSelectedPaint.setTextSize(textSize);
}
public void setIsSelected(boolean isSelected) {
mPresenter.setIsSelected(isSelected);
}
/**
* +1
*/
public void addCount() {
mPresenter.changeCount(1);
}
/**
* -1
*/
public void minusCount() {
mPresenter.changeCount(-1);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float y = PADDING_HEIGHT + mDigitalRect.height();
mPresenter.draw(canvas, 0.0f, y, mDigitalRect.width() + PADDING_SPACE, mCurAniValue);
}
/**
* @param canvas
* @param digital
* @param x
* @param y
*/
@Override
public void drawIn(Canvas canvas, String digital, float x, float y, boolean isSelected) {
Paint inPaint = getCurPaint(isSelected);
inPaint.setAlpha((int) (mCurAniValue * 255));
inPaint.setTextSize(DEFAULT_TEXT_SIZE * (mCurAniValue * 0.5f + 0.5f));
canvas.drawText(digital, x, y, inPaint);
inPaint.setAlpha(255);
inPaint.setTextSize(DEFAULT_TEXT_SIZE);
}
/**
* @param canvas
* @param digital
* @param x
* @param y
*/
@Override
public void drawOut(Canvas canvas, String digital, float x, float y, boolean isSelected) {
Paint outPaint = getCurPaint(!isSelected);
outPaint.setAlpha(255 - (int) (mCurAniValue * 255));
outPaint.setTextSize(DEFAULT_TEXT_SIZE * (1.0f - mCurAniValue * 0.5f));
canvas.drawText(digital, x, y, outPaint);
outPaint.setAlpha(255);
outPaint.setTextSize(DEFAULT_TEXT_SIZE);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
mRect.setEmpty();
mTextNormalPaint.getTextBounds(mPresenter.getText(), 0, mPresenter.getText().length(), mRect);
int textWidth = mRect.width() + PADDING_WIDTH * 2;
int textHeight = mRect.height() + PADDING_HEIGHT * 2;
final int dw = resolveSizeAndState(textWidth, widthMeasureSpec, 0);
final int dh = resolveSizeAndState(textHeight, heightMeasureSpec, 0);
setMeasuredDimension(dw, dh);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mObjectAnimator.end();
}
private Paint getCurPaint(boolean isSelected) {
return isSelected ? mTextSelectedPaint : mTextNormalPaint;
}
}
|
package units.progadv.exceptions;
public class UnexpectedVariableException extends ComputationException {
public UnexpectedVariableException(String message) {
super(message);
}
}
|
package friends.queries.queries;
import friends.queries.data.DataRepository;
import friends.queries.dataloader.DataLoaderConfig;
import friends.queries.model.Item;
import friends.queries.model.User;
import io.leangen.graphql.annotations.*;
import io.leangen.graphql.execution.ResolutionEnvironment;
import io.leangen.graphql.spqr.spring.annotations.GraphQLApi;
import org.dataloader.DataLoader;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@Service
@GraphQLApi
public class ItemResolver {
DataRepository repository;
private static ItemResolver itemResolver;
private ItemResolver() {
repository = DataRepository.getInstance();
}
public static ItemResolver getInstance() {
if (itemResolver == null) {
itemResolver = new ItemResolver();
}
return itemResolver;
}
@GraphQLQuery(name = "items")
public CompletableFuture<List<Item>> getItems(@GraphQLContext User user,
@GraphQLArgument(name = "first",defaultValue = "-1") int first,
@GraphQLArgument(name = "offset",defaultValue = "0") int offset,
@GraphQLEnvironment ResolutionEnvironment environment) {
DataLoader<String,Item> loader = environment.dataFetchingEnvironment.getDataLoader(DataLoaderConfig.ITEM_FETCHER);
var list = user.itemList();
int size = list.size();
offset = Math.max(offset, 0);
offset = Math.min(offset, size);
if(first < 0) first = size;
int end = Math.min(size, first + offset);
return loader.loadMany(list.subList(offset,end));
// return loader.loadMany(user.itemList());
}
// // without data loaders
// public List<Item> getItems(@GraphQLContext User user,
// @GraphQLArgument(name = "first",defaultValue = "-1") int first,
// @GraphQLArgument(name = "offset",defaultValue = "0") int offset,
// @GraphQLEnvironment ResolutionEnvironment env) {
//
// var list = user.itemList();
// int size = list.size();
//
// offset = Math.max(offset, 0);
// offset = Math.min(offset, size);
//
// if(first < 0) first = size;
// int end = Math.min(size, first + offset);
// return user.itemList().subList(offset,end).stream().map(i -> repository.getItem(i)).toList();
// }
@GraphQLMutation(name = "createItem")
public Item createItem(@GraphQLArgument(name = "item") Item item,
@GraphQLEnvironment ResolutionEnvironment env) {
env.dataFetchingEnvironment.getDataLoader(DataLoaderConfig.ITEM_FETCHER).clear(item.getId());
return repository.createItem(item);
}
}
|
package GUI;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Mouse extends JFrame {
private JPanel mousepanel;
private JLabel statusbar;
public Mouse() {
super("Mouse Events");
mousepanel = new JPanel();
mousepanel.setBackground(Color.WHITE);
add(mousepanel, BorderLayout.CENTER);
statusbar = new JLabel ("default");
add(statusbar, BorderLayout.SOUTH); // bottom of the screen
Handlerclass handler = new Handlerclass();
mousepanel.addMouseListener(handler);
mousepanel.addMouseMotionListener(handler);
}
private class Handlerclass implements MouseListener, MouseMotionListener {
public void mouseClicked (MouseEvent event) {
statusbar.setText(String.format("Clicked at %d,%d", event.getX(), event.getY()));
}
public void mousePressed (MouseEvent event) {
statusbar.setText("You pressed down the mouse");
}
public void mouseReleased (MouseEvent event) {
statusbar.setText("You released the button");
}
public void mouseEntered (MouseEvent event) {
statusbar.setText("You entered the area");
mousepanel.setBackground(Color.BLUE);
}
public void mouseExited (MouseEvent event) {
statusbar.setText("The mouse had left the window");
mousepanel.setBackground(Color.WHITE);
}
// These are mouse motion event
public void mouseDragged(MouseEvent event) {
statusbar.setText("You are dragging the mouse");
}
public void mouseMoved(MouseEvent event) {
statusbar.setText("You moved the mouse");
}
}
}
|
package pinno.demo.hackernews.screen.detail.viewholder;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import pinno.demo.hackernews.R;
import pinno.demo.hackernews.base.BaseViewHolder;
import pinno.demo.hackernews.base.ListItem;
import pinno.demo.hackernews.model.Comment;
public class CommentHeaderViewHolder extends BaseViewHolder<ListItem<Comment>> {
@BindView(R.id.tv_author)
TextView tvAuthor;
@BindView(R.id.tv_title)
TextView tvTitle;
@BindView(R.id.tv_score)
TextView tvPoint;
@BindView(R.id.tv_link)
TextView tvLink;
private final int viewType;
public CommentHeaderViewHolder(@NonNull final View itemView, final int viewType) {
super(itemView);
this.viewType = viewType;
ButterKnife.bind(this, itemView);
}
@Override
public void bindTo(@NonNull ListItem<Comment> listItem) {
final Comment comment = listItem.data();
tvAuthor.setText(comment.data().by());
tvTitle.setText(comment.data().title());
tvPoint.setText(String.valueOf(comment.data().score()));
tvLink.setText(comment.data().url());
}
@Override
public int viewType() {
return viewType;
}
}
|
package domain;
/**
* User: Goutham Rathnaswamy
* Date: 19/07/2013
* Time: 14:30
*/
public class CustomerCredit {
private String name;
private String credit;
public CustomerCredit(){};
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCredit() {
return credit;
}
public void setCredit(String credit) {
this.credit = credit;
}
}
|
package com.zerobank.stepdefinitions;
import com.zerobank.pages.AccountActivityPage;
import io.cucumber.java.en.Then;
import org.junit.Assert;
import java.util.List;
public class AccountActivityStepDefinitions {
AccountActivityPage account_activity_page = new AccountActivityPage();
@Then("user verify the title of Account Activity Page as {string}")
public void user_verify_the_title_of_Account_Activity_Page_as(String string) {
Assert.assertEquals( account_activity_page.getTitleAccountActivity(), string );
}
@Then("view default option as {string} in the Account drop down")
public void view_default_option_as_in_the_Account_drop_down(String string) {
Assert.assertEquals(account_activity_page.getSelectedDefault(),string);
}
@Then("view dropdown options in the Account should have following options")
public void view_dropdown_options_in_the_Account_should_have_following_options(List<String> dataTable) {
Assert.assertEquals(account_activity_page.getAllOptionsInDropdown(),dataTable);
}
@Then("view transactions table column names should have the following options")
public void view_transactions_table_column_names_should_have_the_following_options(List<String> dataTable) {
Assert.assertEquals(account_activity_page.getTransactionColumnNames(),dataTable);
}
}
|
package com.gogo.base.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class ConvertUtil {
private static final Logger logger = LoggerFactory.getLogger(ConvertUtil.class);
@SuppressWarnings("unchecked")
public static <T> T convert(Object src, Class<T> destClz) {
if (src == null || destClz == null) {
return null;
}
if (src instanceof Map) {
return convert((Map<String, Object>)src, destClz);
}
if (src.getClass() == destClz) {
return (T) src;
}
try {
T dest = destClz.newInstance();
BeanUtils.copyProperties(src, dest);
return dest;
} catch (InstantiationException | IllegalAccessException e) {
logger.error("convert error: src="+src+", dest class="+destClz);
}
return null;
}
@SuppressWarnings("unchecked")
public static <T> T convert(Map<String, Object> srcMap, Class<T> destClz) {
if (ObjectUtil.isEmpty(srcMap) || destClz == null) {
return null;
}
JSONObject json = new JSONObject();
srcMap.forEach((k,v)->{
json.put(k, v);
});
if (destClz == Map.class) {
return (T) json;
}
return JSON.toJavaObject(json, destClz);
}
private static final SimpleDateFormat datetimeSF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static final SimpleDateFormat msDatetimeSF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
public static String formatDate(Object date) {
if (date == null || "".equals(date.toString())) {
date = new Date();
}
try {
if (date instanceof Date) {
return datetimeSF.format(date);
}
String dateStr = date.toString();
long time = Long.parseLong(dateStr);
return datetimeSF.format(new Date(time));
} catch (Exception e) {
return date.toString();
}
}
public static String formatDateToMS(Object date) {
if (date == null || "".equals(date.toString())) {
date = new Date();
}
try {
if (date instanceof Date) {
return msDatetimeSF.format(date);
}
String dateStr = date.toString();
long time = Long.parseLong(dateStr);
return msDatetimeSF.format(new Date(time));
} catch (Exception e) {
return date.toString();
}
}
public static void main(String[] args) {
System.out.println(formatDate("977404838666"));
System.out.println(formatDateToMS("977404838666"));
// Map<String, Object> map = new HashMap<>();
// map.put("customer_name", "tt");
// map.put("customer_Age", 15);
// map.put("cust_GUID", 110);
// System.out.println(convert(map, Customer.class));
}
static class Customer {
private Integer customerAge;
private Long custGUID;
private String customerName;
public Integer getCustomerAge() {
return customerAge;
}
public void setCustomerAge(Integer customerAge) {
this.customerAge = customerAge;
}
public Long getCustGUID() {
return custGUID;
}
public void setCustGUID(Long custGUID) {
this.custGUID = custGUID;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
@Override
public String toString() {
return JSON.toJSONString(this);
}
}
}
|
package model;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
public class Mecz {
private SimpleStringProperty dr1;
private SimpleStringProperty dr2;
private SimpleIntegerProperty wynik1;
private SimpleIntegerProperty wynik2;
public Mecz(String dr1, String dr2, int wynik1, int wynik2){
this.dr1= new SimpleStringProperty(dr1);
this.dr2=new SimpleStringProperty(dr2);
this.wynik1= new SimpleIntegerProperty(wynik1);
this.wynik2=new SimpleIntegerProperty(wynik2);
}
public String getDr1(){
return dr1.get();
}
public String getDr2(){
return dr2.get();
}
public int getWynik1() {
return wynik1.get();
}
public int getWynik2() {
return wynik2.get();
}
}
|
package num.grapecity.lab4;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.Objects;
public class Provider extends ContentProvider {
public static final String AUTHORITY = "num.grapecity.provider";
static final int STUDENTS = 1;
static final int STUDENT_ID = 2;
static final UriMatcher uriMatcher;
private static final String mimeTypeDirPrefix = "vnd.android.cursor.dir/";
private static final String mimeTypeItemPrefix = "vnd.android.cursor.item/";
private static final String accountPath = "UserInfo";
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
// Match uri to account table.
uriMatcher.addURI(AUTHORITY, accountPath, STUDENTS);
// Match uri to account table row.
uriMatcher.addURI(AUTHORITY, accountPath + "/#", STUDENT_ID);
}
private DatabaseHelper databaseHelper;
@Override
public boolean onCreate() {
databaseHelper = new DatabaseHelper(getContext());
return false;
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables("UserInfo");
Cursor cursor = queryBuilder.query(databaseHelper.getReadableDatabase(), projection, selection, selectionArgs, null, null, null);
cursor.setNotificationUri(Objects.requireNonNull(getContext()).getContentResolver(), uri);
return cursor;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
// Data mimetype string format. vndPrefix/vnd.<authority>.<path>
StringBuilder retBuf = new StringBuilder();
// Parse request code.
int requestCode = uriMatcher.match(uri);
if (requestCode == STUDENTS) {
// If request table.
retBuf.append(mimeTypeDirPrefix);
retBuf.append("vnd.");
retBuf.append(AUTHORITY);
retBuf.append(".");
retBuf.append(accountPath);
} else if (requestCode == STUDENT_ID) {
// If request table rows.
retBuf.append(mimeTypeItemPrefix);
retBuf.append("vnd.");
retBuf.append(AUTHORITY);
retBuf.append(".");
retBuf.append(accountPath);
}
return retBuf.toString();
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
Uri ret;
// Get account db object.
SQLiteDatabase accountDb = databaseHelper.getWritableDatabase();
// Get uri match code.
// Insert user data into SQLite database account table and get newly added account id..
long newAccountId = accountDb.insert("UserInfo", null, contentValues);
// Create new account uri. Uri string format : "content://<authority>/path/id".
String newAccountUriStr = "content://" + AUTHORITY + "/" + accountPath + "/" + newAccountId;
ret = Uri.parse(newAccountUriStr);
return ret;
}
@Override
public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
// Implement this to handle requests to delete one or more rows.
// Get account db object. Below code will create a SQLite database.
SQLiteDatabase accountDb = databaseHelper.getWritableDatabase();
// Delete all rows in account table.
// int ret = accountDb.delete("UserInfo", selection, selectionArgs);
// Delete row with request row id.
String accountId = uri.getPathSegments().get(1);
String whereClause = " _id = ? ";
String[] whereArgsArr = {accountId};
return accountDb.delete("UserInfo", whereClause, whereArgsArr);
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
// Return updated rows count.
int ret;
// Get account db object.
SQLiteDatabase accountDb = databaseHelper.getWritableDatabase();
// Get uri match code.
// int matchCode = uriMatcher.match(uri);
// Update rows with request row id.
String accountId = uri.getPathSegments().get(1);
String whereClause = " _id = ? ";
String[] whereArgsArr = {accountId};
ret = accountDb.update("UserInfo", values, whereClause, whereArgsArr);
return ret;
}
}
|
package ch.erp.management.mvp.contract;
import ch.erp.management.mvp.base.BaseModel;
import ch.erp.management.mvp.base.BasePresenter;
import ch.erp.management.mvp.base.BaseView;
/**
* 采购退货-Contract
*/
public interface MPurchaseReturnsContract {
/**
* 采购退货-IView
*/
interface MPurchaseReturnsIView extends BaseView {
}
/**
* 采购退货-Presenter
*/
abstract class MIPurchaseReturnsActivityP extends BasePresenter<MPurchaseReturnsIView> {
}
/**
* 采购退货-Model
*/
abstract class MIPurchaseReturnsModel extends BaseModel {
}
}
|
package br.com.furb.service;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.furb.domain.User;
import br.com.furb.repository.UserRepository;
import br.com.furb.security.authentication.UserSV;
@Service
public class AuthenticationService {
@Autowired
private UserRepository userRepository;
/**
* Busca o usuário através do username para autenticação do Spring Security
* @param username
* @return
*/
public UserSV loadUserByUsername(String username) {
UserSV userSv = null;
try {
Optional<User> user = userRepository.loadUserByLogin(username);
if(user.isPresent()) {
userSv = new UserSV(user.get().getLogin(), user.get().getPassword());
}
} catch (Exception e) {
throw new RuntimeException("Ocorreram falhas ao realizar a autenticação. Causa: " + e.getMessage());
}
return userSv;
}
}
|
package OnTap2;
public class XeTai extends PTGT{
private String trongTai;
public XeTai() {
super();
}
public XeTai(String hangSX, int namSX, double giaBan, String mau, String congSuat, String trongTai) {
super(hangSX, namSX, giaBan, mau);
this.trongTai = trongTai;
}
public String getCongSuat() {
return trongTai;
}
public void setCongSuat(String trongTai) {
this.trongTai = trongTai;
}
public void nhap() {
super.nhap();
System.out.println("Nhap trong tai: ");
trongTai = scanner.nextLine();
}
public void xuat() {
super.xuat();
System.out.println("Trong tai: "+ trongTai);
}
}
|
/******************************************************************************
* __ *
* <-----/@@\-----> *
* <-< < \\// > >-> *
* <-<-\ __ /->-> *
* Data / \ Crow *
* ^ ^ *
* info@datacrow.net *
* *
* This file is part of Data Crow. *
* Data Crow is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public *
* License as published by the Free Software Foundation; either *
* version 3 of the License, or any later version. *
* *
* Data Crow is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public *
* License along with this program. If not, see http://www.gnu.org/licenses *
* *
******************************************************************************/
package net.datacrow.util.movie;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.util.List;
import java.util.StringTokenizer;
import net.datacrow.core.DataCrow;
import org.apache.log4j.Logger;
abstract class FileProperties {
private static Logger logger = Logger.getLogger(FileProperties.class.getName());
public static final int _TYPE_AUDIO_CODEC = 0;
public static final int _TYPE_VIDEO_CODEC = 1;
public static final int _TYPE_VIDEO_CODEC_EXT = 2;
private String filename = "";
private String language = "";
private String name = "";
private String subtitles = "";
private String videoResolution = "";
private String videoCodec = "";
private double videoRate = 0;
private int videoBitRate = 0;
private int duration = -1;
private String audioCodec = "";
private int audioRate = 0;
private int audioBitRate = 0;
private int audioChannels = 0;
private String container = "";
private String mediaType = "";
private List<String> metaData;
private BufferedReader rdrVideo;
private BufferedReader rdrVideoExt;
private BufferedReader rdrAudio;
public FileProperties() {
try {
InputStreamReader isrVideo = new InputStreamReader(new FileInputStream(new File(DataCrow.resourcesDir, "FOURCCvideo.txt")));
rdrVideo = new BufferedReader(isrVideo);
} catch (Exception e) {
logger.error(e, e);
}
try {
InputStreamReader isrAudio = new InputStreamReader(new FileInputStream(new File(DataCrow.resourcesDir, "FOURCCaudio.txt")));
rdrAudio = new BufferedReader(isrAudio);
} catch (Exception e) {
logger.error(e, e);
}
try {
InputStreamReader isrVideoExt = new InputStreamReader(new FileInputStream(new File(DataCrow.resourcesDir, "videoExtended.txt")));
rdrVideoExt = new BufferedReader(isrVideoExt);
} catch (Exception e) {
logger.error(e, e);
}
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* Returns the subtitles.
*/
public String getSubtitles() {
return subtitles;
}
/**
* Returns the resolution.
*/
public String getVideoResolution() {
return videoResolution;
}
/**
* Returns the video codec.
*/
public String getVideoCodec() {
return videoCodec;
}
/**
* Returns the video rate.
*/
public double getVideoRate() {
return videoRate;
}
/**
* Returns the video bit rate.
*/
public int getVideoBitRate() {
return videoBitRate;
}
/**
* Returns the duration.
*/
public int getDuration() {
return duration;
}
/**
* Returns the audio codec.
*/
public String getAudioCodec() {
return audioCodec;
}
/**
* Returns the audio rate.
*/
public int getAudioRate() {
return audioRate;
}
/**
* Returns the audio bit rate.
*/
public int getAudioBitRate() {
return audioBitRate;
}
/**
* Returns the audio channels.
*/
public int getAudioChannels() {
return audioChannels;
}
/**
* Sets the subtitles.
*/
protected void setSubtitles(String subtitles) {
this.subtitles = subtitles;
}
/**
* Sets the resolution.
*/
protected void setVideoResolution(String videoResolution) {
this.videoResolution = videoResolution;
}
/**
* Sets the video codec (video handler).
*/
protected void setVideoCodec(String videoCodec) {
this.videoCodec = videoCodec;
}
/**
* Sets the video rate.
*/
protected void setVideoRate(double videoRate) {
this.videoRate = videoRate;
}
/**
* Sets the video bit rate.
*/
protected void setVideoBitRate(int videoBitRate) {
this.videoBitRate = videoBitRate;
}
/**
* Sets the duration.
*/
protected void setDuration(int duration) {
this.duration = duration;
}
/**
* Sets the audio Codec (auda handler).
*/
protected void setAudioCodec(String audioCodec) {
this.audioCodec = audioCodec;
}
/**
* Sets the audio rate.
*/
protected void setAudioRate(int audioRate) {
this.audioRate = audioRate;
}
/**
* Sets the audio bit rate.
*/
protected void setAudioBitRate(int audioBitRate) {
this.audioBitRate = audioBitRate;
}
/**
* Sets the audio channels.
*/
protected void setAudioChannels(int audioChannels) {
this.audioChannels = audioChannels;
}
/**
* Sets the container.
*/
protected void setContainer(String container) {
this.container = container;
}
/**
* Returns the container.
*/
protected String getContainer() {
return this.container;
}
/**
* Sets the Media Type.
*/
protected void setMediaType(String mediaType) {
this.mediaType = mediaType;
}
/**
* Returns the Media Type.
*/
protected String getMediaType() {
return this.mediaType;
}
/**
* Sets the meta data ArrayList.
*/
protected void setMetaData(List<String> metaData) {
this.metaData = metaData;
}
/**
* Returns the meta data ArrayList.
*/
protected List<String> getMetaData() {
return metaData;
}
/**
* Processes a file from the given DataInputStream.
*/
protected void process(RandomAccessFile dataStream, String filename) throws Exception {}
/**
* Reads an unsigned 8-bit integer.
*/
protected int readUnsignedByte(byte[] b, int offset) throws Exception {
return b[offset];
}
/**
* Reads an unsigned 16-bit integer.
*/
protected int readUnsignedInt16(byte[] b, int offset) throws Exception {
return (b[offset] | (b[offset + 1] << 8));
}
/**
* Reads an unsigned 32-bit integer.
*/
protected int readUnsignedInt32(byte[] b, int offset) throws Exception {
return (readUnsignedInt16(b, offset) | (readUnsignedInt16(b, offset + 2) << 16));
}
/**
* Returns a 16-bit integer.
*/
protected int getUnsignedInt16(int byte1, int byte2) throws Exception {
return (byte2 | (byte1 << 8));
}
/**
* Returns a 16-bit integer.
*/
protected int getUnsignedInt16(byte byte1, byte byte2) throws Exception {
return byte2 | byte1 << 8;
}
/**
* Returns an unsigned 32-bit integer.
*/
protected int getUnsignedInt32(byte byte1, byte byte2) throws Exception {
return byte2 | byte1 << 16;
}
/**
* Returns an unsigned 32-bit integer.
*/
protected int getUnsignedInt32(int byte1, int byte2) throws Exception {
return (byte1 | byte2 << 16);
}
/**
* Reads an unsigned byte and returns its int representation.
*/
protected int readUnsignedByte(RandomAccessFile dataStream) throws Exception {
int data = dataStream.readUnsignedByte();
if (data == -1) {
throw new Exception("Unexpected end of stream.");
}
return data;
}
/**
* Reads n unsigned bytes and returns it in an int[n].
*/
protected int[] readUnsignedBytes(RandomAccessFile dataStream, int n) throws Exception {
int[] data = new int[n];
for (int i = 0; i < data.length; i++) {
data[i] = readUnsignedByte(dataStream);
}
return data;
}
/**
* Reads an unsigned 16-bit integer.
*/
protected int readUnsignedInt16(RandomAccessFile dataStream) throws Exception {
return (readUnsignedByte(dataStream) | (readUnsignedByte(dataStream) << 8));
}
/**
* Reads an unsigned 32-bit integer.
*/
protected int readUnsignedInt32(RandomAccessFile dataStream) throws Exception {
return (readUnsignedInt16(dataStream) | (readUnsignedInt16(dataStream) << 16));
}
/**
* Discards n bytes.
*/
protected void skipBytes(RandomAccessFile dataStream, int n) throws Exception {
readUnsignedBytes(dataStream, n);
}
/**
* Reverses the byte order
*/
protected int changeEndianness(int num) {
return (num >>> 24) | (num << 24) | ((num << 8) & 0x00FF0000 | ((num >> 8) & 0x0000FF00));
}
/**
* Returns the ASCII value of id
*/
protected String fromByteToAscii(int j, int numberOfBytes) throws Exception {
int id = j;
StringBuffer buffer = new StringBuffer(4);
for (int i = 0; i < numberOfBytes; i++) {
int c = id & 0xff;
buffer.append((char) c);
id >>= 8;
}
return new String(buffer);
}
/**
* Returns the decimal value of a specified number of bytes from a specific
* part of a byte.
*/
protected int getDecimalValue(int[] bits, int start, int stop, boolean printBits) {
String dec = "";
for (int i = start; i >= stop; i--) {
dec += bits[i];
}
return Integer.parseInt(dec, 2);
}
/**
* Returns an array containing the bits from the value.
*/
protected int[] getBits(int value, int numberOfBytes) {
int[] bits = new int[numberOfBytes * 8];
for (int i = bits.length - 1; i >= 0; i--) {
bits[i] = (value >>> i) & 1;
}
return bits;
}
public void close() {
if (metaData != null) metaData.clear();
if (rdrVideo != null) {
try {
rdrVideo.close();
} catch (Exception e) {
logger.debug("Failed to close file", e);
}
}
if (rdrVideoExt != null) {
try {
rdrVideoExt.close();
} catch (Exception e) {
logger.debug("Failed to close file", e);
}
}
if (rdrAudio != null) {
try {
rdrAudio.close();
} catch (Exception e) {
logger.debug("Failed to close file", e);
}
}
}
/**
* Searches in the inputStream stream the name following the string id
* (separated by a \t).
*/
@SuppressWarnings("resource")
protected String findName(String id, int type) throws Exception {
String line = null;
String result = "";
// do not close rdr, reused throughout the session
BufferedReader rdr =
type == _TYPE_AUDIO_CODEC ? rdrAudio :
type == _TYPE_VIDEO_CODEC ? rdrVideo : rdrVideoExt;
if (rdr == null) {
logger.error("No valid resource file found for codec identification");
} else {
while ((line = rdr.readLine()) != null) {
if (line.length() > 0) {
StringTokenizer tokenizer = new StringTokenizer(line, "\t");
if ( tokenizer.countTokens() > 0 &&
id.compareToIgnoreCase(tokenizer.nextToken()) == 0) {
result = tokenizer.nextToken();
break;
}
}
}
}
return result;
}
}
|
package com.mkyong.web.controller;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
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.ModelAndView;
import com.emc.web.model.BuyerData;
import com.emc.web.model.SellerData;
import com.emc.web.model.UserItem;
import com.mkyong.web.dao.MainDAO;
import com.mkyong.web.model.Connection;
import com.mkyong.web.model.Journey;
import com.mkyong.web.model.Location;
import com.mkyong.web.model.RouteMap;
import com.mkyong.web.model.UserRoute;
import com.mkyong.web.model.Users;
import com.mkyong.web.util.DijkstraAlgorithm;
@Controller
@Transactional
public class MainController {
@Autowired
private MainDAO mainDAO;
/**
* both "normal login" and "login for update" shared this form.
*
*/
/*
* @RequestMapping("/") public ModelAndView defaultpage(){ ModelAndView
* model = new ModelAndView(); model.setViewName("afterLogin"); return
* model; }
*/
/**
* both "normal login" and "login for update" shared this form.
*
*/
@RequestMapping({ "/login", "/" })
public @ResponseBody ModelAndView login(
@RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout,
HttpServletRequest request) {
Object principal = SecurityContextHolder.getContext()
.getAuthentication().getPrincipal();
ModelAndView model = new ModelAndView();
if (null != error || "".equals(error)) {
model.addObject("error", "Invalid username and password!");
}
if (logout != null) {
model.addObject("msg", "You've been logged out successfully.");
JSONObject object = new JSONObject();
try {
object.put("jsonmsg", "You've been logged out successfully.");
} catch (JSONException e) {
e.printStackTrace();
}
model.addObject("jsonobj", object);
}
if (principal.equals("anonymousUser")) {
model.setViewName("new_login");
} else {
model.setViewName("afterLogin");
String username1 = ((UserDetails) principal).getUsername();
HttpSession httpSession = request.getSession();
httpSession.setAttribute("username", username1);
model.addObject("username", username1);
}
return model;
}
@RequestMapping(value = "/algo", method = RequestMethod.GET)
public @ResponseBody String shortestPathAlgo(
@RequestParam(value = "source") String src,
@RequestParam(value = "dest") String dest,
HttpServletRequest request) {
// ModelAndView model = new ModelAndView();
String username = (String) request.getSession()
.getAttribute("username");
Users user = mainDAO.getUserByUserName(username);
StringBuilder output = new StringBuilder();
if (user != null) {
List<Connection> connections = mainDAO.getAllConnections();
List<Location> locations = mainDAO.getAllLocations();
Location source = mainDAO.getLocationByName(src);
Location destination = mainDAO.getLocationByName(dest);
RouteMap routeMap = new RouteMap(connections, locations);
DijkstraAlgorithm dijkstra = new DijkstraAlgorithm(routeMap);
dijkstra.execute(source);
LinkedList<Location> path = dijkstra.getPath(destination);
UserRoute route = new UserRoute();
route.setDestinationId(locations.get(8).getLocationId());
route.setSourceId(locations.get(1).getLocationId());
route.setUser(user);
mainDAO.saveUserRoute(route);
int count = 0;
for (Location vertex : path) {
Journey journey = new Journey();
journey.setLocation(vertex);
journey.setUserRoute(route);
mainDAO.saveJourney(journey);
count++;
output.append(journey.getLocation());
if (count < path.size()) {
output.append(" ----> ");
}
}
}
return output.toString();
}
@RequestMapping(value = "/sellerPage", method = RequestMethod.GET)
public ModelAndView ownerPage(HttpServletRequest request) {
ModelAndView model = new ModelAndView();
String username = (String) request.getSession()
.getAttribute("username");
model.addObject("username", username);
model.setViewName("seller_Page");
return model;
}
@RequestMapping(value = "/buyerPage", method = RequestMethod.GET)
public ModelAndView poolinPage(HttpServletRequest request) {
ModelAndView model = new ModelAndView();
String username = (String) request.getSession()
.getAttribute("username");
model.addObject("username", username);
model.setViewName("buyer_Page");
return model;
}
@RequestMapping(value = "/saveSellerData", method = RequestMethod.GET)
public ModelAndView saveSellerData(
@RequestParam(value = "item") String item,
@RequestParam(value = "price") Long price,
HttpServletRequest request) {
ModelAndView model = new ModelAndView();
String username = (String) request.getSession()
.getAttribute("username");
com.emc.web.model.Users user = mainDAO.getBidUserByUserName(username);
if (user != null) {
UserItem userItem = new UserItem();
/* userItem.setUser(user); */
userItem.setItem(item);
userItem = mainDAO.saveUserItem(userItem);
SellerData sellerData = new SellerData();
sellerData.setName(username);
sellerData.setSellerPrice(price);
sellerData.setUserItemId(userItem.getUserItemId());
mainDAO.saveSellerData(sellerData);
}
model.addObject("username", username);
model.setViewName("seller_Page");
return model;
}
@RequestMapping(value = "/saveBuyerData", method = RequestMethod.GET)
public ModelAndView saveBuyerData(
@RequestParam(value = "useritemid") Long userItemId,
@RequestParam(value = "price") Long price,
HttpServletRequest request) {
ModelAndView model = new ModelAndView();
String username = (String) request.getSession()
.getAttribute("username");
com.emc.web.model.Users user = mainDAO.getBidUserByUserName(username);
UserItem userItem = mainDAO.getUserItemById(userItemId);
if (user != null && userItem != null) {
BuyerData buyerData = new BuyerData();
buyerData.setName(username);
buyerData.setUserItem(userItem);
buyerData.setUserItemId(userItem.getUserItemId());
buyerData.setBuyerPrice(price);
mainDAO.saveBuyerData(buyerData);
}
model.addObject("username", username);
model.setViewName("buyer_Page");
return model;
}
@RequestMapping(value = "/userItems", method = RequestMethod.GET)
public ModelAndView getUserItemData(
@RequestParam(value = "itemname") String itemName,
HttpServletRequest request) {
ModelAndView model = new ModelAndView();
String username = (String) request.getSession()
.getAttribute("username");
UserItem userItem = mainDAO.getUserItemByItem(itemName);
HttpSession httpSession = request.getSession();
if (!CollectionUtils.isEmpty(userItem.getBuyerDatas())) {
List<BuyerData> buyerData = userItem.getBuyerDatas();
model.addObject("buyerdata", buyerData);
httpSession.setAttribute("buyerdata", buyerData);
} else {
model.addObject("buyerdata", "");
httpSession.setAttribute("buyerdata", "");
}
List<SellerData> sellerDatas = userItem.getSellerDatas();
/* model.addObject("sellerDatas", sellerDatas.get(0)); */
httpSession.setAttribute("name", sellerDatas.get(0).getName());
httpSession.setAttribute("itemId", sellerDatas.get(0).getUserItemId());
httpSession.setAttribute("itemname", sellerDatas.get(0).getUserItem()
.getItem());
httpSession.setAttribute("price", sellerDatas.get(0).getSellerPrice());
httpSession.setAttribute("username", username);
model.addObject("name", sellerDatas.get(0).getName());
model.addObject("itemId", sellerDatas.get(0).getUserItemId());
model.addObject("itemname", sellerDatas.get(0).getUserItem().getItem());
model.addObject("price", sellerDatas.get(0).getSellerPrice());
model.addObject("username", username);
model.setViewName("buyer_Page");
return model;
}
} |
package com.ehy.utils;/**
* Created by Administrator on 2018-7-17.
*/
import javax.servlet.http.HttpServletRequest;
/**
* @Author zhouyu
* @Date2018-7-17 14:18
**/
public class CheckIdentifyCode {
public static String checkCode(HttpServletRequest request,String identifyCode){
String code = (String) request.getSession().getAttribute("iCode");
if (code == null) {
return "201";
}
String[] codeArr = {""};
if(!"".equals(code)){
codeArr = code.split(";");
}
//验证时间是否过期
if((System.currentTimeMillis()-Double.parseDouble(codeArr[1]))>60*1000*5){
return "201";
}
// 将用户提交的验证码和session中的做比较,相同则进行之后的操作
if (!identifyCode.equals(codeArr[0])) {
return "202";
}
return "200";
}
}
|
package io.codex.cryptogram.signature;
/**
* HmacSHA384签名提供器
*
* @author 杨昌沛 646742615@qq.com
* 2018/10/17
*/
public class HMACSHA384SignatureProvider extends HMACSignatureProvider {
public HMACSHA384SignatureProvider() {
super("HmacSHA384");
}
}
|
package DesignPatternBuilders;
import DesignPatternCodeGenerator.CodeBuilder;
import DesignPatterns.Mediator.Colleague;
import DesignPatterns.Mediator.ConcreteColleague;
import DesignPatterns.Mediator.MediatorClass;
import DesignPatterns.Mediator.MediatorInterface;
import org.apache.commons.io.FileUtils;
import org.eclipse.jface.text.BadLocationException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
/**
* Builder for Mediator design pattern
*
*/
public class MediatorBuilder implements CodeBuilder {
String mediatorInterface, mediatorClass, colleagueInterface, colleague1Class, colleague2Class;
String directoryPath;
private Logger logger;
public MediatorBuilder(String directoryPath, String mediatorInterface, String mediatorClass, String colleagueInterface,
String colleague1Class, String colleague2Class) {
this.logger = LoggerFactory.getLogger("DesignPatternBuilders.Mediator");
this.directoryPath = directoryPath;
this.mediatorInterface = mediatorInterface;
this.mediatorClass = mediatorClass;
this.colleagueInterface = colleagueInterface;
this.colleague1Class = colleague1Class;
this.colleague2Class = colleague2Class;
}
public void writeFile() throws BadLocationException, IOException {
// create file objects
MediatorInterface mediatorInterfaceObject =
new MediatorInterface(this.mediatorInterface, this.colleagueInterface);
MediatorClass mediatorClassObject =
new MediatorClass(this.mediatorClass, this.mediatorInterface, this.colleagueInterface,
this.colleague1Class, this.colleague2Class);
Colleague colleagueInterfaceObject =
new Colleague(this.colleagueInterface, this.mediatorInterface);
ConcreteColleague colleague1Object = new ConcreteColleague(this.colleague1Class,
this.colleagueInterface);
ConcreteColleague colleague2Object = new ConcreteColleague(this.colleague2Class,
this.colleagueInterface);
// write the generated code to files
logger.debug("Creating Mediator Interface file");
String mediatorInterfaceFilename = this.directoryPath + mediatorInterfaceObject.fileName
+ ".java";
FileUtils.writeStringToFile(new File(mediatorInterfaceFilename),
mediatorInterfaceObject.buildCode().get(), StandardCharsets.UTF_8);
logger.debug("Creating Mediator file");
String mediatorClassFilename = this.directoryPath + mediatorClassObject.fileName
+ ".java";
FileUtils.writeStringToFile(new File(mediatorClassFilename),
mediatorClassObject.buildCode().get(), StandardCharsets.UTF_8);
logger.debug("Creating Colleague Interface file");
String colleagueInterfaceFilename = this.directoryPath + colleagueInterfaceObject.fileName
+ ".java";
FileUtils.writeStringToFile(new File(colleagueInterfaceFilename),
colleagueInterfaceObject.buildCode().get(), StandardCharsets.UTF_8);
logger.debug("Creating Colleague1 file");
String colleague1Filename = this.directoryPath + colleague1Object.fileName
+ ".java";
FileUtils.writeStringToFile(new File(colleague1Filename),
colleague1Object.buildCode().get(), StandardCharsets.UTF_8);
logger.debug("Creating Colleague2 file");
String colleague2Filename = this.directoryPath + colleague2Object.fileName
+ ".java";
FileUtils.writeStringToFile(new File(colleague2Filename),
colleague2Object.buildCode().get(), StandardCharsets.UTF_8);
}
}
|
package com.metoo.module.app.view.web.tool;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.metoo.core.tools.Md5Encrypt;
import com.metoo.foundation.domain.CouponInfo;
import com.metoo.foundation.domain.User;
import com.metoo.foundation.service.ICouponInfoService;
@Component
public class AppLoginViewTools {
@Autowired
private ICouponInfoService couponInfoService;
/**
* 当用户登录后生成verify返回给客户端保存,每次发送用户中心中请求时将verify放入到请求头中,
* 用来验证用户密码是否已经被更改,如已经更改,手机客户端提示用户重新登录
*
* @param user
* @return
*/
public String create_appverify(User user) {
String app_verify = user.getPassword() + user.getApp_login_token();
app_verify = Md5Encrypt.md5(app_verify).toLowerCase();
return app_verify;
}
/**
*
* @param user
* @param tourists
* @descript 合并用户优惠券
*/
public void margeCoupon(User user, String tourists) {
Map params = new HashMap();
params.put("tourists", tourists);
List<CouponInfo> couponInfos = this.couponInfoService
.query("select obj from CouponInfo obj where obj.tourists=:tourists", params, -1, -1);
params.clear();
params.put("user_id", user.getId());
List<CouponInfo> userCouponInofs = this.couponInfoService.query("select obj from CouponInfo obj where obj.user.id=:user_id", params, -1, -1);
List<Long> list = new ArrayList<Long>();
if(userCouponInofs.size() > 0){
for(CouponInfo CouponInof : userCouponInofs){
list.add(CouponInof.getCoupon().getId());
}
}
for(CouponInfo couponInfo : couponInfos){
if(list.contains(couponInfo.getCoupon().getId())){
this.couponInfoService.delete(couponInfo.getId());
}else{
couponInfo.setUser(user);
couponInfo.setTourists(null);
this.couponInfoService.update(couponInfo);
}
}
}
public void send_json(String json, HttpServletResponse response) {
response.setContentType("application/json");
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("UTF-8");
PrintWriter writer;
try {
writer = response.getWriter();
writer.print(json);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
/*
* 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 Practica_1;
/**
*
* @author mati
*/
public class Circulo {
private double r;
private Punto centrocir;
//constructores
public Circulo(Punto p, double b){
centrocir = p;
r=b;
}
public Circulo(){
centrocir = new Punto();
r=1;
}
public Circulo (double a, double b, double z){
centrocir = new Punto(a,b);
r=z;
}
public void setr (double a){
r=a;
}
public double getr (){
return r;
}
/*public double getxceentro (){
return ;
}*/
public Punto getcentro (){
return centrocir;
}
/* public double getcentroy (){
return centrocir.gety();
}*/
/* public double calcularDistanciaDesde (Circulo p){
double distx= centrocir.getx()-p.getcentrox();
double disty= centrocir.gety()-p.getcentroy();
return Math.sqrt((Math.pow(distx, 2)+(Math.pow(disty, 2))));
}*/
public double calcularDistanciaDesde (Punto p){
return centrocir.calcularDistanciaDesde(p);
/* double distx= centrocir.getx()-p.
double disty= centrocir.gety()-p.gety();*/
}
public double calcularArea (){
return Math.PI*Math.pow(r, 2);
}
public double calcularPeímetro (){
return Math.PI*r*2;
}
}
|
package java二.Class_String;
public class Dome {
public static void main(String[] args) {
String str1 = "123" ;
String str2 = "1" + "2" + "3" ;
String str3 = "2" ;
String str4 = "1" + str3 + "3" ;
System.out.println(str1 == str2); //true
//str1.length()
/*
* 本程序之间所给出的内容全部都是常量数据(字符串的常量都是匿名对象)
* 所以在程序加载的时候会自动帮你处理好相应的连接
* */
System.out.println(str1 == str4); //false
/*
* 因为程序在加载的时候,程序不确定str3是什么内容,因为字符串连接的时候
* str3采用的是变量,变量的内容可以修改,所以最终不认为str3的结果就是一个所需要的值
* */
}
}
|
package com.asm.entities.client;
import com.asm.entities.Automobile;
import com.asm.entities.MockData;
import java.util.ArrayList;
import java.util.List;
public class Client {
private String id;
private String name;
private String surnames;
private String phone;
private String email;
private String address;
private List<Automobile> cars;
public Client() {
// this.id = "";
this.name = "";
this.surnames = "";
this.phone = "";
this.address = "";
this.email = "";
this.cars = MockData.createMockAutomobileList();
}
public Client(String id, String name, String surnames) {
this.id = id;
this.name = name;
this.surnames = surnames;
}
public Client(String name, String lastname) {
// this.id = "";
this.name = name;
this.email = "defaul@gmail.com";
this.surnames = "Default";
this.phone = "1234";
this.address = "Santa monica";
this.cars = MockData.createMockAutomobileList();
}
@Override
public String toString() {
return name +" " + surnames;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurnames() {
return surnames;
}
public void setSurnames(String surnames) {
this.surnames = surnames;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public List<Automobile> getCars() {
return cars;
}
public void setCars(List<Automobile> cars) {
this.cars = cars;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
} |
package com.cs.session;
import com.cs.player.Player;
import com.cs.system.PlayerSessionRegistry;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
/**
* @author Hadi Movaghar
*/
public interface PlayerSessionRegistryRepository extends JpaRepository<PlayerSessionRegistry, Long>, QueryDslPredicateExecutor<PlayerSessionRegistry> {
PlayerSessionRegistry findBySessionId(final String sessionId);
PlayerSessionRegistry findByPlayer(final Player player);
}
|
package com.xiv.gearplanner.controllers;
import com.xiv.gearplanner.services.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/item")
public class ItemController {
private ItemService itemDao;
@Autowired
public ItemController(ItemService itemDao) {
this.itemDao = itemDao;
}
/*
* TODO: Make searchable, pageable, and auto show tooltip
* */
@GetMapping("/view")
public String viewItems(Model model, @PageableDefault(value=50) Pageable pageable ) {
model.addAttribute("item",itemDao.getItems().findAll(pageable));
return "item/view";
}
}
|
package com.daylyweb.music.mapper;
import java.io.Serializable;
import java.util.Map;
/**
* @ClassName: Music
* @Description:TODO
* @author: 丶Tik
* @date: 2017年10月15日 下午6:18:29
*
*/
public class Music implements Serializable{
/**
* @Fields serialVersionUID : TODO
*
*/
private static final long serialVersionUID = 1L;
private Integer songid;
private String songmid;
private String songname;
private String singer;
private String albumname;
private String albummid;
private String commend;
private String keyword;
public Music() {}
/**
* @Title: Music
* @Description: 构造方法
* @param songid 歌曲id
* @param songmid 歌曲mid
* @param songname 歌曲名
* @param singer 歌手
* @param albumname 专辑名
* @param albummid 专辑mid
* @param commend 是否推荐 Y N
* @param keyword 歌曲关键词
* @throws
*
*/
public Music(Integer songid,String songmid,String songname,String singer,String albumname,String albummid,String commend,String keyword) {
this.setSongid(songid);
this.setSongmid(songmid);
this.setSongname(songname);
this.setSinger(singer);
this.setAlbumname(albumname);
this.setAlbummid(albummid);
this.setCommend(commend);
this.setKeyword(keyword);
}
public Music(Map map) {
Object songid = map.get("songid");
Object songmid = map.get("songmid");
Object songname = map.get("songname");
Object singer = map.get("singer");
Object albumname = map.get("albumname");
Object albummid = map.get("albummid");
Object commend = map.get("commend");
Object keyword = map.get("keyword");
this.songid=(songid!=null?(int) songid:0);
this.songmid=(songmid!=null?(String) songmid:"");
this.songname=(songname!=null?(String) songname:"");
this.singer=(singer!=null?(String) singer:"");
this.albumname=(albumname!=null?(String) albumname:"");
this.albummid=(albummid!=null?(String) albummid:"");
this.commend=(commend!=null?(String) commend:"N");
this.keyword=(keyword!=null?(String) keyword:"");
}
public Integer getSongid() {
return songid;
}
public void setSongid(Integer songid) {
this.songid = songid;
}
public String getSongmid() {
return songmid;
}
public void setSongmid(String songmid) {
this.songmid = songmid == null ? null : songmid.trim();
}
public String getSongname() {
return songname;
}
public void setSongname(String songname) {
this.songname = songname == null ? null : songname.trim();
}
public String getSinger() {
return singer;
}
public void setSinger(String singer) {
this.singer = singer == null ? null : singer.trim();
}
public String getAlbumname() {
return albumname;
}
public void setAlbumname(String albumname) {
this.albumname = albumname == null ? null : albumname.trim();
}
public String getCommend() {
return commend;
}
public String getAlbummid() {
return albummid;
}
public void setAlbummid(String albummid) {
this.albummid = albummid == null ? null:albummid.trim();
}
public void setCommend(String commend) {
this.commend = commend == null ? null : commend.trim();
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword == null ? null : keyword.trim();
}
} |
package queue;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.SimpleTimeZone;
public class QueueElement<T> {
public final String worker;
public final T element;
public final Date date;
final static DateFormat dateFormat;
static {
dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
dateFormat.setTimeZone(new SimpleTimeZone(0, "GMT"));
}
public QueueElement(String worker, T element, Date date) {
this.worker = worker;
this.element = element;
this.date = date;
}
@Override
public String toString() {
return worker + "\t" + element + "\t" + dateFormat.format(date);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (this.getClass() != obj.getClass())
return false;
QueueElement<?> other = (QueueElement<?>) obj;
if (this.element == null) {
if (other.element != null)
return false;
} else if (!element.equals(other.element))
return false;
return true;
}
@SuppressWarnings("unchecked")
public static <U> QueueElement<U> fromString(String string) {
String[] parts = string.split("\t", -1);
Date date = null;
try {
date = dateFormat.parse(parts[2]);
} catch (ParseException e) {
e.printStackTrace();
}
return new QueueElement<U>(parts[0], (U) parts[1], date);
}
}
|
package junit.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.hb.framework.superhelp.util.Md5Tool;
import com.hb.framework.superhelp.util.PageView;
import com.hb.framework.system.entity.BaseData;
import com.hb.framework.system.service.BaseDataService;
import com.hb.framework.system.service.ResourcesService;
public class ResourcesServiceImplTest {
private ResourcesService resourcesService;
@Test
public void test() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-*.xml");
/* ResourcesService bean = (ResourcesService)ctx.getBean("resourcesService");
bean.findAll();
bean.getById("1");
bean.getUserResources("1");
BaseDataService beans = (BaseDataService)ctx.getBean("baseDataService");
PageView pageView=new PageView(10,1);
beans.query(pageView, new BaseData());
//List lists=list.getRecords();
System.out.println(Md5Tool.getMd5("admin"));
System.out.println(Md5Tool.getMd5("123"));
System.out.println(Md5Tool.getMd5("hsc"));*/
}
}
|
package com.sinodynamic.hkgta.scheduler.job;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.web.context.WebApplicationContext;
import com.sinodynamic.hkgta.service.mms.SpaAppointmentRecService;
public class SpaAppointmentBeginNotificationTask extends QuartzJobBean implements ApplicationContextAware{
private final Logger logger = LoggerFactory.getLogger(SpaAppointmentBeginNotificationTask.class);
WebApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.applicationContext = (WebApplicationContext)applicationContext;
}
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
logger.debug("SpaAppointmentBeginNotificationTask run at:" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
try {
SpaAppointmentRecService spaAppointmentRecService = applicationContext.getBean(SpaAppointmentRecService.class);
spaAppointmentRecService.spaAppointmentBeginNotification();
} catch (Exception e) {
e.printStackTrace();
logger.error(e.toString(), e);
}
logger.info("SpaAppointmentBeginNotificationTask execute end ...");
}
}
|
package com.mycompany.controllers;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXTextField;
import com.mycompany.gymadmin.AbrirVentana;
import com.mycompany.interacciondb.TablaSuscriptores;
import com.mycompany.interacciondb.datos;
import com.mycompany.interacciondb.llenarTablaSuscriptores;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.function.Predicate;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.concurrent.WorkerStateEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
/**
* FXML Controller class
* @author elias
*/
public class VisualizarSuscriptorController implements Initializable {
@FXML private TableView<TablaSuscriptores> tablaUsuarios;
@FXML
private TableColumn<TablaSuscriptores, String> ColNombre, ColEdad, ColEmail,ColColonia, ColM, ColL,ColTipoSus, ColVen;
@FXML private JFXTextField Tbuscar;
@FXML private JFXButton BActualizar,BMas;
@FXML private ProgressIndicator progTabla;
@FXML private AnchorPane Pane;
@Override
public void initialize(URL url, ResourceBundle rb) {
llenarTabla(); actualizar(); seleccionar();
mas();
}
//Metodo para abrir la ventana de mas
private void mas(){
BMas.setOnAction((e)->{
datos.setId(tablaUsuarios.getSelectionModel().getSelectedItem().getId());
datos.setNombre(tablaUsuarios.getSelectionModel().getSelectedItem().getNombre());
AbrirVentana av = new AbrirVentana("/fxml/Asitencia.fxml","Suscriptor");
new Thread(av).start();
tablaUsuarios.getSelectionModel().clearSelection();
BMas.setDisable(true);
});
}
//Metodo para actualizar la tabla
private void actualizar(){
BActualizar.setOnAction((e)->{
llenarTabla();
});
}
//Metodo para seleccionar elementos en la tabla
private void seleccionar(){
tablaUsuarios.getSelectionModel().selectedItemProperty().addListener((ObservableValue<? extends TablaSuscriptores>
observable, TablaSuscriptores oldValue, TablaSuscriptores newValue) -> {
if(newValue != null){
Tbuscar.setDisable(true); BMas.setDisable(false); BActualizar.setDisable(true);
datos.setId(tablaUsuarios.getSelectionModel().getSelectedItem().getId());
}
});
Pane.addEventHandler(MouseEvent.MOUSE_PRESSED, (MouseEvent e)->{
Tbuscar.setDisable(false); BMas.setDisable(true); BActualizar.setDisable(false);
tablaUsuarios.getSelectionModel().clearSelection();
});
}
//Metodo para llenar la tabla de suscriptores
private void llenarTabla(){
Tbuscar.setDisable(true); progTabla.setVisible(true);
llenarTablaSuscriptores lts = new llenarTablaSuscriptores();
lts.addEventHandler((WorkerStateEvent.WORKER_STATE_SUCCEEDED), (WorkerStateEvent e)->{
ObservableList<TablaSuscriptores> items = lts.getValue();
tablaUsuarios.setItems(items);
ColNombre.setCellValueFactory(new PropertyValueFactory("nombre"));
ColEdad.setCellValueFactory(new PropertyValueFactory("edad"));
ColEmail.setCellValueFactory(new PropertyValueFactory("email"));
ColColonia.setCellValueFactory(new PropertyValueFactory("colonia"));
ColM.setCellValueFactory(new PropertyValueFactory("mza"));
ColL.setCellValueFactory(new PropertyValueFactory("lote"));
ColTipoSus.setCellValueFactory(new PropertyValueFactory("tipoSus"));
ColVen.setCellValueFactory(new PropertyValueFactory("fechaVen"));
FilteredList<TablaSuscriptores> datos = new FilteredList <> (items, a -> true);
Tbuscar.setOnKeyReleased((el)->{
Tbuscar.textProperty().addListener((observable, oldValue, newValue) ->{
datos.setPredicate((Predicate <? super TablaSuscriptores>) ins -> {
if(newValue == null || newValue.isEmpty()){
return true;
}
String lower = newValue.toLowerCase();
return ins.getNombre().toLowerCase().contains(lower);
});
});
});
SortedList<TablaSuscriptores> dataCam = new SortedList<>(datos);
dataCam.comparatorProperty().bind(tablaUsuarios.comparatorProperty());
tablaUsuarios.setItems(dataCam);
Tbuscar.setDisable(false); progTabla.setVisible(false);
});
new Thread(lts).start();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.