text
stringlengths 10
2.72M
|
|---|
package com.dazhi.authdemo.modules.auth.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.math.BigInteger;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CenterVOSS implements Serializable {
private static final long serialVersionUID = 1L;
// 中心id
private String centerId;
// 中心 名称
private String centerName;
// 经销商 数量
private BigInteger jxsNum;
// 合伙人数量
private BigInteger hsrNum;
// 带单数量
private BigInteger orderNum;
}
|
package com.org.serviceexport.api;
import com.org.serviceexport.service.HelloService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* Create by wangpeijian on 2018/6/22.
*/
@Slf4j
/*@RefreshScope*/
@RequestMapping("hello")
@RestController
public class Hello {
@Autowired
private HelloService helloService;
@Autowired
private RestTemplate restTemplate;
@Value("${foo}")
String foo;
@RequestMapping("user")
public String index(){
String a = "";
long time = System.currentTimeMillis();
log.info("测试超时时间起始: {}", time);
try {
a = helloService.hello("wpj");
}catch (Exception e){
log.error("测试超时时间异常: {}", System.currentTimeMillis() - time);
log.error(e.getMessage());
e.printStackTrace();
}
log.info("测试超时时间结束: {}", System.currentTimeMillis() - time);
return a;
}
@RequestMapping("config")
public String config(){
return foo;
}
@RequestMapping("rest")
public String rest(){
return restTemplate.getForObject("http://service-user/user/hello?name={1}", String.class, "zhenkeng");
}
}
|
package cn.jbit.myshopping;
import java.util.Scanner;
public class AddCust {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
System.out.println("我行我素购物会员管理系统 > 客户信息系统 > 添加客户信息\n");
System.out.print("请输入会员号(<4位整数>):");
int custNo=sc.nextInt();
System.out.print("请输入会员生日(月/日<用两位数表示>):");
String custBirth=sc.next();
System.out.print("请输入积分:");
int custScore=sc.nextInt();
if(custNo>=1000&&custNo<=9999){
System.out.println("\n已录入的会员信息是:\n"+custNo+'\t'+custBirth+'\t'+custScore);
}else System.out.println("\n客户号"+custNo+"是无效会员号!\n录入信息失败!");
}
}
|
package com.smxknife.energy.collector.core.driver;
/**
* @author smxknife
* 2021/5/12
*/
public interface Lifecycle {
default void init() {};
default void start() {};
default void stop() {};
default void terminate() {};
}
|
package com.example.ahmed.octopusmart.holders;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.example.ahmed.octopusmart.R;
import com.example.ahmed.octopusmart.View.ExpandableTextView;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by ahmed on 19/12/2017.
*/
public class UserReviewItemViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.user_review_item_date)
public TextView date;
@BindView(R.id.user_review_item_title)
public TextView title;
@BindView(R.id.user_review_item_summary)
public ExpandableTextView summary;
@BindView(R.id.expand_btn)
public TextView expand;
public UserReviewItemViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
|
package com.example.demo.hello.web;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.example.demo.common.JsonResult;
import com.example.demo.hello.entity.Hello;
import com.example.demo.hello.service.HelloService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/hellos")
public class HelloController {
@Autowired
private HelloService helloService;
@ApiOperation(value = "获得所有", notes = "")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "header", name = "Authorization", value = "token", required = true, dataType = "string"),
@ApiImplicitParam(name = "page", value = "第几页", dataType = "int", required = false, paramType = "query"),
@ApiImplicitParam(name = "size", value = "每页几条", dataType = "int", required = false, paramType = "query"),
})
@RequestMapping(method = RequestMethod.GET)
public JSONObject index(@RequestParam(required = false, defaultValue = "1") Integer page, @RequestParam(required = false, defaultValue = "5") Integer size) {
Page pageinfo = new Page(page, size);
List<Hello> hellos = helloService.findPage(pageinfo);
return JsonResult.success(hellos, pageinfo);
}
@ApiOperation(value = "获得一个", notes = "")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "header", name = "Authorization", value = "token", required = true, dataType = "string"),
@ApiImplicitParam(paramType = "path", name = "id", value = "HelloId", required = true, dataType = "long")
})
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public JSONObject show(@PathVariable Long id) {
Hello hello = helloService.findOne(id);
return JsonResult.success(hello);
}
}
|
package com.cisco.jwt_spring_boot.dao;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class AppRoleRepositoryTest {
@Test
void findByRole() {
}
}
|
package com.getlosthere.apps.peep.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.getlosthere.apps.peep.applications.TwitterApplication;
import com.getlosthere.apps.peep.helpers.NetworkHelper;
import com.getlosthere.apps.peep.models.Tweet;
import com.getlosthere.apps.peep.models.User;
import com.getlosthere.apps.peep.rest_clients.TwitterClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import cz.msebera.android.httpclient.Header;
/**
* Created by violetaria on 8/11/16.
*/
public class UserTimelineFragment extends TweetsListFragment{
private String screenName;
private TwitterClient client;
User user;
private OnLoadedListener listener;
public interface OnLoadedListener {
public void onUserProfileLoaded(User user);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnLoadedListener) {
listener = (OnLoadedListener) context;
} else {
throw new ClassCastException(context.toString() +
" must implement UserTimelineFragment.OnLoadedListener");
}
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
screenName = getArguments().getString("screen_name");
client = TwitterApplication.getRestClient();
populateHeader();
// pb.setVisibility(ProgressBar.VISIBLE);
populateTimeline(1);
// pb.setVisibility(ProgressBar.INVISIBLE);
}
public static UserTimelineFragment newInstance(String screenName) {
UserTimelineFragment fUserTimeline = new UserTimelineFragment();
Bundle args = new Bundle();
args.putString("screen_name",screenName);
fUserTimeline.setArguments(args);
return fUserTimeline;
}
public void populateHeader() {
if (NetworkHelper.isOnline() && NetworkHelper.isNetworkAvailable(getActivity())) {
if (TextUtils.isEmpty(screenName)){
client.getCurrentUserInfo( new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
user = User.findOrCreateFromJson(response);
listener.onUserProfileLoaded(user);
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Log.d("DEBUG", "STATUS CODE = " + Integer.toString(statusCode));
Log.d("DEBUG", responseString);
}
});
} else {
client.getOtherUserInfo(screenName, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
user = User.findOrCreateFromJson(response);
listener.onUserProfileLoaded(user);
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Log.d("DEBUG", "STATUS CODE = " + Integer.toString(statusCode));
Log.d("DEBUG", responseString);
}
});
}
} else {
// TODO Fix this somehow to be the user query for tweets
ArrayList<Tweet> dbTweets = Tweet.getAll();
addAll(dbTweets);
Toast.makeText(getActivity(), "You're offline, using DB. Check your network connection", Toast.LENGTH_LONG).show();
}
}
public void populateTimeline(long maxId) {
if (NetworkHelper.isOnline() && NetworkHelper.isNetworkAvailable(getActivity())) {
client.getUserTimeline(screenName, maxId, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
ArrayList<Tweet> newTweets = Tweet.fromJSONArray(response);
addAll(newTweets);
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Log.d("DEBUG", "STATUS CODE = " + Integer.toString(statusCode));
Log.d("DEBUG", responseString);
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
Log.d("DEBUG", "STATUS CODE = " + Integer.toString(statusCode));
Log.d("DEBUG", errorResponse.toString());
}
@Override
public void onUserException(Throwable error) {
Log.d("DEBUG", error.toString());
}
});
} else {
// TODO Fix this somehow to be the user query for tweets
ArrayList<Tweet> dbTweets = Tweet.getAll();
addAll(dbTweets);
Toast.makeText(getActivity(), "You're offline, using DB. Check your network connection",Toast.LENGTH_LONG).show();
}
}
}
|
package com.thoughtpropulsion.fj;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.junit.Test;
public class LambdaTest {
@FunctionalInterface
interface FI1 {
int scooby(final int x);
}
static class FC1 implements FI1 {
public int scooby(final int x) { return x + 1;}
public static int Scooby(final int x) { return x + 2;}
}
static int callWith4(final FI1 f) { return f.scooby(4);}
@Test
public void objectMethodRefLambdaEquivalenceTest() {
// this makes perfect sense
assertThat(callWith4(new FC1()), is(5));
/*
* These next two are surprising. They are both lambdas (ok).
* What's surprising is callWith4() appears to invoke the "scooby"
* method on each one in turn. Lambda's appear to respond to any
* method invocation, regardless of name. That being the case
* it seems there should be an invocation syntax that elides the name
* like just f(4) instead of f.scooby(4).
*
* see the 2012 discussion on lambda-dev: http://mail.openjdk.java.net/pipermail/lambda-dev/2012-February/004518.html
*/
assertThat(callWith4(FC1::Scooby), is(6));
assertThat(callWith4(x -> x + 3), is(7));
}
@FunctionalInterface
interface FI2 {
int shaggy(final int x);
}
static class FC2 implements FI2 {
public int shaggy(final int x) { return x + 3;}
}
@Test
public void incompatibleFunctionalInterfacesTest() {
/*
* But this doesn't compile. You might think that since FI2 is a functional
* interface, it would be usable as an FI1, the way a lambda/method reference is.
* But the compiler says FC2 cannot be converted to FI1.
* This presents a barrier to combining multiple functional libraries.
* It means if you have a lib that is defined i.t.o. some functional e.g. FI1,
* you can pass lambdas to it, but you can't pass otherwise-compatible
* objects implementing some other functional interface FI2.
* Error:(58, 32) java: incompatible types: com.thoughtpropulsion.fj.LambdaTest.FC2 cannot be converted to com.thoughtpropulsion.fj.LambdaTest.FI1
*/
//assertThat( callWith4( new FC2() ), is(7));
}
}
|
package com.asiainfo.crm.demo.dao.interfaces;
import com.ai.appframe2.util.criteria.Criteria;
import resource.so.bo.BOTempTestUserBean;
/**
* Dao接口
*/
public interface IBOTempTestUserDAO {
/**
* 新增用户
*
* @param iboTempTestUserValue
* @throws Exception
*/
void addUsers(resource.so.ivalues.IBOTempTestUserValue iboTempTestUserValue) throws Exception;
/**
* 删除用户
*
* @param boTempTestUserBeans
* @throws Exception
*/
void delUsers(BOTempTestUserBean[] boTempTestUserBeans) throws Exception;
/**
* 更新用户
*
* @param iboTempTestUserValue
* @throws Exception
*/
void updateUser(resource.so.ivalues.IBOTempTestUserValue iboTempTestUserValue) throws Exception;
/**
* 查询用户
*
* @param userId
* @return
* @throws Exception
*/
BOTempTestUserBean getUserById(long userId) throws Exception;
/**
* 查询用户列表
*
* @param sql 查询语句
* @param startNum 起始下标
* @param endNum 结束下标
* @return
* @throws Exception
*/
BOTempTestUserBean[] getUsers(Criteria sql, int startNum, int endNum) throws Exception;
/**
* 查询用户数量
*
* @param sql
* @return
* @throws Exception
*/
int getUserCount(Criteria sql) throws Exception;
}
|
package org.apache.commons.net.nntp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Vector;
import org.apache.commons.net.MalformedServerReplyException;
import org.apache.commons.net.io.DotTerminatedMessageReader;
import org.apache.commons.net.io.DotTerminatedMessageWriter;
import org.apache.commons.net.io.Util;
public class NNTPClient extends NNTP {
private void __parseArticlePointer(String reply, ArticleInfo pointer) throws MalformedServerReplyException {
String[] tokens = reply.split(" ");
if (tokens.length >= 3) {
int i = 1;
try {
pointer.articleNumber = Long.parseLong(tokens[i++]);
pointer.articleId = tokens[i++];
return;
} catch (NumberFormatException numberFormatException) {}
}
throw new MalformedServerReplyException(
"Could not parse article pointer.\nServer reply: " + reply);
}
private static void __parseGroupReply(String reply, NewsgroupInfo info) throws MalformedServerReplyException {
String[] tokens = reply.split(" ");
if (tokens.length >= 5) {
int i = 1;
try {
info._setArticleCount(Long.parseLong(tokens[i++]));
info._setFirstArticle(Long.parseLong(tokens[i++]));
info._setLastArticle(Long.parseLong(tokens[i++]));
info._setNewsgroup(tokens[i++]);
info._setPostingPermission(0);
return;
} catch (NumberFormatException numberFormatException) {}
}
throw new MalformedServerReplyException(
"Could not parse newsgroup info.\nServer reply: " + reply);
}
static NewsgroupInfo __parseNewsgroupListEntry(String entry) {
String[] tokens = entry.split(" ");
if (tokens.length < 4)
return null;
NewsgroupInfo result = new NewsgroupInfo();
int i = 0;
result._setNewsgroup(tokens[i++]);
try {
long lastNum = Long.parseLong(tokens[i++]);
long firstNum = Long.parseLong(tokens[i++]);
result._setFirstArticle(firstNum);
result._setLastArticle(lastNum);
if (firstNum == 0L && lastNum == 0L) {
result._setArticleCount(0L);
} else {
result._setArticleCount(lastNum - firstNum + 1L);
}
} catch (NumberFormatException e) {
return null;
}
switch (tokens[i++].charAt(0)) {
case 'Y':
case 'y':
result._setPostingPermission(
2);
return result;
case 'N':
case 'n':
result._setPostingPermission(3);
return result;
case 'M':
case 'm':
result._setPostingPermission(1);
return result;
}
result._setPostingPermission(0);
return result;
}
static Article __parseArticleEntry(String line) {
Article article = new Article();
article.setSubject(line);
String[] parts = line.split("\t");
if (parts.length > 6) {
int i = 0;
try {
article.setArticleNumber(Long.parseLong(parts[i++]));
article.setSubject(parts[i++]);
article.setFrom(parts[i++]);
article.setDate(parts[i++]);
article.setArticleId(parts[i++]);
article.addReference(parts[i++]);
} catch (NumberFormatException numberFormatException) {}
}
return article;
}
private NewsgroupInfo[] __readNewsgroupListing() throws IOException {
DotTerminatedMessageReader dotTerminatedMessageReader = new DotTerminatedMessageReader(this._reader_);
Vector<NewsgroupInfo> list = new Vector<>(2048);
try {
String line;
while ((line = dotTerminatedMessageReader.readLine()) != null) {
NewsgroupInfo tmp = __parseNewsgroupListEntry(line);
if (tmp != null) {
list.addElement(tmp);
continue;
}
throw new MalformedServerReplyException(line);
}
} finally {
dotTerminatedMessageReader.close();
}
int size;
if ((size = list.size()) < 1)
return new NewsgroupInfo[0];
NewsgroupInfo[] info = new NewsgroupInfo[size];
list.copyInto((Object[])info);
return info;
}
private BufferedReader __retrieve(int command, String articleId, ArticleInfo pointer) throws IOException {
if (articleId != null) {
if (!NNTPReply.isPositiveCompletion(sendCommand(command, articleId)))
return null;
} else if (!NNTPReply.isPositiveCompletion(sendCommand(command))) {
return null;
}
if (pointer != null)
__parseArticlePointer(getReplyString(), pointer);
return (BufferedReader)new DotTerminatedMessageReader(this._reader_);
}
private BufferedReader __retrieve(int command, long articleNumber, ArticleInfo pointer) throws IOException {
if (!NNTPReply.isPositiveCompletion(sendCommand(command,
Long.toString(articleNumber))))
return null;
if (pointer != null)
__parseArticlePointer(getReplyString(), pointer);
return (BufferedReader)new DotTerminatedMessageReader(this._reader_);
}
public BufferedReader retrieveArticle(String articleId, ArticleInfo pointer) throws IOException {
return __retrieve(0, articleId, pointer);
}
public Reader retrieveArticle(String articleId) throws IOException {
return retrieveArticle(articleId, (ArticleInfo)null);
}
public Reader retrieveArticle() throws IOException {
return retrieveArticle((String)null);
}
public BufferedReader retrieveArticle(long articleNumber, ArticleInfo pointer) throws IOException {
return __retrieve(0, articleNumber, pointer);
}
public BufferedReader retrieveArticle(long articleNumber) throws IOException {
return retrieveArticle(articleNumber, (ArticleInfo)null);
}
public BufferedReader retrieveArticleHeader(String articleId, ArticleInfo pointer) throws IOException {
return __retrieve(3, articleId, pointer);
}
public Reader retrieveArticleHeader(String articleId) throws IOException {
return retrieveArticleHeader(articleId, (ArticleInfo)null);
}
public Reader retrieveArticleHeader() throws IOException {
return retrieveArticleHeader((String)null);
}
public BufferedReader retrieveArticleHeader(long articleNumber, ArticleInfo pointer) throws IOException {
return __retrieve(3, articleNumber, pointer);
}
public BufferedReader retrieveArticleHeader(long articleNumber) throws IOException {
return retrieveArticleHeader(articleNumber, (ArticleInfo)null);
}
public BufferedReader retrieveArticleBody(String articleId, ArticleInfo pointer) throws IOException {
return __retrieve(1, articleId, pointer);
}
public Reader retrieveArticleBody(String articleId) throws IOException {
return retrieveArticleBody(articleId, (ArticleInfo)null);
}
public Reader retrieveArticleBody() throws IOException {
return retrieveArticleBody((String)null);
}
public BufferedReader retrieveArticleBody(long articleNumber, ArticleInfo pointer) throws IOException {
return __retrieve(1, articleNumber, pointer);
}
public BufferedReader retrieveArticleBody(long articleNumber) throws IOException {
return retrieveArticleBody(articleNumber, (ArticleInfo)null);
}
public boolean selectNewsgroup(String newsgroup, NewsgroupInfo info) throws IOException {
if (!NNTPReply.isPositiveCompletion(group(newsgroup)))
return false;
if (info != null)
__parseGroupReply(getReplyString(), info);
return true;
}
public boolean selectNewsgroup(String newsgroup) throws IOException {
return selectNewsgroup(newsgroup, (NewsgroupInfo)null);
}
public String listHelp() throws IOException {
if (!NNTPReply.isInformational(help()))
return null;
StringWriter help = new StringWriter();
DotTerminatedMessageReader dotTerminatedMessageReader = new DotTerminatedMessageReader(this._reader_);
Util.copyReader((Reader)dotTerminatedMessageReader, help);
dotTerminatedMessageReader.close();
help.close();
return help.toString();
}
public String[] listOverviewFmt() throws IOException {
if (!NNTPReply.isPositiveCompletion(sendCommand("LIST", "OVERVIEW.FMT")))
return null;
DotTerminatedMessageReader dotTerminatedMessageReader = new DotTerminatedMessageReader(this._reader_);
ArrayList<String> list = new ArrayList<>();
String line;
while ((line = dotTerminatedMessageReader.readLine()) != null)
list.add(line);
dotTerminatedMessageReader.close();
return list.<String>toArray(new String[list.size()]);
}
public boolean selectArticle(String articleId, ArticleInfo pointer) throws IOException {
if (articleId != null) {
if (!NNTPReply.isPositiveCompletion(stat(articleId)))
return false;
} else if (!NNTPReply.isPositiveCompletion(stat())) {
return false;
}
if (pointer != null)
__parseArticlePointer(getReplyString(), pointer);
return true;
}
public boolean selectArticle(String articleId) throws IOException {
return selectArticle(articleId, (ArticleInfo)null);
}
public boolean selectArticle(ArticleInfo pointer) throws IOException {
return selectArticle((String)null, pointer);
}
public boolean selectArticle(long articleNumber, ArticleInfo pointer) throws IOException {
if (!NNTPReply.isPositiveCompletion(stat(articleNumber)))
return false;
if (pointer != null)
__parseArticlePointer(getReplyString(), pointer);
return true;
}
public boolean selectArticle(long articleNumber) throws IOException {
return selectArticle(articleNumber, (ArticleInfo)null);
}
public boolean selectPreviousArticle(ArticleInfo pointer) throws IOException {
if (!NNTPReply.isPositiveCompletion(last()))
return false;
if (pointer != null)
__parseArticlePointer(getReplyString(), pointer);
return true;
}
public boolean selectPreviousArticle() throws IOException {
return selectPreviousArticle((ArticleInfo)null);
}
public boolean selectNextArticle(ArticleInfo pointer) throws IOException {
if (!NNTPReply.isPositiveCompletion(next()))
return false;
if (pointer != null)
__parseArticlePointer(getReplyString(), pointer);
return true;
}
public boolean selectNextArticle() throws IOException {
return selectNextArticle((ArticleInfo)null);
}
public NewsgroupInfo[] listNewsgroups() throws IOException {
if (!NNTPReply.isPositiveCompletion(list()))
return null;
return __readNewsgroupListing();
}
public Iterable<String> iterateNewsgroupListing() throws IOException {
if (NNTPReply.isPositiveCompletion(list()))
return new ReplyIterator(this._reader_);
throw new IOException("LIST command failed: " + getReplyString());
}
public Iterable<NewsgroupInfo> iterateNewsgroups() throws IOException {
return new NewsgroupIterator(iterateNewsgroupListing());
}
public NewsgroupInfo[] listNewsgroups(String wildmat) throws IOException {
if (!NNTPReply.isPositiveCompletion(listActive(wildmat)))
return null;
return __readNewsgroupListing();
}
public Iterable<String> iterateNewsgroupListing(String wildmat) throws IOException {
if (NNTPReply.isPositiveCompletion(listActive(wildmat)))
return new ReplyIterator(this._reader_);
throw new IOException("LIST ACTIVE " + wildmat + " command failed: " + getReplyString());
}
public Iterable<NewsgroupInfo> iterateNewsgroups(String wildmat) throws IOException {
return new NewsgroupIterator(iterateNewsgroupListing(wildmat));
}
public NewsgroupInfo[] listNewNewsgroups(NewGroupsOrNewsQuery query) throws IOException {
if (!NNTPReply.isPositiveCompletion(newgroups(
query.getDate(), query.getTime(),
query.isGMT(), query.getDistributions())))
return null;
return __readNewsgroupListing();
}
public Iterable<String> iterateNewNewsgroupListing(NewGroupsOrNewsQuery query) throws IOException {
if (NNTPReply.isPositiveCompletion(newgroups(
query.getDate(), query.getTime(),
query.isGMT(), query.getDistributions())))
return new ReplyIterator(this._reader_);
throw new IOException("NEWGROUPS command failed: " + getReplyString());
}
public Iterable<NewsgroupInfo> iterateNewNewsgroups(NewGroupsOrNewsQuery query) throws IOException {
return new NewsgroupIterator(iterateNewNewsgroupListing(query));
}
public String[] listNewNews(NewGroupsOrNewsQuery query) throws IOException {
if (!NNTPReply.isPositiveCompletion(
newnews(query.getNewsgroups(), query.getDate(), query.getTime(),
query.isGMT(), query.getDistributions())))
return null;
Vector<String> list = new Vector<>();
DotTerminatedMessageReader dotTerminatedMessageReader = new DotTerminatedMessageReader(this._reader_);
try {
String line;
while ((line = dotTerminatedMessageReader.readLine()) != null)
list.addElement(line);
} finally {
dotTerminatedMessageReader.close();
}
int size = list.size();
if (size < 1)
return new String[0];
String[] result = new String[size];
list.copyInto((Object[])result);
return result;
}
public Iterable<String> iterateNewNews(NewGroupsOrNewsQuery query) throws IOException {
if (NNTPReply.isPositiveCompletion(newnews(
query.getNewsgroups(), query.getDate(), query.getTime(),
query.isGMT(), query.getDistributions())))
return new ReplyIterator(this._reader_);
throw new IOException("NEWNEWS command failed: " + getReplyString());
}
public boolean completePendingCommand() throws IOException {
return NNTPReply.isPositiveCompletion(getReply());
}
public Writer postArticle() throws IOException {
if (!NNTPReply.isPositiveIntermediate(post()))
return null;
return (Writer)new DotTerminatedMessageWriter(this._writer_);
}
public Writer forwardArticle(String articleId) throws IOException {
if (!NNTPReply.isPositiveIntermediate(ihave(articleId)))
return null;
return (Writer)new DotTerminatedMessageWriter(this._writer_);
}
public boolean logout() throws IOException {
return NNTPReply.isPositiveCompletion(quit());
}
public boolean authenticate(String username, String password) throws IOException {
int replyCode = authinfoUser(username);
if (replyCode == 381) {
replyCode = authinfoPass(password);
if (replyCode == 281) {
this._isAllowedToPost = true;
return true;
}
}
return false;
}
private BufferedReader __retrieveArticleInfo(String articleRange) throws IOException {
if (!NNTPReply.isPositiveCompletion(xover(articleRange)))
return null;
return (BufferedReader)new DotTerminatedMessageReader(this._reader_);
}
public BufferedReader retrieveArticleInfo(long articleNumber) throws IOException {
return __retrieveArticleInfo(Long.toString(articleNumber));
}
public BufferedReader retrieveArticleInfo(long lowArticleNumber, long highArticleNumber) throws IOException {
return
__retrieveArticleInfo(String.valueOf(lowArticleNumber) + "-" +
highArticleNumber);
}
public Iterable<Article> iterateArticleInfo(long lowArticleNumber, long highArticleNumber) throws IOException {
BufferedReader info = retrieveArticleInfo(lowArticleNumber, highArticleNumber);
if (info == null)
throw new IOException("XOVER command failed: " + getReplyString());
return new ArticleIterator(new ReplyIterator(info, false));
}
private BufferedReader __retrieveHeader(String header, String articleRange) throws IOException {
if (!NNTPReply.isPositiveCompletion(xhdr(header, articleRange)))
return null;
return (BufferedReader)new DotTerminatedMessageReader(this._reader_);
}
public BufferedReader retrieveHeader(String header, long articleNumber) throws IOException {
return __retrieveHeader(header, Long.toString(articleNumber));
}
public BufferedReader retrieveHeader(String header, long lowArticleNumber, long highArticleNumber) throws IOException {
return
__retrieveHeader(header, String.valueOf(lowArticleNumber) + "-" + highArticleNumber);
}
@Deprecated
public Reader retrieveHeader(String header, int lowArticleNumber, int highArticleNumber) throws IOException {
return retrieveHeader(header, lowArticleNumber, highArticleNumber);
}
@Deprecated
public Reader retrieveArticleInfo(int lowArticleNumber, int highArticleNumber) throws IOException {
return retrieveArticleInfo(lowArticleNumber, highArticleNumber);
}
@Deprecated
public Reader retrieveHeader(String a, int b) throws IOException {
return retrieveHeader(a, b);
}
@Deprecated
public boolean selectArticle(int a, ArticlePointer ap) throws IOException {
ArticleInfo ai = __ap2ai(ap);
boolean b = selectArticle(a, ai);
__ai2ap(ai, ap);
return b;
}
@Deprecated
public Reader retrieveArticleInfo(int lowArticleNumber) throws IOException {
return retrieveArticleInfo(lowArticleNumber);
}
@Deprecated
public boolean selectArticle(int a) throws IOException {
return selectArticle(a);
}
@Deprecated
public Reader retrieveArticleHeader(int a) throws IOException {
return retrieveArticleHeader(a);
}
@Deprecated
public Reader retrieveArticleHeader(int a, ArticlePointer ap) throws IOException {
ArticleInfo ai = __ap2ai(ap);
Reader rdr = retrieveArticleHeader(a, ai);
__ai2ap(ai, ap);
return rdr;
}
@Deprecated
public Reader retrieveArticleBody(int a) throws IOException {
return retrieveArticleBody(a);
}
@Deprecated
public Reader retrieveArticle(int articleNumber, ArticlePointer pointer) throws IOException {
ArticleInfo ai = __ap2ai(pointer);
Reader rdr = retrieveArticle(articleNumber, ai);
__ai2ap(ai, pointer);
return rdr;
}
@Deprecated
public Reader retrieveArticle(int articleNumber) throws IOException {
return retrieveArticle(articleNumber);
}
@Deprecated
public Reader retrieveArticleBody(int a, ArticlePointer ap) throws IOException {
ArticleInfo ai = __ap2ai(ap);
Reader rdr = retrieveArticleBody(a, ai);
__ai2ap(ai, ap);
return rdr;
}
@Deprecated
public Reader retrieveArticle(String articleId, ArticlePointer pointer) throws IOException {
ArticleInfo ai = __ap2ai(pointer);
Reader rdr = retrieveArticle(articleId, ai);
__ai2ap(ai, pointer);
return rdr;
}
@Deprecated
public Reader retrieveArticleBody(String articleId, ArticlePointer pointer) throws IOException {
ArticleInfo ai = __ap2ai(pointer);
Reader rdr = retrieveArticleBody(articleId, ai);
__ai2ap(ai, pointer);
return rdr;
}
@Deprecated
public Reader retrieveArticleHeader(String articleId, ArticlePointer pointer) throws IOException {
ArticleInfo ai = __ap2ai(pointer);
Reader rdr = retrieveArticleHeader(articleId, ai);
__ai2ap(ai, pointer);
return rdr;
}
@Deprecated
public boolean selectArticle(String articleId, ArticlePointer pointer) throws IOException {
ArticleInfo ai = __ap2ai(pointer);
boolean b = selectArticle(articleId, ai);
__ai2ap(ai, pointer);
return b;
}
@Deprecated
public boolean selectArticle(ArticlePointer pointer) throws IOException {
ArticleInfo ai = __ap2ai(pointer);
boolean b = selectArticle(ai);
__ai2ap(ai, pointer);
return b;
}
@Deprecated
public boolean selectNextArticle(ArticlePointer pointer) throws IOException {
ArticleInfo ai = __ap2ai(pointer);
boolean b = selectNextArticle(ai);
__ai2ap(ai, pointer);
return b;
}
@Deprecated
public boolean selectPreviousArticle(ArticlePointer pointer) throws IOException {
ArticleInfo ai = __ap2ai(pointer);
boolean b = selectPreviousArticle(ai);
__ai2ap(ai, pointer);
return b;
}
private ArticleInfo __ap2ai(ArticlePointer ap) {
if (ap == null)
return null;
ArticleInfo ai = new ArticleInfo();
return ai;
}
private void __ai2ap(ArticleInfo ai, ArticlePointer ap) {
if (ap != null) {
ap.articleId = ai.articleId;
ap.articleNumber = (int)ai.articleNumber;
}
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\apache\commons\net\nntp\NNTPClient.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package lesson29.Ex5;
import lesson25.Ex5.Comparator.SortById;
import lesson25.Ex5.Comparator.SortByIdDown;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class Run {
public static void main(String[] args) {
var input = new Scanner(System.in);
String fileName = "EMP.txt";
int choice = 0;
ArrayList<Employee> employees = new ArrayList<>(readFromFile(fileName));
updateEmpId(employees);
do {
System.out.println("1. Thêm mới một nhân viên");
System.out.println("2. Hiển thị thông tin nhân viên");
System.out.println("3. Tìm nhân viên theo tên");
System.out.println("4. Tìm nhân viên có mức lương lớn hơn mức lương định mức");
System.out.println("5. Tìm giám đốc theo nhiệm kỳ");
System.out.println("6. Xóa nhân viên theo mã cho trước");
System.out.println("7. Tính lương cho nhân viên");
System.out.println("8. Tính thưởng cho nhân viên");
System.out.println("9. Hiển thị bảng lương nhân viên");
System.out.println("10. Sắp xếp danh sách nhân viên");
System.out.println("11. Hiển thị danh sách nhân viên ra file");
System.out.println("============= Vui lòng chọn =============");
choice = Integer.parseInt(input.nextLine());
switch (choice) {
case 0:
showNoti("Đã thoát chương trình");
break;
case 1:
System.out.println("(1) Thêm một nhân viên, (2) Thêm một giám đốc");
var option = Integer.parseInt(input.nextLine());
if (option == 1) {
var newEmp = createEmployee(input);
employees.add(newEmp);
showNoti("Thêm thành công một nhân viên");
} else if (option == 2) {
var newManager = createManager(input);
employees.add(newManager);
showNoti("Thêm thành công một giám đốc");
}
break;
case 2:
if (employees.size() > 0) {
showNoti("Danh sách nhân viên");
showEmployee(employees);
} else {
showNoti("Danh sách trống");
}
break;
case 3:
if (employees.size() > 0) {
System.out.println("Nhập tên cần tìm: ");
var first = input.nextLine();
var result = searchByName(employees, first);
if (result.size() > 0) {
System.out.println("Có " + result.size() + " kết quả");
showEmployee(result);
} else {
showNoti("Không tìm thấy kết quả");
}
} else {
showNoti("Danh sách trống");
}
break;
case 4:
if (employees.size() > 0) {
System.out.println("Nhập mức lương: ");
var amount = Float.parseFloat(input.nextLine());
var result = searchByWages(employees, amount);
if (result.size() > 0) {
System.out.println("Có " + result.size() + " kết quả");
showEmployee(result);
} else {
showNoti("Không tìm thấy kết quả");
}
} else {
showNoti("Danh sách trống");
}
break;
case 5:
if (employees.size() > 0) {
System.out.println("Năm bắt đầu: ");
var startYear = Integer.parseInt(input.nextLine());
System.out.println("Năm kết thúc: ");
var endYear = Integer.parseInt(input.nextLine());
var result = searchByYear(employees, startYear, endYear);
if (result.size() > 0) {
System.out.println("Có " + result.size() + " kết quả");
showEmployee(result);
} else {
showNoti("Không tìm thấy kết quả");
}
} else {
showNoti("Danh sách trống");
}
break;
case 6:
if (employees.size() > 0) {
System.out.println("Nhập mã nhân viên cần xóa: ");
var id = input.nextLine();
var delete = searchById(employees, id);
if (delete) {
showNoti("Xóa thành công");
} else {
showNoti("Xóa không thành công");
}
} else {
showNoti("Danh sách trống");
}
break;
case 7:
if (employees.size() > 0) {
calculatorWagesMethod(employees);
} else {
showNoti("Danh sách trống");
}
break;
case 8:
if (employees.size() > 0) {
calculatorBonusMethod(employees);
} else {
showNoti("Danh sách trống");
}
break;
case 9:
if (employees.size() > 0) {
showPayrolls(employees);
} else {
showNoti("Danh sách trống");
}
break;
case 10:
if (employees.size() > 0) {
showNoti("(1) sắp xếp từ a-z\n(2) sắp xếp từ z-a");
var pick = Integer.parseInt(input.nextLine());
if (pick == 1) {
Collections.sort(employees, new SortById());
showEmployee(employees);
} else if (pick == 2) {
Collections.sort(employees, new SortByIdDown());
showEmployee(employees);
} else {
showNoti("Sai cú pháp, vui lòng chọn lại");
}
}
break;
case 11:
if (employees.size() > 0) {
var isSuccess = writeToFile(employees, fileName);
if (isSuccess) {
showNoti("Ghi file thành công");
} else {
showNoti("Ghi file thất bại");
}
}
break;
default:
showNoti("Sai cú pháp, vui lòng nhập lại");
break;
}
} while (choice != 0);
}
/**
* ghi thông tin danh sách nhân viên vào file
* @param employees
* @return true nếu ghi thành công và false nếu ngược lại
*/
private static boolean writeToFile(ArrayList<Employee> employees, String fileName) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
try {
PrintWriter printWriter = new PrintWriter(fileName);
for (var emp : employees) {
if (emp instanceof Manager) {
printWriter.printf("%s - %s - %s - %s - %s - %s - %s " +
"- %s - %s - %s - %s - %s - %s - %s - %s\n",
emp.getIdCard(), emp.getFullName(), emp.getAddress(),
emp.getDayOfBirth(), emp.getEmail(), emp.getPhoneNumber(),
emp.getIdEmp(), emp.getPosition(), emp.getBasicWages(),
emp.getExperience(), emp.getDayOntheMonth(),
emp.getWages(), emp.getBonus(),
((Manager) emp).getStartDay(), ((Manager) emp).getEndDay());
} else {
printWriter.printf("%s - %s - %s - %s - %s - %s - %s " +
"- %s - %s - %s - %s - %s - %s\n", emp.getIdCard(),
emp.getFullName(), emp.getAddress(),
emp.getDayOfBirth(), emp.getEmail(), emp.getPhoneNumber(),
emp.getIdEmp(), emp.getPosition(), emp.getBasicWages(),
emp.getExperience(), emp.getDayOntheMonth(),
emp.getWages(), emp.getBonus());
}
}
printWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* Cập nhật mã nhân viên mới để không bị đè lên nv cũ
* @param employees
*/
private static void updateEmpId(ArrayList<Employee> employees) {
var maxId = 1000; //giả sử ban đầu danh sách rỗng
for (var emp : employees) {
var currentId = Integer.parseInt(emp.getIdEmp().substring(3));
if (currentId > maxId) {
maxId = currentId;
}
}
Employee.setNextId(maxId + 1);
}
/**
* đọc dữ liệu từ file ra màn hình
* @param fileName
* @return
*/
private static ArrayList<Employee> readFromFile(String fileName) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
ArrayList<Employee> employees = new ArrayList<>();
var file = new File(fileName);
try {
file.createNewFile(); //tạo file
var input = new Scanner(file); //đọc file
while (input.hasNextLine()) {
var line = input.nextLine();
String[] data = line.split(" - ");
Employee employee = createEmpFromData(data, dateFormat);
if (employee != null) {
employees.add(employee);
}
}
input.close();
} catch (IOException e) {
e.printStackTrace();
}
return employees;
}
private static Employee createEmpFromData(String[] data,
SimpleDateFormat dateFormat) {
var idCard = data[0];
var fullName = data[1];
var address = data[2];
Date dob = null;
try {
dob = dateFormat.parse(data[3]);
} catch (ParseException e) {
e.printStackTrace();
}
var email = data[4];
var phone = data[5];
var idEmp = data[6];
var posi = data[7];
var basicWage = Float.parseFloat(data[8]);
var exp = Float.parseFloat(data[9]);
var dom = Integer.parseInt(data[10]);
var wages = Float.parseFloat(data[11]);
var bonus = Float.parseFloat(data[12]);
Date start = null;
Date end = null;
if (data.length > 13) {
try {
start = dateFormat.parse(data[13]);
end = dateFormat.parse(data[14]);
Manager manager = new Manager(idCard, fullName, address,
dob, email, phone, idEmp, posi, basicWage,
exp, dom, wages, bonus, start, end);
return manager;
} catch (ParseException e) {
e.printStackTrace();
}
} else {
Employee employee = new Employee(idCard, fullName, address,
dob, email, phone, idEmp, posi, basicWage,
exp, dom, wages, bonus);
return employee;
}
return null;
}
/**
* hiển thị bảng lương
* @param employees
*/
private static void showPayrolls(ArrayList<Employee> employees) {
System.out.printf("%-17s %-14s %-21s %-17s %-11s %-15s\n", "Mã nhân viên",
"Họ và tên", "Số ngày làm việc", "Lương cứng", "Thưởng", "Tổng lương");
for (var emp : employees) {
System.out.printf("%-17s %-14s %-21d %-17.1f %-11.1f %-15.1f\n",
emp.getIdEmp(), emp.getFullName(), emp.getDayOntheMonth(),
emp.getBasicWages(), emp.getBonus(), emp.getWages());
}
}
/**
* tính thưởng nhân viên
* @param employees
*/
private static void calculatorBonusMethod(ArrayList<Employee> employees) {
for (var emp : employees) {
emp.calcularBonus();
}
}
/**
* tính lương cho nhân viên
* @param employees
*/
private static void calculatorWagesMethod(ArrayList<Employee> employees) {
for (var emp : employees) {
emp.calcularWages();
}
}
/**
* xóa nhân viên theo mã
*/
private static boolean searchById(ArrayList<Employee> employees, String id) {
for (var emp : employees) {
if (emp.getIdEmp().compareToIgnoreCase(id) == 0) {
employees.remove(emp);
return true;
}
}
return false;
}
/**
* Tìm giám đốc có nhiệm kỳ thuộc khoảng xđ
* @param employees
* @param startYear
* @param endYear
* @return
*/
private static ArrayList<Employee> searchByYear(ArrayList<Employee> employees, int startYear, int endYear) {
ArrayList<Employee> res = new ArrayList<>();
Calendar calendar = Calendar.getInstance(); //khởi tạo của lớp Calendar
for (var emp : employees) {
if (emp instanceof Manager) {
var manager = (Manager) emp;
calendar.setTime(manager.getStartDay());
var start = calendar.get(Calendar.YEAR);
calendar.setTime(manager.getEndDay());
var end = calendar.get(Calendar.YEAR);
if (startYear >= start && endYear <= end) {
res.add(emp);
}
}
}
return res;
}
/**
* tìm kiếm nv theo mức lương
* @param employees
* @param amount
* @return
*/
private static ArrayList<Employee> searchByWages(ArrayList<Employee> employees, float amount) {
ArrayList<Employee> res = new ArrayList<>();
for (var emp : employees) {
if (emp.getBasicWages() >= amount) {
res.add(emp);
}
}
return res;
}
private static ArrayList<Employee> searchByName(ArrayList<Employee> employees, String first) {
ArrayList<Employee> res = new ArrayList<>();
for (var emp : employees) {
if (emp.getFullNameStr().getFirstName().compareToIgnoreCase(first) == 0) {
res.add(emp);
}
}
return res;
}
/**
* hiển thị danh sách nhân viên
* @param employees
*/
private static void showEmployee(ArrayList<Employee> employees) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.printf("%-20s %-18s %-15s %-16s %-16s %-18s %-17s %-11s %-11s\n",
"Số thẻ căn cước", "Họ và Tên", "Địa chỉ", "Ngày sinh",
"Email", "Số điện thoại", "Mã nhân viên", "Vị trí", "Kinh nghiệm");
for (var emp : employees) {
System.out.printf("%-20s %-18s %-15s %-16s %-16s %-18s %-17s %-11s %-11.1f\n",
emp.getIdCard(), emp.getFullName(), emp.getAddress(),
dateFormat.format(emp.getDayOfBirth()), emp.getEmail(),
emp.getPhoneNumber(), emp.getIdEmp(), emp.getPosition(),
emp.getExperience());
}
}
/**
* tạo mới một giám đốc
* @param input
* @return
*/
private static Manager createManager(Scanner input) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Employee employee = createEmployee(input);
System.out.println("Ngày bắt đầu nhiệm kỳ: ");
Date start = null;
try {
start = dateFormat.parse(input.nextLine());
} catch (ParseException e) {
e.printStackTrace();
start = new Date();
}
System.out.println("Ngày kết thúc nhiệm kỳ: ");
Date end = null;
try {
end = dateFormat.parse(input.nextLine());
} catch (ParseException e) {
e.printStackTrace();
end = new Date();
}
Manager manager = new Manager(employee, start, end);
return manager;
}
/**
* tạo mới một nhân viên
* @param input
* @return
*/
private static Employee createEmployee(Scanner input) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println("Số thẻ căn cước: ");
var idCard = input.nextLine();
System.out.println("Họ và Tên: ");
var name = input.nextLine();
System.out.println("Địa chỉ: ");
var address = input.nextLine();
System.out.println("Ngày sinh: ");
Date dob = null;
try {
dob = dateFormat.parse(input.nextLine());
} catch (ParseException e) {
e.printStackTrace();
dob = new Date();
}
System.out.println("Email: ");
var mail = input.nextLine();
System.out.println("Số điện thoại: ");
var phone = input.nextLine();
System.out.println("Vị trí: ");
var posi = input.nextLine();
System.out.println("Mức lương: ");
var basicWages = Float.parseFloat(input.nextLine());
System.out.println("Kinh nghiệm: ");
var exp = Float.parseFloat(input.nextLine());
System.out.println("Số ngày làm trong tháng: ");
var day = Integer.parseInt(input.nextLine());
Employee employee = new Employee(idCard, name, address, dob,
mail, phone, null, posi, basicWages, exp, day);
return employee;
}
/**
* hiển thị nội dung thông báo
* @param str
*/
private static void showNoti(String str) {
System.out.println(">>>>>>>>>> " + str + " <<<<<<<<<<");
}
}
|
package com.vic.common.base.result.dtos.req.online;
import java.io.Serializable;
/**
* @classname: BaseRequestEnter
* @description: 基础封装请求参数
* @author: Vayne.Luo
* @date 2019/3/13 16:29
*/
public class BaseRequestEnter implements Serializable{
private static final long serialVersionUID = 4606804421223688087L;
}
|
package com.tencent.mm.plugin.account.friend.ui;
import com.tencent.mm.plugin.account.friend.ui.d.a;
class QQFriendUI$3 implements a {
final /* synthetic */ QQFriendUI eMV;
QQFriendUI$3(QQFriendUI qQFriendUI) {
this.eMV = qQFriendUI;
}
public final void ja(int i) {
if (QQFriendUI.a(this.eMV)) {
if (i > 0) {
QQFriendUI.b(this.eMV).setVisibility(8);
} else {
QQFriendUI.b(this.eMV).setVisibility(0);
}
}
QQFriendUI.a(this.eMV, false);
}
}
|
package me433.tanay.mycam;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.TextureView;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.SeekBar;
import java.io.IOException;
import static android.graphics.Color.blue;
import static android.graphics.Color.green;
import static android.graphics.Color.red;
import static android.graphics.Color.rgb;
public class MainActivity extends Activity implements TextureView.SurfaceTextureListener {
private Camera mCamera;
private TextureView mTextureView;
private SurfaceView mSurfaceView;
private SurfaceHolder mSurfaceHolder;
private Bitmap bmp = Bitmap.createBitmap(640,480,Bitmap.Config.ARGB_8888);
private Canvas canvas = new Canvas(bmp);
private Paint paint1 = new Paint();
private TextView mTextView;
SeekBar myControl1;
SeekBar myControl2;
SeekBar myControl3;
TextView sliderTextView;
static long prevtime = 0; // for FPS calculation
static int thresh1 = 53; // for getting threshold from slider
static int thresh2 = 188; // for getting threshold from slider
static int thresh3 = 68; // for getting threshold from slider
static int dist = 0; // px dist from center (320)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // keeps the screen from turning off
mSurfaceView = (SurfaceView) findViewById(R.id.surfaceview);
mSurfaceHolder = mSurfaceView.getHolder();
mTextureView = (TextureView) findViewById(R.id.textureview);
mTextureView.setSurfaceTextureListener(this);
mTextView = (TextView) findViewById(R.id.cameraStatus);
paint1.setColor(0xffff0000); // red
paint1.setTextSize(24);
myControl1 = (SeekBar) findViewById(R.id.seek1);
myControl2 = (SeekBar) findViewById(R.id.seek2);
myControl3 = (SeekBar) findViewById(R.id.seek3);
sliderTextView = (TextView) findViewById(R.id.sliderStatus);
sliderTextView.setText("Enter RGB thresholds");
setMyControlListener();
}
public void setMyControlListener() {
myControl1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
thresh1 = progress;
sliderTextView.setText("RGB thresholds are: "+thresh1+" "+thresh2+" "+thresh3);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
myControl2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
thresh2 = progress;
sliderTextView.setText("RGB thresholds are: "+thresh1+" "+thresh2+" "+thresh3);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
myControl3.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
thresh3 = progress;
sliderTextView.setText("RGB thresholds are: "+thresh1+" "+thresh2+" "+thresh3);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
mCamera = Camera.open();
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(640, 480);
parameters.setColorEffect(Camera.Parameters.EFFECT_NONE); // black and white
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_INFINITY); // no autofocusing
// parameters.setAutoWhiteBalanceLock(true); // no auto white-balancing
mCamera.setParameters(parameters);
mCamera.setDisplayOrientation(90); // rotate to portrait mode
try {
mCamera.setPreviewTexture(surface);
mCamera.startPreview();
} catch (IOException ioe) {
// Something bad happened
}
}
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
// Ignored, Camera does all the work for us
}
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
mCamera.stopPreview();
mCamera.release();
return true;
}
// the important function
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
// Invoked every time there's a new Camera preview frame
mTextureView.getBitmap(bmp);
final Canvas c = mSurfaceHolder.lockCanvas();
if (c != null) {
int wbTotal_mid = 0; // total mass
int wbCOM_mid = 0; // total (mass time position)
for (int n = 0; n < 440; n = n+150) {
for (int j = n; j < n + 50; j++) {
int[] thresholdedColors = new int[bmp.getWidth()];
int[] pixels_mid = new int[bmp.getWidth()];
int startYmid = 30 + j; // which row in the bitmap to analyse to read
bmp.getPixels(pixels_mid, 0, bmp.getWidth(), 0, startYmid, bmp.getWidth(), 1);
int[] thresholdedPixels_mid = new int[bmp.getWidth()];
for (int i = 0; i < bmp.getWidth(); i++) {
if ((red(pixels_mid[i]) > thresh1) && (green(pixels_mid[i]) < thresh2) && (blue(pixels_mid[i]) < thresh3)) {
thresholdedPixels_mid[i] = 255;
thresholdedColors[i] = rgb(0, 255, 0);
} else {
thresholdedPixels_mid[i] = 0;
thresholdedColors[i] = rgb(0, 0, 0);
}
wbTotal_mid = wbTotal_mid + thresholdedPixels_mid[i];
wbCOM_mid = wbCOM_mid + thresholdedPixels_mid[i] * i;
}
bmp.setPixels(thresholdedColors, 0, bmp.getWidth(), 0, startYmid, bmp.getWidth(), 1);
}
}
int COM_mid;
boolean midFlag;
//watch out for divide by 0
if (wbTotal_mid<=0) {
COM_mid = bmp.getWidth()/2;
midFlag = false;
dist = 0;
}
else {
COM_mid = wbCOM_mid/wbTotal_mid;
midFlag = true;
dist = COM_mid - 320;
// String sendString = String.valueOf(dist + "\n");
// try {
// sPort.write(sendString.getBytes(),10); // 10 is the timeout (error)
// }
// catch (IOException e) {}
}
// draw a circle where you think the COM is
// also write the value as text
if (midFlag) {
canvas.drawCircle(COM_mid, 185, 5, paint1);
canvas.drawText("COM mid = " + COM_mid, 10, 230, paint1);
}
c.drawBitmap(bmp, 0, 0, null);
mSurfaceHolder.unlockCanvasAndPost(c);
// calculate the FPS to see how fast the code is running
long nowtime = System.currentTimeMillis();
long diff = nowtime - prevtime;
mTextView.setText("FPS " + 1000/diff);
prevtime = nowtime;
}
}
}
|
package com.github.bobby.design.observer;
public class ConcreteSubject extends Subject{
public void getState(){
}
public void setState(){
}
}
|
package com.ybh.front.model;
public class FapiaoWithBLOBs extends Fapiao {
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column FreeHost_Fapiao.con
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
private String con;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column FreeHost_Fapiao.usercodeinfo
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
private String usercodeinfo;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column FreeHost_Fapiao.admcodeinfo
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
private String admcodeinfo;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column FreeHost_Fapiao.con
*
* @return the value of FreeHost_Fapiao.con
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public String getCon() {
return con;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column FreeHost_Fapiao.con
*
* @param con the value for FreeHost_Fapiao.con
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setCon(String con) {
this.con = con == null ? null : con.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column FreeHost_Fapiao.usercodeinfo
*
* @return the value of FreeHost_Fapiao.usercodeinfo
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public String getUsercodeinfo() {
return usercodeinfo;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column FreeHost_Fapiao.usercodeinfo
*
* @param usercodeinfo the value for FreeHost_Fapiao.usercodeinfo
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setUsercodeinfo(String usercodeinfo) {
this.usercodeinfo = usercodeinfo == null ? null : usercodeinfo.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column FreeHost_Fapiao.admcodeinfo
*
* @return the value of FreeHost_Fapiao.admcodeinfo
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public String getAdmcodeinfo() {
return admcodeinfo;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column FreeHost_Fapiao.admcodeinfo
*
* @param admcodeinfo the value for FreeHost_Fapiao.admcodeinfo
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setAdmcodeinfo(String admcodeinfo) {
this.admcodeinfo = admcodeinfo == null ? null : admcodeinfo.trim();
}
}
|
package co.nos.noswallet.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import java.util.UUID;
import co.nos.noswallet.model.AvailableCurrency;
import co.nos.noswallet.persistance.currency.CryptoCurrency;
import co.nos.noswallet.ui.home.v2.CurrencyPresenter;
import co.nos.noswallet.ui.settings.lockscreen.LockScreenUtil;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
/**
* Shared Preferences utility module
*/
public class SharedPreferencesUtil {
private static final String LOCAL_CURRENCY = "local_currency";
private static final String APP_INSTALL_UUID = "app_install_uuid";
private static final String CONFIRMED_SEED_BACKEDUP = "confirmed_seed_backedup";
private static final String FROM_NEW_WALLET = "from_new_wallet";
private final SharedPreferences preferences;
public SharedPreferencesUtil(Context context) {
preferences = PreferenceManager.getDefaultSharedPreferences(context);
}
public boolean has(String key) {
return preferences.contains(key);
}
public String get(String key, String defValue) {
return preferences.getString(key, defValue);
}
public Observable<String> observe(final String observedKey) {
return Observable.create(emitter -> {
final SharedPreferences.OnSharedPreferenceChangeListener listener = (sharedPreferences, keyAffected) -> {
if (!emitter.isDisposed() && observedKey.equals(keyAffected)) {
emitter.onNext(keyAffected);
}
};
emitter.setCancellable(() -> preferences.unregisterOnSharedPreferenceChangeListener(listener));
preferences.registerOnSharedPreferenceChangeListener(listener);
});
}
public boolean get(String key, boolean defValue) {
return preferences.getBoolean(key, defValue);
}
public void clear(String key) {
set(key, null);
}
public SharedPreferences.Editor getEditor() {
return preferences.edit();
}
public void set(String key, String value) {
SharedPreferences.Editor editor = preferences.edit();
if (value != null) {
editor.putString(key, value);
} else {
editor.remove(key);
}
editor.apply();
}
public void set(String key, boolean value) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.apply();
}
public boolean hasLocalCurrency() {
return has(LOCAL_CURRENCY);
}
public AvailableCurrency getLocalCurrency() {
return AvailableCurrency.valueOf(get(LOCAL_CURRENCY, AvailableCurrency.USD.toString()));
}
public void setLocalCurrency(AvailableCurrency localCurrency) {
set(LOCAL_CURRENCY, localCurrency.toString());
}
public void clearLocalCurrency() {
set(LOCAL_CURRENCY, null);
}
public boolean hasAppInstallUuid() {
return has(APP_INSTALL_UUID);
}
public String getAppInstallUuid() {
return get(APP_INSTALL_UUID, UUID.randomUUID().toString());
}
public void setAppInstallUuid(String appInstallUuid) {
set(APP_INSTALL_UUID, appInstallUuid);
}
public void clearAppInstallUuid() {
set(APP_INSTALL_UUID, null);
}
public boolean hasFromNewWallet() {
return has(FROM_NEW_WALLET);
}
public Boolean getFromNewWallet() {
return get(FROM_NEW_WALLET, false);
}
public void setFromNewWallet(Boolean fromNewWallet) {
set(FROM_NEW_WALLET, fromNewWallet);
}
public void clearFromNewWallet() {
set(FROM_NEW_WALLET, false);
}
public boolean hasConfirmedSeedBackedUp() {
return has(CONFIRMED_SEED_BACKEDUP);
}
public Boolean getConfirmedSeedBackedUp() {
return get(CONFIRMED_SEED_BACKEDUP, false);
}
public void setConfirmedSeedBackedUp(Boolean confirmedSeedBackedUp) {
set(CONFIRMED_SEED_BACKEDUP, confirmedSeedBackedUp);
}
public void clearConfirmedSeedBackedUp() {
set(CONFIRMED_SEED_BACKEDUP, false);
}
public void clearAll() {
clearLocalCurrency();
clearConfirmedSeedBackedUp();
SharedPreferences.Editor editor = getEditor();
for (CryptoCurrency cryptoCurrency : CryptoCurrency.values()) {
editor.putString(CurrencyPresenter.ACCOUNT_INFO + cryptoCurrency.name(), null);
editor.putString(CurrencyPresenter.ACCOUNT_HISTORY + cryptoCurrency.name(), null);
editor.putBoolean(LockScreenUtil.LOCK_SCREEN_ENABLED, false);
}
editor.commit();
}
}
|
package risk.game.strategy;
import java.io.Serializable;
import java.util.LinkedList;
import risk.game.Player;
import risk.game.Territory;
/**
* The Cheater Strategy that implements strategy and serializable operation
*/
public class CheaterStrategy implements Strategy, Serializable {
private Player player;
private Behavior behavior;
/**
* Constructor for CheaterStrategy
* @param player
* the desired player the user want to use
*/
public CheaterStrategy(Player player) {
this.player = player;
behavior = Behavior.CHEATER;
}
/**
* Method to startup
*/
@Override
public void startup() {
while (player.getUnassignedArmy() != 0) {
Territory randomTerritory = player.getRandomTerritory();
player.placeUnassignedArmy(randomTerritory, 1);
}
}
/**
* Method to reinforce.
*/
@Override
public void reinforce() {
for (Territory territory : player.getTerritoryMap().values()) {
player.setUnsignedArmy(territory.getArmy());
player.placeUnassignedArmy(territory, player.getUnassignedArmy());
}
}
/**
* Method to attack
*/
@Override
public void attack() {
player.updateAttackableMap();
for (LinkedList<Territory> attackableList : player.getAttackableMap().values()) {
for (Territory territory : attackableList) {
if (territory.getOwner() != player) {
territory.getOwner().removeTerritory(territory);
territory.setOwner(player);
territory.setArmy(1);
territory.setColor(player.getColor());
player.addTerritory(territory);
}
}
}
}
/**
* Method to fortify
*/
@Override
public void fortify() {
player.updateAttackableMap();
for (Territory territory : player.getTerritoryMap().values()) {
for (Territory adjacent : territory.getAdjacent().values()) {
if (adjacent.getOwner() != player) {
player.setUnsignedArmy(territory.getArmy());
player.placeUnassignedArmy(territory, player.getUnassignedArmy());
continue;
}
}
}
}
/**
* Method to get its behavior
*
* @return the behavior in Behavior type
*/
@Override
public Behavior getBehavior() {
return behavior;
}
}
|
package com.onesignal;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.HttpURLConnection;
public class OneSignalRemoteParams {
static class FCMParams {
@Nullable String projectId;
@Nullable String appId;
@Nullable String apiKey;
}
public static class InfluenceParams {
// In minutes
int indirectNotificationAttributionWindow = DEFAULT_INDIRECT_ATTRIBUTION_WINDOW;
int notificationLimit = DEFAULT_NOTIFICATION_LIMIT;
// In minutes
int indirectIAMAttributionWindow = DEFAULT_INDIRECT_ATTRIBUTION_WINDOW;
int iamLimit = DEFAULT_NOTIFICATION_LIMIT;
boolean directEnabled = false;
boolean indirectEnabled = false;
boolean unattributedEnabled = false;
boolean outcomesV2ServiceEnabled = false;
public int getIndirectNotificationAttributionWindow() {
return indirectNotificationAttributionWindow;
}
public int getNotificationLimit() {
return notificationLimit;
}
public int getIndirectIAMAttributionWindow() {
return indirectIAMAttributionWindow;
}
public int getIamLimit() {
return iamLimit;
}
public boolean isDirectEnabled() {
return directEnabled;
}
public boolean isIndirectEnabled() {
return indirectEnabled;
}
public boolean isUnattributedEnabled() {
return unattributedEnabled;
}
@Override
public String toString() {
return "InfluenceParams{" +
"indirectNotificationAttributionWindow=" + indirectNotificationAttributionWindow +
", notificationLimit=" + notificationLimit +
", indirectIAMAttributionWindow=" + indirectIAMAttributionWindow +
", iamLimit=" + iamLimit +
", directEnabled=" + directEnabled +
", indirectEnabled=" + indirectEnabled +
", unattributedEnabled=" + unattributedEnabled +
'}';
}
}
static class Params {
String googleProjectNumber;
boolean enterprise;
boolean useEmailAuth;
JSONArray notificationChannels;
boolean firebaseAnalytics;
boolean restoreTTLFilter;
boolean clearGroupOnSummaryClick;
boolean receiveReceiptEnabled;
InfluenceParams influenceParams;
FCMParams fcmParams;
}
interface CallBack {
void complete(Params params);
}
private static int androidParamsRetries = 0;
private static final String OUTCOME_PARAM = "outcomes";
private static final String OUTCOMES_V2_SERVICE_PARAM = "v2_enabled";
private static final String ENABLED_PARAM = "enabled";
private static final String DIRECT_PARAM = "direct";
private static final String INDIRECT_PARAM = "indirect";
private static final String NOTIFICATION_ATTRIBUTION_PARAM = "notification_attribution";
private static final String IAM_ATTRIBUTION_PARAM = "in_app_message_attribution";
private static final String UNATTRIBUTED_PARAM = "unattributed";
private static final String FCM_PARENT_PARAM = "fcm";
private static final String FCM_PROJECT_ID = "project_id";
private static final String FCM_APP_ID = "app_id";
private static final String FCM_API_KEY = "api_key";
private static final int INCREASE_BETWEEN_RETRIES = 10_000;
private static final int MIN_WAIT_BETWEEN_RETRIES = 30_000;
private static final int MAX_WAIT_BETWEEN_RETRIES = 90_000;
public static final int DEFAULT_INDIRECT_ATTRIBUTION_WINDOW = 24 * 60;
public static final int DEFAULT_NOTIFICATION_LIMIT = 10;
static void makeAndroidParamsRequest(final @NonNull CallBack callBack) {
OneSignalRestClient.ResponseHandler responseHandler = new OneSignalRestClient.ResponseHandler() {
@Override
void onFailure(int statusCode, String response, Throwable throwable) {
if (statusCode == HttpURLConnection.HTTP_FORBIDDEN) {
OneSignal.Log(OneSignal.LOG_LEVEL.FATAL, "403 error getting OneSignal params, omitting further retries!");
return;
}
new Thread(new Runnable() {
public void run() {
int sleepTime = MIN_WAIT_BETWEEN_RETRIES + androidParamsRetries * INCREASE_BETWEEN_RETRIES;
if (sleepTime > MAX_WAIT_BETWEEN_RETRIES)
sleepTime = MAX_WAIT_BETWEEN_RETRIES;
OneSignal.Log(OneSignal.LOG_LEVEL.INFO, "Failed to get Android parameters, trying again in " + (sleepTime / 1_000) + " seconds.");
OSUtils.sleep(sleepTime);
androidParamsRetries++;
makeAndroidParamsRequest(callBack);
}
}, "OS_PARAMS_REQUEST").start();
}
@Override
void onSuccess(String response) {
processJson(response, callBack);
}
};
String params_url = "apps/" + OneSignal.appId + "/android_params.js";
String userId = OneSignal.getUserId();
if (userId != null)
params_url += "?player_id=" + userId;
OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, "Starting request to get Android parameters.");
OneSignalRestClient.get(params_url, responseHandler, OneSignalRestClient.CACHE_KEY_REMOTE_PARAMS);
}
static private void processJson(String json, final @NonNull CallBack callBack) {
final JSONObject responseJson;
try {
responseJson = new JSONObject(json);
}
catch (NullPointerException | JSONException t) {
OneSignal.Log(OneSignal.LOG_LEVEL.FATAL, "Error parsing android_params!: ", t);
OneSignal.Log(OneSignal.LOG_LEVEL.FATAL, "Response that errored from android_params!: " + json);
return;
}
Params params = new Params() {{
enterprise = responseJson.optBoolean("enterp", false);
useEmailAuth = responseJson.optBoolean("use_email_auth", false);
notificationChannels = responseJson.optJSONArray("chnl_lst");
firebaseAnalytics = responseJson.optBoolean("fba", false);
restoreTTLFilter = responseJson.optBoolean("restore_ttl_filter", true);
googleProjectNumber = responseJson.optString("android_sender_id", null);
clearGroupOnSummaryClick = responseJson.optBoolean("clear_group_on_summary_click", true);
receiveReceiptEnabled = responseJson.optBoolean("receive_receipts_enable", false);
influenceParams = new InfluenceParams();
// Process outcomes params
if (responseJson.has(OUTCOME_PARAM))
processOutcomeJson(responseJson.optJSONObject(OUTCOME_PARAM), influenceParams);
fcmParams = new FCMParams();
if (responseJson.has(FCM_PARENT_PARAM)) {
JSONObject fcm = responseJson.optJSONObject(FCM_PARENT_PARAM);
fcmParams.apiKey = fcm.optString(FCM_API_KEY, null);
fcmParams.appId = fcm.optString(FCM_APP_ID, null);
fcmParams.projectId = fcm.optString(FCM_PROJECT_ID, null);
}
}};
callBack.complete(params);
}
static private void processOutcomeJson(JSONObject outcomeJson, InfluenceParams influenceParams) {
if (outcomeJson.has(OUTCOMES_V2_SERVICE_PARAM))
influenceParams.outcomesV2ServiceEnabled = outcomeJson.optBoolean(OUTCOMES_V2_SERVICE_PARAM);
if (outcomeJson.has(DIRECT_PARAM)) {
JSONObject direct = outcomeJson.optJSONObject(DIRECT_PARAM);
influenceParams.directEnabled = direct.optBoolean(ENABLED_PARAM);
}
if (outcomeJson.has(INDIRECT_PARAM)) {
JSONObject indirect = outcomeJson.optJSONObject(INDIRECT_PARAM);
influenceParams.indirectEnabled = indirect.optBoolean(ENABLED_PARAM);
if (indirect.has(NOTIFICATION_ATTRIBUTION_PARAM)) {
JSONObject indirectNotificationAttribution = indirect.optJSONObject(NOTIFICATION_ATTRIBUTION_PARAM);
influenceParams.indirectNotificationAttributionWindow = indirectNotificationAttribution.optInt("minutes_since_displayed", DEFAULT_INDIRECT_ATTRIBUTION_WINDOW);
influenceParams.notificationLimit = indirectNotificationAttribution.optInt("limit", DEFAULT_NOTIFICATION_LIMIT);
}
if (indirect.has(IAM_ATTRIBUTION_PARAM)) {
JSONObject indirectIAMAttribution = indirect.optJSONObject(IAM_ATTRIBUTION_PARAM);
influenceParams.indirectIAMAttributionWindow = indirectIAMAttribution.optInt("minutes_since_displayed", DEFAULT_INDIRECT_ATTRIBUTION_WINDOW);
influenceParams.iamLimit = indirectIAMAttribution.optInt("limit", DEFAULT_NOTIFICATION_LIMIT);
}
}
if (outcomeJson.has(UNATTRIBUTED_PARAM)) {
JSONObject unattributed = outcomeJson.optJSONObject(UNATTRIBUTED_PARAM);
influenceParams.unattributedEnabled = unattributed.optBoolean(ENABLED_PARAM);
}
}
}
|
package com.goldgov.portal.study.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.goldgov.gtiles.core.dao.mybatis.annotation.MybatisRepository;
import com.goldgov.portal.study.service.CourseInfo;
import com.goldgov.portal.study.service.CourseInfoQuery;
@MybatisRepository("courseInfoDao")
public interface ICourseInfoDao {
public void saveCourseInfo(CourseInfo courseInfo);
public void updateCourseInfo(CourseInfo courseInfo);
public List<CourseInfo> findCourseInfoList(@Param("query")CourseInfoQuery query);
}
|
package ua.goit.timonov.enterprise.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import ua.goit.timonov.enterprise.service.MenuService;
import java.util.Map;
/**
* Spring MVC controller for mapping menu's common pages
*/
@Controller
public class MenuWebController {
public static final String MENUS = "menus";
public static final String MENU = "menu";
public static final String PATH_MENUS = "/menus";
public static final String MENU_NAME = "menuName";
private MenuService menuService;
@Autowired
public void setMenuService(MenuService menuService) {
this.menuService = menuService;
}
@RequestMapping(value = PATH_MENUS, method = RequestMethod.GET)
public String getAllMenus(Map<String, Object> model) {
model.put(MENUS, menuService.getAllMenus());
return MENUS;
}
@RequestMapping(value = "/menu/{menuName}", method = RequestMethod.GET)
public ModelAndView getMenu(@PathVariable(MENU_NAME) String menuName) {
ModelAndView modelAndView = new ModelAndView(MENU);
modelAndView.addObject(MENU, menuService.getMenuByName(menuName));
return modelAndView;
}
}
|
package com.test;
import java.io.File;
public class TestMethod {
public TestMethod() {
try {
/* DownFileInfoBean bean = new DownFileInfoBean(
"http://cdn.market.hiapk.com/data/upload//2012/09_27/17/car.wu.wei.kyo.shandian_174928.apk", "D:\\temp",
"shandian_174928.apk", 5,true,null); */
File file = new File("D:\\AsjClient-1.0.1-2018-03-27-10-30-08.exe");
DownFileInfoBean bean = new DownFileInfoBean(null, "C:\\Intel",
"AsjClient-1.0.1-2018-03-27-10-30-08.exe", 5,false,file);
DownFileFetch fileFetch = new DownFileFetch(bean);
fileFetch.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new TestMethod();
}
}
|
package edu.congyuandong.checkei.util;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
/**
* 获取手机的各种信息
*
* @author congyuandong
* @date 20130507 21:27:37
*/
public class GetStatus {
/**
* @return 手机型号
*/
public String getModel() {
return android.os.Build.MODEL;
}
/**
* @return 系统版本
*/
public String getRelease() {
return android.os.Build.VERSION.RELEASE;
}
/**
* @return 分辨率
*/
public String getMetrics(Context context) {
DisplayMetrics dm = new DisplayMetrics();
dm = context.getResources().getDisplayMetrics();
return String.valueOf(dm.widthPixels) + "*"
+ String.valueOf(dm.heightPixels);
}
/**
* @return IMEI
*/
public String getIMEI(Context context) {
TelephonyManager tel = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
return tel.getDeviceId();
}
/**
* @return 系统时间
*/
public String getTime(){
Date date=new Date();
SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time=formatter.format(date);
return time;
}
/**
* 获取手机服务商信息
*/
public String getProvidersName(Context context) {
String ProvidersName = "N/A";
try {
TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
String IMSI = telephonyManager.getSubscriberId();
// IMSI号前面3位460是国家,紧接着后面2位00 02是中国移动,01是中国联通,03是中国电信。
System.out.println(IMSI);
if (IMSI.startsWith("46000") || IMSI.startsWith("46002")) {
ProvidersName = "中国移动";
} else if (IMSI.startsWith("46001")) {
ProvidersName = "中国联通";
} else if (IMSI.startsWith("46003")) {
ProvidersName = "中国电信";
}
} catch (Exception e) {
e.printStackTrace();
}
return ProvidersName;
}
/**
*
* @param context
* @return 联网类型
*/
public String getNetWork(Context context) {
ConnectivityManager connectionManager = (ConnectivityManager) context
.getSystemService(context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isAvailable()) {
String net = networkInfo.getTypeName();
if (net.equals("WIFI"))
return "WIFI";
if (net.equals("mobile"))
return "3G";
return "UNKOWN";
} else {
return "无网络";
}
// return networkInfo.getTypeName();
}
/**
* 获取手机应用信息
*/
// public AppInfo getAppInfo(Context context){
// AppInfo appInfo = new AppInfo();
//
// List<PackageInfo> packages =
// context.getPackageManager().getInstalledPackages(0);
// //PackageInfo packageInfo = packages.get(0);
//
// ActivityManager mgr = (ActivityManager)
// context.getSystemService(Context.ACTIVITY_SERVICE);
// RunningTaskInfo info = mgr.getRunningTasks(1).get(0);
//
// for(int i=0;i<packages.size();i++) {
// PackageInfo packageInfo = packages.get(i);
// if(packageInfo.packageName.equals(info.topActivity.getPackageName())){
// appInfo.appName =
// packageInfo.applicationInfo.loadLabel(context.getPackageManager()).toString();
// appInfo.packageName = packageInfo.packageName;
// appInfo.versionName = packageInfo.versionName;
// appInfo.versionCode = packageInfo.versionCode;
// return appInfo;
// }
// }
// //Toast.makeText(this, info.topActivity.getPackageName(),
// Toast.LENGTH_LONG).show();
// return appInfo;
// }
}
|
package com.shopify.mapper;
import java.util.List;
import com.shopify.admin.AdminData;
import com.shopify.admin.AdminScopeData;
public interface AdminMapper {
public int insertAdmin(AdminData admin);
public int updateAdmin(AdminData admin);
public int selectAdminCount (AdminData admin);
public int selectAdminPasswdCount (AdminData admin);
public AdminData selectAdmin (AdminData admin);
public AdminData selectAdminPasswd (AdminData admin);
/* 관리자 관리 목록조회 , 수정, 삭제 , 등록 */
public List<AdminData> selectAdminList (AdminData admin);
public List<AdminData> adminShow (AdminData admin);
public int updateAdminList(AdminData admin);
public int chkAdmin(AdminData admin);
public int insertAdminListPop(AdminData admin);
public int updatePassword(AdminData admin);
public int deleteAdminList(String id);
public AdminData selectAdminShow (AdminData adminData);
public int selectAllAdminCount(AdminData admin);
public List<AdminData> selectAllAdmin(AdminData admin);
public AdminData selectAdminLogin(AdminData admin);
public List<AdminScopeData> selectAdminScope(AdminScopeData scope);
}
|
package com.ojas.rpo.security.dao.Amrejected;
import java.util.List;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.springframework.transaction.annotation.Transactional;
import com.ojas.rpo.security.dao.JpaDao;
import com.ojas.rpo.security.dao.interviewfeedback.InterviewFeedbackDao;
import com.ojas.rpo.security.entity.Amrejected;
import com.ojas.rpo.security.entity.InterviewFeedback;
public class AmrejectedJpaDao extends JpaDao<Amrejected, Long>implements AmrejectedDao{
public AmrejectedJpaDao(Class<Amrejected> entityClass) {
super(entityClass);
}
public AmrejectedJpaDao() {
super(Amrejected.class);
}
@Override
@Transactional(readOnly = true)
public List<Amrejected> findAll() {
final CriteriaBuilder builder = this.getEntityManager().getCriteriaBuilder();
final CriteriaQuery<Amrejected> criteriaQuery = builder.createQuery(Amrejected.class);
Root<Amrejected> root = criteriaQuery.from(Amrejected.class);
criteriaQuery.orderBy(builder.desc(root.get("id")));
TypedQuery<Amrejected> typedQuery = this.getEntityManager().createQuery(criteriaQuery);
return typedQuery.getResultList();
}
@Override
@Transactional
public void updateCandiate(Long candiateId,String status) {
//boolean result=false;
Query q = getEntityManager().createNativeQuery("update Candidate set candidateStatus=?, statusLastUpdatedDate=now() where id =?");
q.setParameter(1, status);
q.setParameter(2, candiateId);
int i=q.executeUpdate();
/*if(i>0){
return true;
}
return result;*/
}
}
|
package baekjoon.numbertheory_combinatorics;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Test_2004 {
//2와 5 개수를 카운트 해주기 위해서 그냥 나눠서 나오는 몫만 더하면 됨
//int로 했다가 범위를 초과해서 전부 long으로 바꿔 해결
//처음 했던건 시간초과가 떠서 검색 후 해결
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
long n = Long.parseLong(st.nextToken());
long m = Long.parseLong(st.nextToken());
long twoCount = 0;
long fiveCount = 0;
twoCount += countTwo(n);
fiveCount += countFive(n);
twoCount -= countTwo(m);
fiveCount -= countFive(m);
twoCount -= countTwo(n-m);
fiveCount -= countFive(n-m);
long answer = Math.min(twoCount, fiveCount);
System.out.println(answer);
}
static long countTwo(long number) {
long count = 0;
for (long i = 2; i <= number; i *= 2) {
count += number / i;
}
return count;
}
static long countFive(long number) {
long count = 0;
for (long i = 5; i <= number; i *= 5) {
count += number / i;
}
return count;
}
}
|
package com.codegym.checkinhotel.controller;
import com.codegym.checkinhotel.model.AppUser;
import com.codegym.checkinhotel.service.user.IAppUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Collection;
@Controller
@RequestMapping("/home")
public class HomeController {
@Autowired
private IAppUserService userService;
private String getPrincipal(){
String userName = null;
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails){
userName = ((UserDetails)principal).getUsername();
}else {
userName = principal.toString();
}
return userName;
}
@GetMapping
public String homePage(Model model){
AppUser user =userService.getUserByUserName(getPrincipal());
if (user!=null){
model.addAttribute("user",user);
}
return "home/index";
}
// @GetMapping("/user")
// public String homeUserPage(Model model){
// model.addAttribute("user",getPrincipal());
// return "home/index";
// }
//
// @GetMapping("/admin")
// public String homeAdminPage(Model model){
// model.addAttribute("user",getPrincipal());
// return "home/index";
// }
}
|
/*
* Copyright 2008 University of California at Berkeley
*
* 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.rebioma.server.services;
import java.util.Date;
/**
* Service for updating and getting the last update time of
* {@link OccurrenceUpdates}.
*
*/
// @ImplementedBy(UpdateServiceImpl.class)
public interface UpdateService {
/**
* @return the last date when an occurrence was created, updated, or deleted
*/
public Date getLastUpdate();
/**
* Updates the OccurrenceUpdates table with the current time.
*/
public void update();
}
|
package Keming;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import javax.swing.JButton;
public class SwingFormExample {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SwingFormExample window = new SwingFormExample();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public SwingFormExample() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lblNewLabel = new JLabel("New label");
frame.getContentPane().add(lblNewLabel, BorderLayout.NORTH);
JButton btnNewButton = new JButton("New button");
frame.getContentPane().add(btnNewButton, BorderLayout.CENTER);
JButton btnNewButton_1 = new JButton("New button");
frame.getContentPane().add(btnNewButton_1, BorderLayout.WEST);
JButton btnNewButton_2 = new JButton("New button");
frame.getContentPane().add(btnNewButton_2, BorderLayout.EAST);
}
}
|
package com.giga.repository;
import com.giga.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Integer> {
}
|
package com.smxknife.java.ex13;
/**
* @author smxknife
* 2018/9/10
*/
public class PackageAuto {
public static void main(String[] args) {
Integer i = 1000;
int j = i;
}
}
|
package com.tencent.mm.protocal.c;
import com.tencent.mm.bk.a;
public final class ask extends a {
public int otY;
public long rUF;
public long rUG;
public String rjK;
protected final int a(int i, Object... objArr) {
int fQ;
if (i == 0) {
f.a.a.c.a aVar = (f.a.a.c.a) objArr[0];
aVar.fT(1, this.otY);
if (this.rjK != null) {
aVar.g(2, this.rjK);
}
aVar.T(3, this.rUG);
aVar.T(4, this.rUF);
return 0;
} else if (i == 1) {
fQ = f.a.a.a.fQ(1, this.otY) + 0;
if (this.rjK != null) {
fQ += f.a.a.b.b.a.h(2, this.rjK);
}
return (fQ + f.a.a.a.S(3, this.rUG)) + f.a.a.a.S(4, this.rUF);
} else if (i == 2) {
f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler);
for (fQ = a.a(aVar2); fQ > 0; fQ = a.a(aVar2)) {
if (!super.a(aVar2, this, fQ)) {
aVar2.cJS();
}
}
return 0;
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
ask ask = (ask) objArr[1];
switch (((Integer) objArr[2]).intValue()) {
case 1:
ask.otY = aVar3.vHC.rY();
return 0;
case 2:
ask.rjK = aVar3.vHC.readString();
return 0;
case 3:
ask.rUG = aVar3.vHC.rZ();
return 0;
case 4:
ask.rUF = aVar3.vHC.rZ();
return 0;
default:
return -1;
}
}
}
}
|
package com.xzj.lerning;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//@EnableDiscoveryClient
//@EnableCircuitBreaker
//@EnableFeignClients
public class LerningApplication {
public static void main(String[] args) {
SpringApplication.run(LerningApplication.class, args);
}
}
|
package BackEnd;
public class Zone {
private int zoneId;
private char zoneName;
private double extension;
public Zone(){}
public Zone(int zoneId, char zoneName, double extension){
this.zoneId = zoneId;
this.zoneName = zoneName;
this.extension = extension;
}
public Zone(Zone zone){
this(zone.getZoneId(), zone.getZoneName(),zone.getExtension());
}
public int getZoneId() {
return zoneId;
}
public void setZoneId(int zoneId) {
this.zoneId = zoneId;
}
public char getZoneName() {
return zoneName;
}
public void setZoneName(char zoneName) {
this.zoneName = zoneName;
}
public double getExtension() {
return extension;
}
public void setExtension(double extension) {
this.extension = extension;
}
}
|
package com.smxknife.servlet.springboot.demo04;
/**
* @author smxknife
* 2020/2/10
*/
public class Demo4InterfaceImpl implements Demo4Interface {
@Override
public String idx() {
return "myIdx";
}
}
|
/* Generated SBE (Simple Binary Encoding) message codec */
package sbe.msg;
import uk.co.real_logic.agrona.DirectBuffer;
import uk.co.real_logic.sbe.codec.java.CodecUtil;
@SuppressWarnings("all")
public class LobDataEncodingDecoder
{
public static final int ENCODED_LENGTH = 4;
private DirectBuffer buffer;
private int offset;
public LobDataEncodingDecoder wrap(final DirectBuffer buffer, final int offset)
{
this.buffer = buffer;
this.offset = offset;
return this;
}
public int encodedLength()
{
return ENCODED_LENGTH;
}
public static long lengthNullValue()
{
return 4294967294L;
}
public static long lengthMinValue()
{
return 0L;
}
public static long lengthMaxValue()
{
return 1073741824L;
}
public long length()
{
return CodecUtil.uint32Get(buffer, offset + 0, java.nio.ByteOrder.LITTLE_ENDIAN);
}
public static short varDataNullValue()
{
return (short)255;
}
public static short varDataMinValue()
{
return (short)0;
}
public static short varDataMaxValue()
{
return (short)254;
}
}
|
package cn.nam.ssm.seckill.dao.cache;
import cn.nam.ssm.seckill.dao.SeckillDao;
import cn.nam.ssm.seckill.entiy.Seckill;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
/**
* RedisDao测试类
*
* @author Nanrong Zeng
* @version 1.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring/spring-dao.xml"})
public class RedisDaoTest {
private long seckillId = 1001;
@Resource
private RedisDao redisDao;
@Resource
private SeckillDao seckillDao;
/**
* 测试ReisDao类的putSeckill和putSeckill方法
*/
@Test
public void testSeckill() {
Seckill seckill = redisDao.getSeckill(seckillId);
if (seckill == null) {
// 若redeis缓存没有,则从数据库中获取
seckill = seckillDao.queryById(seckillId);
if (seckill != null) {
// 当数据库存在id对应的商品,则存入redis缓存
String result = redisDao.putSeckill(seckill);
System.out.println(result);
seckill = redisDao.getSeckill(seckillId);
}
}
System.out.println(seckill);
}
}
|
/*
* Copyright 2009 Kjetil Valstadsve
*
* 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 vanadis.annopro;
import vanadis.core.collections.Generic;
import vanadis.core.lang.Not;
import org.objectweb.asm.ClassReader;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
import java.util.Map;
class BytecodesReader implements AnnotationReader {
private final InputStream bytecode;
private final String targetAnnotation;
private final AnnotationMapper mapper;
BytecodesReader(InputStream bytecode, String targetAnnotation, AnnotationMapper mapper) {
this.mapper = mapper;
this.bytecode = Not.nil(bytecode, "bytecode stream");
this.targetAnnotation = targetAnnotation;
}
@Override
public Map<Constructor, List<List<AnnotationDatum<Integer>>>> readAllConstructorParameters() {
return Collections.emptyMap();
}
@Override
public Map<Method, List<List<AnnotationDatum<Integer>>>> readAllMethodParameters() {
return Collections.emptyMap();
}
@Override
public Map<Method, List<AnnotationDatum<Method>>> readAllMethods() {
return Collections.emptyMap();
}
@Override
public Map<Field, List<AnnotationDatum<Field>>> readAllFields() {
return Collections.emptyMap();
}
@Override
public Map<Constructor, List<AnnotationDatum<Constructor>>> readAllConstructors() {
return Collections.emptyMap();
}
@Override
public Map<String, AnnotationDatum<Class<?>>> annotations() {
Map<String, AnnotationDatum<Class<?>>> annos = Generic.map();
ClassReader reader = createReader();
try {
reader.accept(new ClassAsmVisitor(annos, targetAnnotation, mapper), ClassReader.SKIP_CODE);
} catch (EarlyBreakException ignore) {
}
return annos;
}
private ClassReader createReader() {
try {
return new ClassReader(bytecode);
} catch (IOException e) {
throw new IllegalStateException(this + " failed to read bytecode", e);
}
}
}
|
package com.jdroid.java.mail;
import com.jdroid.java.exception.AbstractException;
public class MailException extends AbstractException {
private static final long serialVersionUID = 7343781404856218086L;
public MailException(Throwable throwable) {
super(throwable);
}
}
|
/**
* Custom button.
*/
package com.neet.entity;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import com.neet.handlers.LevelData;
public class GameButton {
private int x;
private int y;
private int width;
private int height;
private Font font;
private String text;
private GlyphVector gv;
private int textWidth;
private int textHeight;
private boolean hover;
private boolean active;
private int type;
public static final int CENTER = 0;
public static final int LEFT = 1;
public GameButton(int x, int y) {
this.x = x;
this.y = y;
active = true;
type = CENTER;
}
public GameButton(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
active = true;
type = CENTER;
}
public void setActive(boolean b) {
active = b;
}
public boolean isActive() {
return active;
}
public void setType(int i) {
type = i;
}
public void setFont(Font f) {
font = f;
}
public void setText(String s) {
setText(s, font);
}
public void setText(String s, Font f) {
text = s;
font = f;
AffineTransform at = new AffineTransform();
FontRenderContext frc = new FontRenderContext(at, true, true);
gv = font.createGlyphVector(frc, text);
textWidth = (int) gv.getPixelBounds(null, 0, 0).width;
textHeight = (int) gv.getPixelBounds(null, 0, 0).height;
width = textWidth + 20;
height = textHeight + 10;
}
public boolean isHovered() {
return hover;
}
public boolean isHovering(int x, int y) {
if(type == CENTER) {
return x > this.x - width / 2 && x < this.x + width / 2 &&
y > this.y - height / 2 && y < this.y + height / 2;
}
else if(type == LEFT) {
return x > this.x && x < this.x + width &&
y > this.y - height / 2 && y < this.y + height / 2;
}
return false;
}
public void setHover(boolean b) {
hover = b;
}
public void draw(Graphics2D g) {
if(active) g.setColor(Color.WHITE);
else g.setColor(Color.GRAY);
if(hover && active) {
g.setStroke(LevelData.STROKE_2);
if(type == CENTER) {
g.drawLine(
x - width / 2,
y + height / 2 + 4,
x + width / 2,
y + height / 2 + 4
);
}
else if(type == LEFT) {
g.drawLine(
x,
y + height / 2 + 4,
x + width,
y + height / 2 + 4
);
}
}
g.setFont(font);
if(type == CENTER) {
g.drawString(text, x - textWidth / 2, y + 10);
}
else if(type == LEFT) {
g.drawString(text, x, y + 10);
}
}
}
|
/*
* 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 antariksa.fx.roket;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
* @author ale
*/
public class PeluncuranRoket {
IntegerProperty luncurID;
StringProperty tanggal;
StringProperty namaRoket;
StringProperty lokasi;
public PeluncuranRoket(Integer luncurID, String tanggal, String namaRoket, String lokasi) {
this.luncurID = new SimpleIntegerProperty(luncurID);
this.tanggal = new SimpleStringProperty(tanggal);
this.namaRoket = new SimpleStringProperty(namaRoket);
this.lokasi = new SimpleStringProperty(lokasi);
}
public Integer getLuncurID() {
return luncurID.get();
}
public void setLuncurID(Integer luncurID) {
this.luncurID.set(luncurID);
}
public String getTanggal() {
return tanggal.get();
}
public void setTanggal(String tanggal) {
this.tanggal.set(tanggal);
}
public String getNamaRoket() {
return namaRoket.get();
}
public void setNamaRoket(String namaRoket) {
this.namaRoket.set(namaRoket);
}
public String getLokasi() {
return lokasi.get();
}
public void setLokasi(String lokasi) {
this.lokasi.set(lokasi);
}
}
|
package com.smxknife.java.ex31;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author smxknife
* 2020/7/22
*/
public class ConcurrentHashMapKetView {
public static void main(String[] args) {
ConcurrentHashMap<Integer, Set<Integer>> map = new ConcurrentHashMap<>();
map.keySet(new HashSet<>()).addAll(Arrays.asList(1, 3, 5));
map.entrySet().forEach(entry -> {
System.out.println(System.identityHashCode(entry.getValue()));
});
}
}
|
package com.company;
public class People extends Mammal implements Work{
private String nationality; //getter
private String nationalID; //getter
private int salary;
private String[] subject;
public People(String name, boolean sex, int age , String nationality , String nationalID , int salary) {
super(name, sex, age);
this.nationality = nationality;
this.nationalID = nationalID;
this.salary = salary;
subject = new String[2];
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
void introduce(){
System.out.println("I'm people");
}
@Override
void walk() {
System.out.println("I'm walking with 2 legs");
}
@Override
void eat() {
System.out.println("I'm eat breakfast");
}
void introduceMammal(){
super.introduce();
}
public String calculateAge(int age){
if(this.age == age){
return "We are same age";
}
else if(this.age > age){
return "I'm older than you";
}
else{
return "I'm younger than you";
}
}
public String getName(){
return this.name;
}
public void setName(String name1){
name = name1;
}
public boolean getSex(){
return this.sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getNationality() {
return nationality;
}
public String getNationalID() {
return nationalID;
}
@Override
public int working() {
return salary*12;
}
}
|
package com.kuali.sim;
import java.util.List;
public class Floor {
/*
* identity of the floor
*/
private String name;
private int idx;
/*
* Elevator list
*/
private List<Elevator> elevators;
/**
* Constructor
* @param name
*/
public Floor(int idx, List<Elevator> elevators) {
this.name = String.valueOf(idx);
this.idx = idx;
this.elevators = elevators;
}
public boolean isAtThisFloor(int location) {
return location == (this.idx-1) * Service.MOVING_TIME;
}
public int getIdx() {
return this.idx;
}
public String getName() {
return this.name;
}
public List<Elevator> getElevators() {
return elevators;
}
}
|
package com.wshoto.user.anyong.ui.activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import com.wshoto.user.anyong.R;
import com.wshoto.user.anyong.ui.widget.InitActivity;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class ConfirmSuccessActivity extends InitActivity {
@Override
public void initView(Bundle savedInstanceState) {
setContentView(R.layout.activity_confirm_success);
ButterKnife.bind(this);
}
@Override
public void initData() {
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
startActivity(new Intent(ConfirmSuccessActivity.this, LoginActivity.class));
return true;
}
return super.onKeyDown(keyCode, event);
}
@OnClick({R.id.iv_comfirm_back, R.id.iv_confirm_success})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.iv_comfirm_back:
startActivity(new Intent(ConfirmSuccessActivity.this, LoginActivity.class));
break;
case R.id.iv_confirm_success:
startActivity(new Intent(ConfirmSuccessActivity.this, LoginActivity.class));
break;
default:
break;
}
}
}
|
package fr.tenebrae.MMOCore.Bags;
import java.io.IOException;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import fr.tenebrae.MMOCore.Items.Item;
import fr.tenebrae.MMOCore.Items.ItemUtils;
import fr.tenebrae.MMOCore.Items.Components.ItemType;
import fr.tenebrae.MMOCore.Utils.ItemStackBuilder;
import fr.tenebrae.MMOCore.Utils.Serializers.InventorySerializer;
public class Bag {
public static ItemStack LOCKER = new ItemStackBuilder()
.withMaterial(Material.STAINED_GLASS_PANE)
.withDurability(7)
.withDisplayName("§r")
.build();
private Inventory content;
public int size = 0;
public Bag(int size) {
this.size = size;
int invSize = (size/9);
if (invSize%9 != 0) invSize = 9*invSize+9;
Inventory inv = Bukkit.createInventory(null, invSize, " ");
if (size%9 != 0) {
for (int k = 0; k < size%9; k++) {
inv.setItem(inv.getSize()-k-1, getLocker());
}
}
this.content = inv;
this.content.setMaxStackSize(1);
}
public Bag(int size, String serializedInventory) {
this.size = size;
int invSize = (size/9);
if (invSize%9 != 0) invSize = 9*invSize+9;
try {
this.content = InventorySerializer.fromBase64(serializedInventory);
} catch (IOException e) {
Inventory inv = Bukkit.createInventory(null, invSize, " ");
if (size%9 != 0) {
for (int k = 0; k < size%9; k++) {
inv.setItem(inv.getSize()-k-1, getLocker());
}
}
this.content = inv;
}
this.content.setMaxStackSize(1);
}
public Bag(String serializedBag) {
try {
String[] infos = serializedBag.split("@#@");
this.size = Integer.valueOf(infos[0]);
this.content = InventorySerializer.fromBase64(infos[1]);
this.content.setMaxStackSize(1);
} catch (IOException e) {
e.printStackTrace();
}
}
public void setItems(ItemStack... items) {
this.clear();
this.addItem(items);
}
public void addItem(ItemStack... items) {
if (this.isFull()) return;
for (ItemStack is : items) {
if (this.isFull()) break;
if (is != null) this.content.addItem(is);
}
}
public void clear() {
this.content.clear();
if (size%9 != 0) {
for (int k = 0; k < size%9; k++) {
content.setItem(content.getSize()-k-1, getLocker());
}
}
}
public boolean isFull() {
for (ItemStack i: this.content.getContents()) {
if (i == null) return false;
}
return true;
}
public Inventory getInventory() {
return this.content;
}
public int getSize() {
return this.size;
}
public static ItemStack getLocker() {
return Bag.LOCKER.clone();
}
@Override
public String toString() {
return this.size+"@#@"+InventorySerializer.toBase64(this.content);
}
public void display(Inventory sheet) {
int k = 5;
int i = 0;
int j = 0;
for (ItemStack is : this.content.getContents()) {
if (ItemUtils.isMMOItem(is)) {
Item item = new Item(is);
if (ItemUtils.isEquipableItem(item) || item.getType() == ItemType.WEAPON || item.getType() == ItemType.OFFHAND) {
sheet.setItem(k, is);
k++;
i++;
if (i >= 4) {
k += 5;
i = 0;
}
if (k > 53) return;
}
}
}
for(j = k; j < 53; j++) {
sheet.setItem(j, null);
i++;
if (i >= 4) {
j += 5;
i = 0;
}
}
}
}
|
package com.jk.jkproject.net.okhttp;
public interface ResponseListener {
void onFailure(int paramInt, String paramString1, String paramString2);
void onSuccess(String paramString, Object paramObject);
void onStartRequest();
}
|
package steamarbitrage.steamio.tor;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.Proxy;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.LinkedList;
import javax.swing.JButton;
import javax.swing.JFrame;
import steamarbitrage.database.ItemNames;
import steamarbitrage.steamio.tor.control.TorControlConnection;
public class TorTest {
public static Process process = null;
public static int controlPort = 8118;
public static int socketPort = 9050;
public static LinkedList<Gate> gates = new LinkedList<Gate>();
public TorTest() {
}
public static void openFrame() {
JFrame frame = new JFrame("TorTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 200, 200);
frame.setLayout(new FlowLayout());
JButton button0 = new JButton("get IP");
JButton button1 = new JButton("exit Tor");
button0.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// System.out.println(getPublicIP(-1).getHostAddress());
// System.out.println(getPublicIP(socketPort).getHostAddress());
// System.out.println(getPublicIP(socketPort+1).getHostAddress());
for (Gate g : gates) {
System.out.println(g.requestPublicIP().getHostAddress());
}
}
});
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
for (Gate g : gates) {
g.close();
}
// try {
// Socket socket = new Socket("127.0.0.1", controlPort);
// TorControlConnection torCon = TorControlConnection.getConnection(socket);
// torCon.launchThread(true);
// torCon.authenticate(new byte[0]);
//
// torCon.setDebugging(System.out);
//
// torCon.shutdownTor("SHUTDOWN");
//
// socket.close();
//
//
//
//
// socket = new Socket("127.0.0.1", controlPort+1);
// torCon = TorControlConnection.getConnection(socket);
// torCon.launchThread(true);
// torCon.authenticate(new byte[0]);
//
// torCon.setDebugging(System.out);
//
// torCon.shutdownTor("SHUTDOWN");
//
// socket.close();
//
// } catch (UnknownHostException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
}
});
frame.add(button0);
frame.add(button1);
frame.setVisible(true);
}
public static void main(String[] args) {
ItemNames.loadNames();
TestSteamGateListener tsgl = new TestSteamGateListener();
for (int i = 0; i < 2; i++) {
Gate g = new Gate();
g.addGateListener(tsgl);
gates.add(g);
}
openFrame();
}
private static Inet4Address getPublicIP(int torSocketPort) {
String line;
StringBuilder stringBuilder = new StringBuilder();
URL url = null;
HttpURLConnection con = null;
try {
//url = new URL("https://check.torproject.org/");
url = new URL("http://myexternalip.com/raw");
if (torSocketPort != -1) {
Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", torSocketPort));
con = (HttpURLConnection)url.openConnection(proxy);
} else {
con = (HttpURLConnection)url.openConnection();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// try to read from input stream
InputStream is = con.getInputStream();
InputStreamReader isr = new InputStreamReader(is);;
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
stringBuilder.append(line + "\n");
}
br.close();
isr.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
Inet4Address address = null;
try {
address = (Inet4Address)InetAddress.getByName(stringBuilder.toString().trim());
} catch (UnknownHostException e) {
e.printStackTrace();
}
return address;
}
}
|
package com.lolRiver.river.util;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* @author mxia (mxia@lolRiver.com)
* 9/28/13
*/
@Component
public class WebDataFetcher {
public String get(String url) throws Exception {
return get(url, null, null);
}
public String get(String url, String headerName, String headerValue) throws Exception {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
if (StringUtils.isNotBlank(headerName) && StringUtils.isNotBlank(headerValue)) {
request.setHeader(headerName, headerValue);
}
HttpResponse response = client.execute(request);
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
}
|
package com.tencent.mm.modelappbrand.b;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;
import com.tencent.mm.a.g;
import com.tencent.mm.compatible.util.f;
import com.tencent.mm.modelappbrand.b.d.a;
import com.tencent.mm.sdk.f.e;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.sdk.platformtools.ah;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.c;
import com.tencent.mm.sdk.platformtools.h;
import com.tencent.mm.sdk.platformtools.x;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public final class b {
private static final String dFS;
private final Map<h, String> dFM;
private final Map<String, h> dFN;
private final Map<Integer, String> dFO;
private final d dFP;
private final i dFQ;
private final g dFR;
public static class b implements h {
public final void Kc() {
}
public void n(Bitmap bitmap) {
}
public final void Kd() {
}
public final String Ke() {
return "DefaultLoadTarget";
}
}
public interface i {
void d(String str, Bitmap bitmap);
Bitmap jz(String str);
void k(Bitmap bitmap);
}
private static final class k implements a {
final g dFR;
final b dGe;
final String dGg;
private final f dGh;
private final i dGi;
private final e dGj;
private final String dGk;
boolean dGl;
private k(String str, f fVar, b bVar, i iVar, g gVar, e eVar, String str2) {
this.dGl = true;
this.dGg = str;
this.dGh = fVar;
this.dGe = bVar;
this.dGi = iVar;
this.dFR = gVar;
this.dGj = eVar;
this.dGk = str2;
}
final String Ki() {
return b.aa(this.dGk, Kj());
}
final String Kj() {
return b.a(this.dGg, this.dGh, this.dGj);
}
final void Kk() {
try {
Bitmap Kl = Kl();
if (Kl != null && !Kl.isRecycled()) {
this.dGe.dFP.jB(b.jw(this.dGg));
this.dGe.dFP.a(b.jw(this.dGg), this);
p(Kl);
this.dGe.dFP.jA(b.jw(this.dGg));
}
} catch (d e) {
x.d("MicroMsg.AppBrandSimpleImageLoader.LoadTask", " doIOJobImpl, exp %s", new Object[]{e});
this.dGe.dFP.jB(b.jw(this.dGg));
this.dGe.dFP.jC(b.jw(this.dGg));
p(null);
} catch (Throwable e2) {
x.printErrStackTrace("MicroMsg.AppBrandSimpleImageLoader.LoadTask", e2, " doIOJobImpl, io exp ", new Object[0]);
this.dGe.dFP.jB(b.jw(this.dGg));
this.dGe.dFP.a(b.jw(this.dGg), this);
this.dGe.dFP.jA(b.jw(this.dGg));
}
}
public final void Kf() {
final Bitmap jz = this.dGi.jz(Kj());
if (jz == null || jz.isRecycled()) {
d d = this.dGe.dFP;
String access$1500 = b.jw(this.dGg);
if (bi.oW(access$1500) ? false : d.dGd.containsKey(access$1500)) {
d d2 = this.dGe.dFP;
String access$15002 = b.jw(this.dGg);
if (!(bi.oW(access$15002) || this == null)) {
List list = (List) d2.dGc.get(access$15002);
if (list == null) {
list = new LinkedList();
d2.dGc.put(access$15002, list);
}
list.add(this);
}
x.d("MicroMsg.AppBrandSimpleImageLoader.LoadTask", "already has job processing, make this job pending, key %s", new Object[]{b.jw(this.dGg)});
return;
}
d = this.dGe.dFP;
String access$15003 = b.jw(this.dGg);
if (!bi.oW(access$15003)) {
d.dGd.put(access$15003, Boolean.valueOf(true));
}
Kk();
return;
}
x.d("MicroMsg.AppBrandSimpleImageLoader.LoadTask", "before actually doIOJob, same keyForMemory bitmap already exists, key %s", new Object[]{Kj()});
ah.A(new Runnable() {
public final void run() {
k.this.n(jz);
}
});
}
public final void Kg() {
h hVar = (h) this.dGe.dFN.remove(Ki());
if (hVar != null) {
this.dGe.dFM.remove(hVar);
}
}
final void n(Bitmap bitmap) {
h hVar = (h) this.dGe.dFN.remove(Ki());
if (hVar != null) {
hVar.n(bitmap);
this.dGe.dFM.remove(hVar);
}
}
private void p(Bitmap bitmap) {
boolean z = false;
String str = "MicroMsg.AppBrandSimpleImageLoader.LoadTask";
String str2 = "postLoadInWorkerThread bitmap ok %b";
Object[] objArr = new Object[1];
boolean z2 = (bitmap == null || bitmap.isRecycled()) ? false : true;
objArr[0] = Boolean.valueOf(z2);
x.d(str, str2, objArr);
if (!(this.dGh == null || bitmap == null || bitmap.isRecycled())) {
Bitmap o = this.dGh.o(bitmap);
x.d("MicroMsg.AppBrandSimpleImageLoader.LoadTask", "postLoadInWorkerThread, transform bmp, origin %s, transformed %s", new Object[]{bitmap, o});
if (o != bitmap) {
this.dGi.k(bitmap);
}
bitmap = o;
}
this.dGi.d(Kj(), bitmap);
String str3 = "MicroMsg.AppBrandSimpleImageLoader.LoadTask";
str = "postLoadInWorkerThread before post to main thread, bitmap %s, ok %b";
Object[] objArr2 = new Object[2];
objArr2[0] = bitmap;
if (!(bitmap == null || bitmap.isRecycled())) {
z = true;
}
objArr2[1] = Boolean.valueOf(z);
x.d(str3, str, objArr2);
ah.A(new Runnable() {
public final void run() {
k kVar = k.this;
Bitmap bitmap = bitmap;
if (bitmap == null || bitmap.isRecycled()) {
x.d("MicroMsg.AppBrandSimpleImageLoader.LoadTask", "postLoadInMainThread, onLoadFailed bmp %s", new Object[]{bitmap});
h hVar = (h) kVar.dGe.dFN.remove(kVar.Ki());
if (hVar != null) {
hVar.Kd();
kVar.dGe.dFM.remove(hVar);
return;
}
return;
}
x.d("MicroMsg.AppBrandSimpleImageLoader.LoadTask", "postLoadInMainThread, onBitmapLoaded bmp %s", new Object[]{bitmap});
kVar.n(bitmap);
}
});
}
private Bitmap Kl() {
Bitmap bitmap = null;
if (f.zZ()) {
InputStream openRead;
if (this.dGg == null || !this.dGg.startsWith("file://")) {
openRead = this.dFR.openRead(b.jw(this.dGg));
if (openRead == null) {
x.d("MicroMsg.AppBrandSimpleImageLoader.LoadTask", "loadFromDiskOrTriggerDownload, null from disk, tryDownload %b", new Object[]{Boolean.valueOf(this.dGl)});
if (this.dGl) {
e.post(new 4(this), "AppBrandSimpleImageLoaderDownloadThread");
} else {
this.dGe.dFP.jC(b.jw(this.dGg));
this.dGe.dFP.jB(b.jw(this.dGg));
}
}
} else {
try {
openRead = new FileInputStream(this.dGg.replaceFirst("file://", ""));
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.AppBrandSimpleImageLoader.LoadTask", e, "load from local file ", new Object[0]);
}
}
if (openRead != null) {
try {
bitmap = k(openRead);
} catch (Throwable e2) {
x.printErrStackTrace("MicroMsg.AppBrandSimpleImageLoader.LoadTask", e2, " decode ", new Object[0]);
}
if (bitmap == null || bitmap.isRecycled()) {
x.d("MicroMsg.AppBrandSimpleImageLoader.LoadTask", "loadFromDiskOrTriggerDownload, decode failed, bmp %s", new Object[]{bitmap});
throw new a();
}
x.d("MicroMsg.AppBrandSimpleImageLoader.LoadTask", "loadFromDiskOrTriggerDownload, decoded bmp %s, size %d KB, url %s", new Object[]{bitmap, Integer.valueOf(android.support.v4.b.a.e(bitmap) / 1024), this.dGg});
}
return bitmap;
}
x.d("MicroMsg.AppBrandSimpleImageLoader.LoadTask", "loadFromDiskOrTriggerDownload, sdcard unavailable");
throw new b();
}
private Bitmap k(InputStream inputStream) {
try {
Bitmap j;
if (this.dGj != null) {
j = this.dGj.j(inputStream);
} else {
j = c.decodeStream(inputStream);
bi.d(inputStream);
}
return j;
} finally {
bi.d(inputStream);
}
}
}
/* synthetic */ b(byte b) {
this();
}
public static b Ka() {
return l.dGq;
}
private b() {
this.dFM = new ConcurrentHashMap();
this.dFN = new ConcurrentHashMap();
this.dFO = new ConcurrentHashMap();
this.dFQ = new c();
this.dFR = new a((byte) 0);
this.dFP = new d(new ag(new ah("AppBrandSimpleImageLoaderDiskIOHandlerThread").lnJ.getLooper()), (byte) 0);
}
public final Bitmap jv(String str) {
Bitmap jz = this.dFQ.jz(str);
if (jz == null || jz.isRecycled()) {
return null;
}
return jz;
}
public final Bitmap a(String str, e eVar) {
Closeable fileInputStream;
Throwable e;
if (bi.oW(str)) {
return null;
}
String a = a(str, null, eVar);
Bitmap jz = this.dFQ.jz(a);
if (jz != null) {
return jz;
}
try {
if (str.startsWith("file://")) {
try {
fileInputStream = new FileInputStream(str.replaceFirst("file://", ""));
} catch (FileNotFoundException e2) {
x.e("MicroMsg.AppBrandSimpleImageLoader", "findCachedLocal: load from local file, file not found ");
bi.d(null);
return null;
}
}
fileInputStream = this.dFR.openRead(jw(str));
if (eVar != null) {
try {
jz = eVar.j(fileInputStream);
} catch (Exception e3) {
e = e3;
}
} else {
jz = c.decodeStream(fileInputStream);
}
if (jz != null) {
this.dFQ.d(a, jz);
}
bi.d(fileInputStream);
return jz;
} catch (Exception e4) {
e = e4;
fileInputStream = null;
} catch (Throwable th) {
e = th;
fileInputStream = null;
bi.d(fileInputStream);
throw e;
}
try {
x.printErrStackTrace("MicroMsg.AppBrandSimpleImageLoader", e, "findCachedLocal", new Object[0]);
bi.d(fileInputStream);
return null;
} catch (Throwable th2) {
e = th2;
bi.d(fileInputStream);
throw e;
}
}
public final String a(h hVar, String str, f fVar, e eVar) {
String str2 = null;
if (hVar != null) {
if (bi.oW(str)) {
hVar.Kd();
} else {
x.d("MicroMsg.AppBrandSimpleImageLoader", "load before start LoadTask url %s", new Object[]{str});
k kVar = new k(str, fVar, this, this.dFQ, this.dFR, eVar, hVar.Ke());
str2 = kVar.Kj();
final h hVar2 = hVar;
final String str3 = str;
final k kVar2 = kVar;
Runnable anonymousClass1 = new Runnable() {
public final void run() {
Bitmap jv = b.this.jv(str2);
if (jv != null) {
hVar2.n(jv);
x.d("MicroMsg.AppBrandSimpleImageLoader", "load already cached, url %s, bitmap %s", new Object[]{str3, jv});
return;
}
String Ki = kVar2.Ki();
b.this.dFM.put(hVar2, Ki);
b.this.dFN.put(Ki, hVar2);
hVar2.Kc();
k kVar = kVar2;
kVar.dGe.dFP.j(new 2(kVar));
}
};
if (ah.isMainThread()) {
anonymousClass1.run();
} else {
ah.A(anonymousClass1);
}
}
}
return str2;
}
public final String a(h hVar, String str, f fVar) {
return a(hVar, str, fVar, null);
}
public final String a(ImageView imageView, String str, Drawable drawable, f fVar) {
return a(imageView, str, drawable, fVar, null);
}
public final String a(ImageView imageView, String str, final Drawable drawable, f fVar, e eVar) {
if (imageView == null) {
return null;
}
String str2;
if (imageView != null) {
str2 = (String) this.dFO.get(Integer.valueOf(imageView.hashCode()));
if (str2 != null) {
h hVar = (h) this.dFN.get(str2);
if (hVar != null) {
str2 = (String) this.dFM.get(hVar);
if (!bi.oW(str2)) {
this.dFN.remove(str2);
}
}
}
}
if (bi.oW(str)) {
if (drawable != null) {
imageView.setImageDrawable(drawable);
}
return null;
}
h anonymousClass2 = new j(imageView, this) {
public final void Kc() {
if (getImageView() != null && drawable != null) {
getImageView().setImageDrawable(drawable);
}
}
};
str2 = a(anonymousClass2, str, fVar, eVar);
if (anonymousClass2.dGf) {
return str2;
}
this.dFO.put(Integer.valueOf(imageView.hashCode()), aa(anonymousClass2.aAL, str2));
return str2;
}
private static String aa(String str, String str2) {
return str + str2;
}
private static String a(String str, f fVar, e eVar) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(str);
if (fVar != null) {
stringBuilder.append("|transformation:");
stringBuilder.append(fVar.Ke());
}
if (eVar != null) {
stringBuilder.append("|decoder:");
stringBuilder.append(eVar.Ke());
}
return stringBuilder.toString();
}
static {
String str = com.tencent.mm.compatible.util.e.bnE;
if (!str.endsWith("/")) {
str = str + "/";
}
str = str + "wxacache/";
dFS = str;
h.Ey(str);
}
private static String jw(String str) {
if (bi.oW(str)) {
return null;
}
return g.u(str.getBytes());
}
}
|
package org.zalando.nakadi.service;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.data.Stat;
import org.echocat.jomon.runtime.concurrent.RetryForSpecifiedCountStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.zalando.nakadi.domain.CursorError;
import org.zalando.nakadi.domain.EventType;
import org.zalando.nakadi.domain.EventTypePartition;
import org.zalando.nakadi.domain.NakadiCursor;
import org.zalando.nakadi.domain.Subscription;
import org.zalando.nakadi.domain.Timeline;
import org.zalando.nakadi.exceptions.InternalNakadiException;
import org.zalando.nakadi.exceptions.InvalidCursorException;
import org.zalando.nakadi.exceptions.InvalidStreamIdException;
import org.zalando.nakadi.exceptions.NakadiException;
import org.zalando.nakadi.exceptions.NakadiRuntimeException;
import org.zalando.nakadi.exceptions.NoSuchEventTypeException;
import org.zalando.nakadi.exceptions.ServiceUnavailableException;
import org.zalando.nakadi.repository.EventTypeRepository;
import org.zalando.nakadi.repository.TopicRepository;
import org.zalando.nakadi.repository.db.SubscriptionDbRepository;
import org.zalando.nakadi.repository.zookeeper.ZooKeeperHolder;
import org.zalando.nakadi.service.subscription.model.Partition;
import org.zalando.nakadi.service.subscription.zk.CuratorZkSubscriptionClient;
import org.zalando.nakadi.service.timeline.TimelineService;
import static java.text.MessageFormat.format;
import static org.echocat.jomon.runtime.concurrent.Retryer.executeWithRetry;
@Component
public class CursorsService {
private static final Logger LOG = LoggerFactory.getLogger(CursorsService.class);
private static final String PATH_ZK_OFFSET = "/nakadi/subscriptions/{0}/topics/{1}/{2}/offset";
private static final String PATH_ZK_PARTITION = "/nakadi/subscriptions/{0}/topics/{1}/{2}";
private static final String PATH_ZK_PARTITIONS = "/nakadi/subscriptions/{0}/topics/{1}";
private static final String PATH_ZK_SESSION = "/nakadi/subscriptions/{0}/sessions/{1}";
private static final String ERROR_COMMUNICATING_WITH_ZOOKEEPER = "Error communicating with zookeeper";
private static final int COMMIT_CONFLICT_RETRY_TIMES = 5;
private final ZooKeeperHolder zkHolder;
private final TimelineService timelineService;
private final SubscriptionDbRepository subscriptionRepository;
private final EventTypeRepository eventTypeRepository;
@Autowired
public CursorsService(final ZooKeeperHolder zkHolder,
final TimelineService timelineService,
final SubscriptionDbRepository subscriptionRepository,
final EventTypeRepository eventTypeRepository) {
this.zkHolder = zkHolder;
this.timelineService = timelineService;
this.subscriptionRepository = subscriptionRepository;
this.eventTypeRepository = eventTypeRepository;
}
/**
* It is guaranteed, that len(cursors) == len(result)
**/
public List<Boolean> commitCursors(final String streamId, final String subscriptionId,
final List<NakadiCursor> cursors)
throws ServiceUnavailableException, InvalidCursorException, InvalidStreamIdException,
NoSuchEventTypeException, InternalNakadiException {
validateStreamId(cursors, streamId, subscriptionId);
LOG.debug("[COMMIT_CURSORS] stream IDs validation finished");
final Map<EventTypePartition, List<NakadiCursor>> cursorsByPartition = cursors.stream()
.collect(Collectors.groupingBy(
cursor -> new EventTypePartition(cursor.getEventType(), cursor.getPartition())));
final HashMap<EventTypePartition, Iterator<Boolean>> partitionCommits = new HashMap<>();
for (final EventTypePartition etPartition : cursorsByPartition.keySet()) {
final Iterator<Boolean> commitResultIterator = processPartitionCursors(subscriptionId,
cursorsByPartition.get(etPartition)).iterator();
partitionCommits.put(etPartition, commitResultIterator);
LOG.debug("[COMMIT_CURSORS] committed {} cursor(s) for partition {}",
cursorsByPartition.get(etPartition).size(), etPartition);
}
return cursors.stream()
.map(cursor -> partitionCommits.get(cursor.getEventTypePartition()).next())
.collect(Collectors.toList());
}
private void validateStreamId(final List<NakadiCursor> cursors, final String streamId,
final String subscriptionId)
throws ServiceUnavailableException, InvalidCursorException, InvalidStreamIdException,
NoSuchEventTypeException, InternalNakadiException {
if (!isActiveSession(subscriptionId, streamId)) {
throw new InvalidStreamIdException("Session with stream id " + streamId + " not found");
}
final HashMap<EventTypePartition, String> partitionSessions = new HashMap<>();
for (final NakadiCursor cursor : cursors) {
final EventTypePartition etPartition = cursor.getEventTypePartition();
String partitionSession = partitionSessions.get(etPartition);
if (partitionSession == null) {
partitionSession = getPartitionSession(subscriptionId, cursor.getTopic(), cursor);
partitionSessions.put(etPartition, partitionSession);
}
if (!streamId.equals(partitionSession)) {
throw new InvalidStreamIdException("Cursor " + cursor + " cannot be committed with stream id "
+ streamId);
}
}
}
private String getPartitionSession(final String subscriptionId, final String topic, final NakadiCursor cursor)
throws ServiceUnavailableException, InvalidCursorException {
try {
final String partitionPath = format(PATH_ZK_PARTITION, subscriptionId, topic, cursor.getPartition());
final byte[] partitionData = zkHolder.get().getData().forPath(partitionPath);
final Partition.PartitionKey partitionKey = new Partition.PartitionKey(topic, cursor.getPartition());
return CuratorZkSubscriptionClient.deserializeNode(partitionKey, partitionData).getSession();
} catch (final KeeperException.NoNodeException e) {
throw new InvalidCursorException(CursorError.PARTITION_NOT_FOUND, cursor);
} catch (final Exception e) {
LOG.error(ERROR_COMMUNICATING_WITH_ZOOKEEPER, e);
throw new ServiceUnavailableException(ERROR_COMMUNICATING_WITH_ZOOKEEPER);
}
}
private boolean isActiveSession(final String subscriptionId, final String streamId)
throws ServiceUnavailableException {
try {
final String sessionsPath = format(PATH_ZK_SESSION, subscriptionId, streamId);
return zkHolder.get().checkExists().forPath(sessionsPath) != null;
} catch (final Exception e) {
LOG.error(ERROR_COMMUNICATING_WITH_ZOOKEEPER, e);
throw new ServiceUnavailableException(ERROR_COMMUNICATING_WITH_ZOOKEEPER);
}
}
private List<Boolean> processPartitionCursors(final String subscriptionId, final List<NakadiCursor> cursors)
throws InternalNakadiException, NoSuchEventTypeException, ServiceUnavailableException,
InvalidCursorException {
try {
final List<NakadiCursor> nakadiCursors = cursors.stream()
.map(cursor -> {
final NakadiCursor nakadiCursor = new NakadiCursor(
cursor.getTimeline(),
cursor.getPartition(),
cursor.getOffset());
try {
timelineService.getTopicRepository(cursor.getTimeline()).validateCommitCursor(nakadiCursor);
return nakadiCursor;
} catch (final InvalidCursorException e) {
throw new NakadiRuntimeException(e);
}
})
.collect(Collectors.toList());
LOG.debug("[COMMIT_CURSORS] finished validation of {} cursor(s) for partition {} {}", cursors.size(),
cursors.get(0).getEventType(), cursors.get(0).getTopic());
return commitPartitionCursors(subscriptionId, nakadiCursors);
} catch (final NakadiRuntimeException e) {
throw (InvalidCursorException) e.getException();
}
}
private List<Boolean> commitPartitionCursors(final String subscriptionId, final List<NakadiCursor> cursors)
throws ServiceUnavailableException {
final NakadiCursor first = cursors.get(0);
final String offsetPath = format(
PATH_ZK_OFFSET, subscriptionId, first.getTopic(), first.getPartition());
// TODO: fix while switching to timelines
final TopicRepository topicRepository = timelineService.getTopicRepository(first.getTimeline());
try {
@SuppressWarnings("unchecked")
final List<Boolean> committed = executeWithRetry(() -> {
final Stat stat = new Stat();
final byte[] currentOffsetData = zkHolder.get()
.getData()
.storingStatIn(stat)
.forPath(offsetPath);
final String currentOffset = new String(currentOffsetData, Charsets.UTF_8);
NakadiCursor currentMaxCursor = first.withOffset(currentOffset);
final List<Boolean> commits = Lists.newArrayList();
for (final NakadiCursor cursor : cursors) {
if (topicRepository.compareOffsets(cursor, currentMaxCursor) > 0) {
currentMaxCursor = cursor;
commits.add(true);
} else {
commits.add(false);
}
}
if (!currentMaxCursor.getOffset().equals(currentOffset)) {
final String offsetToUse = currentMaxCursor.getOffset();
zkHolder.get()
.setData()
.withVersion(stat.getVersion())
.forPath(offsetPath, offsetToUse.getBytes(Charsets.UTF_8));
}
return commits;
},
new RetryForSpecifiedCountStrategy<List<Boolean>>(COMMIT_CONFLICT_RETRY_TIMES)
.withExceptionsThatForceRetry(KeeperException.BadVersionException.class));
return Optional.ofNullable(committed)
.orElse(Collections.nCopies(cursors.size(), false));
} catch (final Exception e) {
throw new ServiceUnavailableException(ERROR_COMMUNICATING_WITH_ZOOKEEPER, e);
}
}
public List<NakadiCursor> getSubscriptionCursors(final String subscriptionId) throws NakadiException {
final Subscription subscription = subscriptionRepository.getSubscription(subscriptionId);
final ImmutableList.Builder<NakadiCursor> cursorsListBuilder = ImmutableList.builder();
for (final String eventTypeName : subscription.getEventTypes()) {
final EventType eventType = eventTypeRepository.findByName(eventTypeName);
final Timeline timeline = timelineService.getTimeline(eventType);
final String partitionsPath = format(PATH_ZK_PARTITIONS, subscriptionId, timeline.getTopic());
try {
final List<String> partitions = zkHolder.get().getChildren().forPath(partitionsPath);
final List<NakadiCursor> eventTypeCursors = partitions.stream()
.map(partition -> readCursor(subscriptionId, timeline, partition))
.collect(Collectors.toList());
cursorsListBuilder.addAll(eventTypeCursors);
} catch (final KeeperException.NoNodeException nne) {
LOG.debug(nne.getMessage(), nne);
return Collections.emptyList();
} catch (final Exception e) {
LOG.error(e.getMessage(), e);
throw new ServiceUnavailableException(ERROR_COMMUNICATING_WITH_ZOOKEEPER, e);
}
}
return cursorsListBuilder.build();
}
private NakadiCursor readCursor(final String subscriptionId, final Timeline timeline, final String partition)
throws RuntimeException {
try {
final String offsetPath = format(PATH_ZK_OFFSET, subscriptionId, timeline.getTopic(), partition);
return new NakadiCursor(
timeline,
partition,
new String(zkHolder.get().getData().forPath(offsetPath), Charsets.UTF_8));
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
}
|
package com.tencent.mm.plugin.wallet.pay.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import com.tencent.mm.ab.l;
import com.tencent.mm.plugin.wallet_core.c.w;
import com.tencent.mm.plugin.wallet_core.ui.n;
import com.tencent.mm.protocal.c.btd;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.base.a;
import com.tencent.mm.wallet_core.ui.WalletBaseUI;
@a(7)
public class WalletPayCustomUI extends WalletBaseUI {
private String cZH = "";
private int fdx = 0;
private btd kkd;
protected n pfQ;
private String pfR = "";
private boolean pfS = false;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
ux(8);
this.pfR = getIntent().getStringExtra("INTENT_PAYFEE");
this.cZH = getIntent().getStringExtra("INTENT_TITLE");
this.pfS = getIntent().getIntExtra("INTENT_CAN_TOUCH", 0) == 1;
byte[] byteArrayExtra = getIntent().getByteArrayExtra("INTENT_TOKENMESS");
this.kkd = new btd();
try {
this.kkd.aG(byteArrayExtra);
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.WalletPayCustomUI", e, "", new Object[0]);
}
x.i("MicroMsg.WalletPayCustomUI", "mTokeMess packageex:%s busi_id:%s sign:%s can_use_touch %s mPayFee %s mTitle %s", new Object[]{this.kkd.sqy, this.kkd.rFf, this.kkd.sign, Boolean.valueOf(this.pfS), this.pfR, this.cZH});
this.pfQ = n.a(this, this.cZH, this.pfR, "", this.pfS, new 1(this), new OnCancelListener() {
public final void onCancel(DialogInterface dialogInterface) {
WalletPayCustomUI.this.finish();
}
}, new 3(this));
}
protected final int getLayoutId() {
return -1;
}
public void onResume() {
super.onResume();
}
public void onPause() {
super.onPause();
}
public void onDestroy() {
super.onDestroy();
}
public final boolean d(int i, int i2, String str, l lVar) {
x.i("MicroMsg.WalletPayCustomUI", "errorType %s errCode %s, errmsg %s, scene %s", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), str, lVar});
if (lVar instanceof w) {
if (i == 0 && i2 == 0) {
w wVar = (w) lVar;
Intent intent = new Intent();
intent.putExtra("INTENT_RESULT_TOKEN", wVar.pjE);
setResult(-1, intent);
}
finish();
}
return false;
}
}
|
package demo.helloworld;
import act.view.excel.JexlFunc;
@JexlFunc("util")
public class JexlUtils {
public int sum(int a, int b) {
return a + b;
}
}
|
/**
*
*/
package com.wonders.schedule.manage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import com.wonders.schedule.common.util.SimpleLogger;
import com.wonders.schedule.execute.IExecutable;
import com.wonders.schedule.model.bo.TScheduleConfig;
/**
* @ClassName: ScheduleManager
* @Description: TODO(这里用一句话描述这个类的作用)
* @author zhoushun
* @date 2012-12-4 下午02:58:39
*
*/
@Component("scheduleManager")
public class ScheduleManager {
private static IExecutable executeService;
static SimpleLogger log = new SimpleLogger(ScheduleManager.class);
public static void operate(TScheduleConfig t) {
String result = "0";
try {
result = executeService.execute(t);
log.debug("ScheduleManager " + t.getDescription() + "--------"
+ result);
} catch (Exception e) {
e.printStackTrace();
}
}
public static IExecutable getExecuteService() {
return executeService;
}
@Autowired
public void setExecuteService(
@Qualifier(value = "executeService") IExecutable executeService) {
ScheduleManager.executeService = executeService;
}
public static void main(String[] args) {
System.out.println(ScheduleManager.class.getName());
System.out.println(new java.util.Date().getTime());
}
}
|
package com.xlickr.dao;
import javax.transaction.Transactional;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.xlickr.hibernate.entities.FlickrImage;
@Repository
@Transactional
public class ImageDaoImpl implements ImageDao {
@Autowired
private SessionFactory sessionFactory;
@Override
public void persistImage(FlickrImage image) {
// TODO Auto-generated method stub
sessionFactory.getCurrentSession().save(image);
}
}
|
package primary.soursefour.selfcode;
//折纸问题 【题目】 请把一段纸条竖着放在桌子上,
// 然后从纸条的下边向上方对折1次,压出折痕后展开。此时折痕是凹下去的,
// 即折痕突起的方向指向纸条的背面。
// 如果从纸条的下边向上方连续对折 2 次,
// 压出折痕后展开,此时有三条折痕,从上到下依次是下折痕、下折痕和上折痕。
// 给定一个输入参数N,代表纸条都从下边向上方连续对折N次,
// 请从上到下打印所有折痕的方向。
// 例如:N=1时,打印: down N=2时,打印:down down up
// 实质: 满二叉树的【中序遍历】.根节点为down,其他节点递归定义:左孩子为down && 右孩子为up
// 网上解法: https://blog.csdn.net/caoxiaohong1005/article/details/78384281
public class PaperFolding {
public static void paperFolding(int n){ // n -- 折纸的次数
inOderPaperFold(1,n,true);
}
public static void inOderPaperFold(int cur, int n, Boolean isDown){
// cur -- 当前为第 i 次折; n -- 总的折叠次数设置 isDown -- 判断是否为向下
if(cur > n){
return;
}
inOderPaperFold(cur + 1 ,n,true);
System.out.println(isDown? "down" : "up");
inOderPaperFold(cur + 1,n,false);
}
public static void main(String[] args) {
System.out.println("折叠三次的结果为:");
paperFolding(3);
System.out.println("折叠两次的结果为:");
paperFolding(2);
}
}
|
package server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Server {
private int port;
private int threadPoolMax = 5;
public Server(int port) {
this.port = port;
}
public void start() throws IOException {
// Init
final ExecutorService executor = Executors.newFixedThreadPool(threadPoolMax);
final ServerSocket serverSocket = new ServerSocket(port);
System.out.println("listening on port " + port + " ...");
Runtime.getRuntime().addShutdownHook(new Thread() {
// This code will run when exiting server (through user interruption (^C))
public void run() {
try {
serverSocket.close();
executor.shutdown();
} catch (IOException e) {
e.printStackTrace();
}
}
});
// Server loop
while(true){
Socket socket = serverSocket.accept();
Callable<Void> callable = new ClientHandler(socket);
executor.submit(callable);
}
}
}
|
/**
* shopmobile for tpshop
* ============================================================================
* 版权所有 2015-2099 深圳搜豹网络科技有限公司,并保留所有权利。
* 网站地址: http://www.tp-shop.cn
* ——————————————————————————————————————
* 这不是一个自由软件!您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
* 不允许对程序代码以任何形式任何目的的再发布。
* ============================================================================
* Author: 飞龙 wangqh01292@163.com
* Date: @date 2015年10月20日 下午7:19:26
* Description:MineFragment
* @version V1.0
*/
package com.tpshop.mallc.fragment;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ListView;
import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.tpshop.mallc.R;
import com.tpshop.mallc.activity.person.SPCouponListActivity;
import com.tpshop.mallc.activity.shop.SPProductListActivity;
import com.tpshop.mallc.adapter.SPCouponListAdapter;
import com.tpshop.mallc.http.base.SPFailuredListener;
import com.tpshop.mallc.http.base.SPMobileHttptRequest;
import com.tpshop.mallc.http.base.SPSuccessListener;
import com.tpshop.mallc.http.condition.SPProductCondition;
import com.tpshop.mallc.http.person.SPPersonRequest;
import com.tpshop.mallc.http.shop.SPShopRequest;
import com.tpshop.mallc.model.SPProduct;
import com.tpshop.mallc.model.shop.SPCoupon;
import com.tpshop.mallc.model.shop.SPGoodsComment;
import com.tpshop.mallc.model.shop.SPShopOrder;
import com.tpshop.mallc.utils.SMobileLog;
import com.tpshop.mallc.utils.SPDialogUtils;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* 优惠券列表 -> 优惠券
*
*/
public class SPCouponListFragment extends SPBaseFragment {
private String TAG = "SPCouponListFragment";
private Context mContext;
private int mType ;
SPCouponListAdapter mAdapter;
boolean hasLoadData = false;
PtrClassicFrameLayout ptrClassicFrameLayout;
ListView listView;
List<SPCoupon> coupons;
int mPageIndex; //当前第几页:从1开始
/**
* 最大页数
*/
boolean mIsMaxPage;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.mContext = activity;
}
public void setType(int type){
this.mType = type;
hasLoadData = false;
if(mAdapter != null)mAdapter.setType(mType);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
hasLoadData = false;
View view = inflater.inflate(R.layout.person_coupon_fragment_view, null,false);
mAdapter = new SPCouponListAdapter(getActivity() , mType);
initSubView(view);
return view;
}
public void loadData(){
if (hasLoadData){
return;
}
refreshData();
}
@Override
public void onDetach() {
super.onDetach();
}
@Override
public void initSubView(View view) {
ptrClassicFrameLayout = (PtrClassicFrameLayout)view.findViewById(R.id.coupon_list_view_frame);
listView = (ListView)view.findViewById(R.id.coupon_listv);
listView.setAdapter(mAdapter);
ptrClassicFrameLayout.setPtrHandler(new PtrDefaultHandler() {
@Override
public void onRefreshBegin(PtrFrameLayout frame) {
//下拉刷新
refreshData();
}
});
ptrClassicFrameLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
@Override
public void loadMore() {
//上拉加载更多
loadMoreData();
}
});
}
/**
* 加载数据
* @Description: 加载数据
* @return void 返回类型
* @throws
*/
public void refreshData(){
coupons = new ArrayList<SPCoupon>();
mPageIndex = 1;
mIsMaxPage = false;
SPCouponListActivity couponListActivity = (SPCouponListActivity)getActivity();
SPPersonRequest.getCouponListWithType(mType , mPageIndex , new SPSuccessListener(){
@Override
public void onRespone(String msg, Object response) {
if (response != null){
coupons = (List<SPCoupon> )response;
mIsMaxPage = false;
mAdapter.setData(coupons);
ptrClassicFrameLayout.setLoadMoreEnable(true);
} else {
mIsMaxPage = true;
ptrClassicFrameLayout.setLoadMoreEnable(false);
}
hasLoadData = true;
ptrClassicFrameLayout.refreshComplete();
}
} , new SPFailuredListener(couponListActivity){
@Override
public void onRespone(String msg, int errorCode) {
ptrClassicFrameLayout.setLoadMoreEnable(false);
}
});
}
public void loadMoreData() {
if (mIsMaxPage) {
return;
}
mPageIndex++;
SPPersonRequest.getCouponListWithType(mType, mPageIndex, new SPSuccessListener() {
@Override
public void onRespone(String msg, Object response) {
if(response!=null){
List<SPCoupon> tempComment = (List<SPCoupon>) response;
coupons.addAll(tempComment);
//更新收藏数据
mAdapter.setData(coupons);
mIsMaxPage = false;
ptrClassicFrameLayout.setLoadMoreEnable(true);
}else{
mPageIndex--;
mIsMaxPage = true;
ptrClassicFrameLayout.setLoadMoreEnable(false);
}
ptrClassicFrameLayout.loadMoreComplete(true);
}
}, new SPFailuredListener() {
@Override
public void onRespone(String msg, int errorCode) {
showToast(msg);
mPageIndex--;
}
});
}
@Override
public void initEvent() {
}
@Override
public void initData() {
}
}
|
package p4_group_8_repo.Game_levels;
import java.util.concurrent.TimeUnit;
import javafx.collections.ObservableList;
import p4_group_8_repo.Game_actor.End;
import p4_group_8_repo.Game_actor.Vehicle;
import p4_group_8_repo.Game_scene.MyStage;
/**
* Class of Level 6
* @author Jun Yuan
*
*/
public class Level_6 {
/**
* Set cars faster
* @param background is the container for the scene
*/
public Level_6(MyStage background) {
String car_left = "/graphic_animation/car1"+"Left.png";
int car_size = 50;
ObservableList animation_list = background.getChildren();
// TOP car
animation_list.set(25, new Vehicle(car_left, 500, 490, -5.0, car_size, car_size));
// Bottom car
animation_list.set(30, new Vehicle(car_left, 175, 700, -3.5, car_size, car_size));
animation_list.set(31, new Vehicle(car_left, 475, 700, -3.5, car_size, car_size));
System.out.println("Top & Bottom cars are Faster");
try {
TimeUnit.SECONDS.sleep(2); //Timer is STOP for 2 seconds
animation_list.set(15, new End(11, 95, 60));
animation_list.set(16, new End(139, 95, 60));
animation_list.set(17, new End(267,95, 60));
animation_list.set(18, new End(394,95, 60));
animation_list.set(19, new End(523,95, 60));
System.out.println("End Goal is RESET\n");
}
catch(InterruptedException e) {
System.err.format("IOException: %s%n", e);
}
}
}
|
package com.tencent.mm.plugin.ipcall.ui;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.tencent.mm.R;
import com.tencent.mm.aa.f;
import com.tencent.mm.aa.q;
import com.tencent.mm.plugin.ipcall.a.g.c;
import com.tencent.mm.plugin.ipcall.a.g.k;
import com.tencent.mm.plugin.ipcall.a.g.m;
import com.tencent.mm.plugin.ipcall.a.i;
import com.tencent.mm.plugin.ipcall.b.a;
import com.tencent.mm.sdk.platformtools.ah;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.ui.r;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
public final class h extends r<c> implements f.c {
private static HashMap<String, c> ksx = null;
private boolean hoW = false;
private HashSet<String> ktA = new HashSet();
private boolean ktB = false;
private d kty;
private HashMap<Long, c> ktz = new HashMap();
ArrayList<k> kxg;
private OnClickListener kxh = new 1(this);
public final /* synthetic */ Object a(Object obj, Cursor cursor) {
c cVar = (c) obj;
if (cVar == null) {
cVar = new c();
}
cVar.d(cursor);
return cVar;
}
public h(Context context) {
super(context, null);
lB(true);
this.kty = new d(context);
q.Kp().a(this);
}
protected final void WS() {
this.kxg = m.aXY();
}
public final void WT() {
this.kxg = m.aXY();
}
public final int getCount() {
if (this.kxg == null) {
this.kxg = m.aXY();
}
if (this.kxg != null) {
return this.kxg.size();
}
return 0;
}
public final k rG(int i) {
return (k) this.kxg.get(i);
}
public final View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
view = LayoutInflater.from(this.context).inflate(R.i.ipcall_address_item, viewGroup, false);
a aVar = new a(this, (byte) 0);
aVar.ktO = view.findViewById(R.h.item_header);
aVar.ktP = view.findViewById(R.h.divider_bottom);
aVar.eBM = (ImageView) view.findViewById(R.h.avatar_iv);
aVar.eIH = (TextView) view.findViewById(R.h.nickname_tv);
aVar.ktG = (TextView) view.findViewById(R.h.phonenumber_tv);
aVar.ktH = (LinearLayout) view.findViewById(R.h.recent_info_ll);
aVar.ktI = (TextView) view.findViewById(R.h.recent_state_tv);
aVar.ktJ = (TextView) view.findViewById(R.h.recent_time_tv);
aVar.ktK = (TextView) view.findViewById(R.h.address_spell_category_tv);
aVar.ktL = (TextView) view.findViewById(R.h.address_item_category_tv);
aVar.ktM = (ImageView) view.findViewById(R.h.address_item_info);
aVar.ktN = view.findViewById(R.h.item_info_ll);
aVar.ktN.setClickable(true);
aVar.ktQ = (ImageView) view.findViewById(R.h.divider);
view.setTag(aVar);
}
a aVar2 = (a) view.getTag();
aVar2.ktN.setClickable(true);
aVar2.ktN.setTag(Integer.valueOf(i));
aVar2.ktQ.setVisibility(8);
if (qY(i)) {
aVar2.eIH.setVisibility(8);
aVar2.ktG.setVisibility(8);
aVar2.ktH.setVisibility(8);
aVar2.eBM.setVisibility(8);
aVar2.eBM.setTag(null);
aVar2.ktL.setVisibility(8);
aVar2.ktK.setVisibility(8);
aVar2.ktM.setVisibility(8);
} else {
k rG = rG(i);
if (rG != null) {
c dN;
if (i == 0) {
aVar2.ktL.setVisibility(0);
aVar2.ktK.setVisibility(8);
aVar2.ktL.setText(this.context.getString(R.l.ip_call_recently_contact));
} else {
aVar2.ktL.setVisibility(8);
aVar2.ktK.setVisibility(8);
}
aVar2.ktQ.setVisibility(0);
aVar2.eIH.setVisibility(0);
LayoutParams layoutParams = (LayoutParams) aVar2.ktO.getLayoutParams();
layoutParams.height = (int) aVar2.ktG.getContext().getResources().getDimension(R.f.address_item_height);
aVar2.ktO.setLayoutParams(layoutParams);
RelativeLayout.LayoutParams layoutParams2 = (RelativeLayout.LayoutParams) aVar2.eBM.getLayoutParams();
layoutParams2.height = (int) aVar2.eBM.getContext().getResources().getDimension(R.f.address_item_avatar_size_normal);
layoutParams2.width = (int) aVar2.eBM.getContext().getResources().getDimension(R.f.address_item_avatar_size_normal);
aVar2.eBM.setLayoutParams(layoutParams2);
if (rG.field_addressId > 0) {
dN = this.ktz.containsKey(Long.valueOf(rG.field_addressId)) ? (c) this.ktz.get(Long.valueOf(rG.field_addressId)) : i.aXv().dN(rG.field_addressId);
if (dN != null) {
this.ktz.put(Long.valueOf(rG.field_addressId), dN);
aVar2.eIH.setText(dN.field_systemAddressBookUsername);
}
} else {
aVar2.eIH.setText(a.Ft(rG.field_phonenumber));
dN = null;
}
aVar2.ktG.setVisibility(8);
aVar2.ktH.setVisibility(0);
aVar2.ktJ.setText(com.tencent.mm.plugin.ipcall.b.c.dR(rG.field_calltime));
if (rG.field_duration > 0) {
aVar2.ktI.setText(com.tencent.mm.plugin.ipcall.b.c.dT(rG.field_duration));
} else {
aVar2.ktI.setText(com.tencent.mm.plugin.ipcall.b.c.rL(rG.field_status));
}
ImageView imageView = aVar2.eBM;
if (imageView != null) {
imageView.setVisibility(0);
imageView.setTag(null);
imageView.setImageResource(R.g.ipcall_default_avatar);
if (dN != null) {
if (!bi.oW(dN.field_contactId) && !bi.oW(dN.field_wechatUsername)) {
this.kty.a(dN.field_contactId, dN.field_wechatUsername, imageView);
} else if (!bi.oW(dN.field_contactId)) {
this.kty.b(dN.field_contactId, imageView);
} else if (!bi.oW(dN.field_wechatUsername)) {
this.kty.c(dN.field_wechatUsername, imageView);
}
if (!bi.oW(dN.field_wechatUsername)) {
this.ktA.add(dN.field_wechatUsername);
}
}
}
}
aVar2.ktN.setVisibility(0);
aVar2.ktM.setVisibility(0);
aVar2.ktN.setOnClickListener(this.kxh);
}
return view;
}
public final int getItemViewType(int i) {
return super.getItemViewType(i);
}
public final int getViewTypeCount() {
return super.getViewTypeCount();
}
public final void jX(String str) {
if (this.ktA.contains(str)) {
ah.A(new 2(this));
}
}
public final void notifyDataSetChanged() {
this.kxg = m.aXY();
this.ktz.clear();
super.notifyDataSetChanged();
}
}
|
package zystudio.cases.graphics;
import android.util.Log;
public class CaseForMath {
private static CaseForMath sCase;
public static CaseForMath obtain() {
if (sCase == null) {
sCase = new CaseForMath();
}
return sCase;
}
public void work() {
computeFunc();
// computeRadios();
}
private void computeFunc(){
float tempAngle = 360 / 6;
double toRadian=Math.toRadians(tempAngle);
double result=Math.cos(toRadian);
//cos(PI/3)也即cos(60'),确实就是0.5
Log.i("ertewu", "result is:"+result);
}
private void computeRadios() {
float tempAngle = 360 / 6;
for (float angle = 0; angle < 360; angle += tempAngle) {
Log.i("ertewu", "r33:" + angle + "|" + Math.toRadians(angle));
}
/**
* 从结果来看就是把角度制转成弧度制,比如60.那Math.toRadians(60)是1.04719.. 其实就是PI/3
*/
}
}
|
package ebid;
import java.sql.*;
import java.util.*;
import java.io.*;
public class DriverClass
{
static Scanner in=new Scanner(System.in);
public static void main(String[] args)
{
int no_of_people=0;
Connection c;
String out;
try
{
FileWriter fr=new FileWriter("D:/bidding_logs.txt");
System.out.println("Welcome to the Auction.\nHere we auction the 2011 Cricket World Cup accessories");
System.out.println("\nRules : You will get 15 seconds to bid . Bids after 15 secs would be discarded");
Thread.sleep(5000);
Class.forName("com.mysql.jdbc.Driver");
c=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/Ebidding","root","1234");
Statement s1;
Statement s;
s1=c.createStatement();
s=c.createStatement();
ResultSet rs;
ResultSet rs1;
rs=s.executeQuery("select count(ID) from People");
while(rs.next())
no_of_people=rs.getInt(1);
rs=s.executeQuery("select * from Items");
while(rs.next())
{
int id=0;
double amt;
int soldto=0;
int itemid=rs.getInt(1);
String iname=rs.getString(2);
double base=rs.getDouble(3);
String des=rs.getString(6);
System.out.println("\nThe item id: "+itemid+" ,name: "+iname+" with base price: $"+base+" is now open for auction.");
System.out.println("\nItem Description: "+des);
System.out.println("\nBid starts at $"+base);
Thread.sleep(500);System.out.println();
while(id>=0)
{
System.out.print("Enter your id(1-"+no_of_people+") for bidding:");
Timer t=new Timer(no_of_people);
while(true)
{
id=in.nextInt();
//if(id<=0){System.out.println("ID should be greater than 0.Enter again:");continue;}
if(t.time<15)
t.end=false;
break;
}
if(t.end)
{
id=-1;
System.out.println("Time out");
}
if(!t.end)
{
if(id>no_of_people||id<=0)
{ System.out.println("Invalid ID");id=0;}
else
{
System.out.println("Enter your bid:");
amt=in.nextDouble();
rs1=s1.executeQuery("select Balance from people where ID="+id);
double bal=0;
while(rs1.next())
bal=rs1.getDouble(1);
if(amt<=base)
{
System.out.println("Invalid bid.Bid can't be less than previous bid or base price.\n");
id=soldto;
}
else if((bal-amt)<0)
{
System.out.println("Invalid bid.You don't have enough balance for this bid.\n");
id=soldto;
}
else
{
base=amt;
System.out.println("Bid Accepted\n");
soldto=id;
}
}
}
}
if(soldto>0)
{
String query="update People set Balance=Balance-"+base+" where ID="+soldto;
s1.executeUpdate(query);
query="update Items set SoldTo="+soldto+",SellingPrice="+base+" where ItemID="+itemid;
s1.executeUpdate(query);
query="select Name from People where ID="+soldto;
rs1=s1.executeQuery(query);
String name="";
while(rs1.next())
name=rs1.getString(1);
out="Item: "+itemid+" name: "+iname+" sold to Mr."+name+" with ID: "+soldto+" for price: $"+base;
System.out.println(out);
fr.write(out+"\n");
}
else
{
String query="update Items set SoldTo=null,SellingPrice=null where ItemID="+itemid;
s1.executeUpdate(query);
out="Item: "+itemid+" name: "+iname+" is not sold to anyone.";
System.out.println(out+"Auction closed for this item");
fr.write(out+"\n");
}
Thread.sleep(2000);
System.out.println();
}
fr.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
|
package com.qgbase.biz.reportSystem.service;
import com.qgbase.biz.reportSystem.domain.RsDeviceerrorlog;
import com.qgbase.biz.reportSystem.repository.RsDeviceerrorlogRespository;
import com.qgbase.common.TBaseBo;
import com.qgbase.common.dao.CommonDao;
import com.qgbase.common.domain.OperInfo;
import com.qgbase.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
/**
* Created by Mark on 2019-10-09
* * 主要用于:设备异常记录 业务处理,此代码为自动生成
*/
@Component
public class RsDeviceerrorlogService extends TBaseBo<RsDeviceerrorlog>{
@Autowired
CommonDao commonDao;
@Autowired
RsDeviceerrorlogRespository rsDeviceerrorlogRespository;
@Override
public RsDeviceerrorlog createObj() {
return new RsDeviceerrorlog();
}
@Override
public Class getEntityClass() {
return RsDeviceerrorlog.class;
}
@Override
public RsDeviceerrorlog newObj(OperInfo oper) throws Exception {
RsDeviceerrorlog obj = super.newObj(oper);
//这里对新创建的对象进行初始化 ,比如 obj.setIsUsed(1);
//写下你的处理方法
obj.setLogId(commonDao.getNewKey("elog", "elog", 4, 2));
obj.setHandleBak("");
obj.setStartDate(new Date());
obj.setUseTime(0);
return obj;
}
@Override
public String checkAddorUpdate(RsDeviceerrorlog obj, OperInfo oper, boolean isNew) throws Exception {
//这里对 新增和修改 保存前进行检查,检查失败返回错误信息
//写下你的处理方法
return super.checkAddorUpdate(obj, oper, isNew);
}
@Override
public String checkDelete(RsDeviceerrorlog obj, OperInfo oper) throws Exception {
//这里对 删除前进行检查,检查失败返回错误信息
//写下你的处理方法
return super.checkDelete(obj, oper);
}
public void handleError(String deviceid,String errorType, OperInfo oper) throws Exception {
List<RsDeviceerrorlog> rsDeviceerrorlogs= rsDeviceerrorlogRespository.findByDeviceIdAndErrorTypeAndEndDateIsNull(deviceid,errorType);
for (RsDeviceerrorlog rslog:rsDeviceerrorlogs
) {
rslog.setEndDate(new Date());
updateobj(rslog,oper);
}
}
}
|
package com.redhat.labs.service;
import com.redhat.labs.service.example.TestService;
import com.redhat.labs.service.example.TestServiceImpl;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.eventbus.ReplyException;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.StaticHandler;
import io.vertx.ext.web.handler.sockjs.BridgeOptions;
import io.vertx.ext.web.handler.sockjs.PermittedOptions;
import io.vertx.ext.web.handler.sockjs.SockJSHandler;
import io.vertx.serviceproxy.ProxyHelper;
import io.vertx.serviceproxy.ServiceException;
import java.time.Instant;
import static io.netty.handler.codec.http.HttpHeaderValues.APPLICATION_JSON;
import static io.vavr.API.$;
import static io.vavr.API.Case;
import static io.vavr.API.Match;
import static io.vavr.Predicates.instanceOf;
public class MainVerticle extends AbstractVerticle {
private static final String TEST_SERVICE = "test.service";
private static final String PERIODIC_TIMER = "periodic.timer";
@Override
public void start(Future startFuture) {
TestService svc = new TestServiceImpl(vertx);
ProxyHelper.registerService(TestService.class, vertx, svc, TEST_SERVICE);
vertx.setPeriodic(1000, (t) -> vertx.eventBus().publish(PERIODIC_TIMER, Instant.now().toString()));
vertx.setPeriodic(125, (t) -> vertx.eventBus().publish(PERIODIC_TIMER, "SPACER"));
Router router = Router.router(vertx);
BridgeOptions bOpts = new BridgeOptions();
bOpts.addInboundPermitted(new PermittedOptions()
.setAddress(TEST_SERVICE));
bOpts.addOutboundPermitted(new PermittedOptions()
.setAddress(TEST_SERVICE)
.setAddress(PERIODIC_TIMER));
SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
sockJSHandler.bridge(bOpts);
router.route("/eventbus/*").handler(sockJSHandler);
router.route().handler(StaticHandler.create()
.setCachingEnabled(false)
.setIndexPage("index.html"));
Router restV1 = Router.router(vertx);
// Set all REST API requests to use JSON and handle uploads for appropriate HTTP verbs
restV1.route()
.consumes(APPLICATION_JSON.toString())
.produces(APPLICATION_JSON.toString())
.handler(ctx -> ctx.next());
restV1.post()
.handler(BodyHandler.create());
restV1.put()
.handler(BodyHandler.create());
// Mount REST endpoints
restV1.get("/test").handler(ctx -> svc.test(res -> this.genericResultHandler(ctx, res)));
// Attach subrouter to main router
router.mountSubRouter("/rest/v1", restV1);
Future httpFuture = Future.future();
vertx.createHttpServer().requestHandler(router::accept).listen(8080, startFuture.completer());
}
/**
* Handle the result of a Service call and send the appropriate response
* @param ctx The {@link RoutingContext} of the request
* @param res The {@link AsyncResult} of the service call
*/
void genericResultHandler(RoutingContext ctx, AsyncResult res) {
if (res.succeeded()) {
ctx.response().end(res.result().toString());
} else {
HttpResponseStatus status = HttpResponseStatus.valueOf(Match(res.cause()).of(
Case($(instanceOf(ServiceException.class)), (c) -> ((ServiceException)c).failureCode()),
Case($(instanceOf(ReplyException.class)), (c) -> ((ReplyException)c).failureCode()),
Case($(), () -> 500)
));
ctx.response()
.setStatusMessage(status.reasonPhrase())
.setStatusCode(status.code());
}
}
}
|
package dstr_linkedlist;
import java.util.ArrayList;
public class Finder {
private final FamilyTree familyTree;
public Finder(FamilyTree familyTree) {
this.familyTree = familyTree;
}
public void findParents(String name) {
if (isMember(name)) {
if (familyTree.getParents(name).isEmpty()) {
System.out.println(name + " has no parents in the family tree");
} else {
System.out.println("Parents of " + name + " are:");
familyTree.getParents(name).stream().forEach(parent -> System.out.println("-" + parent.getName()));
}
}
}
public void findChildren(String name) {
try {
if (familyTree.getMember(name).getChildren().isEmpty()) {
System.out.println(name + " has no children in the family tree");
} else {
System.out.println("Children for " + name + " are: ");
familyTree.getMember(name).getChildren().stream().forEach(child -> System.out.println("-" + child.getName()));
}
} catch (Exception e) {
System.out.println(name + " is not a member of the family tree");
}
}
public void areSiblings(String firstName, String secondName) {
if (isMember(firstName) && isMember(secondName)) {
if (familyTree.getParents(firstName).equals(familyTree.getParents(secondName))) {
if (familyTree.getParents(firstName).isEmpty()) {
System.out.println(firstName + " and " + secondName + " are not siblings.");
return;
}
System.out.println(firstName + " and " + secondName + " are siblings.");
} else {
System.out.println(firstName + " and " + secondName + " are not siblings.");
}
}
}
public void findAncestors(String name) {
if (isMember(name)) {
ArrayList<Member> ancestors = familyTree.getParents(name);
if (ancestors.isEmpty()) {
System.out.println(name + " has no ancestors in the family tree");
return;
} else {
for (int i = 0; i < ancestors.size(); i++) {
if (familyTree.hasParents(ancestors.get(i).getName())) {
ancestors.addAll(familyTree.getParents(ancestors.get(i).getName()));
}
}
}
System.out.println("Ancestors for " + name + " are: ");
ancestors.stream().forEach(ancestor -> System.out.println("-" + ancestor.getName()));
}
}
public void showAllMembers() {
familyTree.getFamilyTree().stream().forEach(member -> System.out.println("-" + member.getName()));
}
private boolean isMember(String name) {
if (!familyTree.getFamilyTree().contains(familyTree.getMember(name))) {
System.out.println(name + " is not a member of the family tree");
return false;
}
return true;
}
}
|
package base.policy.impl;
import base.policy.Policy;
import base.policy.PolicyDecision;
import base.policy.PolicyPackage;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Policy</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link base.policy.impl.PolicyImpl#getName <em>Name</em>}</li>
* <li>{@link base.policy.impl.PolicyImpl#getBusinessValue <em>Business Value</em>}</li>
* <li>{@link base.policy.impl.PolicyImpl#getFeature <em>Feature</em>}</li>
* <li>{@link base.policy.impl.PolicyImpl#getDecision <em>Decision</em>}</li>
* </ul>
*
* @generated
*/
public class PolicyImpl extends MinimalEObjectImpl.Container implements Policy {
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected static final String NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected String name = NAME_EDEFAULT;
/**
* The default value of the '{@link #getBusinessValue() <em>Business Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getBusinessValue()
* @generated
* @ordered
*/
protected static final Integer BUSINESS_VALUE_EDEFAULT = null;
/**
* The cached value of the '{@link #getBusinessValue() <em>Business Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getBusinessValue()
* @generated
* @ordered
*/
protected Integer businessValue = BUSINESS_VALUE_EDEFAULT;
/**
* The default value of the '{@link #getFeature() <em>Feature</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getFeature()
* @generated
* @ordered
*/
protected static final String FEATURE_EDEFAULT = null;
/**
* The cached value of the '{@link #getFeature() <em>Feature</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getFeature()
* @generated
* @ordered
*/
protected String feature = FEATURE_EDEFAULT;
/**
* The cached value of the '{@link #getDecision() <em>Decision</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDecision()
* @generated
* @ordered
*/
protected PolicyDecision decision;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected PolicyImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return PolicyPackage.Literals.POLICY;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setName(String newName) {
String oldName = name;
name = newName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, PolicyPackage.POLICY__NAME, oldName, name));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Integer getBusinessValue() {
return businessValue;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setBusinessValue(Integer newBusinessValue) {
Integer oldBusinessValue = businessValue;
businessValue = newBusinessValue;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, PolicyPackage.POLICY__BUSINESS_VALUE, oldBusinessValue, businessValue));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getFeature() {
return feature;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setFeature(String newFeature) {
String oldFeature = feature;
feature = newFeature;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, PolicyPackage.POLICY__FEATURE, oldFeature, feature));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PolicyDecision getDecision() {
return decision;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetDecision(PolicyDecision newDecision, NotificationChain msgs) {
PolicyDecision oldDecision = decision;
decision = newDecision;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, PolicyPackage.POLICY__DECISION, oldDecision, newDecision);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setDecision(PolicyDecision newDecision) {
if (newDecision != decision) {
NotificationChain msgs = null;
if (decision != null)
msgs = ((InternalEObject)decision).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - PolicyPackage.POLICY__DECISION, null, msgs);
if (newDecision != null)
msgs = ((InternalEObject)newDecision).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - PolicyPackage.POLICY__DECISION, null, msgs);
msgs = basicSetDecision(newDecision, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, PolicyPackage.POLICY__DECISION, newDecision, newDecision));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case PolicyPackage.POLICY__DECISION:
return basicSetDecision(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case PolicyPackage.POLICY__NAME:
return getName();
case PolicyPackage.POLICY__BUSINESS_VALUE:
return getBusinessValue();
case PolicyPackage.POLICY__FEATURE:
return getFeature();
case PolicyPackage.POLICY__DECISION:
return getDecision();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case PolicyPackage.POLICY__NAME:
setName((String)newValue);
return;
case PolicyPackage.POLICY__BUSINESS_VALUE:
setBusinessValue((Integer)newValue);
return;
case PolicyPackage.POLICY__FEATURE:
setFeature((String)newValue);
return;
case PolicyPackage.POLICY__DECISION:
setDecision((PolicyDecision)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case PolicyPackage.POLICY__NAME:
setName(NAME_EDEFAULT);
return;
case PolicyPackage.POLICY__BUSINESS_VALUE:
setBusinessValue(BUSINESS_VALUE_EDEFAULT);
return;
case PolicyPackage.POLICY__FEATURE:
setFeature(FEATURE_EDEFAULT);
return;
case PolicyPackage.POLICY__DECISION:
setDecision((PolicyDecision)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case PolicyPackage.POLICY__NAME:
return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
case PolicyPackage.POLICY__BUSINESS_VALUE:
return BUSINESS_VALUE_EDEFAULT == null ? businessValue != null : !BUSINESS_VALUE_EDEFAULT.equals(businessValue);
case PolicyPackage.POLICY__FEATURE:
return FEATURE_EDEFAULT == null ? feature != null : !FEATURE_EDEFAULT.equals(feature);
case PolicyPackage.POLICY__DECISION:
return decision != null;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuilder result = new StringBuilder(super.toString());
result.append(" (name: ");
result.append(name);
result.append(", businessValue: ");
result.append(businessValue);
result.append(", feature: ");
result.append(feature);
result.append(')');
return result.toString();
}
} //PolicyImpl
|
package com.bastiaanjansen.jwt.exceptions;
public class JWTExpiredException extends JWTValidationException {
public JWTExpiredException() {}
public JWTExpiredException(String message) {
super(message);
}
}
|
package com.jim.multipos.ui.mainpospage.presenter;
import com.jim.multipos.core.Presenter;
/**
* Created by Sirojiddin on 27.10.2017.
*/
public interface SearchModePresenter extends Presenter {
void setSkuSearchMode(boolean active);
void setNameSearchMode(boolean active);
void setBarcodeSearchMode(boolean active);
void onSearchTextChange(String s);
void onOkPressed();
}
|
package org.itstep.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
@Setter
@Getter
public class User {
}
|
package api.longpoll.bots.adapters.deserializers;
import api.longpoll.bots.model.events.VkEvent;
import api.longpoll.bots.model.events.EventType;
import api.longpoll.bots.model.events.boards.BoardPostDeleteEvent;
import api.longpoll.bots.model.events.boards.BoardPostEvent;
import api.longpoll.bots.model.events.likes.LikeEvent;
import api.longpoll.bots.model.events.market.MarketCommentDeleteEvent;
import api.longpoll.bots.model.events.market.MarketCommentEvent;
import api.longpoll.bots.model.events.messages.MessageAllowEvent;
import api.longpoll.bots.model.events.messages.MessageDenyEvent;
import api.longpoll.bots.model.events.messages.MessageEvent;
import api.longpoll.bots.model.events.messages.MessageNewEvent;
import api.longpoll.bots.model.events.messages.MessageTypingStateEvent;
import api.longpoll.bots.model.events.other.AppPayload;
import api.longpoll.bots.model.events.other.GroupChangePhotoEvent;
import api.longpoll.bots.model.events.other.GroupChangeSettingsEvent;
import api.longpoll.bots.model.events.other.VkpayTransaction;
import api.longpoll.bots.model.events.photos.PhotoCommentDeleteEvent;
import api.longpoll.bots.model.events.photos.PhotoCommentEvent;
import api.longpoll.bots.model.events.users.GroupJoinEvent;
import api.longpoll.bots.model.events.users.GroupLeaveEvent;
import api.longpoll.bots.model.events.users.UserBlockEvent;
import api.longpoll.bots.model.events.users.UserUnblockEvent;
import api.longpoll.bots.model.events.video.VideoCommentDeleteEvent;
import api.longpoll.bots.model.events.video.VideoCommentEvent;
import api.longpoll.bots.model.events.wall.comments.WallReplyDeleteEvent;
import api.longpoll.bots.model.events.wall.comments.WallReplyEvent;
import api.longpoll.bots.model.objects.basic.MarketOrder;
import api.longpoll.bots.model.objects.basic.Message;
import api.longpoll.bots.model.objects.basic.WallPost;
import api.longpoll.bots.model.objects.media.Audio;
import api.longpoll.bots.model.objects.media.Photo;
import api.longpoll.bots.model.objects.media.Video;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
/**
* Deserializes JSON objects to {@link VkEvent}.
*/
public class EventDeserializer implements JsonDeserializer<VkEvent> {
@Override
public final VkEvent deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
JsonObject jsonEvent = jsonElement.getAsJsonObject();
VkEvent event = new VkEvent();
event.setType(jsonDeserializationContext.deserialize(
jsonEvent.get("type"),
EventType.class
));
event.setGroupId(jsonEvent.get("group_id").getAsInt());
event.setEventId(jsonEvent.get("event_id").getAsString());
event.setObject(jsonDeserializationContext.deserialize(
jsonEvent.get("object"),
getType(event.getType())
));
return event;
}
private Type getType(EventType type) {
switch (type) {
case APP_PAYLOAD:
return AppPayload.class;
case AUDIO_NEW:
return Audio.class;
case BOARD_POST_DELETE:
return BoardPostDeleteEvent.class;
case BOARD_POST_EDIT:
case BOARD_POST_NEW:
case BOARD_POST_RESTORE:
return BoardPostEvent.class;
case GROUP_CHANGE_PHOTO:
return GroupChangePhotoEvent.class;
case GROUP_CHANGE_SETTINGS:
return GroupChangeSettingsEvent.class;
case GROUP_JOIN:
return GroupJoinEvent.class;
case GROUP_LEAVE:
return GroupLeaveEvent.class;
case MARKET_COMMENT_DELETE:
return MarketCommentDeleteEvent.class;
case MARKET_COMMENT_EDIT:
case MARKET_COMMENT_NEW:
case MARKET_COMMENT_RESTORE:
return MarketCommentEvent.class;
case MARKET_ORDER_EDIT:
case MARKET_ORDER_NEW:
return MarketOrder.class;
case MESSAGE_EDIT:
return Message.class;
case MESSAGE_EVENT:
return MessageEvent.class;
case MESSAGE_NEW:
return MessageNewEvent.class;
case MESSAGE_REPLY:
return Message.class;
case MESSAGE_ALLOW:
return MessageAllowEvent.class;
case MESSAGE_DENY:
return MessageDenyEvent.class;
case MESSAGE_TYPING_STATE:
return MessageTypingStateEvent.class;
case LIKE_ADD:
case LIKE_REMOVE:
return LikeEvent.class;
case PHOTO_COMMENT_DELETE:
return PhotoCommentDeleteEvent.class;
case PHOTO_COMMENT_EDIT:
case PHOTO_COMMENT_NEW:
case PHOTO_COMMENT_RESTORE:
return PhotoCommentEvent.class;
case PHOTO_NEW:
return Photo.class;
case USER_BLOCK:
return UserBlockEvent.class;
case USER_UNBLOCK:
return UserUnblockEvent.class;
case VIDEO_COMMENT_DELETE:
return VideoCommentDeleteEvent.class;
case VIDEO_COMMENT_EDIT:
case VIDEO_COMMENT_NEW:
case VIDEO_COMMENT_RESTORE:
return VideoCommentEvent.class;
case VIDEO_NEW:
return Video.class;
case WALL_POST_NEW:
return WallPost.class;
case WALL_REPLY_DELETE:
return WallReplyDeleteEvent.class;
case WALL_REPLY_EDIT:
case WALL_REPLY_NEW:
case WALL_REPLY_RESTORE:
return WallReplyEvent.class;
case WALL_REPOST:
return WallPost.class;
case VKPAY_TRANSACTION:
default:
return VkpayTransaction.class;
}
}
}
|
package zm.gov.moh.core.repository.database.entity.domain;
import androidx.room.*;
import com.squareup.moshi.Json;
import org.threeten.bp.LocalDateTime;
@Entity(tableName = "patient_identifier_type")
public class PatientIdentifierType {
@PrimaryKey
@ColumnInfo(name = "patient_identifier_type_id")
@Json(name = "patient_identifier_type_id")
private Long patientIdentifierTypeId;
@ColumnInfo(name = "name")
@Json(name = "name")
private String name;
@ColumnInfo(name = "description")
@Json(name = "description")
private String description;
@ColumnInfo(name = "format")
@Json(name = "format")
private String format;
@ColumnInfo(name = "check_digit")
@Json(name = "check_digit")
private short checkDigit;
@ColumnInfo(name = "creator")
@Json(name = "creator")
private Long creator;
@ColumnInfo(name = "date_created")
@Json(name = "date_created")
private LocalDateTime dateCreated;
@ColumnInfo(name = "required")
@Json(name = "required")
private short required;
@ColumnInfo(name = "format_description")
@Json(name = "format_description")
private String formatDescription;
@ColumnInfo(name = "validator")
@Json(name = "validator")
private String validator;
@ColumnInfo(name = "location_behavior")
@Json(name = "location_behavior")
private String locationBehavior;
@ColumnInfo(name = "retired")
@Json(name = "retired")
private short retired;
@ColumnInfo(name = "retired_by")
@Json(name = "retired_by")
private Long retiredBy;
@ColumnInfo(name = "date_retired")
@Json(name = "date_retired")
private LocalDateTime dateRetired;
@ColumnInfo(name = "retired_reason")
@Json(name = "retired_reason")
private String retiredReason;
@ColumnInfo(name = "uuid")
@Json(name = "uuid")
private String uuid;
@ColumnInfo(name = "uniqueness_behavior")
@Json(name = "uniqueness_behavior")
private String uniquenessBehavior;
@ColumnInfo(name = "date_changed")
@Json(name = "date_changed")
private LocalDateTime dateChanged;
@ColumnInfo(name = "changed_by")
@Json(name = "changed_by")
private Long changedBy;
public Long getPatientIdentifierTypeId() {
return patientIdentifierTypeId;
}
public void setPatientIdentifierTypeId(Long patientIdentifierTypeId) {
this.patientIdentifierTypeId = patientIdentifierTypeId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public short getCheckDigit() {
return checkDigit;
}
public void setCheckDigit(short checkDigit) {
this.checkDigit = checkDigit;
}
public Long getCreator() {
return creator;
}
public void setCreator(Long creator) {
this.creator = creator;
}
public LocalDateTime getDateCreated() {
return dateCreated;
}
public void setDateCreated(LocalDateTime dateCreated) {
this.dateCreated = dateCreated;
}
public short getRequired() {
return required;
}
public void setRequired(short required) {
this.required = required;
}
public String getFormatDescription() {
return formatDescription;
}
public void setFormatDescription(String formatDescription) {
this.formatDescription = formatDescription;
}
public String getValidator() {
return validator;
}
public void setValidator(String validator) {
this.validator = validator;
}
public String getLocationBehavior() {
return locationBehavior;
}
public void setLocationBehavior(String locationBehavior) {
this.locationBehavior = locationBehavior;
}
public short getRetired() {
return retired;
}
public void setRetired(short retired) {
this.retired = retired;
}
public Long getRetiredBy() {
return retiredBy;
}
public void setRetiredBy(Long retiredBy) {
this.retiredBy = retiredBy;
}
public LocalDateTime getDateRetired() {
return dateRetired;
}
public void setDateRetired(LocalDateTime dateRetired) {
this.dateRetired = dateRetired;
}
public String getRetiredReason() {
return retiredReason;
}
public void setRetiredReason(String retiredReason) {
this.retiredReason = retiredReason;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getUniquenessBehavior() {
return uniquenessBehavior;
}
public void setUniquenessBehavior(String uniquenessBehavior) {
this.uniquenessBehavior = uniquenessBehavior;
}
public LocalDateTime getDateChanged() {
return dateChanged;
}
public void setDateChanged(LocalDateTime dateChanged) {
this.dateChanged = dateChanged;
}
public Long getChangedBy() {
return changedBy;
}
public void setChangedBy(Long changedBy) {
this.changedBy = changedBy;
}
}
|
package test_strutturali;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.util.*;
import org.junit.Before;
import org.junit.Test;
import sistema.*;
public class ApplicazioneGestoreCinemaTest {
ApplicazioneGestoreCinema app;
Calendar birthday;
GestoreCinema gestore;
ApplicazioneAmministratoreSistema adminApp;
@Before
public void setUp() throws Exception {
app = new ApplicazioneGestoreCinema();
birthday = Calendar.getInstance();
birthday.set(1980, 0, 1);
gestore = new GestoreCinema("Luca", "Rossi", "RSSLCU80A01D969P",
birthday, "RSSLCU80A01D969P", "0000", "luca.rossi@gmail.com");
Calendar c = Calendar.getInstance();
c.set(1975, 2, 5);
adminApp = new ApplicazioneAmministratoreSistema("Anna",
"Bianchi", "BNCNNA75C45D969Q", c, "AnnaBianchi", "0000", "anna.bianchi@gmail.com");
assertTrue(adminApp.login("AnnaBianchi", "0000"));
adminApp.resetApplication();
}
@Test
public void testConstructor() {
assertNotNull(app);
}
@Test
public void testLoginAndLogout() {
assertFalse(app.login("RSSLCU80A01D969P", "0000"));
assertFalse(app.logout());
// Registration of two GestoreCinema
assertTrue(adminApp.registraNuovoGestoreCinema("Luca", "Rossi", "RSSLCU80A01D969P", birthday, "luca.rossi@gmail.com"));
assertTrue(adminApp.registraNuovoGestoreCinema("Marco", "Verdi", "VRDMRC80A01D969X", birthday, "luca.rossi@gmail.com"));
assertFalse(app.login(null, null));
assertFalse(app.login("RSSLCU80A01D969P", null));
assertFalse(app.login("RSSLCU80A01D969P", "WrongPassword"));
assertTrue(app.login("RSSLCU80A01D969P", "0000"));
assertFalse(app.login("RSSLCU80A01D969P", "0000"));
assertTrue(app.logout());
assertFalse(app.logout());
assertTrue(app.login("VRDMRC80A01D969X", "0000"));
assertTrue(app.logout());
assertTrue(adminApp.removeGestoreCinema("VRDMRC80A01D969X"));
assertTrue(adminApp.registraNuovoGestoreCinema("Marco", "Verdi", "VRDMRC80A01D969X", birthday, "luca.rossi@gmail.com"));
assertTrue(app.login("VRDMRC80A01D969X", "0000"));
// Remotion of the GestoreCinema
assertTrue(adminApp.removeGestoreCinema("VRDMRC80A01D969X"));
assertFalse(app.logout());
}
@Test
public void testInserisciNuovaSalaAndEliminaSala() {
assertEquals(-1, app.inserisciNuovaSala(-1, "Sala A", 10, 10, 10));
assertFalse(app.eliminaSala(-1, -1));
// Registration of the GestoreCinema
adminApp.registraNuovoGestoreCinema("Luca", "Rossi", "RSSLCU80A01D969P", birthday, "luca.rossi@gmail.com");
app.login("RSSLCU80A01D969P", "0000");
assertEquals(-1, app.inserisciNuovaSala(-1, "Sala A", 10, 10, 10));
assertFalse(app.eliminaSala(-1, -1));
app.logout();
assertEquals(-1, app.inserisciNuovaSala(-1, "Sala A", 10, 10, 10));
assertFalse(app.eliminaSala(-1, -1));
app.login("RSSLCU80A01D969P", "0000");
Cinema cinema = new Cinema("Odeon", "Corso Buenos Aires, 83, 16129 Genova");
assertTrue(adminApp.addNewCinema("RSSLCU80A01D969P", cinema));
assertEquals(-1, app.inserisciNuovaSala(-1, "Sala A", 10, 10, 10));
int id = app.inserisciNuovaSala(cinema.getId(), "Sala A", 10, 10, 10);
assertNotEquals(-1, id);
assertFalse(app.eliminaSala(-1, id));
assertTrue(app.eliminaSala(cinema.getId(), id));
}
@Test
public void testPrint() {
ArrayList<Sala> rooms = new ArrayList<Sala>();
Cinema cinema = new Cinema("Odeon", "Corso Buenos Aires, 83, 16129 Genova");
rooms.add(new Sala("Sala A", 10, 10, 10, cinema));
app.printRoomsFromList(rooms);
assertFalse(app.printProfilo());
assertFalse(app.printRooms(-1));
// Registration of the GestoreCinema
adminApp.registraNuovoGestoreCinema("Luca", "Rossi", "RSSLCU80A01D969P", birthday, "luca.rossi@gmail.com");
assertFalse(app.printProfilo());
assertFalse(app.printRooms(-1));
app.login("RSSLCU80A01D969P", "0000");
assertTrue(app.printProfilo());
assertFalse(app.printRooms(-1));
adminApp.removeGestoreCinema("RSSLCU80A01D969P");
adminApp.registraNuovoGestoreCinema("Luca", "Rossi", "RSSLCU80A01D969P", birthday, "luca.rossi@gmail.com");
assertFalse(app.logout());
app.login("RSSLCU80A01D969P", "0000");
adminApp.addNewCinema("RSSLCU80A01D969P", cinema);
assertTrue(app.printProfilo());
assertFalse(app.printRooms(-1));
assertFalse(app.printRooms(cinema.getId()));
app.logout();
assertFalse(app.printProfilo());
assertFalse(app.printRooms(-1));
}
@Test
public void testPrintAllCinemaAndAllShows() {
assertFalse(app.printAllCinema());
assertFalse(app.printAllShows(-1, -1));
// Registration of the GestoreCinema
adminApp.registraNuovoGestoreCinema("Luca", "Rossi", "RSSLCU80A01D969P", birthday, "luca.rossi@gmail.com");
app.login("RSSLCU80A01D969P", "0000");
assertFalse(app.printAllCinema());
assertFalse(app.printAllShows(-1, -1));
Cinema cinema = new Cinema("Odeon", "Corso Buenos Aires, 83, 16129 Genova");
adminApp.addNewCinema("RSSLCU80A01D969P", cinema);
assertTrue(app.printAllCinema());
assertFalse(app.printAllShows(cinema.getId(), -1));
assertFalse(app.printAllShows(-1, -1));
app.logout();
assertFalse(app.printAllCinema());
assertFalse(app.printAllShows(-1, -1));
}
@Test
public void testAddShowAndVerifyRoomsAvailability() {
Spettacolo mockedShow = mock(Spettacolo.class);
assertNull(app.verifyRoomsAvailability(-1, mockedShow, 5));
assertFalse(app.addShows(-1, mockedShow, 5, -1));
// Registration of the GestoreCinema
assertTrue(adminApp.registraNuovoGestoreCinema("Luca", "Rossi", "RSSLCU80A01D969P", birthday, "luca.rossi@gmail.com"));
assertNull(app.verifyRoomsAvailability(-1, mockedShow, 5));
assertFalse(app.addShows(-1, mockedShow, 5, -1));
app.login("RSSLCU80A01D969P", "0000");
assertNull(app.verifyRoomsAvailability(-1, mockedShow, 5));
assertFalse(app.addShows(-1, mockedShow, 5, -1));
Cinema cinema = new Cinema("Odeon", "Corso Buenos Aires, 83, 16129 Genova");
adminApp.addNewCinema("RSSLCU80A01D969P", cinema);
assertNull(app.verifyRoomsAvailability(-1, mockedShow, 5));
assertFalse(app.addShows(-1, mockedShow, 5, -1));
assertNotNull(app.verifyRoomsAvailability(cinema.getId(), mockedShow, 5));
assertFalse(app.addShows(cinema.getId(), mockedShow, 0, -1));
// Returns false because there are no rooms registered for this cinema
assertFalse(app.addShows(cinema.getId(), mockedShow, 5, -1));
app.logout();
assertNull(app.verifyRoomsAvailability(-1, mockedShow, 5));
assertFalse(app.addShows(-1, mockedShow, 5, -1));
}
@Test
public void testSendEmail() {
app.sendEmail("luca.rossi@gmail.com", "params");
}
@Test
public void testHasCinemaAndHasRoom() {
assertFalse(app.hasCinema(-1));
assertFalse(app.hasRoom(-1, -1));
// Registration of the GestoreCinema
assertTrue(adminApp.registraNuovoGestoreCinema("Luca", "Rossi", "RSSLCU80A01D969P", birthday, "luca.rossi@gmail.com"));
app.login("RSSLCU80A01D969P", "0000");
assertFalse(app.hasCinema(-1));
assertFalse(app.hasRoom(-1, -1));
Cinema cinema = new Cinema("Odeon", "Corso Buenos Aires, 83, 16129 Genova");
adminApp.addNewCinema("RSSLCU80A01D969P", cinema);
assertTrue(app.hasCinema(cinema.getId()));
assertFalse(app.hasCinema(-1));
assertFalse(app.hasRoom(cinema.getId(), -1));
assertFalse(app.hasRoom(-1, -1));
app.logout();
assertFalse(app.hasCinema(-1));
assertFalse(app.hasRoom(-1, -1));
}
}
|
package base;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;
import pages.ContactPage;
import pages.HomePage;
import pages.SubmissionGuidPage;
import java.util.Map;
/**
*
*/
public class BasePage extends BaseUtil {
protected BaseUtil base;
protected ContactPage contactPage;
protected Map<String, String> data;
protected HomePage homePage;
protected SubmissionGuidPage submissionGuidPage;
protected WebDriverWait wait;
public BasePage(BaseUtil base) {
this.base = base;
this.contactPage = PageFactory.initElements(base.driver, ContactPage.class);
this.homePage = PageFactory.initElements(base.driver, HomePage.class);
this.submissionGuidPage = PageFactory.initElements(base.driver, SubmissionGuidPage.class);
this.wait = new WebDriverWait(base.driver, 15);
}
}
|
package com.mycompany.dao;
/**
* Created by reza on 2/8/17.
*/
public interface CorporateEventDao {
}
|
package yul.board;
import java.util.HashMap;
import java.util.List;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import yul.common.FileVO;
import yul.common.SearchVO;
@Service
public class BoardSvc {
@Autowired
private SqlSessionTemplate sqlSession;
@Autowired
private DataSourceTransactionManager txManager;
public Integer selectBoardCount(SearchVO param) {
return sqlSession.selectOne("selectBoard6Count", param);
}
public List<?> selectBoardList(SearchVO param) {
return sqlSession.selectList("selectBoard6List", param);
}
/**
* 글 저장.
*/
public void insertBoard(BoardVO param, List<FileVO> filelist, String[] fileno) {
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
TransactionStatus status = txManager.getTransaction(def);
try {
if (param.getBrdno() == null || "".equals(param.getBrdno())) {
sqlSession.insert("insertBoard6", param);
} else {
sqlSession.update("updateBoard6", param);
}
if (fileno != null) {
HashMap<String, String[]> fparam = new HashMap<String, String[]>();
fparam.put("fileno", fileno);
sqlSession.insert("deleteBoard6File", fparam);
}
for (FileVO f : filelist) {
f.setParentPK(param.getBrdno());
sqlSession.insert("insertBoard6File", f);
}
txManager.commit(status);
} catch (TransactionException ex) {
txManager.rollback(status);
System.out.println("데이터 저장 오류: " + ex.toString());
}
}
public BoardVO selectBoardOne(String param) {
return sqlSession.selectOne("selectBoard6One", param);
}
public void updateBoard6Read(String param) {
sqlSession.insert("updateBoard6Read", param);
}
public void deleteBoardOne(String param) {
sqlSession.delete("deleteBoard6One", param);
}
public List<?> selectBoard6FileList(String param) {
return sqlSession.selectList("selectBoard6FileList", param);
}
/* =============================================================== */
public List<?> selectBoard6ReplyList(String param) {
return sqlSession.selectList("selectBoard6ReplyList", param);
}
/**
* 댓글 저장.
*/
public void insertBoardReply(BoardReplyVO param) {
if (param.getReno() == null || "".equals(param.getReno())) {
if (param.getReparent() != null) {
BoardReplyVO replyInfo = sqlSession.selectOne("selectBoard6ReplyParent", param.getReparent());
param.setRedepth(replyInfo.getRedepth());
param.setReorder(replyInfo.getReorder() + 1);
sqlSession.selectOne("updateBoard6ReplyOrder", replyInfo);
} else {
Integer reorder = sqlSession.selectOne("selectBoard6ReplyMaxOrder", param.getBrdno());
param.setReorder(reorder);
}
sqlSession.insert("insertBoard6Reply", param);
} else {
sqlSession.insert("updateBoard6Reply", param);
}
}
/**
* 댓글 삭제.
* 자식 댓글이 있으면 삭제 안됨.
*/
public boolean deleteBoard6Reply(String param) {
Integer cnt = sqlSession.selectOne("selectBoard6ReplyChild", param);
if ( cnt > 0) {
return false;
}
sqlSession.update("updateBoard6ReplyOrder4Delete", param);
sqlSession.delete("deleteBoard6Reply", param);
return true;
}
}
|
/*
* Copyright (c) 2013 University of Tartu
*/
package org.dmg.pmml;
public class FieldName {
private String value = null;
public FieldName(String value){
setValue(value);
}
@Override
public int hashCode(){
return getValue().hashCode();
}
@Override
public boolean equals(Object object){
if(object instanceof FieldName){
FieldName that = (FieldName)object;
return (this.getValue()).equals(that.getValue());
}
return super.equals(object);
}
@Override
public String toString(){
return getValue();
}
public String getValue(){
return this.value;
}
private void setValue(String value){
if(value == null){
throw new NullPointerException();
}
this.value = value;
}
static
public FieldName unmarshal(String value){
return new FieldName(value);
}
static
public String marshal(FieldName name){
return name.getValue();
}
}
|
package com.lr.service;
import com.lr.mapper.UtilMapper;
import com.lr.util.subjectUtil;
import com.lr.util.testPaperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class utilService {
@Autowired
private UtilMapper utilMapper;
public List<testPaperUtil> paperMange(String testPaperId) {
return utilMapper.paperMange(testPaperId);
}
public List<subjectUtil> addTestPaper() {
return utilMapper.addTestPaper();
}
}
|
class FastReader {
private BufferedReader br;
private StringTokenizer st;
FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
private String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
// FastReader in = new FastReader();
// int n = in.nextInt();
|
package com.epam.strings.text.entity;
import java.util.List;
public class TokenLeaf implements Component{
private final String value;
private final TypeLeaf type;
private TokenLeaf(String value, TypeLeaf type) {
this.value = value;
this.type = type;
}
@Override
public String getValue() {
return value;
}
public TypeLeaf getType() {
return type;
}
public static TokenLeaf newWord(String value) {
return new TokenLeaf(value, TypeLeaf.WORD);
}
public static TokenLeaf newExpression(String value) {
return new TokenLeaf(value, TypeLeaf.EXPRESSION);
}
public static TokenLeaf newMark(String value) {
return new TokenLeaf(value, TypeLeaf.MARK);
}
@Override
public void add(Component component) {
throw new UnsupportedOperationException();
}
@Override
public List<Component> getComponents() {
throw new UnsupportedOperationException();
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
if(type != TypeLeaf.MARK) {
stringBuilder.append(" ");
}
stringBuilder.append(value);
return stringBuilder.toString();
}
}
|
package teat;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class KeySet {
public static void main(String[] args) {
Map<String,String> map = new HashMap<>();
map.put("PS4","战神");
map.put("Switch","萨尔达");
map.put("Xbox","光环");
map.put("PC","嘿嘿");
Set<String> keySet = map.keySet();
for (String key:keySet) {
System.out.println("KEY:"+key);
}
}
}
|
package AsyncTask;
import android.os.AsyncTask;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.google.android.gms.maps.model.LatLng;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import DTO.Jam;
import Listener.OnLoadListener;
/**
* Created by lequan on 5/13/2016.
*/
public class TrafficAst extends AsyncTask<String, Integer, ArrayList<LatLng>>
{
OnLoadListener listener;
ArrayList<LatLng> list;
public void setOnLoadListener(OnLoadListener listener)
{
this.listener = listener;
}
public TrafficAst()
{
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
}
@Override
protected void onPostExecute(ArrayList<LatLng> result)
{
listener.onFinish(result);
super.onPostExecute(result);
}
@Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
}
@Override
protected ArrayList<LatLng> doInBackground(String... params)
{
list = new ArrayList<>();
Firebase ref = new Firebase("https://androidtraffic.firebaseio.com/");
ref.addValueEventListener(new ValueEventListener()
{
@Override
public void onDataChange(DataSnapshot snapshot)
{
try
{
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
Date date = new Date();
int timeNow = 60 * date.getHours() + date.getMinutes();
int meta = ((Long) snapshot.child("meta").getValue()).intValue();
DataSnapshot traffic = snapshot.child("traffic");
for (DataSnapshot item : traffic.getChildren())
{
ArrayList<Jam> jamList = new ArrayList<>();
DataSnapshot jamData = item.child("jam");
for (DataSnapshot jam : jamData.getChildren())
{
String time = (String) jam.child("time").getValue();
Date jamTime = formatter.parse(time);
int span = timeNow - 60 * jamTime.getHours() - jamTime.getMinutes();
if (span > -90 && span < 90) // timespan between 90 minutes earlier or later
{
int vote = ((Integer) jam.child("voteList").getValue()).intValue();
if (vote > meta)
{
jamList.add(new Jam(time, vote));
break;
}
}
}
if (jamList.size() > 0)
{
//sortDescending(jamList);
double lat = (double) item.child("position/lat").getValue();
double lng = (double) item.child("position/lng").getValue();
list.add(new LatLng(lat, lng));
//Traffic traffic = new Traffic(lat, lng, jamList.get(0).getVote());
}
}
}
catch (ParseException e)
{
e.printStackTrace();
}
}
@Override
public void onCancelled(FirebaseError firebaseError)
{
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
return list;
}
}
|
package com.example.android.jokesapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.example.android.jokedisplayer.JokeActivity;
import com.example.android.jokesource.Joke;
public class MainActivity extends AppCompatActivity {
private static String JOKE_KEY = "joke key";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void showJoke(View view) {
Joke joke = new Joke();
String jokeText = joke.getJoke();
Intent jokeActivity = new Intent(this, JokeActivity.class);
jokeActivity.putExtra(JOKE_KEY, jokeText);
startActivity(jokeActivity);
}
}
|
package unalcol.agents;
import java.util.Hashtable;
/**
* <p>Title: Percept</p>
* <p>
* <p>Description: Abstract definition of a perception</p>
* <p>
* <p>Copyright: Copyright (c) 2007</p>
* <p>
* <p>Company: Universidad Nacional de Colombia</p>
*
* @author Jonatan Gomez
* @version 1.0
*/
public class Percept {
Hashtable<String, Object> table = new Hashtable<String, Object>();
public Percept() {
}
public Object getAttribute(String code) {
return table.get(code);
}
public void setAttribute(String key, Object value) {
table.put(key, value);
}
}
|
package com.tao.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.tao.model.Commodity;
import com.tao.model.User;
import com.tao.utils.*;
public class UserDao extends Dao{
public UserDao(DataProcess dataProcess) {
super(dataProcess);
}
public User findByUsername(String username) {
if (username == null) {
return null;
}
String sql = "select * from user where email = ?";
// String sql = "select * from user";
String[] userInfo = { username };
ResultSet resultSet = dataProcess.executeQuery(sql, userInfo);
try {
while (resultSet.next()) {
User user = new User(resultSet.getString("email"),
resultSet.getString("passwd"),
resultSet.getDouble("account"),
resultSet.getDouble("buyerCredit"),
resultSet.getDouble("sellerCredit"));
return user;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public void add(User user) throws SQLException {
String sql = "insert into user(email,passwd) values(?,?)";
dataProcess.execute(sql,user.getEmail(),user.getPassword());
}
public void cost(User user,double cost){
String sql = "update user set account = ? where email = ?";
double price = user.getAccount()-cost;
dataProcess.execute(sql, price,user.getEmail());
}
public void earn(User user){
System.out.println("earn:"+user.getAccount());
String sql = "update user set account = ? where email = ?";
double price = user.getAccount();
dataProcess.execute(sql, price,user.getEmail());
}
public ResultSet queryUser(String email){
String sql = "select * from user where email = ?";
return dataProcess.executeQuery(sql, email);
}
}
|
package Serializacao;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Scanner;
public class Program {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
Tenis[] arrayTenis = new Tenis[3];
Tenis tenis1 = new Tenis("Adidas", "bolts", 44);
Tenis tenis2 = new Tenis("AllStar", "allstart", 44);
Tenis tenis3 = new Tenis("Nike", "corrida", 44);
arrayTenis[0] = tenis1;
arrayTenis[1] = tenis2;
arrayTenis[2] = tenis3;
serializaListaTenis(arrayTenis);
desserializaListaTenis();
sc.close();
}
public static void serializaListaTenis(Tenis[] tenis) {
try {
ObjectOutputStream oS = new ObjectOutputStream(
new FileOutputStream("src/Serializacao/Tenis.txt"));
oS.writeObject(tenis);
oS.close();
System.out.println("Dados salvo com sucesso.");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void desserializaListaTenis() throws IOException {
Tenis[] arrayTenis = new Tenis[3];
try {
FileInputStream fileIn = new FileInputStream("src/Serializacao/Tenis.txt");
ObjectInputStream in = new ObjectInputStream(fileIn);
arrayTenis = (Tenis[]) in.readObject();
System.out.println("Dados do Tenis:");
for (int i = 0; i < arrayTenis.length; i++) {
System.out.println(arrayTenis[i].toString());
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
|
package com.book.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
/**
* @author weigs
* @date 2017/10/5 0005
*/
public class TestDriver {
public static void main(String[] args) {
PersonBean personBean1 = new PersonBeanImpl();
PersonBean personBean2 = new PersonBeanImpl();
InvocationHandler invocationHandler1 =
new NonOwnerInvocationHandler(personBean1);
InvocationHandler invocationHandler2 =
new OwnerInvocationHander(personBean2);
PersonBean proxy1 = (PersonBean) Proxy.newProxyInstance(invocationHandler1.getClass().getClassLoader(),
personBean1.getClass().getInterfaces(), invocationHandler1);
System.out.println("proxy1----------------");
proxy1.setGender("nan");
proxy1.setHotOrNotRating(1);
PersonBean proxy2 = (PersonBean) Proxy.newProxyInstance(invocationHandler2.getClass().getClassLoader(),
personBean2.getClass().getInterfaces(), invocationHandler2);
System.out.println("proxy2-----------------");
proxy2.setGender("nv");
proxy2.setHotOrNotRating(2);
}
}
|
package rs.code9.taster.service.memory;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import rs.code9.taster.model.Question;
import rs.code9.taster.service.QuestionService;
/**
* In memory backed {@link QuestionService} implementation.
*
* @author d.gajic
*/
@Service
public class InMemoryQuestionService extends AbstractInMemoryService<Question> implements QuestionService {
/**
* @see rs.code9.taster.service.QuestionService#findByCategoryId(java.lang.Long)
*/
@Override
public List<Question> findByCategoryId(Long categoryId) {
List<Question> res = new ArrayList<>();
for (Question q : findAll()) {
if (q.getCategory() != null && q.getCategory().getId().equals(categoryId)) {
res.add(q);
}
}
return res;
}
}
|
package com.mitelcel.pack.bean.api.request;
import com.google.gson.Gson;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.mitelcel.pack.bean.GenericBean;
import com.mitelcel.pack.utils.MiUtils;
/**
* Created by sudhanshu.thanedar on 11/17/15.
*/
public class BeanRechargeAccount extends BeanGenericApi {
public static final String NAME = "recharge_account";
@Expose
private Params params;
public BeanRechargeAccount(float amount) {
this.id = System.currentTimeMillis();
this.method = NAME;
this.params = new Params(amount);
}
public BeanRechargeAccount(float amount, String password) {
this.id = System.currentTimeMillis();
this.method = NAME;
this.params = new Params(amount, password);
}
@Override
public String toString() {
return new Gson().toJson(this);
}
public class Params extends GenericBean {
@Expose
private float amount;
@SerializedName("app_token")
@Expose
private String appToken;
@SerializedName("session_id")
@Expose
private String sessionId;
@Expose
private BeanCredentials credentials;
public Params(float amount) {
this.amount = amount;
this.appToken = MiUtils.MiAppPreferences.getToken();
this.sessionId = MiUtils.MiAppPreferences.getSessionId();
this.credentials = new BeanCredentials();
}
public Params(float amount, String password) {
this.amount = amount;
this.appToken = MiUtils.MiAppPreferences.getToken();
this.sessionId = MiUtils.MiAppPreferences.getSessionId();
String msisdn = MiUtils.MiAppPreferences.getMsisdn();
this.credentials = new BeanCredentials(msisdn, password);
}
}
}
|
package chapter04;
import java.util.Scanner;
public class Exercise04_07 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the radius of the bounding circle: ");
double radius = input.nextDouble();
double a = Math.PI / 2.;
int side = 5;
double increase = (2. * Math.PI) / side;
System.out.println("The coordinates of five points on the pentagon are");
System.out.println("(" + (radius * Math.cos(a)) + ", " + (radius * Math.sin(a)) + ")");
a += increase;
System.out.println("(" + (radius * Math.cos(a)) + ", " + (radius * Math.sin(a)) + ")");
a += increase;
System.out.println("(" + (radius * Math.cos(a)) + ", " + (radius * Math.sin(a)) + ")");
a += increase;
System.out.println("(" + (radius * Math.cos(a)) + ", " + (radius * Math.sin(a)) + ")");
a += increase;
System.out.println("(" + (radius * Math.cos(a)) + ", " + (radius * Math.sin(a)) + ")");
}
}
|
package com.tencent.mm.plugin.ipcall.ui;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
class IPCallMyGiftCardUI$1 implements OnMenuItemClickListener {
final /* synthetic */ IPCallMyGiftCardUI kwG;
IPCallMyGiftCardUI$1(IPCallMyGiftCardUI iPCallMyGiftCardUI) {
this.kwG = iPCallMyGiftCardUI;
}
public final boolean onMenuItemClick(MenuItem menuItem) {
this.kwG.finish();
return true;
}
}
|
package com.pfchoice.springboot.repositories;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
import com.pfchoice.springboot.model.CPTMeasure;
import com.pfchoice.springboot.repositories.intf.RecordDetailsAwareRepository;
@Repository
public interface CPTMeasureRepository
extends PagingAndSortingRepository<CPTMeasure, Integer>, JpaSpecificationExecutor<CPTMeasure>, RecordDetailsAwareRepository<CPTMeasure, Integer> {
public CPTMeasure findById(Integer id);
public CPTMeasure findByCode(String code);
public CPTMeasure findByDescription(String description);
}
|
package com.ntech.service.impl;
import com.ntech.dao.OperationLogMapper;
import com.ntech.model.OperationLog;
import com.ntech.model.OperationLogExample;
import com.ntech.service.inf.IOperationLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by hasee on 2017/10/25.
*/
@Service
public class OperationLogService implements IOperationLogService {
@Autowired
private OperationLogMapper OperationLogMapper;
@Override
public List<OperationLog> findByName(String name) {
return null;
}
@Transactional
public void add(OperationLog OperationLog) {
OperationLogMapper.insert(OperationLog);
}
@Override
public List<OperationLog> findAll() {
return null;
}
@Override
public long totalCount() {
return 0;
}
@Override
public List<OperationLog> findPage(int limit, int offset) {
return null;
}
@Override
public List<OperationLog> findByNameWithLimit(String name, int limit, int offset) {
return null;
}
@Override
public List<OperationLog> findWithConditions(String name, int limit, int offset, String type, String start, String end) {
return null;
}
@Override
public long findCount(String name, int limit, int offset, String type, String start, String end) {
return 0;
}
}
|
package com.an.an_be.controller;
import com.alibaba.fastjson.JSONObject;
import com.an.an_be.entity.Result;
import com.an.an_be.service.BillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/**
* @description:
* @Author zhangan
* @date: 2019/12/19
*/
@RestController
public class BillController {
@Autowired
private BillService billService;
/**
* 获取所有账单列表
* */
@GetMapping(value="/getAllBill")
public Result getAllBill(){
JSONObject result = new JSONObject();
try{
return new Result(200,"操作成功",true, billService.getAllBill());
}catch (Exception e){
e.printStackTrace();
return new Result(404,"系统错误",false);
}
}
/**
* 获取所有账单列表
* */
@GetMapping(value="/getBillByCondition")
public Result getBillByCondition(Map<String,Object> param){
try{
return new Result(200,"操作成功",true, billService.getBillByCondition(param));
}catch (Exception e){
e.printStackTrace();
return new Result(404,"系统错误",false);
}
}
}
|
package com.tencent.mm.an;
import com.tencent.mm.g.a.js;
import com.tencent.mm.protocal.c.avq;
import com.tencent.mm.sdk.b.a;
class b$5 implements Runnable {
final /* synthetic */ avq eba;
b$5(avq avq) {
this.eba = avq;
}
public final void run() {
js jsVar = new js();
jsVar.bTw.action = 6;
jsVar.bTw.bTy = this.eba;
a.sFg.m(jsVar);
}
}
|
package com.yougou.merchant.api;
import javax.annotation.Resource;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import com.yougou.base.JUnitServiceBase;
import com.yougou.merchant.api.supplier.service.IContactApi;
import com.yougou.merchant.api.supplier.vo.ContactsVo;
//@ContextConfiguration(locations = { "classpath*:applicationContext*.xml" })
//public class ContactsTest extends AbstractTransactionalJUnit4SpringContextTests {
public class ContactsTest extends JUnitServiceBase{
@Resource
private IContactApi contactApi;
@Test
public void insertContact() {
System.out.println("bbbbbbbbbbbbbbbbbbbbbbbbb");
}
}
|
package com.mycompany.sport.Domain;
/**
* Created by KristinnH on 16.8.2016.
*/
public class Activity {
int rating;
int lengthMinutes;
ActivityType activityType;
ActivityWith activityWith;
public enum ActivityType{
practice,match
}
public enum ActivityWith{
team,individual,nationalteam
}
}
|
package com.pfchoice.springboot.service.impl;
import com.pfchoice.springboot.configuration.ConfigProperties;
import com.pfchoice.springboot.model.MembershipProblem;
import com.pfchoice.springboot.repositories.MembershipProblemRepository;
import com.pfchoice.springboot.service.MembershipProblemService;
import com.pfchoice.springboot.util.PrasUtil;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("membershipProblemService")
@Transactional
public class MembershipProblemServiceImpl implements MembershipProblemService {
@Autowired
private MembershipProblemRepository membershipProblemRepository;
@Autowired
ConfigProperties configProperties;
@Autowired
PrasUtil prasUtil;
public MembershipProblem findById(Integer id) {
return membershipProblemRepository.findOne(id);
}
public void saveMembershipProblem(MembershipProblem membershipProblem) {
membershipProblemRepository.save(membershipProblem);
}
public void updateMembershipProblem(MembershipProblem membershipProblem) {
saveMembershipProblem(membershipProblem);
}
public void deleteMembershipProblemById(Integer id) {
membershipProblemRepository.delete(id);
}
public void deleteAllMembershipProblems() {
membershipProblemRepository.deleteAll();
}
public List<MembershipProblem> findAllMembershipProblems() {
return (List<MembershipProblem>) membershipProblemRepository.findAll();
}
public Page<MembershipProblem> findAllMembershipProblemsByPage(Specification<MembershipProblem> spec, Pageable pageable) {
return membershipProblemRepository.findAll(spec, pageable);
}
public boolean isMembershipProblemExist(MembershipProblem membershipProblem, Integer mbrId) {
System.out.println("membershipProblem.getIcdMeasure().getCode()"+membershipProblem.getIcdMeasure().getCode());
return membershipProblemRepository.isMembershipProblemExist(membershipProblem.getIcdMeasure().getCode() ,mbrId).size()>0 ;
}
public Integer loadData(final Map<String, Object> parameters, String insuranceCode) throws IOException, InterruptedException{
return prasUtil.executeSQLQuery(membershipProblemRepository,insuranceCode,parameters, configProperties.getQueryTypeInsert() );
}
}
|
/*
* UniTime 3.5 (University Timetabling Application)
* Copyright (C) 2014, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.unitime.timetable.server.rooms;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.fileupload.FileItem;
import org.unitime.localization.impl.Localization;
import org.unitime.timetable.gwt.command.client.GwtRpcException;
import org.unitime.timetable.gwt.command.server.GwtRpcImplementation;
import org.unitime.timetable.gwt.command.server.GwtRpcImplements;
import org.unitime.timetable.gwt.resources.GwtMessages;
import org.unitime.timetable.gwt.server.UploadServlet;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomPictureInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomPictureRequest;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomPictureRequest.Apply;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomPictureResponse;
import org.unitime.timetable.model.Location;
import org.unitime.timetable.model.LocationPicture;
import org.unitime.timetable.model.NonUniversityLocation;
import org.unitime.timetable.model.NonUniversityLocationPicture;
import org.unitime.timetable.model.Room;
import org.unitime.timetable.model.RoomPicture;
import org.unitime.timetable.model.dao.LocationDAO;
import org.unitime.timetable.security.SessionContext;
import org.unitime.timetable.security.rights.Right;
/**
* @author Tomas Muller
*/
@GwtRpcImplements(RoomPictureRequest.class)
public class RoomPicturesBackend implements GwtRpcImplementation<RoomPictureRequest, RoomPictureResponse> {
protected static final GwtMessages MESSAGES = Localization.create(GwtMessages.class);
@Override
public RoomPictureResponse execute(RoomPictureRequest request, SessionContext context) {
RoomPictureResponse response = new RoomPictureResponse();
org.hibernate.Session hibSession = LocationDAO.getInstance().getSession();
Location location = LocationDAO.getInstance().get(request.getLocationId(), hibSession);
if (location == null)
throw new GwtRpcException(MESSAGES.errorRoomDoesNotExist(request.getLocationId().toString()));
response.setName(location.getLabel());
context.checkPermission(location, Right.RoomEditChangePicture);
Map<Long, LocationPicture> temp = (Map<Long, LocationPicture>)context.getAttribute(RoomPictureServlet.TEMP_ROOM_PICTURES);
switch (request.getOperation()) {
case LOAD:
for (LocationPicture p: new TreeSet<LocationPicture>(location.getPictures()))
response.addPicture(new RoomPictureInterface(p.getUniqueId(), p.getFileName(), p.getContentType()));
boolean samePast = true, sameFuture = true;
for (Location other: (List<Location>)hibSession.createQuery("from Location loc where permanentId = :permanentId and not uniqueId = :uniqueId")
.setLong("uniqueId", location.getUniqueId()).setLong("permanentId", location.getPermanentId()).list()) {
if (!samePictures(location, other)) {
if (other.getSession().getSessionBeginDateTime().before(location.getSession().getSessionBeginDateTime())) {
samePast = false;
} else {
sameFuture = false;
}
}
if (!sameFuture) break;
}
if (samePast && sameFuture)
response.setApply(Apply.ALL_SESSIONS);
else if (sameFuture)
response.setApply(Apply.ALL_FUTURE_SESSIONS);
else
response.setApply(Apply.THIS_SESSION_ONLY);
context.setAttribute(RoomPictureServlet.TEMP_ROOM_PICTURES, null);
break;
case SAVE:
Map<Long, LocationPicture> pictures = new HashMap<Long, LocationPicture>();
for (LocationPicture p: location.getPictures())
pictures.put(p.getUniqueId(), p);
for (RoomPictureInterface p: request.getPictures()) {
LocationPicture picture = pictures.remove(p.getUniqueId());
if (picture == null && temp != null) {
picture = temp.get(p.getUniqueId());
if (picture != null) {
if (location instanceof Room) {
((RoomPicture)picture).setLocation((Room)location);
((Room)location).getPictures().add((RoomPicture)picture);
} else {
((NonUniversityLocationPicture)picture).setLocation((NonUniversityLocation)location);
((NonUniversityLocation)location).getPictures().add((NonUniversityLocationPicture)picture);
}
hibSession.saveOrUpdate(picture);
}
}
}
for (LocationPicture picture: pictures.values()) {
location.getPictures().remove(picture);
hibSession.delete(picture);
}
hibSession.saveOrUpdate(location);
if (request.getApply() != Apply.THIS_SESSION_ONLY) {
for (Location other: (List<Location>)hibSession.createQuery("from Location loc where permanentId = :permanentId and not uniqueId = :uniqueId")
.setLong("uniqueId", location.getUniqueId()).setLong("permanentId", location.getPermanentId()).list()) {
if (request.getApply() == Apply.ALL_FUTURE_SESSIONS && other.getSession().getSessionBeginDateTime().before(location.getSession().getSessionBeginDateTime()))
continue;
Set<LocationPicture> otherPictures = new HashSet<LocationPicture>(other.getPictures());
p1: for (LocationPicture p1: location.getPictures()) {
for (Iterator<LocationPicture> i = otherPictures.iterator(); i.hasNext(); ) {
LocationPicture p2 = i.next();
if (samePicture(p1, p2)) {
i.remove();
continue p1;
}
}
if (location instanceof Room) {
RoomPicture p2 = ((RoomPicture)p1).clonePicture();
p2.setLocation(other);
((Room)other).getPictures().add(p2);
hibSession.saveOrUpdate(p2);
} else {
NonUniversityLocationPicture p2 = ((NonUniversityLocationPicture)p1).clonePicture();
p2.setLocation(other);
((NonUniversityLocation)other).getPictures().add(p2);
hibSession.saveOrUpdate(p2);
}
}
for (LocationPicture picture: otherPictures) {
other.getPictures().remove(picture);
hibSession.delete(picture);
}
hibSession.saveOrUpdate(other);
}
}
hibSession.flush();
context.setAttribute(RoomPictureServlet.TEMP_ROOM_PICTURES, null);
break;
case UPLOAD:
final FileItem file = (FileItem)context.getAttribute(UploadServlet.SESSION_LAST_FILE);
if (file != null) {
if (temp == null) {
temp = new HashMap<Long, LocationPicture>();
context.setAttribute(RoomPictureServlet.TEMP_ROOM_PICTURES, temp);
}
LocationPicture picture = null;
if (location instanceof Room)
picture = new RoomPicture();
else
picture = new NonUniversityLocationPicture();
picture.setDataFile(file.get());
String name = file.getName();
if (name.indexOf('.') >= 0)
name = name.substring(0, name.lastIndexOf('.'));
picture.setFileName(name);
picture.setContentType(file.getContentType());
picture.setTimeStamp(new Date());
temp.put(- picture.getTimeStamp().getTime(), picture);
response.addPicture(new RoomPictureInterface(- picture.getTimeStamp().getTime(), picture.getFileName(), picture.getContentType()));
}
break;
}
return response;
}
private boolean samePictures(Location l1, Location l2) {
if (l1.getPictures().size() != l2.getPictures().size()) return false;
p1: for (LocationPicture p1: l1.getPictures()) {
for (LocationPicture p2: l2.getPictures()) {
if (samePicture(p1, p2)) continue p1;
}
return false;
}
return true;
}
private boolean samePicture(LocationPicture p1, LocationPicture p2) {
return p1.getFileName().equals(p2.getFileName()) && Math.abs(p1.getTimeStamp().getTime() - p2.getTimeStamp().getTime()) < 1000 && p1.getContentType().equals(p2.getContentType());
}
}
|
package com.tencent.mm.plugin.appbrand.f;
import android.content.Context;
import com.tencent.mm.plugin.fts.a.d.a;
import com.tencent.mm.plugin.fts.a.d.e.b;
public final class e extends a {
public final com.tencent.mm.plugin.fts.a.d.e a(Context context, b bVar, int i) {
return new f(context, bVar, i);
}
public final int getType() {
return 4224;
}
public final int getPriority() {
return Integer.MAX_VALUE;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.