blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 332 | content_id stringlengths 40 40 | detected_licenses listlengths 0 50 | license_type stringclasses 2 values | repo_name stringlengths 7 115 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 557 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 77.7k | fork_events_count int64 0 48k | gha_license_id stringclasses 17 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 82 values | src_encoding stringclasses 28 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 5.41M | extension stringclasses 11 values | content stringlengths 7 5.41M | authors listlengths 1 1 | author stringlengths 0 161 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a9518d22c1d407246600a0b98b5fbbfb0a7b1f20 | 6e9daba07718ddac46cbd46c68e4ed5b13816eb6 | /app/src/main/java/com/example/prabhubalu/bookhouse/User.java | e8856f808cc211d0aacc9df6985ab353d8cf3455 | [] | no_license | Prabhubalu/BookHouse | 2e0fdd4e8323cc94b33e7a7a2cc10c346ad3f9d3 | e9980f1765fd97969c092afaef5949eb60254ceb | refs/heads/master | 2021-05-09T10:25:50.661219 | 2018-03-11T06:01:57 | 2018-03-11T06:01:57 | 118,960,981 | 0 | 1 | null | 2018-01-25T21:27:16 | 2018-01-25T19:57:26 | Java | UTF-8 | Java | false | false | 602 | java | package com.example.prabhubalu.bookhouse;
public class User {
String emailAddress, phoneNumber;
public User(String emailAddress, String phoneNumber) {
this.emailAddress = emailAddress;
this.phoneNumber = phoneNumber;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
| [
"im.prabhub@gmail.com"
] | im.prabhub@gmail.com |
f5e8961a8c6fcdfd025fa12bfc60c0bb8e8521ab | 60eae63a46f8569835b0ee9778e3a0b6927affc4 | /web-manager/src/main/java/com/github/config/ManagerInterceptor.java | 638e98ff77c1ee8f796e711690867909c0107b22 | [] | no_license | wenzhihong2003/mall | aa64d4f3dc152e6eb9a7b7526b99c6d6648b8be6 | 3c7dabd812176d03d6805d60c9882872aca99480 | refs/heads/master | 2021-01-09T12:57:58.605962 | 2020-01-16T08:58:51 | 2020-01-16T08:58:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,870 | java | package com.github.config;
import com.github.common.annotation.NotNeedLogin;
import com.github.common.annotation.NotNeedPermission;
import com.github.common.util.LogUtil;
import com.github.common.util.RequestUtils;
import com.github.util.ManagerSessionUtil;
import com.google.common.collect.Lists;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.util.List;
public class ManagerInterceptor implements HandlerInterceptor {
private static final List<String> LET_IT_GO = Lists.newArrayList(
"/error", "/api/info", "/api/version"
);
private boolean online;
ManagerInterceptor(boolean online) {
this.online = online;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
bindParam();
checkLoginAndPermission(handler);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) throws Exception {
if (ex != null) {
if (LogUtil.ROOT_LOG.isDebugEnabled()) {
LogUtil.ROOT_LOG.debug("request was over, but have exception: " + ex.getMessage());
}
}
unbindParam();
}
private void bindParam() {
LogUtil.RequestLogContext logContextInfo = RequestUtils.logContextInfo()
.setId(String.valueOf(ManagerSessionUtil.getUserId()))
.setName(ManagerSessionUtil.getUserName());
LogUtil.bind(logContextInfo);
}
private void unbindParam() {
LogUtil.unbind();
}
/** 检查登录及权限 */
private void checkLoginAndPermission(Object handler) {
/*if (!online) {
return;
}*/
if (LET_IT_GO.contains(RequestUtils.getRequest().getRequestURI())) {
return;
}
if (!handler.getClass().isAssignableFrom(HandlerMethod.class)) {
return;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
// 在不需要登录的 url 上标注 @NotNeedLogin
NotNeedLogin notNeedLogin = getAnnotation(handlerMethod, NotNeedLogin.class);
// 标注了 NotNeedLogin 且 flag 为 true(默认就是 true)则表示当前的请求不需要验证登录
if (notNeedLogin != null && notNeedLogin.value()) {
return;
}
// 检查登录
ManagerSessionUtil.checkLogin();
// 在不需要验证权限的 url 上标注 @NotNeedPermission
NotNeedPermission notNeedPermission = getAnnotation(handlerMethod, NotNeedPermission.class);
// 标注了 NotNeedPermission 且 flag 为 true(默认就是 true)则表示当前的请求不需要验证权限
if (notNeedPermission != null && notNeedPermission.value()) {
return;
}
// 检查权限
ManagerSessionUtil.checkPermission();
}
private <T extends Annotation> T getAnnotation(HandlerMethod handlerMethod, Class<T> clazz) {
// 先找方法上的注解, 没有再找类上的注解
T annotation = handlerMethod.getMethodAnnotation(clazz);
return annotation == null ? AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), clazz) : annotation;
}
}
| [
"liu_anxin@163.com"
] | liu_anxin@163.com |
b45342344420536f9285645bb837e293b9e7d28c | d9589baf42d1f9550f0f0e03ea7b32b3cfa8eeb9 | /src/main/java/com/avlija/parts/entities/Orders.java | bc0df1a28e89d9fe0b55e1d561dbfb2010b5f3fa | [] | no_license | jadilovic/car_parts_app | f5c62657feb2c16a78571b46aebf4ef3386c555a | 3ff13e7d3c99420949020f88342a57b2ba232fc3 | refs/heads/master | 2022-07-12T08:56:40.606068 | 2020-05-13T18:35:28 | 2020-05-13T18:35:28 | 250,385,710 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,586 | java | package com.avlija.parts.entities;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.CreationTimestamp;
@Entity
@Table(name = "orders")
public class Orders implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ordernum", updatable = false, nullable = false)
private Long ordernum;
@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column
private Date orderdate;
@Column
private String sifra;
@Column
private String naziv;
@Column
private String marka;
@Column
private String grupa;
@Column
private int kolicina;
@Column
private float cijena;
@Column
private float ukupno;
public Orders() {
}
public Orders(Date orderdate, String sifra, String naziv, String marka, String grupa, int kolicina,
float cijena, float ukupno) {
super();
this.orderdate = orderdate;
this.sifra = sifra;
this.naziv = naziv;
this.marka = marka;
this.grupa = grupa;
this.kolicina = kolicina;
this.cijena = cijena;
this.ukupno = ukupno;
}
public Orders(Long ordernum, Date orderdate, String sifra, String naziv, String marka, String grupa, int kolicina,
float cijena, float ukupno) {
super();
this.ordernum = ordernum;
this.orderdate = orderdate;
this.sifra = sifra;
this.naziv = naziv;
this.marka = marka;
this.grupa = grupa;
this.kolicina = kolicina;
this.cijena = cijena;
this.ukupno = ukupno;
}
/**
* @return the ordernum
*/
public Long getOrdernum() {
return ordernum;
}
/**
* @param ordernum the ordernum to set
*/
public void setOrdernum(Long ordernum) {
this.ordernum = ordernum;
}
/**
* @return the orderdate
*/
public Date getOrderdate() {
return orderdate;
}
/**
* @param orderdate the orderdate to set
*/
public void setOrderdate(Date orderdate) {
this.orderdate = orderdate;
}
/**
* @return the sifra
*/
public String getSifra() {
return sifra;
}
/**
* @param sifra the sifra to set
*/
public void setSifra(String sifra) {
this.sifra = sifra;
}
/**
* @return the naziv
*/
public String getNaziv() {
return naziv;
}
/**
* @param naziv the naziv to set
*/
public void setNaziv(String naziv) {
this.naziv = naziv;
}
/**
* @return the marka
*/
public String getMarka() {
return marka;
}
/**
* @param marka the marka to set
*/
public void setMarka(String marka) {
this.marka = marka;
}
/**
* @return the grupa
*/
public String getGrupa() {
return grupa;
}
/**
* @param grupa the grupa to set
*/
public void setGrupa(String grupa) {
this.grupa = grupa;
}
/**
* @return the kolicina
*/
public int getKolicina() {
return kolicina;
}
/**
* @param kolicina the kolicina to set
*/
public void setKolicina(int kolicina) {
this.kolicina = kolicina;
}
/**
* @return the cijena
*/
public float getCijena() {
return cijena;
}
/**
* @param cijena the cijena to set
*/
public void setCijena(float cijena) {
this.cijena = cijena;
}
/**
* @return the ukupno
*/
public float getUkupno() {
return ukupno;
}
/**
* @param ukupno the ukupno to set
*/
public void setUkupno(float ukupno) {
this.ukupno = ukupno;
}
}
| [
"adilovic79@yahoo.com"
] | adilovic79@yahoo.com |
01430f00bd6fb0fd9b933eb870130a789c231149 | 93470a6b302a16a0825b81ae265312d1297853e1 | /src/main/java/ch/aptkn/estimatekwd/service/SearchVolumeEstimateService.java | 0f7e20397f4d1e398cd5f2895a92f0f9cf62b64b | [
"MIT"
] | permissive | aspyatkin/estimatekwd | d6d4a2c93973e14e599a41e293ad00051b4c605b | ae64183c9b8a701c02d9ba3460a07bb84d06a753 | refs/heads/master | 2023-07-04T17:57:04.227317 | 2021-08-22T13:28:54 | 2021-08-22T13:28:54 | 398,806,769 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,229 | java | package ch.aptkn.estimatekwd.service;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
@Service
public class SearchVolumeEstimateService {
/**
* Estimate given keyword's search volume
*
* @param keyword sanitized keyword
* @param suggestions map of autocomplete suggestions for each subkeyword
* @return estimated score in range 0-100
*/
public int getScore(String keyword, Map<String, List<String>> suggestions) {
// find the length of the shortest subkeyword, which suggestions contain the keyword
AtomicInteger minSubkeywordMatchLen = new AtomicInteger(keyword.length() + 1);
suggestions.forEach((key, value) -> {
if (value.contains(keyword) && minSubkeywordMatchLen.get() > key.length()) {
minSubkeywordMatchLen.set(key.length());
}
});
int maxWeight = 0;
int curWeight = 0;
// an abstraction - each numeric level has its weight and represents the significance of the match:
// 1 - the top. This keyword is treated as one of the most 10 searched ones by Amazon. Max weight.
// 2 - less significant. Weight is less.
// N - the last letters in a word give significantly less new information
// compared to the first ones, since natural languages are superfluous.
// This means each next level must have its weight drastically decreased.
// For instance, given "s", one can think of "sketchers", "shoe rack", etc.
// Given "sa", one can think of "sanitizer" or "safety glasses"
// Given "sam", it's almost certain it's something related to "samsung"
for (int i = 1; i < keyword.length() + 1; i++) {
// just sqr
int levelWeight = (keyword.length() + 1 - i) * (keyword.length() + 1 - i);
maxWeight += levelWeight;
// a match on the higher level also means a match on every lower one
if (i >= minSubkeywordMatchLen.get()) {
curWeight += levelWeight;
}
}
return (int) Math.round(curWeight * 100.0 / maxWeight);
}
}
| [
"aspyatkin@users.noreply.github.com"
] | aspyatkin@users.noreply.github.com |
0f7e0eeae0fe2f8c185e33745af60856528aeb69 | d71e879b3517cf4fccde29f7bf82cff69856cfcd | /ExtractedJars/Apk_Extractor_com.ext.ui.apk/javafiles/android/support/v4/widget/AutoScrollHelper.java | 3a6e1c74b6804a1c7e048159db7efb459e1be4f3 | [
"MIT"
] | permissive | Andreas237/AndroidPolicyAutomation | b8e949e072d08cf6c6166c3f15c9c63379b8f6ce | c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a | refs/heads/master | 2020-04-10T02:14:08.789751 | 2019-05-16T19:29:11 | 2019-05-16T19:29:11 | 160,739,088 | 5 | 1 | null | null | null | null | UTF-8 | Java | false | false | 49,320 | java | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package android.support.v4.widget;
import android.content.res.Resources;
import android.os.SystemClock;
import android.support.v4.view.ViewCompat;
import android.util.DisplayMetrics;
import android.view.*;
import android.view.animation.*;
public abstract class AutoScrollHelper
implements android.view.View.OnTouchListener
{
private static class ClampedScroller
{
private float getValueAt(long l)
{
if(l < mStartTime)
//* 0 0:lload_1
//* 1 1:aload_0
//* 2 2:getfield #29 <Field long mStartTime>
//* 3 5:lcmp
//* 4 6:ifge 11
return 0.0F;
// 5 9:fconst_0
// 6 10:freturn
if(mStopTime < 0L || l < mStopTime)
//* 7 11:aload_0
//* 8 12:getfield #33 <Field long mStopTime>
//* 9 15:lconst_0
//* 10 16:lcmp
//* 11 17:iflt 29
//* 12 20:lload_1
//* 13 21:aload_0
//* 14 22:getfield #33 <Field long mStopTime>
//* 15 25:lcmp
//* 16 26:ifge 51
{
return AutoScrollHelper.constrain((float)(l - mStartTime) / (float)mRampUpDuration, 0.0F, 1.0F) * 0.5F;
// 17 29:lload_1
// 18 30:aload_0
// 19 31:getfield #29 <Field long mStartTime>
// 20 34:lsub
// 21 35:l2f
// 22 36:aload_0
// 23 37:getfield #44 <Field int mRampUpDuration>
// 24 40:i2f
// 25 41:fdiv
// 26 42:fconst_0
// 27 43:fconst_1
// 28 44:invokestatic #48 <Method float AutoScrollHelper.constrain(float, float, float)>
// 29 47:ldc1 #49 <Float 0.5F>
// 30 49:fmul
// 31 50:freturn
} else
{
long l1 = mStopTime;
// 32 51:aload_0
// 33 52:getfield #33 <Field long mStopTime>
// 34 55:lstore 5
float f = mStopValue;
// 35 57:aload_0
// 36 58:getfield #51 <Field float mStopValue>
// 37 61:fstore_3
float f1 = mStopValue;
// 38 62:aload_0
// 39 63:getfield #51 <Field float mStopValue>
// 40 66:fstore 4
return AutoScrollHelper.constrain((float)(l - l1) / (float)mEffectiveRampDown, 0.0F, 1.0F) * f1 + (1.0F - f);
// 41 68:lload_1
// 42 69:lload 5
// 43 71:lsub
// 44 72:l2f
// 45 73:aload_0
// 46 74:getfield #53 <Field int mEffectiveRampDown>
// 47 77:i2f
// 48 78:fdiv
// 49 79:fconst_0
// 50 80:fconst_1
// 51 81:invokestatic #48 <Method float AutoScrollHelper.constrain(float, float, float)>
// 52 84:fload 4
// 53 86:fmul
// 54 87:fconst_1
// 55 88:fload_3
// 56 89:fsub
// 57 90:fadd
// 58 91:freturn
}
}
private float interpolateValue(float f)
{
return -4F * f * f + 4F * f;
// 0 0:ldc1 #56 <Float -4F>
// 1 2:fload_1
// 2 3:fmul
// 3 4:fload_1
// 4 5:fmul
// 5 6:ldc1 #57 <Float 4F>
// 6 8:fload_1
// 7 9:fmul
// 8 10:fadd
// 9 11:freturn
}
public void computeScrollDelta()
{
if(mDeltaTime == 0L)
//* 0 0:aload_0
//* 1 1:getfield #35 <Field long mDeltaTime>
//* 2 4:lconst_0
//* 3 5:lcmp
//* 4 6:ifne 19
{
throw new RuntimeException("Cannot compute scroll delta before calling start()");
// 5 9:new #60 <Class RuntimeException>
// 6 12:dup
// 7 13:ldc1 #62 <String "Cannot compute scroll delta before calling start()">
// 8 15:invokespecial #65 <Method void RuntimeException(String)>
// 9 18:athrow
} else
{
long l = AnimationUtils.currentAnimationTimeMillis();
// 10 19:invokestatic #71 <Method long AnimationUtils.currentAnimationTimeMillis()>
// 11 22:lstore_2
float f = interpolateValue(getValueAt(l));
// 12 23:aload_0
// 13 24:aload_0
// 14 25:lload_2
// 15 26:invokespecial #73 <Method float getValueAt(long)>
// 16 29:invokespecial #75 <Method float interpolateValue(float)>
// 17 32:fstore_1
long l1 = l - mDeltaTime;
// 18 33:lload_2
// 19 34:aload_0
// 20 35:getfield #35 <Field long mDeltaTime>
// 21 38:lsub
// 22 39:lstore 4
mDeltaTime = l;
// 23 41:aload_0
// 24 42:lload_2
// 25 43:putfield #35 <Field long mDeltaTime>
mDeltaX = (int)((float)l1 * f * mTargetVelocityX);
// 26 46:aload_0
// 27 47:lload 4
// 28 49:l2f
// 29 50:fload_1
// 30 51:fmul
// 31 52:aload_0
// 32 53:getfield #77 <Field float mTargetVelocityX>
// 33 56:fmul
// 34 57:f2i
// 35 58:putfield #37 <Field int mDeltaX>
mDeltaY = (int)((float)l1 * f * mTargetVelocityY);
// 36 61:aload_0
// 37 62:lload 4
// 38 64:l2f
// 39 65:fload_1
// 40 66:fmul
// 41 67:aload_0
// 42 68:getfield #79 <Field float mTargetVelocityY>
// 43 71:fmul
// 44 72:f2i
// 45 73:putfield #39 <Field int mDeltaY>
return;
// 46 76:return
}
}
public int getDeltaX()
{
return mDeltaX;
// 0 0:aload_0
// 1 1:getfield #37 <Field int mDeltaX>
// 2 4:ireturn
}
public int getDeltaY()
{
return mDeltaY;
// 0 0:aload_0
// 1 1:getfield #39 <Field int mDeltaY>
// 2 4:ireturn
}
public int getHorizontalDirection()
{
return (int)(mTargetVelocityX / Math.abs(mTargetVelocityX));
// 0 0:aload_0
// 1 1:getfield #77 <Field float mTargetVelocityX>
// 2 4:aload_0
// 3 5:getfield #77 <Field float mTargetVelocityX>
// 4 8:invokestatic #88 <Method float Math.abs(float)>
// 5 11:fdiv
// 6 12:f2i
// 7 13:ireturn
}
public int getVerticalDirection()
{
return (int)(mTargetVelocityY / Math.abs(mTargetVelocityY));
// 0 0:aload_0
// 1 1:getfield #79 <Field float mTargetVelocityY>
// 2 4:aload_0
// 3 5:getfield #79 <Field float mTargetVelocityY>
// 4 8:invokestatic #88 <Method float Math.abs(float)>
// 5 11:fdiv
// 6 12:f2i
// 7 13:ireturn
}
public boolean isFinished()
{
return mStopTime > 0L && AnimationUtils.currentAnimationTimeMillis() > mStopTime + (long)mEffectiveRampDown;
// 0 0:aload_0
// 1 1:getfield #33 <Field long mStopTime>
// 2 4:lconst_0
// 3 5:lcmp
// 4 6:ifle 28
// 5 9:invokestatic #71 <Method long AnimationUtils.currentAnimationTimeMillis()>
// 6 12:aload_0
// 7 13:getfield #33 <Field long mStopTime>
// 8 16:aload_0
// 9 17:getfield #53 <Field int mEffectiveRampDown>
// 10 20:i2l
// 11 21:ladd
// 12 22:lcmp
// 13 23:ifle 28
// 14 26:iconst_1
// 15 27:ireturn
// 16 28:iconst_0
// 17 29:ireturn
}
public void requestStop()
{
long l = AnimationUtils.currentAnimationTimeMillis();
// 0 0:invokestatic #71 <Method long AnimationUtils.currentAnimationTimeMillis()>
// 1 3:lstore_1
mEffectiveRampDown = AutoScrollHelper.constrain((int)(l - mStartTime), 0, mRampDownDuration);
// 2 4:aload_0
// 3 5:lload_1
// 4 6:aload_0
// 5 7:getfield #29 <Field long mStartTime>
// 6 10:lsub
// 7 11:l2i
// 8 12:iconst_0
// 9 13:aload_0
// 10 14:getfield #94 <Field int mRampDownDuration>
// 11 17:invokestatic #97 <Method int AutoScrollHelper.constrain(int, int, int)>
// 12 20:putfield #53 <Field int mEffectiveRampDown>
mStopValue = getValueAt(l);
// 13 23:aload_0
// 14 24:aload_0
// 15 25:lload_1
// 16 26:invokespecial #73 <Method float getValueAt(long)>
// 17 29:putfield #51 <Field float mStopValue>
mStopTime = l;
// 18 32:aload_0
// 19 33:lload_1
// 20 34:putfield #33 <Field long mStopTime>
// 21 37:return
}
public void setRampDownDuration(int i)
{
mRampDownDuration = i;
// 0 0:aload_0
// 1 1:iload_1
// 2 2:putfield #94 <Field int mRampDownDuration>
// 3 5:return
}
public void setRampUpDuration(int i)
{
mRampUpDuration = i;
// 0 0:aload_0
// 1 1:iload_1
// 2 2:putfield #44 <Field int mRampUpDuration>
// 3 5:return
}
public void setTargetVelocity(float f, float f1)
{
mTargetVelocityX = f;
// 0 0:aload_0
// 1 1:fload_1
// 2 2:putfield #77 <Field float mTargetVelocityX>
mTargetVelocityY = f1;
// 3 5:aload_0
// 4 6:fload_2
// 5 7:putfield #79 <Field float mTargetVelocityY>
// 6 10:return
}
public void start()
{
mStartTime = AnimationUtils.currentAnimationTimeMillis();
// 0 0:aload_0
// 1 1:invokestatic #71 <Method long AnimationUtils.currentAnimationTimeMillis()>
// 2 4:putfield #29 <Field long mStartTime>
mStopTime = -1L;
// 3 7:aload_0
// 4 8:ldc2w #30 <Long -1L>
// 5 11:putfield #33 <Field long mStopTime>
mDeltaTime = mStartTime;
// 6 14:aload_0
// 7 15:aload_0
// 8 16:getfield #29 <Field long mStartTime>
// 9 19:putfield #35 <Field long mDeltaTime>
mStopValue = 0.5F;
// 10 22:aload_0
// 11 23:ldc1 #49 <Float 0.5F>
// 12 25:putfield #51 <Field float mStopValue>
mDeltaX = 0;
// 13 28:aload_0
// 14 29:iconst_0
// 15 30:putfield #37 <Field int mDeltaX>
mDeltaY = 0;
// 16 33:aload_0
// 17 34:iconst_0
// 18 35:putfield #39 <Field int mDeltaY>
// 19 38:return
}
private long mDeltaTime;
private int mDeltaX;
private int mDeltaY;
private int mEffectiveRampDown;
private int mRampDownDuration;
private int mRampUpDuration;
private long mStartTime;
private long mStopTime;
private float mStopValue;
private float mTargetVelocityX;
private float mTargetVelocityY;
ClampedScroller()
{
// 0 0:aload_0
// 1 1:invokespecial #25 <Method void Object()>
mStartTime = 0x0L;
// 2 4:aload_0
// 3 5:ldc2w #26 <Long 0x0L>
// 4 8:putfield #29 <Field long mStartTime>
mStopTime = -1L;
// 5 11:aload_0
// 6 12:ldc2w #30 <Long -1L>
// 7 15:putfield #33 <Field long mStopTime>
mDeltaTime = 0L;
// 8 18:aload_0
// 9 19:lconst_0
// 10 20:putfield #35 <Field long mDeltaTime>
mDeltaX = 0;
// 11 23:aload_0
// 12 24:iconst_0
// 13 25:putfield #37 <Field int mDeltaX>
mDeltaY = 0;
// 14 28:aload_0
// 15 29:iconst_0
// 16 30:putfield #39 <Field int mDeltaY>
// 17 33:return
}
}
private class ScrollAnimationRunnable
implements Runnable
{
public void run()
{
if(!mAnimating)
//* 0 0:aload_0
//* 1 1:getfield #15 <Field AutoScrollHelper this$0>
//* 2 4:getfield #24 <Field boolean AutoScrollHelper.mAnimating>
//* 3 7:ifne 11
return;
// 4 10:return
if(mNeedsReset)
//* 5 11:aload_0
//* 6 12:getfield #15 <Field AutoScrollHelper this$0>
//* 7 15:getfield #27 <Field boolean AutoScrollHelper.mNeedsReset>
//* 8 18:ifeq 39
{
mNeedsReset = false;
// 9 21:aload_0
// 10 22:getfield #15 <Field AutoScrollHelper this$0>
// 11 25:iconst_0
// 12 26:putfield #27 <Field boolean AutoScrollHelper.mNeedsReset>
mScroller.start();
// 13 29:aload_0
// 14 30:getfield #15 <Field AutoScrollHelper this$0>
// 15 33:getfield #31 <Field AutoScrollHelper$ClampedScroller AutoScrollHelper.mScroller>
// 16 36:invokevirtual #36 <Method void AutoScrollHelper$ClampedScroller.start()>
}
ClampedScroller clampedscroller = mScroller;
// 17 39:aload_0
// 18 40:getfield #15 <Field AutoScrollHelper this$0>
// 19 43:getfield #31 <Field AutoScrollHelper$ClampedScroller AutoScrollHelper.mScroller>
// 20 46:astore_3
if(clampedscroller.isFinished() || !shouldAnimate())
//* 21 47:aload_3
//* 22 48:invokevirtual #40 <Method boolean AutoScrollHelper$ClampedScroller.isFinished()>
//* 23 51:ifne 64
//* 24 54:aload_0
//* 25 55:getfield #15 <Field AutoScrollHelper this$0>
//* 26 58:invokevirtual #43 <Method boolean AutoScrollHelper.shouldAnimate()>
//* 27 61:ifne 73
{
mAnimating = false;
// 28 64:aload_0
// 29 65:getfield #15 <Field AutoScrollHelper this$0>
// 30 68:iconst_0
// 31 69:putfield #24 <Field boolean AutoScrollHelper.mAnimating>
return;
// 32 72:return
}
if(mNeedsCancel)
//* 33 73:aload_0
//* 34 74:getfield #15 <Field AutoScrollHelper this$0>
//* 35 77:getfield #46 <Field boolean AutoScrollHelper.mNeedsCancel>
//* 36 80:ifeq 98
{
mNeedsCancel = false;
// 37 83:aload_0
// 38 84:getfield #15 <Field AutoScrollHelper this$0>
// 39 87:iconst_0
// 40 88:putfield #46 <Field boolean AutoScrollHelper.mNeedsCancel>
cancelTargetTouch();
// 41 91:aload_0
// 42 92:getfield #15 <Field AutoScrollHelper this$0>
// 43 95:invokevirtual #49 <Method void AutoScrollHelper.cancelTargetTouch()>
}
clampedscroller.computeScrollDelta();
// 44 98:aload_3
// 45 99:invokevirtual #52 <Method void AutoScrollHelper$ClampedScroller.computeScrollDelta()>
int i = clampedscroller.getDeltaX();
// 46 102:aload_3
// 47 103:invokevirtual #56 <Method int AutoScrollHelper$ClampedScroller.getDeltaX()>
// 48 106:istore_1
int j = clampedscroller.getDeltaY();
// 49 107:aload_3
// 50 108:invokevirtual #59 <Method int AutoScrollHelper$ClampedScroller.getDeltaY()>
// 51 111:istore_2
scrollTargetBy(i, j);
// 52 112:aload_0
// 53 113:getfield #15 <Field AutoScrollHelper this$0>
// 54 116:iload_1
// 55 117:iload_2
// 56 118:invokevirtual #63 <Method void AutoScrollHelper.scrollTargetBy(int, int)>
ViewCompat.postOnAnimation(mTarget, ((Runnable) (this)));
// 57 121:aload_0
// 58 122:getfield #15 <Field AutoScrollHelper this$0>
// 59 125:getfield #67 <Field View AutoScrollHelper.mTarget>
// 60 128:aload_0
// 61 129:invokestatic #73 <Method void ViewCompat.postOnAnimation(View, Runnable)>
// 62 132:return
}
final AutoScrollHelper this$0;
ScrollAnimationRunnable()
{
this$0 = AutoScrollHelper.this;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #15 <Field AutoScrollHelper this$0>
super();
// 3 5:aload_0
// 4 6:invokespecial #18 <Method void Object()>
// 5 9:return
}
}
public AutoScrollHelper(View view)
{
// 0 0:aload_0
// 1 1:invokespecial #79 <Method void Object()>
// 2 4:aload_0
// 3 5:new #8 <Class AutoScrollHelper$ClampedScroller>
// 4 8:dup
// 5 9:invokespecial #80 <Method void AutoScrollHelper$ClampedScroller()>
// 6 12:putfield #82 <Field AutoScrollHelper$ClampedScroller mScroller>
// 7 15:aload_0
// 8 16:new #84 <Class AccelerateInterpolator>
// 9 19:dup
// 10 20:invokespecial #85 <Method void AccelerateInterpolator()>
// 11 23:putfield #87 <Field Interpolator mEdgeInterpolator>
// 12 26:aload_0
// 13 27:iconst_2
// 14 28:newarray float[]
// 15 30:dup
// 16 31:iconst_0
// 17 32:fconst_0
// 18 33:fastore
// 19 34:dup
// 20 35:iconst_1
// 21 36:fconst_0
// 22 37:fastore
// 23 38:putfield #89 <Field float[] mRelativeEdges>
// 24 41:aload_0
// 25 42:iconst_2
// 26 43:newarray float[]
// 27 45:dup
// 28 46:iconst_0
// 29 47:ldc1 #19 <Float 3.402823E+38F>
// 30 49:fastore
// 31 50:dup
// 32 51:iconst_1
// 33 52:ldc1 #19 <Float 3.402823E+38F>
// 34 54:fastore
// 35 55:putfield #91 <Field float[] mMaximumEdges>
// 36 58:aload_0
// 37 59:iconst_2
// 38 60:newarray float[]
// 39 62:dup
// 40 63:iconst_0
// 41 64:fconst_0
// 42 65:fastore
// 43 66:dup
// 44 67:iconst_1
// 45 68:fconst_0
// 46 69:fastore
// 47 70:putfield #93 <Field float[] mRelativeVelocity>
// 48 73:aload_0
// 49 74:iconst_2
// 50 75:newarray float[]
// 51 77:dup
// 52 78:iconst_0
// 53 79:fconst_0
// 54 80:fastore
// 55 81:dup
// 56 82:iconst_1
// 57 83:fconst_0
// 58 84:fastore
// 59 85:putfield #95 <Field float[] mMinimumVelocity>
// 60 88:aload_0
// 61 89:iconst_2
// 62 90:newarray float[]
// 63 92:dup
// 64 93:iconst_0
// 65 94:ldc1 #19 <Float 3.402823E+38F>
// 66 96:fastore
// 67 97:dup
// 68 98:iconst_1
// 69 99:ldc1 #19 <Float 3.402823E+38F>
// 70 101:fastore
// 71 102:putfield #97 <Field float[] mMaximumVelocity>
mTarget = view;
// 72 105:aload_0
// 73 106:aload_1
// 74 107:putfield #99 <Field View mTarget>
view = ((View) (Resources.getSystem().getDisplayMetrics()));
// 75 110:invokestatic #105 <Method Resources Resources.getSystem()>
// 76 113:invokevirtual #109 <Method DisplayMetrics Resources.getDisplayMetrics()>
// 77 116:astore_1
int i = (int)(1575F * ((DisplayMetrics) (view)).density + 0.5F);
// 78 117:ldc1 #110 <Float 1575F>
// 79 119:aload_1
// 80 120:getfield #115 <Field float DisplayMetrics.density>
// 81 123:fmul
// 82 124:ldc1 #116 <Float 0.5F>
// 83 126:fadd
// 84 127:f2i
// 85 128:istore_2
int j = (int)(((DisplayMetrics) (view)).density * 315F + 0.5F);
// 86 129:aload_1
// 87 130:getfield #115 <Field float DisplayMetrics.density>
// 88 133:ldc1 #117 <Float 315F>
// 89 135:fmul
// 90 136:ldc1 #116 <Float 0.5F>
// 91 138:fadd
// 92 139:f2i
// 93 140:istore_3
setMaximumVelocity(i, i);
// 94 141:aload_0
// 95 142:iload_2
// 96 143:i2f
// 97 144:iload_2
// 98 145:i2f
// 99 146:invokevirtual #121 <Method AutoScrollHelper setMaximumVelocity(float, float)>
// 100 149:pop
setMinimumVelocity(j, j);
// 101 150:aload_0
// 102 151:iload_3
// 103 152:i2f
// 104 153:iload_3
// 105 154:i2f
// 106 155:invokevirtual #124 <Method AutoScrollHelper setMinimumVelocity(float, float)>
// 107 158:pop
setEdgeType(1);
// 108 159:aload_0
// 109 160:iconst_1
// 110 161:invokevirtual #128 <Method AutoScrollHelper setEdgeType(int)>
// 111 164:pop
setMaximumEdges(3.402823E+38F, 3.402823E+38F);
// 112 165:aload_0
// 113 166:ldc1 #19 <Float 3.402823E+38F>
// 114 168:ldc1 #19 <Float 3.402823E+38F>
// 115 170:invokevirtual #131 <Method AutoScrollHelper setMaximumEdges(float, float)>
// 116 173:pop
setRelativeEdges(0.2F, 0.2F);
// 117 174:aload_0
// 118 175:ldc1 #28 <Float 0.2F>
// 119 177:ldc1 #28 <Float 0.2F>
// 120 179:invokevirtual #134 <Method AutoScrollHelper setRelativeEdges(float, float)>
// 121 182:pop
setRelativeVelocity(1.0F, 1.0F);
// 122 183:aload_0
// 123 184:fconst_1
// 124 185:fconst_1
// 125 186:invokevirtual #137 <Method AutoScrollHelper setRelativeVelocity(float, float)>
// 126 189:pop
setActivationDelay(DEFAULT_ACTIVATION_DELAY);
// 127 190:aload_0
// 128 191:getstatic #74 <Field int DEFAULT_ACTIVATION_DELAY>
// 129 194:invokevirtual #140 <Method AutoScrollHelper setActivationDelay(int)>
// 130 197:pop
setRampUpDuration(500);
// 131 198:aload_0
// 132 199:sipush 500
// 133 202:invokevirtual #143 <Method AutoScrollHelper setRampUpDuration(int)>
// 134 205:pop
setRampDownDuration(500);
// 135 206:aload_0
// 136 207:sipush 500
// 137 210:invokevirtual #146 <Method AutoScrollHelper setRampDownDuration(int)>
// 138 213:pop
// 139 214:return
}
private float computeTargetVelocity(int i, float f, float f1, float f2)
{
f = getEdgeValue(mRelativeEdges[i], f1, mMaximumEdges[i], f);
// 0 0:aload_0
// 1 1:aload_0
// 2 2:getfield #89 <Field float[] mRelativeEdges>
// 3 5:iload_1
// 4 6:faload
// 5 7:fload_3
// 6 8:aload_0
// 7 9:getfield #91 <Field float[] mMaximumEdges>
// 8 12:iload_1
// 9 13:faload
// 10 14:fload_2
// 11 15:invokespecial #152 <Method float getEdgeValue(float, float, float, float)>
// 12 18:fstore_2
if(f == 0.0F)
//* 13 19:fload_2
//* 14 20:fconst_0
//* 15 21:fcmpl
//* 16 22:ifne 27
return 0.0F;
// 17 25:fconst_0
// 18 26:freturn
float f4 = mRelativeVelocity[i];
// 19 27:aload_0
// 20 28:getfield #93 <Field float[] mRelativeVelocity>
// 21 31:iload_1
// 22 32:faload
// 23 33:fstore 6
f1 = mMinimumVelocity[i];
// 24 35:aload_0
// 25 36:getfield #95 <Field float[] mMinimumVelocity>
// 26 39:iload_1
// 27 40:faload
// 28 41:fstore_3
float f3 = mMaximumVelocity[i];
// 29 42:aload_0
// 30 43:getfield #97 <Field float[] mMaximumVelocity>
// 31 46:iload_1
// 32 47:faload
// 33 48:fstore 5
f2 = f4 * f2;
// 34 50:fload 6
// 35 52:fload 4
// 36 54:fmul
// 37 55:fstore 4
if(f > 0.0F)
//* 38 57:fload_2
//* 39 58:fconst_0
//* 40 59:fcmpl
//* 41 60:ifle 74
return constrain(f * f2, f1, f3);
// 42 63:fload_2
// 43 64:fload 4
// 44 66:fmul
// 45 67:fload_3
// 46 68:fload 5
// 47 70:invokestatic #156 <Method float constrain(float, float, float)>
// 48 73:freturn
else
return -constrain(-f * f2, f1, f3);
// 49 74:fload_2
// 50 75:fneg
// 51 76:fload 4
// 52 78:fmul
// 53 79:fload_3
// 54 80:fload 5
// 55 82:invokestatic #156 <Method float constrain(float, float, float)>
// 56 85:fneg
// 57 86:freturn
}
static float constrain(float f, float f1, float f2)
{
if(f > f2)
//* 0 0:fload_0
//* 1 1:fload_2
//* 2 2:fcmpl
//* 3 3:ifle 8
return f2;
// 4 6:fload_2
// 5 7:freturn
if(f < f1)
//* 6 8:fload_0
//* 7 9:fload_1
//* 8 10:fcmpg
//* 9 11:ifge 16
return f1;
// 10 14:fload_1
// 11 15:freturn
else
return f;
// 12 16:fload_0
// 13 17:freturn
}
static int constrain(int i, int j, int k)
{
if(i > k)
//* 0 0:iload_0
//* 1 1:iload_2
//* 2 2:icmple 7
return k;
// 3 5:iload_2
// 4 6:ireturn
if(i < j)
//* 5 7:iload_0
//* 6 8:iload_1
//* 7 9:icmpge 14
return j;
// 8 12:iload_1
// 9 13:ireturn
else
return i;
// 10 14:iload_0
// 11 15:ireturn
}
private float constrainEdgeValue(float f, float f1)
{
if(f1 != 0.0F) goto _L2; else goto _L1
// 0 0:fload_2
// 1 1:fconst_0
// 2 2:fcmpl
// 3 3:ifne 8
_L1:
return 0.0F;
// 4 6:fconst_0
// 5 7:freturn
_L2:
mEdgeType;
// 6 8:aload_0
// 7 9:getfield #161 <Field int mEdgeType>
JVM INSTR tableswitch 0 2: default 40
// 0 42
// 1 42
// 2 77;
// 8 12:tableswitch 0 2: default 40
// 0 42
// 1 42
// 2 77
goto _L3 _L4 _L4 _L5
_L5:
continue; /* Loop/switch isn't completed */
_L3:
return 0.0F;
// 9 40:fconst_0
// 10 41:freturn
_L4:
if(f >= f1) goto _L1; else goto _L6
// 11 42:fload_1
// 12 43:fload_2
// 13 44:fcmpg
// 14 45:ifge 6
_L6:
if(f >= 0.0F)
//* 15 48:fload_1
//* 16 49:fconst_0
//* 17 50:fcmpl
//* 18 51:iflt 60
return 1.0F - f / f1;
// 19 54:fconst_1
// 20 55:fload_1
// 21 56:fload_2
// 22 57:fdiv
// 23 58:fsub
// 24 59:freturn
if(!mAnimating || mEdgeType != 1) goto _L1; else goto _L7
// 25 60:aload_0
// 26 61:getfield #163 <Field boolean mAnimating>
// 27 64:ifeq 6
// 28 67:aload_0
// 29 68:getfield #161 <Field int mEdgeType>
// 30 71:iconst_1
// 31 72:icmpne 6
_L7:
return 1.0F;
// 32 75:fconst_1
// 33 76:freturn
if(f >= 0.0F) goto _L1; else goto _L8
// 34 77:fload_1
// 35 78:fconst_0
// 36 79:fcmpg
// 37 80:ifge 6
_L8:
return f / -f1;
// 38 83:fload_1
// 39 84:fload_2
// 40 85:fneg
// 41 86:fdiv
// 42 87:freturn
}
private float getEdgeValue(float f, float f1, float f2, float f3)
{
float f4;
f4 = 0.0F;
// 0 0:fconst_0
// 1 1:fstore 5
f = constrain(f * f1, 0.0F, f2);
// 2 3:fload_1
// 3 4:fload_2
// 4 5:fmul
// 5 6:fconst_0
// 6 7:fload_3
// 7 8:invokestatic #156 <Method float constrain(float, float, float)>
// 8 11:fstore_1
f2 = constrainEdgeValue(f3, f);
// 9 12:aload_0
// 10 13:fload 4
// 11 15:fload_1
// 12 16:invokespecial #165 <Method float constrainEdgeValue(float, float)>
// 13 19:fstore_3
f1 = constrainEdgeValue(f1 - f3, f) - f2;
// 14 20:aload_0
// 15 21:fload_2
// 16 22:fload 4
// 17 24:fsub
// 18 25:fload_1
// 19 26:invokespecial #165 <Method float constrainEdgeValue(float, float)>
// 20 29:fload_3
// 21 30:fsub
// 22 31:fstore_2
if(f1 >= 0.0F) goto _L2; else goto _L1
// 23 32:fload_2
// 24 33:fconst_0
// 25 34:fcmpg
// 26 35:ifge 61
_L1:
f = -mEdgeInterpolator.getInterpolation(-f1);
// 27 38:aload_0
// 28 39:getfield #87 <Field Interpolator mEdgeInterpolator>
// 29 42:fload_2
// 30 43:fneg
// 31 44:invokeinterface #171 <Method float Interpolator.getInterpolation(float)>
// 32 49:fneg
// 33 50:fstore_1
_L6:
f = constrain(f, -1F, 1.0F);
// 34 51:fload_1
// 35 52:ldc1 #172 <Float -1F>
// 36 54:fconst_1
// 37 55:invokestatic #156 <Method float constrain(float, float, float)>
// 38 58:fstore_1
_L4:
return f;
// 39 59:fload_1
// 40 60:freturn
_L2:
f = f4;
// 41 61:fload 5
// 42 63:fstore_1
if(f1 <= 0.0F) goto _L4; else goto _L3
// 43 64:fload_2
// 44 65:fconst_0
// 45 66:fcmpl
// 46 67:ifle 59
_L3:
f = mEdgeInterpolator.getInterpolation(f1);
// 47 70:aload_0
// 48 71:getfield #87 <Field Interpolator mEdgeInterpolator>
// 49 74:fload_2
// 50 75:invokeinterface #171 <Method float Interpolator.getInterpolation(float)>
// 51 80:fstore_1
if(true) goto _L6; else goto _L5
// 52 81:goto 51
_L5:
}
private void requestStop()
{
if(mNeedsReset)
//* 0 0:aload_0
//* 1 1:getfield #175 <Field boolean mNeedsReset>
//* 2 4:ifeq 13
{
mAnimating = false;
// 3 7:aload_0
// 4 8:iconst_0
// 5 9:putfield #163 <Field boolean mAnimating>
return;
// 6 12:return
} else
{
mScroller.requestStop();
// 7 13:aload_0
// 8 14:getfield #82 <Field AutoScrollHelper$ClampedScroller mScroller>
// 9 17:invokevirtual #177 <Method void AutoScrollHelper$ClampedScroller.requestStop()>
return;
// 10 20:return
}
}
private void startAnimating()
{
if(mRunnable == null)
//* 0 0:aload_0
//* 1 1:getfield #180 <Field Runnable mRunnable>
//* 2 4:ifnonnull 19
mRunnable = ((Runnable) (new ScrollAnimationRunnable()));
// 3 7:aload_0
// 4 8:new #11 <Class AutoScrollHelper$ScrollAnimationRunnable>
// 5 11:dup
// 6 12:aload_0
// 7 13:invokespecial #183 <Method void AutoScrollHelper$ScrollAnimationRunnable(AutoScrollHelper)>
// 8 16:putfield #180 <Field Runnable mRunnable>
mAnimating = true;
// 9 19:aload_0
// 10 20:iconst_1
// 11 21:putfield #163 <Field boolean mAnimating>
mNeedsReset = true;
// 12 24:aload_0
// 13 25:iconst_1
// 14 26:putfield #175 <Field boolean mNeedsReset>
if(!mAlreadyDelayed && mActivationDelay > 0)
//* 15 29:aload_0
//* 16 30:getfield #185 <Field boolean mAlreadyDelayed>
//* 17 33:ifne 65
//* 18 36:aload_0
//* 19 37:getfield #187 <Field int mActivationDelay>
//* 20 40:ifle 65
ViewCompat.postOnAnimationDelayed(mTarget, mRunnable, mActivationDelay);
// 21 43:aload_0
// 22 44:getfield #99 <Field View mTarget>
// 23 47:aload_0
// 24 48:getfield #180 <Field Runnable mRunnable>
// 25 51:aload_0
// 26 52:getfield #187 <Field int mActivationDelay>
// 27 55:i2l
// 28 56:invokestatic #193 <Method void ViewCompat.postOnAnimationDelayed(View, Runnable, long)>
else
//* 29 59:aload_0
//* 30 60:iconst_1
//* 31 61:putfield #185 <Field boolean mAlreadyDelayed>
//* 32 64:return
mRunnable.run();
// 33 65:aload_0
// 34 66:getfield #180 <Field Runnable mRunnable>
// 35 69:invokeinterface #198 <Method void Runnable.run()>
mAlreadyDelayed = true;
//* 36 74:goto 59
}
public abstract boolean canTargetScrollHorizontally(int i);
public abstract boolean canTargetScrollVertically(int i);
void cancelTargetTouch()
{
long l = SystemClock.uptimeMillis();
// 0 0:invokestatic #208 <Method long SystemClock.uptimeMillis()>
// 1 3:lstore_1
MotionEvent motionevent = MotionEvent.obtain(l, l, 3, 0.0F, 0.0F, 0);
// 2 4:lload_1
// 3 5:lload_1
// 4 6:iconst_3
// 5 7:fconst_0
// 6 8:fconst_0
// 7 9:iconst_0
// 8 10:invokestatic #214 <Method MotionEvent MotionEvent.obtain(long, long, int, float, float, int)>
// 9 13:astore_3
mTarget.onTouchEvent(motionevent);
// 10 14:aload_0
// 11 15:getfield #99 <Field View mTarget>
// 12 18:aload_3
// 13 19:invokevirtual #220 <Method boolean View.onTouchEvent(MotionEvent)>
// 14 22:pop
motionevent.recycle();
// 15 23:aload_3
// 16 24:invokevirtual #223 <Method void MotionEvent.recycle()>
// 17 27:return
}
public boolean isEnabled()
{
return mEnabled;
// 0 0:aload_0
// 1 1:getfield #227 <Field boolean mEnabled>
// 2 4:ireturn
}
public boolean isExclusive()
{
return mExclusive;
// 0 0:aload_0
// 1 1:getfield #230 <Field boolean mExclusive>
// 2 4:ireturn
}
public boolean onTouch(View view, MotionEvent motionevent)
{
boolean flag;
flag = true;
// 0 0:iconst_1
// 1 1:istore 5
if(!mEnabled)
//* 2 3:aload_0
//* 3 4:getfield #227 <Field boolean mEnabled>
//* 4 7:ifne 12
return false;
// 5 10:iconst_0
// 6 11:ireturn
motionevent.getActionMasked();
// 7 12:aload_2
// 8 13:invokevirtual #235 <Method int MotionEvent.getActionMasked()>
JVM INSTR tableswitch 0 3: default 48
// 0 65
// 1 153
// 2 75
// 3 153;
// 9 16:tableswitch 0 3: default 48
// 0 65
// 1 153
// 2 75
// 3 153
goto _L1 _L2 _L3 _L4 _L3
_L1:
break; /* Loop/switch isn't completed */
_L3:
break MISSING_BLOCK_LABEL_153;
_L5:
float f;
float f1;
if(!mExclusive || !mAnimating)
//* 10 48:aload_0
//* 11 49:getfield #230 <Field boolean mExclusive>
//* 12 52:ifeq 160
//* 13 55:aload_0
//* 14 56:getfield #163 <Field boolean mAnimating>
//* 15 59:ifeq 160
//* 16 62:iload 5
//* 17 64:ireturn
//* 18 65:aload_0
//* 19 66:iconst_1
//* 20 67:putfield #237 <Field boolean mNeedsCancel>
//* 21 70:aload_0
//* 22 71:iconst_0
//* 23 72:putfield #185 <Field boolean mAlreadyDelayed>
//* 24 75:aload_0
//* 25 76:iconst_0
//* 26 77:aload_2
//* 27 78:invokevirtual #241 <Method float MotionEvent.getX()>
//* 28 81:aload_1
//* 29 82:invokevirtual #244 <Method int View.getWidth()>
//* 30 85:i2f
//* 31 86:aload_0
//* 32 87:getfield #99 <Field View mTarget>
//* 33 90:invokevirtual #244 <Method int View.getWidth()>
//* 34 93:i2f
//* 35 94:invokespecial #246 <Method float computeTargetVelocity(int, float, float, float)>
//* 36 97:fstore_3
//* 37 98:aload_0
//* 38 99:iconst_1
//* 39 100:aload_2
//* 40 101:invokevirtual #249 <Method float MotionEvent.getY()>
//* 41 104:aload_1
//* 42 105:invokevirtual #252 <Method int View.getHeight()>
//* 43 108:i2f
//* 44 109:aload_0
//* 45 110:getfield #99 <Field View mTarget>
//* 46 113:invokevirtual #252 <Method int View.getHeight()>
//* 47 116:i2f
//* 48 117:invokespecial #246 <Method float computeTargetVelocity(int, float, float, float)>
//* 49 120:fstore 4
//* 50 122:aload_0
//* 51 123:getfield #82 <Field AutoScrollHelper$ClampedScroller mScroller>
//* 52 126:fload_3
//* 53 127:fload 4
//* 54 129:invokevirtual #256 <Method void AutoScrollHelper$ClampedScroller.setTargetVelocity(float, float)>
//* 55 132:aload_0
//* 56 133:getfield #163 <Field boolean mAnimating>
//* 57 136:ifne 48
//* 58 139:aload_0
//* 59 140:invokevirtual #259 <Method boolean shouldAnimate()>
//* 60 143:ifeq 48
//* 61 146:aload_0
//* 62 147:invokespecial #261 <Method void startAnimating()>
//* 63 150:goto 48
//* 64 153:aload_0
//* 65 154:invokespecial #262 <Method void requestStop()>
//* 66 157:goto 48
flag = false;
// 67 160:iconst_0
// 68 161:istore 5
return flag;
_L2:
mNeedsCancel = true;
mAlreadyDelayed = false;
_L4:
f = computeTargetVelocity(0, motionevent.getX(), view.getWidth(), mTarget.getWidth());
f1 = computeTargetVelocity(1, motionevent.getY(), view.getHeight(), mTarget.getHeight());
mScroller.setTargetVelocity(f, f1);
if(!mAnimating && shouldAnimate())
startAnimating();
goto _L5
requestStop();
goto _L5
//* 69 163:goto 62
}
public abstract void scrollTargetBy(int i, int j);
public AutoScrollHelper setActivationDelay(int i)
{
mActivationDelay = i;
// 0 0:aload_0
// 1 1:iload_1
// 2 2:putfield #187 <Field int mActivationDelay>
return this;
// 3 5:aload_0
// 4 6:areturn
}
public AutoScrollHelper setEdgeType(int i)
{
mEdgeType = i;
// 0 0:aload_0
// 1 1:iload_1
// 2 2:putfield #161 <Field int mEdgeType>
return this;
// 3 5:aload_0
// 4 6:areturn
}
public AutoScrollHelper setEnabled(boolean flag)
{
if(mEnabled && !flag)
//* 0 0:aload_0
//* 1 1:getfield #227 <Field boolean mEnabled>
//* 2 4:ifeq 15
//* 3 7:iload_1
//* 4 8:ifne 15
requestStop();
// 5 11:aload_0
// 6 12:invokespecial #262 <Method void requestStop()>
mEnabled = flag;
// 7 15:aload_0
// 8 16:iload_1
// 9 17:putfield #227 <Field boolean mEnabled>
return this;
// 10 20:aload_0
// 11 21:areturn
}
public AutoScrollHelper setExclusive(boolean flag)
{
mExclusive = flag;
// 0 0:aload_0
// 1 1:iload_1
// 2 2:putfield #230 <Field boolean mExclusive>
return this;
// 3 5:aload_0
// 4 6:areturn
}
public AutoScrollHelper setMaximumEdges(float f, float f1)
{
mMaximumEdges[0] = f;
// 0 0:aload_0
// 1 1:getfield #91 <Field float[] mMaximumEdges>
// 2 4:iconst_0
// 3 5:fload_1
// 4 6:fastore
mMaximumEdges[1] = f1;
// 5 7:aload_0
// 6 8:getfield #91 <Field float[] mMaximumEdges>
// 7 11:iconst_1
// 8 12:fload_2
// 9 13:fastore
return this;
// 10 14:aload_0
// 11 15:areturn
}
public AutoScrollHelper setMaximumVelocity(float f, float f1)
{
mMaximumVelocity[0] = f / 1000F;
// 0 0:aload_0
// 1 1:getfield #97 <Field float[] mMaximumVelocity>
// 2 4:iconst_0
// 3 5:fload_1
// 4 6:ldc2 #268 <Float 1000F>
// 5 9:fdiv
// 6 10:fastore
mMaximumVelocity[1] = f1 / 1000F;
// 7 11:aload_0
// 8 12:getfield #97 <Field float[] mMaximumVelocity>
// 9 15:iconst_1
// 10 16:fload_2
// 11 17:ldc2 #268 <Float 1000F>
// 12 20:fdiv
// 13 21:fastore
return this;
// 14 22:aload_0
// 15 23:areturn
}
public AutoScrollHelper setMinimumVelocity(float f, float f1)
{
mMinimumVelocity[0] = f / 1000F;
// 0 0:aload_0
// 1 1:getfield #95 <Field float[] mMinimumVelocity>
// 2 4:iconst_0
// 3 5:fload_1
// 4 6:ldc2 #268 <Float 1000F>
// 5 9:fdiv
// 6 10:fastore
mMinimumVelocity[1] = f1 / 1000F;
// 7 11:aload_0
// 8 12:getfield #95 <Field float[] mMinimumVelocity>
// 9 15:iconst_1
// 10 16:fload_2
// 11 17:ldc2 #268 <Float 1000F>
// 12 20:fdiv
// 13 21:fastore
return this;
// 14 22:aload_0
// 15 23:areturn
}
public AutoScrollHelper setRampDownDuration(int i)
{
mScroller.setRampDownDuration(i);
// 0 0:aload_0
// 1 1:getfield #82 <Field AutoScrollHelper$ClampedScroller mScroller>
// 2 4:iload_1
// 3 5:invokevirtual #271 <Method void AutoScrollHelper$ClampedScroller.setRampDownDuration(int)>
return this;
// 4 8:aload_0
// 5 9:areturn
}
public AutoScrollHelper setRampUpDuration(int i)
{
mScroller.setRampUpDuration(i);
// 0 0:aload_0
// 1 1:getfield #82 <Field AutoScrollHelper$ClampedScroller mScroller>
// 2 4:iload_1
// 3 5:invokevirtual #273 <Method void AutoScrollHelper$ClampedScroller.setRampUpDuration(int)>
return this;
// 4 8:aload_0
// 5 9:areturn
}
public AutoScrollHelper setRelativeEdges(float f, float f1)
{
mRelativeEdges[0] = f;
// 0 0:aload_0
// 1 1:getfield #89 <Field float[] mRelativeEdges>
// 2 4:iconst_0
// 3 5:fload_1
// 4 6:fastore
mRelativeEdges[1] = f1;
// 5 7:aload_0
// 6 8:getfield #89 <Field float[] mRelativeEdges>
// 7 11:iconst_1
// 8 12:fload_2
// 9 13:fastore
return this;
// 10 14:aload_0
// 11 15:areturn
}
public AutoScrollHelper setRelativeVelocity(float f, float f1)
{
mRelativeVelocity[0] = f / 1000F;
// 0 0:aload_0
// 1 1:getfield #93 <Field float[] mRelativeVelocity>
// 2 4:iconst_0
// 3 5:fload_1
// 4 6:ldc2 #268 <Float 1000F>
// 5 9:fdiv
// 6 10:fastore
mRelativeVelocity[1] = f1 / 1000F;
// 7 11:aload_0
// 8 12:getfield #93 <Field float[] mRelativeVelocity>
// 9 15:iconst_1
// 10 16:fload_2
// 11 17:ldc2 #268 <Float 1000F>
// 12 20:fdiv
// 13 21:fastore
return this;
// 14 22:aload_0
// 15 23:areturn
}
boolean shouldAnimate()
{
ClampedScroller clampedscroller = mScroller;
// 0 0:aload_0
// 1 1:getfield #82 <Field AutoScrollHelper$ClampedScroller mScroller>
// 2 4:astore_3
int i = clampedscroller.getVerticalDirection();
// 3 5:aload_3
// 4 6:invokevirtual #276 <Method int AutoScrollHelper$ClampedScroller.getVerticalDirection()>
// 5 9:istore_1
int j = clampedscroller.getHorizontalDirection();
// 6 10:aload_3
// 7 11:invokevirtual #279 <Method int AutoScrollHelper$ClampedScroller.getHorizontalDirection()>
// 8 14:istore_2
return i != 0 && canTargetScrollVertically(i) || j != 0 && canTargetScrollHorizontally(j);
// 9 15:iload_1
// 10 16:ifeq 27
// 11 19:aload_0
// 12 20:iload_1
// 13 21:invokevirtual #281 <Method boolean canTargetScrollVertically(int)>
// 14 24:ifne 39
// 15 27:iload_2
// 16 28:ifeq 41
// 17 31:aload_0
// 18 32:iload_2
// 19 33:invokevirtual #283 <Method boolean canTargetScrollHorizontally(int)>
// 20 36:ifeq 41
// 21 39:iconst_1
// 22 40:ireturn
// 23 41:iconst_0
// 24 42:ireturn
}
private static final int DEFAULT_ACTIVATION_DELAY = ViewConfiguration.getTapTimeout();
private static final int DEFAULT_EDGE_TYPE = 1;
private static final float DEFAULT_MAXIMUM_EDGE = 3.402823E+38F;
private static final int DEFAULT_MAXIMUM_VELOCITY_DIPS = 1575;
private static final int DEFAULT_MINIMUM_VELOCITY_DIPS = 315;
private static final int DEFAULT_RAMP_DOWN_DURATION = 500;
private static final int DEFAULT_RAMP_UP_DURATION = 500;
private static final float DEFAULT_RELATIVE_EDGE = 0.2F;
private static final float DEFAULT_RELATIVE_VELOCITY = 1F;
public static final int EDGE_TYPE_INSIDE = 0;
public static final int EDGE_TYPE_INSIDE_EXTEND = 1;
public static final int EDGE_TYPE_OUTSIDE = 2;
private static final int HORIZONTAL = 0;
public static final float NO_MAX = 3.402823E+38F;
public static final float NO_MIN = 0F;
public static final float RELATIVE_UNSPECIFIED = 0F;
private static final int VERTICAL = 1;
private int mActivationDelay;
private boolean mAlreadyDelayed;
boolean mAnimating;
private final Interpolator mEdgeInterpolator = new AccelerateInterpolator();
private int mEdgeType;
private boolean mEnabled;
private boolean mExclusive;
private float mMaximumEdges[] = {
3.402823E+38F, 3.402823E+38F
};
private float mMaximumVelocity[] = {
3.402823E+38F, 3.402823E+38F
};
private float mMinimumVelocity[] = {
0.0F, 0.0F
};
boolean mNeedsCancel;
boolean mNeedsReset;
private float mRelativeEdges[] = {
0.0F, 0.0F
};
private float mRelativeVelocity[] = {
0.0F, 0.0F
};
private Runnable mRunnable;
final ClampedScroller mScroller = new ClampedScroller();
final View mTarget;
static
{
// 0 0:invokestatic #72 <Method int ViewConfiguration.getTapTimeout()>
// 1 3:putstatic #74 <Field int DEFAULT_ACTIVATION_DELAY>
//* 2 6:return
}
}
| [
"silenta237@gmail.com"
] | silenta237@gmail.com |
13cdca81f5a0713eda5c061067bdeb86bcebb384 | 00d47cff5883a7462839fd1780bab0d6d6c4c083 | /Numbers.java | 84a82f5ef66df06d12ff128aa2f1687343e8c988 | [] | no_license | simonwhiteQA/java_solutions | f9f542d9316af169135d94581e950a3be5d97ddb | 69c884657576acf0cf60a7394bd33d6d19c1040c | refs/heads/master | 2023-06-03T12:41:44.924832 | 2021-06-25T13:59:03 | 2021-06-25T13:59:03 | 379,558,052 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 492 | java | package com.qa.community;
public class Numbers {
public static void main(String[] args) {
System.out.println("Sum of two numbers = " + methodOne(74));
}
public static int methodOne(int num) {
String[] parts = Integer.toString(num).split("(?!^)");
int sum = 0;
for(String p : parts) {
int number = 0;
try {
number = Integer.parseInt(p);
} catch (NumberFormatException ex) {
ex.printStackTrace();
}
sum += number;
}
return sum;
}
}
| [
"simonwhite17@icloud.com"
] | simonwhite17@icloud.com |
7eb6775594d21ffefacd687612d8bfa88935d640 | 57ac2aadeb06fdfc984e1a9b7d45fe6ed812419b | /src/hackerrank/BallContainer.java | 80711bb9ae1c6dcffab7ef80cdac9752862939ea | [] | no_license | ydhanda/Jakarta | 00bb860de05be34d1256cb688764f44e3a4d26b8 | f9e4fbcdffdb41474b596dd2af79f530948ef2e8 | refs/heads/master | 2023-04-06T11:19:45.450709 | 2018-09-15T06:03:47 | 2018-09-15T06:03:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,492 | java | /*
* Copyright (c) 2018. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
* Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
* Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
* Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
* Vestibulum commodo. Ut rhoncus gravida arcu.
*/
package hackerrank;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* Created by anda on 6/27/2018.
*/
public class BallContainer {
// Complete the organizingContainers function below.
static String organizingContainers(int[][] container) {
int n = container.length;
List<Integer> listBall = new ArrayList<Integer>();
List<Integer> listContainer = new ArrayList<Integer>();
for(int i=0;i<n;i++){
int sumBall = 0;
int sumContainer = 0;
for(int j = 0;j<n;j++){
sumContainer = sumContainer + container[i][j];
sumBall = sumBall + container[j][i];
}
listContainer.add(sumContainer);
listBall.add(sumBall);
}
listContainer.removeAll(listBall);
return listContainer.isEmpty()? "Possible" : "Impossible";
}
public static void main(String[] args) throws IOException {
// BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
Scanner scanner = new Scanner(new File("BallContainer.txt"));
int q = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int qItr = 0; qItr < q; qItr++) {
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
int[][] container = new int[n][n];
for (int i = 0; i < n; i++) {
String[] containerRowItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int j = 0; j < n; j++) {
int containerItem = Integer.parseInt(containerRowItems[j]);
container[i][j] = containerItem;
}
}
String result = organizingContainers(container);
System.out.println(result);
}
scanner.close();
}
}
| [
"andayudha@gmail.com"
] | andayudha@gmail.com |
604d9e5579d3b8f4171eb4321e1024c8d48e95b7 | 786681937a0fb2bc4390675308181611ab67476c | /src/com/clint/yinyue_xiazai/controller/YinyueController.java | 5bf491d2b5f69855fec68d6498c50b3048ca8289 | [] | no_license | xiaoduanduan1021/shishitongxun | 0b71f13553cd390ed01c8ca6bc9d5232c2fa1e51 | 46912b94fa2c83f369381e6ec67f4c851a042cd7 | refs/heads/master | 2020-06-20T03:15:19.201115 | 2019-03-30T03:43:31 | 2019-03-30T03:43:31 | 94,191,687 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,808 | java | package com.clint.yinyue_xiazai.controller;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.chainsaw.Main;
import org.hibernate.mapping.Array;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.clint.yinyue_xiazai.dao.YinyueXiazaiDao;
import com.clint.yinyue_xiazai.model.YinyueXiazai;
import com.clint.yinyue_xiazai.util.BBDJ;
import com.clint.yinyue_xiazai.util.DJye;
import com.clint.yinyue_xiazai.util.Ik123;
import com.clint.yinyue_xiazai.util.KuGou;
import com.clint.yinyue_xiazai.util.QianQianYinYue;
import com.clint.yinyue_xiazai.util.WWW_72dj;
import com.clint.yinyue_xiazai.util.yinyueUtil;
import net.sf.json.JSONObject;
import util.page.PageList;
import util.string.StringCode;
@Controller
@RequestMapping(value = "/yinyue_xiazai")
public class YinyueController {
@Resource(name="yinyueXiazaiDao")
private YinyueXiazaiDao yinyueXiazaiDao;
@Resource(name="kugou")
private KuGou kugou;
//首页
@RequestMapping(value = "/home")
public String home() {
System.out.println("index");
System.out.println("index");
System.out.println("index");
System.out.println("index");
System.out.println("index");
return "/index.jsp";
}
//进入客户端录入试听地址页面
@RequestMapping(value = "/yinyue_xiazai_home")
public String yinyue_xiazai_home() {
return "/yinyue_xiazai/home/home.jsp";
}
//提交试听地址
@RequestMapping(value = "/saveShiting")
public void saveShiting(YinyueXiazai yinyueXiazai,HttpServletResponse response) throws IOException {
JSONObject json = new JSONObject();
//存储
System.out.println(yinyueXiazai.toString());
//不能为空
if(StringUtils.isBlank(yinyueXiazai.getShiting_url())){
json.put("type", "noNull");
response.getWriter().write(json.toString());
return;
}
//默认获取页面标题,获取标题名称
Connection con = Jsoup.connect(yinyueXiazai.getShiting_url()).timeout(1000 * 30).ignoreContentType(true);
Document doc=con.get();
yinyueXiazai.setGequ_name(doc.title());
//查询是否是酷狗,如果是则直接查询地址并存储
if(yinyueXiazai.getShiting_url().indexOf("www.kugou.com")>0){
String[] kugoud = new KuGou().urlToMusic(yinyueXiazai.getShiting_url());
yinyueXiazai.setGequ_name(kugoud[0]);
yinyueXiazai.setXiazai_dizhi(kugoud[1]);
yinyueXiazai.setStatus(1);
}
//千千音乐定制
if(yinyueXiazai.getShiting_url().indexOf("music.taihe.com")>0){
String[] qianqian = new QianQianYinYue().urlToMusic(yinyueXiazai.getShiting_url());
yinyueXiazai.setGequ_name(qianqian[0]);
yinyueXiazai.setXiazai_dizhi(qianqian[1]);
yinyueXiazai.setStatus(1);
}
//Ik123定制
if(yinyueXiazai.getShiting_url().indexOf("www.ik123.com")>0){
String ik = new Ik123().urlToMusic(yinyueXiazai.getShiting_url());
yinyueXiazai.setXiazai_dizhi(ik);
yinyueXiazai.setStatus(1);
}
//djye定制
if(yinyueXiazai.getShiting_url().indexOf("www.djye.com")>0){
String djye = new DJye().urlToMusic(yinyueXiazai.getShiting_url());
yinyueXiazai.setXiazai_dizhi(djye);
yinyueXiazai.setStatus(1);
}
//djkk定制
if(yinyueXiazai.getShiting_url().indexOf("www.djkk.com")>0){
String djkk = new com.clint.yinyue_xiazai.util.djkk().urlToMusic(yinyueXiazai.getShiting_url());
yinyueXiazai.setXiazai_dizhi(djkk);
yinyueXiazai.setStatus(1);
}
//72dj定制
if(yinyueXiazai.getShiting_url().indexOf("www.72dj.com")>0){
String djkk = new WWW_72dj().urlToMusic(yinyueXiazai.getShiting_url());
yinyueXiazai.setXiazai_dizhi(djkk);
yinyueXiazai.setStatus(1);
}
//bbdj定制
if(yinyueXiazai.getShiting_url().indexOf("www.bbdj.com")>0){
String djkk = new BBDJ().urlToMusic(yinyueXiazai.getShiting_url());
yinyueXiazai.setXiazai_dizhi(djkk);
yinyueXiazai.setStatus(1);
}
yinyueXiazai.setDatetime(StringCode.getDateTime());
yinyueXiazaiDao.saveYinyueXiazai(yinyueXiazai);
json.put("type", "ok");
response.getWriter().write(json.toString());
}
//获取最近的下载列表
@RequestMapping(value = "/huoquLiebiao")
public void huoquLiebiao(String uuid,HttpServletResponse response) throws IOException {
JSONObject json = new JSONObject();
Map<String, Object> tiaojian = new HashMap<String, Object>();
tiaojian.put("uuid", uuid);
PageList pageList = yinyueXiazaiDao.getPageYinyueXiazaiS(tiaojian);
json.put("data", pageList.getDatalist());
json.put("type", "ok");
response.getWriter().write(json.toString());
}
//处理端进入页面
@RequestMapping(value = "/yinyueChuli")
public String yinyueChuli() {
return "/yinyue_xiazai/chuli/chuli.jsp";
}
//获取未处理的音乐列表,//正序排列,
@RequestMapping(value = "/weichuliLiebiao")
public void weichuliLiebiao(HttpServletResponse response) throws IOException {
JSONObject json = new JSONObject();
PageList pageList = yinyueXiazaiDao.getPageYinyue_weichuli();
json.put("data", pageList.getDatalist());
response.getWriter().write(json.toString());
}
//提交下载地址
@RequestMapping(value = "/saveXiazai")
public void saveXiazai(YinyueXiazai yinyueXiazai,HttpServletResponse response) throws IOException {
JSONObject json = new JSONObject();
YinyueXiazai yinyueXiazaiDb = yinyueXiazaiDao.getYinyueXiazai(yinyueXiazai.getId());
//如果地址栏是空则分析失败
if(StringUtils.isBlank(yinyueXiazai.getXiazai_dizhi())){
yinyueXiazaiDb.setStatus(2);
}else{
yinyueXiazaiDb.setStatus(1);
}
yinyueXiazaiDb.setXiazai_dizhi(yinyueXiazai.getXiazai_dizhi());
yinyueXiazaiDao.updataYinyueXiazai(yinyueXiazaiDb);
json.put("type", "ok");
response.getWriter().write(json.toString());
}
//下载链接获取
@RequestMapping(value = "/XiazaiLianjie")
public void XiazaiLianjie(HttpServletResponse response) throws IOException {
response.getWriter().write("http://fs.w.kugou.com/201902171402/9dcc6059af2ea3ccacb7efcb4c9d5f57/G126/M06/1B/03/vg0DAFxk5QaAZQLmADDYqT1x8PY410.mp3");
}
//分析酷狗排行榜存入数据库
@RequestMapping(value = "/fenxiPaihang")
public void fenxiPaihang() throws IOException {
kugou.ListToDB("https://www.kugou.com/yy/rank/home/1-31311.html?from=rank",25,"酷狗"+"自动期");
}
//分析酷狗排行榜存入数据库
@RequestMapping(value = "/fenxiGedan")
public void fenxiGedan() throws IOException {
System.out.println("开始");
kugou.gedanAllCunchu("https://www.kugou.com/yy/special/index/1-5-0.html");
kugou.gedanAllCunchu("https://www.kugou.com/yy/special/index/1-6-0.html");
kugou.gedanAllCunchu("https://www.kugou.com/yy/special/index/1-3-0.html");
kugou.gedanAllCunchu("https://www.kugou.com/yy/special/index/1-8-0.html");
System.out.println("结束");
}
//分析酷狗歌手排行榜存入数据库
@RequestMapping(value = "/fenxiGeshou")
public void fenxigeshou() throws IOException, InterruptedException {
System.out.println("开始--分析--歌手");
kugou.bianliRemenGeshou();
System.out.println("结束--分析--歌手");
}
//根据id获取一首歌的下载地址,进入下载页面
@RequestMapping(value = "/xiazai")
public String xiazai(int id, HttpServletRequest req) throws IOException {
//查询出改id对应信息
YinyueXiazai yinyueXiazai = yinyueXiazaiDao.getYinyueXiazai(id);
req.setAttribute("yinyueXiazai", yinyueXiazai);
return "/yinyue_xiazai/xiazaiByid/index.jsp";
}
//异步更新下载地址
@RequestMapping(value = "/gengxin_url")
public void gengxin_url(int id, HttpServletRequest req,HttpServletResponse response) throws IOException {
//查询出改id对应信息
YinyueXiazai yinyueXiazai = yinyueXiazaiDao.getYinyueXiazai(id);
//如果是酷狗则更新下载链接
//查询是否是酷狗,如果是则直接查询地址并存储
if(yinyueXiazai.getShiting_url().indexOf("www.kugou.com")>0){
String[] kugoud = new KuGou().urlToMusic(yinyueXiazai.getShiting_url());
yinyueXiazai.setGequ_name(kugoud[0]);
yinyueXiazai.setXiazai_dizhi(kugoud[1]);
yinyueXiazai.setStatus(1);
this.yinyueXiazaiDao.updataYinyueXiazai(yinyueXiazai);
}
//返回地址
response.getWriter().write(yinyueXiazai.getXiazai_dizhi());
}
//给所有歌曲增加伪原创文字,随机生成汉字,生成30行,并随机插入标题文字10次,并保存到数据库
@RequestMapping(value = "/weiyuanchuang")
public void weiyuanchuang() throws UnsupportedEncodingException {
//查询出所有没有伪原创文章的歌曲记录
List<YinyueXiazai> list = this.yinyueXiazaiDao.getNoWeiyuanchuang();
for (int i = 0; i < list.size(); i++) {
YinyueXiazai yy = list.get(i);
//生成随机文字30行
String zongwenzi = "";
for (int j = 0; j < 30; j++) {
//每行40以内,随机数量
//组合成p标签字符串,插入标题多次
zongwenzi+="<p>";
for (int j2 = 0; j2 < 40; j2++) {
//在随机位置添加歌名关键词
if(j==5||j==16||j==23||j==28||j==32||j==38){
if(j2==24){
zongwenzi+="音乐250网"+yy.getGequ_name()+" mp3高清歌曲免费下载";
}
}
//添加汉字
zongwenzi+=this.getRandomChar();
//添加逗号
if(j2==10||j2==20||j2==30){
zongwenzi+=",";
}
}
//添加句号
zongwenzi+="。";
zongwenzi+="</p>";
}
//存储到数据库
yy.setWeiYuanChuang(zongwenzi);
this.yinyueXiazaiDao.updataYinyueXiazai(yy);
}
}
//随机汉字生成
public static String getRandomChar() throws UnsupportedEncodingException {
String str = null;
int hightPos, lowPos; // 定义高低位
Random random = new Random();
hightPos = (176 + Math.abs(random.nextInt(39)));//获取高位值
lowPos = (161 + Math.abs(random.nextInt(93)));//获取低位值
byte[] b = new byte[2];
b[0] = (new Integer(hightPos).byteValue());
b[1] = (new Integer(lowPos).byteValue());
str = new String(b, "GBk");//转成中文
return str;
// return (char) (0x4e00 + (int) (Math.random() * (0x9fa5 - 0x4e00 + 1)));
}
public static void main(String[] args) throws UnsupportedEncodingException {
for (int i = 0; i < 30; i++) {
System.out.println(new YinyueController().getRandomChar());
}
}
//获取歌曲列表
@RequestMapping(value = "/gequList")
public String gequList(int start, HttpServletRequest request) throws IOException {
//查询出改id对应信息
Map<String, Object> tiaojian = new HashMap<String, Object>();
PageList page = yinyueXiazaiDao.getPageYinyue(tiaojian, start, 20);
page.setUrl(yinyueUtil.getYuming(request)+"yinyue_xiazai/gequList.action?start=");
request.setAttribute("page", page);
return "/yinyue_xiazai/yinyueList/yinyueList.jsp";
}
}
| [
"1021567205@qq.com"
] | 1021567205@qq.com |
66bc2e135dcb91fce541c866c6a26f20e2243f92 | 91a894ced06ddf65665a5d41de150a3daaf97b1d | /multiply.java | 9f9ebc226c2e2205bf086c3ceb33cdddca4f4a17 | [] | no_license | tusquake/GIT | 2f0ebf911205d728b56a66966f1f11598ef06f23 | 5912d878fa857cb7fb2a4552dcd7b2433208d9d8 | refs/heads/master | 2023-05-28T20:22:06.044567 | 2021-06-04T10:12:02 | 2021-06-04T10:12:02 | 373,779,834 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 131 | java | public class multiply{
public static void main(String[] args) {
int a=4;
int b=2;
System.out.println("The product is "+(a*b));
}
} | [
"tusharrealme@gmail.com"
] | tusharrealme@gmail.com |
783a998b23e3b8c69bed2afd4c44b08b8daf0141 | 3022b7013433e3c76bc574cbfb748c6c189212c2 | /src/main/java/it/jpanik/jgaming/repositories/RankRepository.java | 44a6225d4e76a235726bf5ded10760094ebbb957 | [] | no_license | MarcoFantini/jgaming-memory-be | 74706452249c3890c130ee7a6e8e04d2067c281e | 7fa363d346e7b753cfc9effe9bd612b8d67969aa | refs/heads/master | 2023-08-30T14:01:51.637444 | 2021-10-31T14:37:03 | 2021-10-31T14:37:03 | 423,172,866 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 525 | java | package it.jpanik.jgaming.repositories;
import it.jpanik.jgaming.entities.Rank;
import it.jpanik.jgaming.entities.User;
import it.jpanik.jgaming.enums.GameType;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
import java.util.Optional;
/**
* @author Jacopo Cervellini
*/
public interface RankRepository extends CrudRepository<Rank,Long> {
List<Rank> findByGameTypeOrderByScoreDesc(GameType gameType);
Optional<Rank> findByUserAndGameType(User username, GameType gameType);
}
| [
"mar.fantini@outlook.it"
] | mar.fantini@outlook.it |
a904baf93f1ae2e856aa9863b3192b74b12008cc | 1921774cf1fdaaef6c6249bc228434fc6a3efc40 | /RAR文件/蓝桥杯1,2,3,4,5,6届真题-1/蓝桥杯1,2,3,4,5,6届真题/蓝桥杯赛事规则阅读与解析/2014北京研讨会资料/题目例解 往届真题/往届真题 仅供参考解/黄金连分数/Main.java | 95a1e7014a1418918985509643ddc28d44a1239c | [] | no_license | 1123Javayanglei/suanFaXue | 2fee48184a3278c8e51f14242afb118e4f982eb1 | de25b67fd86d9ec56535737a903160951308b905 | refs/heads/master | 2020-12-14T22:05:56.992653 | 2020-01-19T12:19:50 | 2020-01-19T12:19:50 | 234,884,134 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 834 | java | import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
/*
0.
6180339887
4989484820
4586834365
6381177203
0917980576
2862135448
6227052604
6281890244
9707207204
1893911374
8475408807
5386891752
1266338622
2353693179
3180060766
7263544333
*/
public class Main
{
public static void main(String[] args)
{
BigDecimal a = new BigDecimal(
new BigInteger("16031593418561412247332727650013131485560413591546962950711890"
+ "9263076087590471022644452597131283888029087109729"),110);
BigDecimal b = new BigDecimal(
new BigInteger("990806962649007214722085159567487591879198048406087340073676610"
+ "59706052043279378932885908102386332543066271936"),110);
BigDecimal c = b.divide(a, RoundingMode.HALF_DOWN);
System.out.println(c.toPlainString().substring(0,103));
}
} | [
"yanglei1123@163.com"
] | yanglei1123@163.com |
7d13395b193d87d76762835d5e05d7654452585b | b597f04b81ad517862e4b2cfe37dae14e9894c89 | /src/main/java/com/website/reports/ReportGenerator.java | 6534637bfb63acaa80475aa9d5b5eea24d2546b0 | [] | no_license | ShaikHajara/SampleFramework | 48c52e6be09fa5e417b5e3d7c1de30033b2a2dd6 | c0bcd8afd680082d0656f9453ce255c485c08883 | refs/heads/master | 2020-04-08T11:40:53.565812 | 2019-01-06T09:58:36 | 2019-01-06T09:58:36 | 159,315,432 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,116 | java | package com.website.reports;
import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.testng.IReporter;
import org.testng.IResultMap;
import org.testng.ISuite;
import org.testng.ISuiteResult;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.xml.XmlSuite;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
public class ReportGenerator implements IReporter {
private ExtentReports extent;
private void buildTestNodes(IResultMap tests, LogStatus status) {
ExtentTest test;
if (tests.size() > 0) {
for (final ITestResult result : tests.getAllResults()) {
test = extent.startTest(result.getMethod().getMethodName());
test.setStartedTime(getTime(result.getStartMillis()));
test.setEndedTime(getTime(result.getEndMillis()));
for (final String group : result.getMethod().getGroups()) {
test.assignCategory(group);
}
if (result.getThrowable() != null) {
test.log(status, result.getThrowable());
} else {
test.log(status, "Test " + status.toString().toLowerCase() + "ed");
}
extent.endTest(test);
}
}
}
@Override
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
// TODO Auto-generated method stub
extent = new ExtentReports(outputDirectory + File.separator + "Extent.html", true);
for (final ISuite suite : suites) {
final Map<String, ISuiteResult> result = suite.getResults();
for (final ISuiteResult r : result.values()) {
final ITestContext context = r.getTestContext();
buildTestNodes(context.getPassedTests(), LogStatus.PASS);
buildTestNodes(context.getFailedTests(), LogStatus.FAIL);
buildTestNodes(context.getSkippedTests(), LogStatus.SKIP);
}
}
extent.flush();
extent.close();
}
private Date getTime(long millis) {
final Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(millis);
return calendar.getTime();
}
}
| [
"Shaik.Hajara@ATMECS.CORP"
] | Shaik.Hajara@ATMECS.CORP |
19bdd37428fde523fbd4ed0cc91d715ea03004c7 | 071a9fa7cfee0d1bf784f6591cd8d07c6b2a2495 | /corpus/norm-class/eclipse.jdt.ui/2519.java | 79e938ebd1c3a428e11435fca002d5da754232f7 | [
"MIT"
] | permissive | masud-technope/ACER-Replication-Package-ASE2017 | 41a7603117f01382e7e16f2f6ae899e6ff3ad6bb | cb7318a729eb1403004d451a164c851af2d81f7a | refs/heads/master | 2021-06-21T02:19:43.602864 | 2021-02-13T20:44:09 | 2021-02-13T20:44:09 | 187,748,164 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,502 | java | copyright ibm corporation rights reserved program accompanying materials terms eclipse license accompanies distribution http eclipse org legal epl html contributors ibm corporation initial api implementation org eclipse jdt internal wizards build paths buildpaths java util array list arraylist java util list org eclipse equinox bidi structured text type handler factory structuredtexttypehandlerfactory org eclipse swt swt org eclipse swt layout grid data griddata org eclipse swt layout grid layout gridlayout org eclipse swt widgets button org eclipse swt widgets composite org eclipse swt widgets control org eclipse swt widgets shell org eclipse swt widgets text org eclipse core runtime core exception coreexception org eclipse core runtime i path ipath org eclipse core runtime i status istatus org eclipse core resources i container icontainer org eclipse core resources i folder ifolder org eclipse core resources i project iproject org eclipse core resources i resource iresource org eclipse core resources i workspace root iworkspaceroot org eclipse jface dialogs status dialog statusdialog org eclipse jface util bidi utils bidiutils org eclipse jface viewers i label provider ilabelprovider org eclipse jface viewers i tree content provider itreecontentprovider org eclipse jface viewers viewer filter viewerfilter org eclipse jface window window org eclipse platformui org eclipse dialogs i selection status validator iselectionstatusvalidator org eclipse model workbench content provider workbenchcontentprovider org eclipse model workbench label provider workbenchlabelprovider org eclipse views navigator resource comparator resourcecomparator org eclipse jdt core i java project ijavaproject org eclipse jdt internal corext build path buildpath cp java project cpjavaproject org eclipse jdt internal corext build path buildpath classpath modifier classpathmodifier org eclipse jdt internal corext util messages org eclipse jdt internal i java help context ids ijavahelpcontextids org eclipse jdt internal java plugin javaplugin org eclipse jdt internal dialogs status info statusinfo org eclipse jdt internal util swt util swtutil org eclipse jdt internal viewsupport basic element labels basicelementlabels org eclipse jdt internal wizards new wizard messages newwizardmessages org eclipse jdt internal wizards type d element selection validator typedelementselectionvalidator org eclipse jdt internal wizards type d viewer filter typedviewerfilter org eclipse jdt internal wizards dialogfields dialog field dialogfield org eclipse jdt internal wizards dialogfields i dialog field listener idialogfieldlistener org eclipse jdt internal wizards dialogfields i string button adapter istringbuttonadapter org eclipse jdt internal wizards dialogfields selection button dialog field selectionbuttondialogfield org eclipse jdt internal wizards dialogfields string button dialog field stringbuttondialogfield output location dialog outputlocationdialog status dialog statusdialog string button dialog field stringbuttondialogfield f container dialog field fcontainerdialogfield selection button dialog field selectionbuttondialogfield f use default fusedefault selection button dialog field selectionbuttondialogfield f use specific fusespecific i status istatus f container field status fcontainerfieldstatus i path ipath f output location foutputlocation i project iproject f curr project fcurrproject cp list element cplistelement f entry to edit fentrytoedit f allow invalid classpath fallowinvalidclasspath cp java project cpjavaproject fcpjavaproject output location dialog outputlocationdialog shell parent cp list element cplistelement entry to edit entrytoedit list cp list element cplistelement class path list classpathlist i path ipath default output folder defaultoutputfolder allow invalid classpath allowinvalidclasspath parent f entry to edit fentrytoedit entry to edit entrytoedit f allow invalid classpath fallowinvalidclasspath allow invalid classpath allowinvalidclasspath set title settitle new wizard messages newwizardmessages output location dialog outputlocationdialog title f container field status fcontainerfieldstatus status info statusinfo output location adapter outputlocationadapter adapter output location adapter outputlocationadapter f use default fusedefault selection button dialog field selectionbuttondialogfield swt radio f use default fusedefault set label text setlabeltext messages format new wizard messages newwizardmessages output location dialog outputlocationdialog used efault usedefault label basic element labels basicelementlabels get path label getpathlabel default output folder defaultoutputfolder f use default fusedefault set dialog field listener setdialogfieldlistener adapter string label messages format new wizard messages newwizardmessages output location dialog outputlocationdialog uses pecific usespecific label basic element labels basicelementlabels get resource name getresourcename entry to edit entrytoedit get path getpath segment f use specific fusespecific selection button dialog field selectionbuttondialogfield swt radio f use specific fusespecific set label text setlabeltext label f use specific fusespecific set dialog field listener setdialogfieldlistener adapter f container dialog field fcontainerdialogfield string button dialog field stringbuttondialogfield adapter f container dialog field fcontainerdialogfield set button label setbuttonlabel new wizard messages newwizardmessages output location dialog outputlocationdialog location button f container dialog field fcontainerdialogfield set dialog field listener setdialogfieldlistener adapter f use specific fusespecific attach dialog field attachdialogfield f container dialog field fcontainerdialogfield i java project ijavaproject java project javaproject entry to edit entrytoedit get java project getjavaproject f curr project fcurrproject java project javaproject get project getproject fcpjavaproject cp java project cpjavaproject java project javaproject class path list classpathlist default output folder defaultoutputfolder i path ipath output location outputlocation i path ipath entry to edit entrytoedit get attribute getattribute cp list element cplistelement output output location outputlocation f use default fusedefault set selection setselection f use specific fusespecific set selection setselection f container dialog field fcontainerdialogfield set text settext output location outputlocation remove first segments removefirstsegments make relative makerelative to string tostring override control create dialog area createdialogarea composite parent composite composite composite create dialog area createdialogarea parent width hint widthhint convert width in chars to pixels convertwidthincharstopixels indent convert width in chars to pixels convertwidthincharstopixels composite composite composite swt grid layout gridlayout layout grid layout gridlayout layout margin height marginheight layout margin width marginwidth layout num columns numcolumns set layout setlayout layout f use default fusedefault do fill into grid dofillintogrid f use specific fusespecific do fill into grid dofillintogrid text text control textcontrol f container dialog field fcontainerdialogfield get text control gettextcontrol grid data griddata text data textdata grid data griddata text data textdata width hint widthhint width hint widthhint text data textdata grab excess horizontal space grabexcesshorizontalspace text data textdata horizontal indent horizontalindent indent text control textcontrol set layout data setlayoutdata text data textdata bidi utils bidiutils apply bidi processing applybidiprocessing text control textcontrol structured text type handler factory structuredtexttypehandlerfactory file button button control buttoncontrol f container dialog field fcontainerdialogfield get change control getchangecontrol grid data griddata button data buttondata grid data griddata button data buttondata width hint widthhint swt util swtutil get button width hint getbuttonwidthhint button control buttoncontrol button control buttoncontrol set layout data setlayoutdata button data buttondata apply dialog font applydialogfont composite composite output location adapter outputlocationadapter i dialog field listener idialogfieldlistener i string button adapter istringbuttonadapter i dialog field listener idialogfieldlistener override dialog field changed dialogfieldchanged dialog field dialogfield field do status line update dostatuslineupdate override change control pressed changecontrolpressed dialog field dialogfield field do change control pressed dochangecontrolpressed do change control pressed dochangecontrolpressed i container icontainer container choose output location chooseoutputlocation container f container dialog field fcontainerdialogfield set text settext container get project relative path getprojectrelativepath to string tostring do status line update dostatuslineupdate check if path valid checkifpathvalid update status updatestatus f container field status fcontainerfieldstatus check if path valid checkifpathvalid f output location foutputlocation f container field status fcontainerfieldstatus status info statusinfo status f use default fusedefault is selected isselected string path str pathstr f container dialog field fcontainerdialogfield get text gettext path str pathstr length nls f container field status fcontainerfieldstatus status info statusinfo i status istatus error i path ipath project path projectpath fcpjavaproject get java project getjavaproject get project getproject get full path getfullpath i path ipath output path outputpath project path projectpath append path str pathstr f container field status fcontainerfieldstatus classpath modifier classpathmodifier check set output location precondition checksetoutputlocationprecondition f entry to edit fentrytoedit output path outputpath f allow invalid classpath fallowinvalidclasspath fcpjavaproject f container field status fcontainerfieldstatus get severity getseverity i status istatus error f output location foutputlocation output path outputpath core exception coreexception java plugin javaplugin log i path ipath get output location getoutputlocation f output location foutputlocation org eclipse jface window window configure shell configureshell shell override configure shell configureshell shell new shell newshell configure shell configureshell new shell newshell platformui get workbench getworkbench get help system gethelpsystem set help sethelp new shell newshell i java help context ids ijavahelpcontextids output location dialog util method i container icontainer choose output location chooseoutputlocation i workspace root iworkspaceroot root f curr project fcurrproject get workspace getworkspace get root getroot accepted classes acceptedclasses i project iproject i folder ifolder i project iproject all projects allprojects root get projects getprojects array list arraylist i project iproject rejected elements rejectedelements array list arraylist all projects allprojects length all projects allprojects length all projects allprojects equals f curr project fcurrproject rejected elements rejectedelements add all projects allprojects viewer filter viewerfilter filter type d viewer filter typedviewerfilter accepted classes acceptedclasses rejected elements rejectedelements to array toarray i label provider ilabelprovider workbench label provider workbenchlabelprovider i tree content provider itreecontentprovider workbench content provider workbenchcontentprovider i resource iresource init selection initselection f output location foutputlocation init selection initselection root find member findmember f output location foutputlocation folder selection dialog folderselectiondialog dialog folder selection dialog folderselectiondialog get shell getshell dialog set title settitle new wizard messages newwizardmessages output location dialog outputlocationdialog choose output folder chooseoutputfolder title dialog set validator setvalidator i selection status validator iselectionstatusvalidator i selection status validator iselectionstatusvalidator validator type d element selection validator typedelementselectionvalidator accepted classes acceptedclasses override i status istatus validate object selection i status istatus type d status typedstatus validator validate selection type d status typedstatus isok type d status typedstatus selection i folder ifolder i folder ifolder folder i folder ifolder selection i status istatus result classpath modifier classpathmodifier check set output location precondition checksetoutputlocationprecondition f entry to edit fentrytoedit folder get full path getfullpath f allow invalid classpath fallowinvalidclasspath fcpjavaproject result get severity getseverity i status istatus error result core exception coreexception java plugin javaplugin log status info statusinfo nls status info statusinfo i status istatus error dialog set message setmessage new wizard messages newwizardmessages output location dialog outputlocationdialog choose output folder chooseoutputfolder description dialog add filter addfilter filter dialog set input setinput root dialog set initial selection setinitialselection init selection initselection dialog set comparator setcomparator resource comparator resourcecomparator resource comparator resourcecomparator dialog open window i container icontainer dialog get first result getfirstresult | [
"masudcseku@gmail.com"
] | masudcseku@gmail.com |
4ca9dfd93c4f327f103028ca77694270cd92f640 | 332ff04d51a93a105e80858953a06142141b21ef | /src/test/java/EchoServerTest.java | 934dc4b02606291f7f23d6832210e81fe1dfc9ff | [] | no_license | Himalee/echo-server | e5872087b272b88e7c98cc704b397b3817c341b4 | c06edd8ad16f5c1cd7d0cb85dfe66777c86ed46c | refs/heads/master | 2020-04-25T22:03:43.845126 | 2019-04-26T16:54:01 | 2019-04-26T16:54:01 | 173,098,133 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,378 | java | import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.*;
import static org.hamcrest.CoreMatchers.containsString;
public class EchoServerTest {
private int port = 1234;
private ByteArrayInputStream input;
private MockServerSocketManager mockServerSocketManager;
private ByteArrayOutputStream output = new ByteArrayOutputStream();
private String clientInput;
@Before
public void setUp() throws IOException {
clientInput = "echo\nhello\nworld\nq\n";
input = new ByteArrayInputStream(clientInput.getBytes());
mockServerSocketManager = new MockServerSocketManager(input, output);
EchoServer echoServer = new EchoServer(mockServerSocketManager);
echoServer.start(port);
}
@Test
public void startEchoServer_checkConnection() {
Assert.assertTrue(mockServerSocketManager.wasConnectCalled());
}
@Test
public void startEchoServer_confirmClientMessageWasReceived() {
Assert.assertThat(output.toString(), containsString("Message received"));
}
@Test
public void startEchoServer_echoClientMessage() {
Assert.assertThat(output.toString(), containsString("echo"));
}
@Test
public void startEchoServer_clientAbleToSendMultipleMessages() {
Assert.assertThat(output.toString(), containsString("Goodbye"));
}
}
| [
"himalee.tailor@gmail.com"
] | himalee.tailor@gmail.com |
686b5c9248d9fc39075f880ef78d77d5d5c84c26 | fab818b9ccc6e49ec09cacf80a3b90ad6f469c71 | /obase-risedsn/src/main/java/com/github/obase/risedsn/spring/TripleDESCodec.java | 1d247f99b7910b658e4bdbd034e25d281a08a7fa | [] | no_license | liumingmin/java | f8613c4f5ebaa86393728f1a87c16947aae41518 | aaf478ddc7a61a232cbfd088b934810ecc5d5bbc | refs/heads/master | 2020-04-13T07:14:08.496269 | 2018-03-27T03:53:18 | 2018-03-27T03:53:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,201 | java | package com.github.obase.risedsn.spring;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
public final class TripleDESCodec {
static final SecureRandom SECURE_RANDOM = new SecureRandom();
protected static final byte[] codec(int mode, String password, byte[] bytes) throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
if (password.length() != DESedeKeySpec.DES_EDE_KEY_LEN) {
throw new IllegalArgumentException("3DES的密码长度必须是24位");
}
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
SecretKey securekey = keyFactory.generateSecret(new DESedeKeySpec(password.getBytes()));
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(mode, securekey, SECURE_RANDOM);
return cipher.doFinal(bytes);
}
public static byte[] encrypt(String password, byte[] src) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
return codec(Cipher.ENCRYPT_MODE, password, src);
}
public static byte[] decrypt(String password, byte[] dst) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
return codec(Cipher.DECRYPT_MODE, password, dst);
}
public static String encrypt(String password, String srcStr, String charset) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
byte[] src = charset == null ? srcStr.getBytes() : srcStr.getBytes(charset);
byte[] dst = codec(Cipher.ENCRYPT_MODE, password, src);
return charset == null ? new String(dst) : new String(dst, charset);
}
public static byte[] encryptByte(String password, String srcStr, String charset) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
byte[] src = charset == null ? srcStr.getBytes() : srcStr.getBytes(charset);
byte[] dst = codec(Cipher.ENCRYPT_MODE, password, src);
return dst;
}
public static String decrypt(String password, String dstStr, String charset) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
byte[] dst = charset == null ? dstStr.getBytes() : dstStr.getBytes(charset);
byte[] src = codec(Cipher.DECRYPT_MODE, password, dst);
return charset == null ? new String(src) : new String(src, charset);
}
}
| [
"jason@JASONPC"
] | jason@JASONPC |
f5cd3e2e65b104017d0529c9e5566abe6c8ff754 | f22256192af28d89a06c68254b14ffcb44829b8c | /app/src/main/java/com/zjmobile/apple/moeweather/gson/Suggestion.java | c5f85ab406178e54d2f818bc3e7414d08773ec75 | [
"Apache-2.0"
] | permissive | napoleofj/moeweather | 3ea5e86ca63eca490ad168c9177594dca59959ea | 60d8b129bf9f08de57bbbbb594110c112052eeb1 | refs/heads/master | 2021-01-20T16:55:30.220403 | 2017-05-20T00:42:24 | 2017-05-20T00:42:24 | 90,751,473 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 582 | java | package com.zjmobile.apple.moeweather.gson;
import com.google.gson.annotations.SerializedName;
/**
* Created by apple on 17/5/17.
*/
public class Suggestion {
@SerializedName("comf")
public Comfort comfort;
@SerializedName("cw")
public CarWash carWash;
public Sport sport;
public class Comfort{
@SerializedName("txt")
public String info;
}
public class CarWash{
@SerializedName("txt")
public String info;
}
public class Sport{
@SerializedName("txt")
public String info;
}
}
| [
"napoleofj@gmail.com"
] | napoleofj@gmail.com |
4119b17d23a48d34b7eaf9f82a414323d021d95a | 30eff8153f5ac5896fb917cb0f691ecf90ca589d | /src/com/agl/graphics/Polygon.java | bdfbcea80579058d70f1eddd9cf4728a525b02b0 | [] | no_license | slallement/AndroidGraphicLib | 75549ea1aad428cf0998210ea26d2da42c9b4432 | badd9003194f12f23adb10eb94e2c6cb6c4c30fd | refs/heads/master | 2021-01-19T18:30:05.496414 | 2014-09-11T18:19:05 | 2014-09-11T18:19:58 | 23,027,286 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,367 | java | package com.agl.graphics;
import android.opengl.GLES20;
import android.util.Log;
/**
* @author Sergu Class representing any polygon with an arbitrary list of points
*/
public class Polygon extends Sprite {
int nbPoints = 0;
/**
* Constructor of a polygon
*
* @param posX position x
* @param posY position y
* @param points ist of points
*/
public Polygon(float posX, float posY, float[] points) {
super(posX, posY);
if (points.length % 2 != 0) {
Log.v("opengl", "Error: attempt to create a polygon "
+ "whith missing coordinates");
return;
}
nbPoints = points.length / 2;
mCoords = new float[3 * (nbPoints + 2)];
float centerX = 0.f, centerY = 0.f;
for (int i = 0; i < nbPoints; i++) {
mCoords[3 * (i + 1)] = points[2 * i];
mCoords[3 * (i + 1) + 1] = points[2 * i + 1];
centerX += points[2 * i];
centerY += points[2 * i + 1];
}
mCoords[0] = centerX / nbPoints;
mCoords[1] = centerY / nbPoints;
mCoords[3 * (nbPoints + 1)] = points[0];
mCoords[3 * (nbPoints + 1) + 1] = points[1];
// setTexture(R.drawable.blank);
init();
}
/**
* Constructor of a polygon at coordinates (0,0)
*
* @param points
*/
public Polygon(float[] points) {
this(0.f, 0.f, points);
}
/**
* @Override
*/
protected void drawShape() {
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_FAN, 0, vertexCount);
}
}
| [
"serguei.l@orange.fr"
] | serguei.l@orange.fr |
69015a44796d3f9e5b38da920e5e12a49e04dc2e | cbd2fa4a34bde1fa551d905b51bdb8704b86e8dc | /src/com/yoya/page/message/SystemMessage.java | e5e01c4c123bde4d73e35c3b2961a3003ab570ad | [] | no_license | skk4/Web | cdb9f0e45704668df2b1138c22cad5c291e6fb0d | 2ce23049971c6abd44f201ceef5f957b809623c1 | refs/heads/master | 2021-01-11T18:47:48.699578 | 2017-01-21T06:03:17 | 2017-01-21T06:03:17 | 79,627,029 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,314 | java | package com.yoya.page.message;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import com.yoya.util.Wait;
public class SystemMessage {
private WebDriver driver;
public SystemMessage(WebDriver driver){
this.driver=driver;
}
public WebElement findUnreadMessage(){
WebElement message=driver.findElement(By.xpath("//div[@id='list_data']/table/tbody[@class='unread']"));
return message;
}
public WebElement findfirstMessage(){
WebElement message=driver.findElement(By.xpath("//div[@id='list_data']/table/tbody[1]"));
return message;
}
public WebElement findMessageFromID(String message_id){
return driver.findElement(By.xpath("//tbody[@bill_m_sys_id='"+message_id+"']"));
}
public void clickReadBtn(WebElement message){
WebElement readbtn=message.findElement(By.xpath(".//div[@class='opts']/a[contains(@class,'btn_read')]"));
if(readbtn.isEnabled()){
readbtn.click();
Wait.waitMilliSeconds(3000);
}
}
public void clickDeleteBtn(WebElement message){
WebElement btn=message.findElement(By.xpath(".//div[@class='opts']/a[contains(@class,'btn_del')]"));
if(btn.isEnabled()){
btn.click();
Wait.waitMilliSeconds(5000);
}
}
}
| [
"skk_4@163.com"
] | skk_4@163.com |
469f43cec1ec55175466edbf4172e6a793835332 | 8149790201497a56173554b1725eae01287af790 | /src/cl/ciisa/cokedb/controller/actions/PopulateSelectActionProductos.java | 2998bdb39e28edc83892414b262a0beb57225604 | [] | no_license | cgalvezs/CokeSystem | 2664325b9b4fe55ec78d713fe73a418014df15db | 3efeb455e3dba315e85630193bb298bafd68df9e | refs/heads/master | 2016-09-02T06:15:13.720678 | 2014-10-05T03:01:17 | 2014-10-05T03:01:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,311 | java | package cl.ciisa.cokedb.controller.actions;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import cl.ciisa.cokedb.model.ProductosBeans;
import cl.ciisa.cokedb.services.impl.ProductosService;
import cl.ciisa.cokedb.services.interfaces.IProductosService;
public class PopulateSelectActionProductos extends Action{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
ActionMessages messages = new ActionMessages();
try {
IProductosService productosService = new ProductosService();
ArrayList<ProductosBeans> productosList = productosService.getAll();
request.setAttribute("productosList", productosList);
} catch (Exception e) {
messages.add("errors", new ActionMessage("errors.detail",e.getMessage()));
this.saveErrors(request, messages);
return mapping.findForward("failure");
}
return mapping.findForward("success");
}
}
| [
"c.galvez.sanchez@gmail.com"
] | c.galvez.sanchez@gmail.com |
81962187f9acf4df1fc3cdab7e51f70a3527a20e | 0345724b5e6cb403d2960c527a9df0caab8b119d | /src/main/java/com/laptrinhjavaweb/dto/AbstractDTO.java | 1b736694db7f26687b9ad3ef435119339a9a5521 | [] | no_license | xxminhmie/SpringBoot-WebAPI | 1fceaa3bb7c4eaf6bbaa7beab259b795283b3217 | 882ad1c4208cdf10e3eb015b072e731155813362 | refs/heads/master | 2023-04-13T16:50:41.122421 | 2021-04-27T12:17:24 | 2021-04-27T12:17:24 | 360,564,334 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,017 | java | package com.laptrinhjavaweb.dto;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class AbstractDTO<T>{
private long id;
private String createdBy;
private Date createdDate;
private String modifiedBy;
private Date modifiedDate;
//private T t;
//generic T type
private List<T> listResult = new ArrayList<>();
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
public Date getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
}
| [
"minhmie2112@gmail.com"
] | minhmie2112@gmail.com |
185d46593a4d6c0e5689521c3e5ea955d13cb671 | c4c321beed135313d811fc350322bf38bddfa82c | /common-library/src/main/java/com/jinyi/ihome/module/newshop/CustomerServiceTo.java | ba4895b2fade28f56c9c5f9f222eba07194428ec | [] | no_license | hupulin/joyProperty | ebf97ef80d28ec03de0df9bb13afdaf02ea540de | a0336ca57b44a997bde6299f2c2e05deea6a1555 | refs/heads/master | 2021-09-04T11:35:18.404336 | 2017-12-27T02:00:23 | 2017-12-27T02:00:23 | 113,118,715 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 657 | java | package com.jinyi.ihome.module.newshop;
/**
* Created by xz on 2017/1/22.
*/
public class CustomerServiceTo {
/**
* workingDay : mock
* customerServicePhone : mock
*/
private String workingDay;
private String customerServicePhone;
public String getWorkingDay() {
return workingDay;
}
public void setWorkingDay(String workingDay) {
this.workingDay = workingDay;
}
public String getCustomerServicePhone() {
return customerServicePhone;
}
public void setCustomerServicePhone(String customerServicePhone) {
this.customerServicePhone = customerServicePhone;
}
}
| [
"hpl635768909@gmail.com"
] | hpl635768909@gmail.com |
7b37f38b6473c3aaee45121a48dcd471427ed537 | a55e14b2baf85bade11480f7e26f10e1be341686 | /SmartHome/0.2-code/2.1-Trunk/2.1.1-app/SmartHome/src/com/hw/smarthome/view/pop/progress/PopProgress.java | 3b54df656e58c2a9e6d2f9d6e66dcf35717c8fc9 | [] | no_license | soon14/CODE | e9819180127c1d5c0e354090c25f55622e619d7b | 69a8dd13072cd7b181c98ec526b25ecdf98b228a | refs/heads/master | 2023-03-17T06:30:40.644267 | 2015-11-30T09:13:59 | 2015-11-30T09:13:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,055 | java | package com.hw.smarthome.view.pop.progress;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager.LayoutParams;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.hw.smarthome.R;
import com.hw.util.Ln;
/**
* 弹出窗体状态栏
*
* @author 曾凡
* @time 2014年6月26日 下午3:19:07
*/
public class PopProgress {
public static PopProgress singlePopProgress = null;
public static PopProgress getInstance(Context context,
View parent) {
singlePopProgress = new PopProgress(context, parent);
return singlePopProgress;
}
public static PopProgress getInstance(Context context,
View parent,boolean flag,String failTest) {
singlePopProgress = new PopProgress(context, parent,flag,failTest);
return singlePopProgress;
}
public static PopProgress getInstance(Context context,
View parent, long time) {
if (singlePopProgress == null) {
singlePopProgress = new PopProgress(context, parent,
time);
}
return singlePopProgress;
}
OtherIntent otherIntent;
public static interface OtherIntent {
void closeIntent();
}
public void setOtherIntent(OtherIntent d) {
otherIntent = d;
}
private PopupWindow popupWindow = null;
private Context mContext = null;
private View mParent = null;
private TextView mPopProgressText = null;
private ProgressBar mPopProgressBar = null;
private ImageView mPopResultImage = null;
// private long startTime;// 定义成员变量,标记pop显示的时间
private boolean isTimeOut = false;
private long delayTime = 60*1000;
private boolean flag = false; //判断是否可以中断
private String failText = null;
private boolean rsour = false;
public PopProgress(Context context, View parent) {
this.mContext = context;
this.mParent = parent;
setPopupWindow(initPopWindow());
MyThread mThread = new MyThread();
mThread.start();// 开启线程
// startTime = System.currentTimeMillis();//为显示的开始时间赋值
}
public PopProgress(Context context, View parent, boolean flag,String failText) {
this.mContext = context;
this.mParent = parent;
this.flag = flag;
setPopupWindow(initPopWindow());
MyThread mThread = new MyThread();
delayTime = 120*1000;
this.failText = failText;
mThread.start();// 开启线程
// startTime = System.currentTimeMillis();//为显示的开始时间赋值
}
public PopProgress(Context context, View parent, long time) {
this(context, parent);
this.delayTime = time;
}
/**
* 初始化一个[弹出窗体状态栏]
*
* @author 曾凡
* @time 2014年6月26日 下午3:30:43
*/
public PopupWindow initPopWindow() {
View popView = LayoutInflater.from(mContext).inflate(
R.layout.view_pop_progress, null);
mPopProgressText = (TextView) popView
.findViewById(R.id.popProgressText);
mPopProgressBar = (ProgressBar) popView
.findViewById(R.id.popProgressBar);
mPopResultImage = (ImageView) popView
.findViewById(R.id.popResultImage);
mPopResultImage.setVisibility(View.GONE);
popupWindow = new PopupWindow(popView,
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, false);
popupWindow.setOutsideTouchable(flag);
popupWindow.setTouchable(true);
popupWindow.getContentView().setOnTouchListener(
new View.OnTouchListener() {
@Override
public boolean onTouch(View v,
MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
popupWindow.dismiss();
}
return false;
}
});
popupWindow.showAtLocation(mParent,
Gravity.CENTER_VERTICAL, 0, 0);
return popupWindow;
}
/**
* 显示结果
*
* @author 曾凡
* @param res
* 成功或失败
* @param msg
* @time 2014年7月3日 下午12:30:18
*/
public void showResult(boolean res, String msg) {
rsour = res;
showImage(res);
setText(msg);
delayTime = 3000;
}
public void showImage(boolean res) {
if (res) {
// mPopResultImage
// .setImageResource(R.drawable.view_pop_progress_success);
mPopResultImage.setImageResource(R.drawable.success);
} else {
// mPopResultImage
// .setImageResource(R.drawable.view_pop_progress_failure);
mPopResultImage.setImageResource(R.drawable.fail);
}
mPopResultImage.setVisibility(View.VISIBLE);
mPopProgressBar.setVisibility(View.GONE);
}
public void showProgress() {
mPopProgressBar.setVisibility(View.VISIBLE);
}
public void hiddenProgerss() {
mPopProgressBar.setVisibility(View.INVISIBLE);
}
/**
* 设置状态内容
*
* @author 曾凡
* @param msg
* @time 2014年7月3日 上午11:45:43
*/
public void setText(String msg) {
mPopProgressText.setText(msg);
popupWindow.update();
}
public void setOutsideTouchable(Boolean flag){
popupWindow.setOutsideTouchable(flag);
}
public PopupWindow getPopupWindow() {
return popupWindow;
}
public void setPopupWindow(PopupWindow popupWindow) {
this.popupWindow = popupWindow;
}
private class MyThread extends Thread {
public void run() {
try {
// Thread.sleep(delayTime);
// long endTime = System.currentTimeMillis();
// Ln.i(endTime-startTime-5000);
// 注意:由于程序的执行也需要耗费时间,所以结束时间和开始时间不可能完全相差5s,
// 只能控制在一个很小的误差内,而这个误差对用户的点击间隔而言是可以忽略的,这里去误差时间为50毫秒。
if (popupWindow != null) {
Message msgMessage = handler
.obtainMessage(1);
handler.sendMessageDelayed(msgMessage, 1000);
}
} catch (Exception e) {
e.printStackTrace();
}
};
}
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
delayTime = delayTime - 1000;
if (delayTime > 0) {
if (failText!=null) {
Message msgMessage = handler
.obtainMessage(2);
handler.sendMessageDelayed(msgMessage, 1000);
}else{
Message msgMessage = handler
.obtainMessage(1);
handler.sendMessageDelayed(msgMessage, 1000);
}
} else {
if (popupWindow.isShowing()) {
try {
popupWindow.dismiss();
} catch (Exception e) {
}
}
singlePopProgress = null;
Ln.i("计数完成");
}
break;
case 2:
delayTime = delayTime - 1000;
if (delayTime > 0) {
Message msgMessage = handler
.obtainMessage(2);
handler.sendMessageDelayed(msgMessage, 1000);
} else {
if (popupWindow.isShowing()) {
try {
if (!rsour) {
showImage(rsour);
setText(failText);
}
} catch (Exception e) {
}
}
singlePopProgress = null;
Ln.i("计数完成");
}
break;
}
}
};
}
| [
"835337572@qq.com"
] | 835337572@qq.com |
41d3c8b06142b278f46fb2d04cbe6fe619b93509 | 573b9c497f644aeefd5c05def17315f497bd9536 | /src/main/java/com/alipay/api/domain/AlipayCommerceTransportVehicleownerCampaignQueryModel.java | 805711b23d52855a438c08f4c41de284264df321 | [
"Apache-2.0"
] | permissive | zzzyw-work/alipay-sdk-java-all | 44d72874f95cd70ca42083b927a31a277694b672 | 294cc314cd40f5446a0f7f10acbb5e9740c9cce4 | refs/heads/master | 2022-04-15T21:17:33.204840 | 2020-04-14T12:17:20 | 2020-04-14T12:17:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 763 | java | package com.alipay.api.domain;
import java.util.List;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.internal.mapping.ApiListField;
/**
* 营销活动接口查询
*
* @author auto create
* @since 1.0, 2020-01-10 17:35:17
*/
public class AlipayCommerceTransportVehicleownerCampaignQueryModel extends AlipayObject {
private static final long serialVersionUID = 8587196311382868238L;
/**
* 活动id的列表
*/
@ApiListField("activity_id")
@ApiField("string")
private List<String> activityId;
public List<String> getActivityId() {
return this.activityId;
}
public void setActivityId(List<String> activityId) {
this.activityId = activityId;
}
}
| [
"ben.zy@antfin.com"
] | ben.zy@antfin.com |
18d1fbee585c182820529096f052699695377e8b | 28109559ba5142fadf7689f5b8cc171ccf2470c2 | /ProfessorGradeBook/src/Actions.java | 141256b83cd57401e7956bb75e30709fd943d23e | [] | no_license | NelsonALi/ProfessorGradeBook | 09ed6b12ad00f1dc78550b5bb1cd8d9afb1ecf92 | 16e43070c6b8df53afacf2eb763f6db142811cc5 | refs/heads/master | 2021-01-10T15:52:05.319109 | 2015-11-02T14:03:11 | 2015-11-02T14:03:11 | 45,274,238 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,121 | java |
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Actions
*/
@WebServlet("/Actions")
public class Actions extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Actions() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
| [
"GBTC440008UR@GBTC440A21W7.wdce.local"
] | GBTC440008UR@GBTC440A21W7.wdce.local |
b9f84e80c8952e154aeeddc3c45b2e2b1f510657 | e1d2dc7dd96dfc8e9cb441cecfd0ba6939ed86ab | /src/main/java/com/buttons/mastermind/domain/exception/OvercomeAttemptsException.java | b783e4ff6646daf58b471cadedad826f81295b94 | [] | no_license | freetimefarmers/ddd-spring-mastermind | 8131e472a670b1fc64b91d10f23e4254682b1eda | 349840d67e8bf9b17b11ba549e4444e4adb84401 | refs/heads/master | 2020-06-25T05:19:57.742977 | 2019-05-20T07:06:57 | 2019-05-20T07:06:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 263 | java | package com.buttons.mastermind.domain.exception;
public class OvercomeAttemptsException extends RuntimeException {
private static final String MESSAGE = "HAS OVERCAME THE ATTEMPTS";
public OvercomeAttemptsException() {
super(MESSAGE);
}
}
| [
"rraulqm92@gmail.com"
] | rraulqm92@gmail.com |
a118766952609e3ba0f71e1d0ed755c480b35ace | 00205fdbc8b54e04fc76ba88c3e5a5fd7696ff2e | /src/th/ac/nu/student/u54341611/compro/ch02/DynamicInit.java | 6e26dedea3d2461e4d862e847d0c81df10c44090 | [] | no_license | chanisara/compro1611 | 461d78d1c649230e0c75c69b1f89a4f0d808aa62 | 304a420add415212a37eaa74100dc966b264896a | refs/heads/master | 2016-09-06T13:57:21.784433 | 2012-07-16T12:12:41 | 2012-07-16T12:12:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 524 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package th.ac.nu.student.u54341611.compro.ch02.homework;
/**
*
* @author user
*/
public class DynamicInit {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
if (args.length == 2) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
double c = Math.sqrt(a * a + b * b);
System.out.println(c);
}
}
} | [
"chanitsaral@gmail.com"
] | chanitsaral@gmail.com |
a26bcf840e4dd64d423890f2861cbb8199d32982 | 1b79b68617280b693a1824f4c759a9ee876fb63a | /app/src/main/java/com/example/o_x/UstawieniaActivity.java | c161539ffa2a89620ec1192c1989af97a36bcbee | [] | no_license | marcinponiewozik/KolkoKrzyzykApp | 1943aa7622953b654b559c4b9969540a57fd652d | 9e0cc69fadbf588fdadb1a898f26d66af9a7fdfb | refs/heads/master | 2021-01-10T07:54:30.123238 | 2016-03-03T11:18:51 | 2016-03-03T11:18:51 | 52,963,734 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,418 | java | package com.example.o_x;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import java.io.File;
import de.hdodenhof.circleimageview.CircleImageView;
public class UstawieniaActivity extends AppCompatActivity {
Context context = this;
EditText etStareHaslo, etNoweHaslo;
Osoba osobaTemp;
private Uri mImageCaptureUri;
Bitmap noweLogo;
View coordinatorLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ustawienia);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
etNoweHaslo = (EditText) findViewById(R.id.etNoweHaslo);
etStareHaslo = (EditText) findViewById(R.id.etStareHaslo);
coordinatorLayout = findViewById(R.id.coordinatorLayout);
}
public void zmianaHaslo(View view) {
String nowe = etNoweHaslo.getText().toString();
String stare = etStareHaslo.getText().toString();
osobaTemp = Dane.osobaZalogowana;
if (etNoweHaslo.getText().length() > 4 && etStareHaslo.getText().length() > 4) {
if (Dane.md5(stare).equals(Dane.osobaZalogowana.getHaslo())) {
osobaTemp.setHaslo(Dane.md5(nowe));
PutOsoba zmianaHasla = new PutOsoba();
zmianaHasla.execute(osobaTemp);
} else {
Snackbar.make(view, "Wprowadzono nieprawidłowe hasło", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
} else {
Snackbar.make(view, "Haslo musza miec minimum 4 znaki", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
}
public void wyloguj(View v) {
SharedPreferences preferences = getSharedPreferences("uzytkownik", MODE_PRIVATE);
preferences.edit().clear().commit();
context.deleteDatabase("test");
finish();
}
public void zmianaZdjecia(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
Bitmap bitmap = null;
String path = "";
if (requestCode == 1) {
mImageCaptureUri = data.getData();
path = getRealPathFromURI(mImageCaptureUri); //from Gallery
if (path == null)
path = mImageCaptureUri.getPath(); //from File Manager
if (path != null)
bitmap = getBitmap(path);
File file = new File(path);
float size = file.length() / 1024;
if (size < 201)
dialogPotwierdzenie(bitmap);
else
Snackbar.make(getCurrentFocus(), "Maksymalny rozmiar zdjęcia to 200Kb", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
} else
Snackbar.make(getCurrentFocus(), "Error", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
public void dialogPotwierdzenie(final Bitmap bitmap) {
noweLogo = bitmap;
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.dialog_zmiana_zdjecia, null);
dialogBuilder.setView(dialogView);
final CircleImageView ivLogo = (CircleImageView) dialogView.findViewById(R.id.ivLogo);
ivLogo.setImageBitmap(noweLogo);
final CircleImageView ivLogoStare = (CircleImageView) dialogView.findViewById(R.id.ivLogoStare);
byte[] logo = Dane.osobaZalogowana.getLogo();
Bitmap bitmapLogo = BitmapFactory.decodeByteArray(logo, 0, logo.length);
ivLogoStare.setImageBitmap(bitmapLogo);
Button btnObroc = (Button) dialogView.findViewById(R.id.btnObroc);
btnObroc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
noweLogo = obroc(noweLogo);
final CircleImageView ivLogo = (CircleImageView) dialogView.findViewById(R.id.ivLogo);
ivLogo.setImageBitmap(noweLogo);
}
});
dialogBuilder.setTitle("Potwierdzenie zmiany");
dialogBuilder.setPositiveButton("Potwierdzam", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
osobaTemp = Dane.osobaZalogowana;
byte[] logo = Dane.bitmapToByteArray(noweLogo);
osobaTemp.setLogo(logo);
PutOsoba putOsoba = new PutOsoba();
putOsoba.execute(osobaTemp);
dialog.dismiss();
}
});
dialogBuilder.setNegativeButton("Anuluj", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
AlertDialog b = dialogBuilder.create();
b.setCancelable(false);
b.show();
}
private Bitmap obroc(Bitmap bitmap) {
Matrix matrix = new Matrix();
matrix.preRotate(90);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
private Bitmap getBitmap(String path) {
Bitmap bitmap;
bitmap = BitmapFactory.decodeFile(path);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), null, true);
return bitmap;
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private class PutOsoba extends AsyncTask<Osoba, Void, Integer> {
ProgressDialog dialog;
@Override
protected void onPreExecute() {
if (dialog != null)
dialog = null;
dialog = new ProgressDialog(context);
dialog.setMessage("Przesyłanie danych");
dialog.setCancelable(false);
dialog.show();
}
@Override
protected Integer doInBackground(Osoba... osoba) {
String url = Dane.URL + "/osoba/" + osoba[0].getId();
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(new MediaType("application", "json"));
HttpEntity<Osoba> requestEntity = new HttpEntity<Osoba>(osoba[0], requestHeaders);
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
ResponseEntity<String> responseEntity;
try {
responseEntity = restTemplate.exchange(url, HttpMethod.PUT, requestEntity, String.class);
} catch (HttpClientErrorException e) {
return e.getStatusCode().value();
}
return responseEntity.getStatusCode().value();
}
@Override
protected void onPostExecute(Integer s) {
dialog.dismiss();
if (s != 204) {
Snackbar.make(coordinatorLayout, "Wystąpił błąd po stronie serwera", Snackbar.LENGTH_SHORT)
.setAction("Action", null).show();
} else {
zalogujUzytkownika(osobaTemp);
etNoweHaslo.setText("");
etStareHaslo.setText("");
Snackbar.make(coordinatorLayout, "Zmiany zostały zapisane", Snackbar.LENGTH_SHORT)
.setAction("Action", null).show();
}
}
}
private void zalogujUzytkownika(Osoba osoba) {
SharedPreferences.Editor preferences = getSharedPreferences("uzytkownik", MODE_PRIVATE).edit();
preferences.putBoolean("zalogowany", true);
preferences.putLong("id", osoba.getId());
preferences.putString("login", osoba.getLogin());
preferences.putString("haslo", osoba.getHaslo());
preferences.putString("email", osoba.getEmail());
preferences.putString("logo", Base64.encodeToString(osoba.getLogo(), Base64.DEFAULT));
preferences.putInt("pkt", osoba.getPkt());
preferences.putInt("liczbaRozegranychGier", osoba.getLiczbaRozegranychGier());
preferences.putInt("liczbaSkonczonychGier", osoba.getLiczbaSkonczonychGier());
preferences.putInt("liczbaWygranych", osoba.getLiczbaWygranych());
preferences.putInt("liczbaRemisow", osoba.getLiczbaRemisow());
preferences.putInt("liczbaPorazek", osoba.getLiczbaPorazek());
preferences.apply();
Dane.osobaZalogowana = osoba;
}
}
| [
"Marcin Poniewozik"
] | Marcin Poniewozik |
3225503509a72ea5e34c12144e6655e43a9d16ca | 0e8f59a803b49d7b1b9a7f6cea4f151ca8778ff5 | /SimpleIntegration/android/app/src/main/java/com/simpleintegration/MainApplication.java | 6427f708810e3ac69121a2dee038ad4164e9d7b3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | ramisalem/react-native-ngenius | f3fbea3a16844062c5112925e121986fb7f3f84d | f293e50dd92da22ef8d0f0e150b26355228a84e3 | refs/heads/master | 2023-06-04T23:13:33.326305 | 2021-06-21T09:50:32 | 2021-06-21T09:50:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,617 | java | package com.simpleintegration;
import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost =
new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
return packages;
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
}
/**
* Loads Flipper in React Native templates. Call this in the onCreate method with something like
* initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
*
* @param context
* @param reactInstanceManager
*/
private static void initializeFlipper(
Context context, ReactInstanceManager reactInstanceManager) {
if (BuildConfig.DEBUG) {
try {
/*
We use reflection here to pick up the class that initializes Flipper,
since Flipper library is not available in release mode
*/
Class<?> aClass = Class.forName("com.simpleintegration.ReactNativeFlipper");
aClass
.getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
.invoke(null, context, reactInstanceManager);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
| [
"johnnypeter2002@gmail.com"
] | johnnypeter2002@gmail.com |
98655c17c82a144c7179ab402f578f39e51ad07d | 76f8e954df446f83afda6d84d3a2dd0080ecd850 | /lovers-api/src/com/lovers/common/utils/DateUtils.java | 241738a1f63edb2ceba18897a19a6dd7ff7700a6 | [] | no_license | wzflxt2017/lovers-enhance | 033165bc787732403a09a868a51c18287a59f9e0 | 0c4385d1cebc1eceb12b4e0723d3eb4c6afd0c00 | refs/heads/master | 2020-12-06T00:47:53.467559 | 2020-01-20T07:12:48 | 2020-01-20T07:12:48 | 232,288,272 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,827 | java | package com.lovers.common.utils;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* Created by wangzefeng on 2019/11/29 0029.
*/
public class DateUtils {
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);// 输出北京时间
public static String webUrl2 = "http://www.taobao.com";//淘宝
public static String webUrl3 = "http://www.baidu.com";//百度
public static String webUrl4 = "http://www.ntsc.ac.cn";//中国科学院国家授时中心
public static String webUrl5 = "http://www.360.cn";//360
public static String webUrl6 = "http://www.beijing-time.org";
/**
* 获取指定网站的日期时间
* @return
* @auther wangzefeng
* @date 2019年11月29日
*/
public static Date getWebDate(){
Date websiteDatetime = getWebsiteDatetime(webUrl2);
if(websiteDatetime==null){
websiteDatetime=getWebsiteDatetime(webUrl3);
}
if(websiteDatetime==null){
websiteDatetime=getWebsiteDatetime(webUrl4);
}
if(websiteDatetime==null){
websiteDatetime=getWebsiteDatetime(webUrl5);
}
if(websiteDatetime==null){
websiteDatetime=getWebsiteDatetime(webUrl6);
}
return websiteDatetime;
}
/**
* 获取指定网站的日期时间
* @return
* @auther wangzefeng
* @date 2019年11月29日
*/
public static String getWebDateToString(){
Date websiteDatetime = getWebsiteDatetime(webUrl2);
if(websiteDatetime==null){
websiteDatetime=getWebsiteDatetime(webUrl3);
}
if(websiteDatetime==null){
websiteDatetime=getWebsiteDatetime(webUrl4);
}
if(websiteDatetime==null){
websiteDatetime=getWebsiteDatetime(webUrl5);
}
if(websiteDatetime==null){
websiteDatetime=getWebsiteDatetime(webUrl6);
}
return sdf.format(websiteDatetime);
}
/**
* 获取指定网站的日期时间
* @param webUrl
*/
public static Date getWebsiteDatetime(String webUrl){
try {
URL url = new URL(webUrl);// 取得资源对象
URLConnection uc = url.openConnection();// 生成连接对象
uc.connect();// 发出连接
long ld = uc.getDate();// 读取网站日期时间
Date date = new Date(ld);// 转换为标准时间对象
return date;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
| [
"wzflxt2017@163.com"
] | wzflxt2017@163.com |
02c3bb30bee3234e379c091575197ad2cca8d023 | 598b769228c792c4da7ddbf97ebb2b3f8128f993 | /modules/visualizer/src/main/java/ru/cos/sim/visualizer/trace/item/base/Entity.java | 697a4f3e0973c40dabf5a877892cf1469acb9699 | [] | no_license | XealRedan/cos-sim | dba2db0a0f953a43f6c2883218243f65bf82a02c | 86783393d3846c4a3c63be9c8847ac6f0a692243 | refs/heads/master | 2020-03-31T09:19:03.576275 | 2015-04-22T13:44:34 | 2015-04-22T13:44:34 | 34,106,788 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 191 | java | package ru.cos.sim.visualizer.trace.item.base;
public class Entity {
protected int uid;
public Entity(int uid) {
super();
this.uid = uid;
}
public int id()
{
return uid;
}
}
| [
"alexandre.lombard@utbm.fr"
] | alexandre.lombard@utbm.fr |
2f8b06029ca69058d985ef5c75bbc9b7c93601fa | c43369d8bbf59eeb7c062ebdc7dc26e5c7a0d4c3 | /utakephoto/src/main/java/com/sl/utakephoto/utils/TUriUtils.java | 3cefce7af9f6d7c56488e2a1aa6e3f2e0b0beacd | [
"Apache-2.0"
] | permissive | msdgwzhy6/uTakePhoto | b74159523fb9fc36a5a52faf70a8b8230fbb3bcf | ba46442939bb07b271801197185fb635f056d0b3 | refs/heads/master | 2020-09-03T14:45:39.816859 | 2019-11-04T11:21:59 | 2019-11-04T11:21:59 | 219,488,054 | 1 | 0 | null | 2019-11-04T11:42:04 | 2019-11-04T11:42:04 | null | UTF-8 | Java | false | false | 7,433 | java | package com.sl.utakephoto.utils;
import android.content.ContentResolver;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;
import com.sl.utakephoto.exception.TakeException;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* author : Sl
* createDate : 2019-10-1711:14
* desc :
*/
public class TUriUtils {
/**
* uri检查 将scheme为file的转换为FileProvider提供的uri,判断输入的SCHEME_FILE格式的在androidQ上是否能够使用
*
* @param context
* @param uri
* @param suffix 默认.jpg
* @return
*/
public static Uri checkTakePhotoUri(Context context, Uri uri, String suffix) throws TakeException {
if (uri == null) return getTempSchemeContentUri(context, suffix);
if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (Environment.isExternalStorageLegacy()) {
Log.w(TConstant.TAG, "当前是Legacy View视图,兼容File方式访问");
File file = new File(uri.getPath());
if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
return getUriFromFile(context, file);
} else {
if (checkAppSpecific(uri, context)) {
File file = new File(uri.getPath());
if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
return getUriFromFile(context, file);
} else {
Log.w(TConstant.TAG, "当前存储空间视图模式是Filtered View,不能直接访问App-specific外的文件");
throw new TakeException(TConstant.TYPE_ANDROID_Q_PERMISSION, "当前是Filtered View,不能直接访问App-specific外的文件,Environment.getExternalStorageDirectory()不能使用,请使用MediaStore或者使用getExternalFilesDirs、" +
"getExternalCacheDirs等,可查看" + " https://developer.android.google.cn/preview/privacy/scoped-storage");
}
}
} else {
File file = new File(uri.getPath());
if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return getUriFromFile(context, file);
} else {
return Uri.fromFile(file);
}
}
}
return uri;
}
/**
* uri检查 判断裁剪输出的uri 在androidQ上是否正确
*
* @param context
* @param uri
* @param suffix 默认.jpg
* @return
*/
public static Uri checkCropUri(Context context, Uri uri, String suffix) throws TakeException {
if (uri == null) return getTempSchemeFileUri(context, suffix);
if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (Environment.isExternalStorageLegacy()) {
Log.w(TConstant.TAG, "当前是Legacy View视图,兼容File方式访问");
File file = new File(uri.getPath());
if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
return uri;
} else {
if (checkAppSpecific(uri, context)) {
File file = new File(uri.getPath());
if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
return uri;
} else {
Log.w(TConstant.TAG, "当前存储空间视图模式是Filtered View,不能直接访问App-specific外的文件");
throw new TakeException(TConstant.TYPE_ANDROID_Q_PERMISSION, "当前是Filtered View,不能直接访问App-specific外的文件,Environment.getExternalStorageDirectory()不能使用,请使用MediaStore或者使用getExternalFilesDirs、" +
"getExternalCacheDirs等,可查看" + " https://developer.android.google.cn/preview/privacy/scoped-storage");
}
}
} else {
File file = new File(uri.getPath());
if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
return Uri.fromFile(file);
}
}
return uri;
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private static boolean checkAppSpecific(Uri uri, Context context) {
if (uri == null || uri.getPath() == null) return false;
String path = uri.getPath();
if (context.getExternalMediaDirs().length != 0 && path.startsWith(context.getExternalMediaDirs()[0].getAbsolutePath())) {
return true;
} else if (path.startsWith(context.getObbDir().getAbsolutePath())) {
return true;
} else if (path.startsWith(context.getExternalCacheDir().getAbsolutePath())) {
return true;
} else if (path.startsWith(context.getExternalFilesDir("").getAbsolutePath())) {
return true;
}
return false;
}
/**
* 创建一个用于拍照图片输出路径的Uri (FileProvider)
*
* @param context
* @return
*/
public static Uri getUriFromFile(Context context, File file) {
return FileProvider.getUriForFile(context, TConstant.getFileProviderName(context), file);
}
/**
* 创建Scheme为Content临时的uri
*
* @param context
* @param suffix
* @return
*/
public static Uri getTempSchemeContentUri(@NonNull Context context, String suffix) {
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(new Date());
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "/" + timeStamp + (TextUtils.isEmpty(suffix) ? ".jpg" : suffix));
if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return getUriFromFile(context, file);
} else {
return Uri.fromFile(file);
}
}
/**
* 创建Scheme为file临时的uri
*
* @param context
* @return
*/
public static Uri getTempSchemeFileUri(@NonNull Context context) {
return getTempSchemeFileUri(context, null);
}
/**
* 创建Scheme为file临时的uri
*
* @param context
* @return
*/
public static Uri getTempSchemeFileUri(@NonNull Context context, String suffix) {
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(new Date());
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "/" + timeStamp + (TextUtils.isEmpty(suffix) ? ".jpg" : suffix));
if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
return Uri.fromFile(file);
}
}
| [
"songlong@dingtalk.com"
] | songlong@dingtalk.com |
cf8aec23e4ee83a32af3b28ecec164acf70ba07e | 3b7e1dbe57614fc1e9a4052c79e36ae76c9e4a25 | /app/src/main/java/com/example/katarzkubat/musicapp/MazurkasActivity.java | 2ff52b83db74e1fdb33cf513e526d67dcd6d847f | [] | no_license | Katarzkubat/MusicApp | 4d34157fbb23eb255e7ddb187ea2e809543419ff | 7a4c78c57ec52aa7eb643f285edfa0faae1b6e43 | refs/heads/master | 2021-07-02T14:43:29.661756 | 2017-09-23T14:10:21 | 2017-09-23T14:10:21 | 104,571,872 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 853 | java | package com.example.katarzkubat.musicapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
/**
* Created by katarz.kubat on 07.05.2017.
*/
public class MazurkasActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mazurkas);
View record1 = (Button) findViewById(R.id.record1);
record1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick (View view) {
Intent record1Intent = new Intent(MazurkasActivity.this, PlaynowActivity.class);
startActivity(record1Intent);
}
});
}
} | [
"katarz.kubat@gmail.com"
] | katarz.kubat@gmail.com |
bf33654a142c8002c54cd2e05244456175c21d43 | e838e40fbdb0be1da3db23d50def9c4ce765ce7e | /src/api/java/thaumcraft/api/research/theorycraft/ITheorycraftAid.java | fe98fab0d6122f55cc70b986ab0935f65a64b022 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | Railcraft/Railcraft | 8fd64b7e165d327dc9d8356acd05a6638366735c | 34416755a312fd0ba6813d9a80169fe56dab369f | refs/heads/mc-1.12.2 | 2023-07-03T18:47:09.498982 | 2022-06-30T01:45:22 | 2022-06-30T01:45:22 | 7,177,096 | 343 | 195 | NOASSERTION | 2022-10-27T15:35:22 | 2012-12-15T07:42:00 | Java | UTF-8 | Java | false | false | 831 | java | package thaumcraft.api.research.theorycraft;
/**
* See AidBookshelf for an example
*
* @author Azanor
*
*/
public interface ITheorycraftAid {
/**
* The block, dropped item or entity class that will trigger the Aid cards to be added.
* A 9x9x3 area around table is checked.
* This method should return an entity class, block or itemstack - itemstack is based on items block will drop when broken.
* @return
*/
Object getAidObject();
/**
* The cards that are added to the draw rotation. Each time a card
* is draw there is a chance it is one of the Aid cards.
* Once drawn the card is removed from the Aid list.
* Each card is added once, but you can add the card
* more than once by simply adding it to the array multiple times.
* @return
*/
Class<TheorycraftCard>[] getCards();
}
| [
"liach@users.noreply.github.com"
] | liach@users.noreply.github.com |
6b1911f97d0173e76cd2f5425ed7be43c34d1cc7 | 91c994ec1a61c9e9acca9dc37d0305215adea074 | /target/generated-sources/java/com/capitalone/dashboard/model/QBuildStage.java | 4efef2fce8a090fc956ceff221ced34976b71bcb | [
"Apache-2.0"
] | permissive | ritessh/hygieia-core | de187faa5e98232e05876e24b927a1889227d8eb | 4a3ee699518b86be820c5b779b07e8a5b6a4262a | refs/heads/main | 2023-04-14T22:13:01.161406 | 2021-05-05T04:58:23 | 2021-05-05T04:58:23 | 364,463,324 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,639 | java | package com.capitalone.dashboard.model;
import static com.querydsl.core.types.PathMetadataFactory.*;
import com.querydsl.core.types.dsl.*;
import com.querydsl.core.types.PathMetadata;
import javax.annotation.Generated;
import com.querydsl.core.types.Path;
import com.querydsl.core.types.dsl.PathInits;
/**
* QBuildStage is a Querydsl query type for BuildStage
*/
@Generated("com.querydsl.codegen.EmbeddableSerializer")
public class QBuildStage extends BeanPath<BuildStage> {
private static final long serialVersionUID = 744214162L;
private static final PathInits INITS = PathInits.DIRECT2;
public static final QBuildStage buildStage = new QBuildStage("buildStage");
public final QBaseModel _super;
public final MapPath<String, Object, SimplePath<Object>> _links = this.<String, Object, SimplePath<Object>>createMap("_links", String.class, Object.class, SimplePath.class);
//inherited
public final StringPath clientReference;
public final StringPath durationMillis = createString("durationMillis");
public final StringPath endTime = createString("endTime");
public final SimplePath<Error> error = createSimple("error", Error.class);
public final StringPath exec_node_logUrl = createString("exec_node_logUrl");
// inherited
public final org.bson.types.QObjectId id;
public final StringPath log = createString("log");
public final StringPath name = createString("name");
public final StringPath parentId = createString("parentId");
public final StringPath stageId = createString("stageId");
public final StringPath startTimeMillis = createString("startTimeMillis");
public final StringPath status = createString("status");
//inherited
public final DateTimePath<java.util.Date> upsertTime;
public QBuildStage(String variable) {
this(BuildStage.class, forVariable(variable), INITS);
}
public QBuildStage(Path<? extends BuildStage> path) {
this(path.getType(), path.getMetadata(), PathInits.getFor(path.getMetadata(), INITS));
}
public QBuildStage(PathMetadata metadata) {
this(metadata, PathInits.getFor(metadata, INITS));
}
public QBuildStage(PathMetadata metadata, PathInits inits) {
this(BuildStage.class, metadata, inits);
}
public QBuildStage(Class<? extends BuildStage> type, PathMetadata metadata, PathInits inits) {
super(type, metadata, inits);
this._super = new QBaseModel(type, metadata, inits);
this.clientReference = _super.clientReference;
this.id = _super.id;
this.upsertTime = _super.upsertTime;
}
}
| [
"test@test.com"
] | test@test.com |
8e587922531501047862b111b29513a3b84f248b | e401d45d26579c233688086cd26aa7453b984161 | /basic_io/src/ru/mail/track/AuthorizationService.java | 8e5533f7072bdd0e06c8ceffa99897af5406bc8c | [] | no_license | TheAviat0r/Sky-Track | 09c3a2d0617e06bfe0c80ac2a26f38671d26384a | 0fe61d8d31b817eb197f817dc492af28c8481e66 | refs/heads/master | 2021-01-10T15:16:03.474240 | 2017-05-21T15:16:37 | 2017-05-21T15:16:37 | 43,392,857 | 0 | 0 | null | 2015-11-17T14:53:47 | 2015-09-29T20:33:25 | Java | UTF-8 | Java | false | false | 2,905 | java | package ru.mail.track;
import java.util.*;
import java.io.Console;
public class AuthorizationService {
final static String USER_LOGIN = "login";
final static String USER_CREATE = "create";
final static String USER_EXIT = "exit";
final static int USER_LOGIN_HASH = USER_LOGIN.hashCode();
final static int USER_CREATE_HASH = USER_CREATE.hashCode();
final static int USER_EXIT_HASH = USER_EXIT.hashCode();
private UserStore userStore;
public AuthorizationService(UserStore userStore) {
this.userStore = userStore;
}
void startAuthorization() {
String userChoise = "";
Scanner input = new Scanner(System.in);
System.out.println("Type commands: login, create, exit");
while (true) {
if (input.hasNextLine()) {
userChoise = input.nextLine();
userChoise.toLowerCase();
if (userChoise.hashCode() == USER_LOGIN_HASH) {
login();
continue;
}
if (userChoise.hashCode() == USER_CREATE_HASH) {
creatUser();
continue;
}
if (userChoise.hashCode() == USER_EXIT_HASH) {
System.out.println("See you soon!");
break;
}
}
}
}
User login() {
// 1. Ask for name
// 2. Ask for password
// 3. Ask UserStore for user: userStore.getUser(name, pass)
System.out.println("What is your name?");
Scanner input = new Scanner(System.in);
String userName = input.nextLine();
System.out.println("Enter your password");
String userPassword = input.nextLine();
User user = userStore.getUser(userName, userPassword);
if (user == null) {
System.out.println("User doesn't exist: " + userName + " Register now!");
return creatUser();
}
if (user.getName().length() == 0) {
System.out.println("Wrong password! ");
return null;
}
System.out.println("You are welcome!");
return user;
}
User creatUser() {
// 1. Ask for name
// 2. Ask for pass
// 3. Add user to UserStore: userStore.addUser(user)
Scanner input = new Scanner(System.in);
System.out.println("What is your name?");
String newUserName = input.nextLine();
System.out.println("Type your password");
String newUserPass = input.nextLine();
User user = new User(newUserName, newUserPass);
if (userStore.addUser(user)) {
System.out.println("Welcome to our system!");
}
else {
System.out.println("Unable to add - " + user.toString());
return null;
}
return user;
}
}
| [
"theairvideo@gmail.com"
] | theairvideo@gmail.com |
4f488bd3a23c3081cebaf0e178f347461d9b234a | f4f657ac3f3033c72bed9e5bb583e0f5937be64a | /src/main/java/com/example/websocketdemo/controller/WebSocketEventListener.java | f7ee9903c254cb5ca41f686f806a26da085ed0ec | [] | no_license | yanaatere/Spring-Boot-Web-Socket | 25ea3c43e19c7054012cfa0f80f564234901dbe7 | 2997197b441f753499add8635f7eb6ad1531dd2c | refs/heads/master | 2020-03-17T03:29:29.449800 | 2018-05-13T14:50:04 | 2018-05-13T14:50:04 | 133,237,673 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,499 | java | package com.example.websocketdemo.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import com.example.websocketdemo.model.ChatMessage;
import com.example.websocketdemo.model.ChatMessage.MessageType;
public class WebSocketEventListener {
private static final Logger logger = LoggerFactory.getLogger(WebSocketEventListener.class);
@Autowired
private SimpMessageSendingOperations messagingTemplate;
@EventListener
public void handlerWebSocketConnectListener(SessionConnectedEvent event) {
logger.info("Received a new Web socket Connection");
}
@EventListener
public void handleWebSocketDisconnectListener(SessionConnectedEvent event) {
StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
String username = (String)headerAccessor.getSessionAttributes().get("username");
if (username != null) {
logger.info("User Disconnected " + username);
ChatMessage chatMessage = new ChatMessage();
chatMessage.setType(MessageType.LEAVE);
chatMessage.setSender(username);
messagingTemplate.convertAndSend("/topic/public",chatMessage);
}
}
}
| [
"yanaandika@gmail.com"
] | yanaandika@gmail.com |
fa3b2c66bd2887808ab1bd95ede94c24bca95846 | 85c22e3200bf76ae23031403be0dc801272a394a | /src/main/java/dao/QueryItem.java | 4779ff99b5143fc755d12b5d34fb5f51be7bc69d | [] | no_license | mimaserver/spitterMaven | 07c911f6f47147e6b0a682076161abef386d2f5e | fad8e54bb640cb94cdec36746205d56f62f13aee | refs/heads/master | 2020-04-06T04:09:12.555624 | 2015-05-05T07:41:59 | 2015-05-05T07:41:59 | 35,085,679 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 948 | java | package dao;
import javax.persistence.Entity;
@Entity
public class QueryItem {
public String id, title, text;
public QueryItem() {
super();
// TODO Auto-generated constructor stub
}
public QueryItem(String id, String title, String text) {
super();
this.id = id;
this.title = title;
this.text = text;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String toString()
{
StringBuilder s = new StringBuilder();
s.append("id:\t").append(this.id).append("\n").
append("title:\t").append(title).append("\n").
append("text:\t").append(this.text).append("\n");
return s.toString();
}
}
| [
"mimaserver@mima.com"
] | mimaserver@mima.com |
6b38cdb109f3cbeffe623430b4ad64bf2f362350 | 490c97f561f20600814f321efd2a47cf9a1a66e2 | /andorid_app/kailos-nav/src/kr/ac/kaist/isilab/kailos/route/RouteManager.java | 3e0900ebe8f301b8639804e25443d468b65077c2 | [] | no_license | ko9ma7/kailos-nav-pdr | 986c5d6e8967597c50f0c3c6cdfdc2377f65acd6 | 15055f91cef0583b87c7f1bc34e85fb459c9eba1 | refs/heads/master | 2021-05-28T09:15:41.565845 | 2013-12-24T06:27:51 | 2013-12-24T06:27:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 18,199 | java | package kr.ac.kaist.isilab.kailos.route;
import java.util.ArrayList;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import com.google.android.gms.maps.model.LatLng;
import kr.ac.kaist.isilab.kailos.indoormap.IndoorMap;
import kr.ac.kaist.isilab.kailos.indoormap.IndoorMapRequestThread;
import kr.ac.kaist.isilab.kailos.location.EstimatedLocation;
import kr.ac.kaist.isilab.kailos.navi.GoogleMapFragment;
import kr.ac.kaist.isilab.kailos.navi.KAILOSService;
import kr.ac.kaist.isilab.kailos.navi.POISearchActivity;
import kr.ac.kaist.isilab.kailos.poi.POI;
import kr.ac.kaist.isilab.kailos.util.Constants;
import android.location.Location;
import android.os.Handler;
import android.os.Message;
public class RouteManager {
// Routing data, all of them, oh god, that is a lot of statics, damn!
private static ArrayList<RouteVertex> m_lstEntirePath;
private static ArrayList<FloorPath> m_lstFloorPath;
private static POI m_poiDeparture;
private static POI m_poiDestination;
public static Handler m_handlerResponse = new Handler() {
public void handleMessage(Message msg) {
switch( msg.what ) {
case Constants.MESSAGE_ROUTE_THREAD_RESPONSE:
String strRouteJSON = (String)msg.obj;
if( strRouteJSON == null || strRouteJSON.compareTo("") == 0 ) {
// Generate message for dismiss routing calculation dialog...
Message newMsg = new Message();
newMsg.what = Constants.MESSAGE_DISMISS_ROUTING_CALCULATION_PROGRESS_DIALOG;
POISearchActivity.m_responseHanlder.sendMessage(newMsg);
return;
}
// Create a new list for storing the path...
m_lstEntirePath = new ArrayList<RouteVertex>();
// Parse the vertices and add them into the list....
try {
JSONObject json = (JSONObject) JSONValue.parse(strRouteJSON);
Iterator<?> iter = json.keySet().iterator();
while( iter.hasNext() ) {
String key = (String) iter.next();
Object value = json.get(key);
if( key.compareToIgnoreCase("path") == 0 ) {
JSONArray pathArray = (JSONArray)value;
for(int i=0; i<pathArray.size(); i++) {
JSONArray path = (JSONArray)pathArray.get(i);
if( path.size() != 3 )
continue;
RouteVertex newVertex = new RouteVertex(Double.parseDouble(path.get(1).toString()),
Double.parseDouble(path.get(0).toString()),
path.get(2).toString());
if( newVertex.getFloorID().compareTo("null") == 0 )
newVertex.setFloorID("");
m_lstEntirePath.add(newVertex);
}
}
}
} catch( Exception e ) {
// No handling!.. yet..
}
// No result..
if( m_lstEntirePath.size() == 0 ) {
// Generate message for dismiss routing calculation dialog...
Message newMsg = new Message();
newMsg.what = Constants.MESSAGE_DISMISS_ROUTING_CALCULATION_PROGRESS_DIALOG;
POISearchActivity.m_responseHanlder.sendMessage(newMsg);
return;
}
// Sift out the floor connecting vertices...
for(int i=1; i<m_lstEntirePath.size()-1; i++) {
RouteVertex predecessor = m_lstEntirePath.get(i-1);
RouteVertex current = m_lstEntirePath.get(i);
RouteVertex successor = m_lstEntirePath.get(i+1);
if( predecessor.getFloorID().compareTo(current.getFloorID()) != 0 &&
successor.getFloorID().compareTo(current.getFloorID()) != 0 ) {
m_lstEntirePath.remove(i);
i--;
}
}
m_lstFloorPath = new ArrayList<FloorPath>();
// Group those paths by floorID!
RouteVertex startVertex = m_lstEntirePath.get(0);
FloorPath floorPath = new FloorPath();
floorPath.setFloorID(startVertex.getFloorID());
floorPath.getPath().add(startVertex);
for(int i=1; i<m_lstEntirePath.size(); i++) {
RouteVertex currentVertex = m_lstEntirePath.get(i);
floorPath.getPath().add(currentVertex);
if( startVertex.getFloorID().compareTo(currentVertex.getFloorID()) != 0 ) {
m_lstFloorPath.add(floorPath);
// new ploy line for the different floor..
floorPath = new FloorPath();
floorPath.setFloorID(currentVertex.getFloorID());
floorPath.getPath().add(currentVertex);
startVertex = currentVertex;
}
if( i == m_lstEntirePath.size()-1 )
m_lstFloorPath.add(floorPath);
}
// Request indoor maps for both the departure floor and the destination floor!
String strDepartureFloorID = getDepartureFloorID();
String strDestinationFloorID = getDestinationFloorID();
if( strDepartureFloorID != null && strDepartureFloorID.compareTo("") != 0 && strDepartureFloorID.compareTo("null") != 0 ) {
IndoorMapRequestThread departureFloorMapRequestThread = new IndoorMapRequestThread();
departureFloorMapRequestThread.setRequestDataWithFloorID(strDepartureFloorID);
departureFloorMapRequestThread.setResponseHandler(this);
departureFloorMapRequestThread.start();
}
if( strDestinationFloorID != null && strDestinationFloorID.compareTo("") != 0 && strDestinationFloorID.compareTo("null") != 0 ) {
IndoorMapRequestThread destinationFloorMapRequestThread = new IndoorMapRequestThread();
destinationFloorMapRequestThread.setRequestDataWithFloorID(strDestinationFloorID);
destinationFloorMapRequestThread.setResponseHandler(this);
destinationFloorMapRequestThread.start();
}
// Change the mode of the google map...
GoogleMapFragment.setCurrentMode(Constants.SHOW_ROUTE_MODE);
// Hide all location markers...
GoogleMapFragment.removeGoogleWPSMarker();
GoogleMapFragment.removeKAILOSMarker();
// Maker for the departure and the destination...
GoogleMapFragment.showDepartureMarker(new LatLng(m_poiDeparture.getLatitude(), m_poiDeparture.getLongitude()));
GoogleMapFragment.showDestinationMarker(new LatLng(m_poiDestination.getLatitude(), m_poiDestination.getLongitude()));
// Generate message for drawing route...
Message newMsg1 = new Message();
newMsg1.what = Constants.MESSAGE_DRAW_ENTIRE_ROUTE;
KAILOSService.m_handleRoute.sendMessage(newMsg1);
// Generate message for dismiss routing calculation dialog...
Message newMsg2 = new Message();
newMsg2.what = Constants.MESSAGE_DISMISS_ROUTING_CALCULATION_PROGRESS_DIALOG;
POISearchActivity.m_responseHanlder.sendMessage(newMsg2);
break;
case Constants.MESSAGE_INDOOR_MAP_THREAD_RESPONSE:
IndoorMap indoormap = (IndoorMap)msg.obj;
GoogleMapFragment.addIndoorMapOverlayForNavigation(indoormap);
break;
default:
break;
}
}
};
public RouteManager() {
}
public static ArrayList<RouteVertex> getRoutePath() {
return m_lstEntirePath;
}
public static void setRoutePath(ArrayList<RouteVertex> newPath) {
m_lstEntirePath = newPath;
}
public static void setDeparturePOI(POI poi) {
m_poiDeparture = poi;
}
public static void setDestinationPOI(POI poi) {
m_poiDestination = poi;
}
// Also called, map matching..
public static EstimatedLocation FindNearestLocationOnRoute(EstimatedLocation prevLocation) {
if( m_lstEntirePath == null || m_lstEntirePath.size() == 0 || m_lstFloorPath == null )
return prevLocation;
EstimatedLocation projectedLocation = EstimatedLocation.createFromString(prevLocation.toString());
ModifiedCoordinate loc = new ModifiedCoordinate();
ArrayList<RouteVertex> lstCurrentFloorVertices = null;
loc.y = (int)(prevLocation.getLatitude() * 1000000);
loc.x = (int)(prevLocation.getLongitude() * 1000000);
for(int i=0; i<m_lstFloorPath.size(); i++) {
FloorPath floorPath = m_lstFloorPath.get(i);
if( floorPath.getFloorID().compareTo(prevLocation.getFloorID()) == 0 ) {
lstCurrentFloorVertices = floorPath.getPath();
break;
}
}
// lstCurrentFloorVertices = RouteManager.getRoutePath();
// Somehow cannot find routes...
if( lstCurrentFloorVertices == null )
return prevLocation;
// 1) Find the nearest link form prevLoctaion...
ModifiedCoordinate nearestStart = null;
ModifiedCoordinate nearestEnd = null;
double dbShortestDist = Double.MAX_VALUE;
for(int i=1; i<lstCurrentFloorVertices.size(); i++) {
ModifiedCoordinate startCoordinate = new ModifiedCoordinate();
ModifiedCoordinate endCoordinate = new ModifiedCoordinate();
double dbEdgeLength = 0.0f;
double distanceFormLocation = 0.0f;
// Prepare an edge connecting (i-1)-th vertex to i-th vertex...
startCoordinate.x = (int)(lstCurrentFloorVertices.get(i-1).getLocation().longitude * 1000000);
startCoordinate.y = (int)(lstCurrentFloorVertices.get(i-1).getLocation().latitude * 1000000);
endCoordinate.x = (int)(lstCurrentFloorVertices.get(i).getLocation().longitude * 1000000);
endCoordinate.y = (int)(lstCurrentFloorVertices.get(i).getLocation().latitude * 1000000);
dbEdgeLength = Math.sqrt(Math.pow(startCoordinate.x-endCoordinate.x, 2.0f) + Math.pow(startCoordinate.y-endCoordinate.y, 2.0f));
if( dbEdgeLength == 0 )
distanceFormLocation = Math.sqrt(Math.pow(startCoordinate.y-loc.y, 2.0f) + Math.pow(startCoordinate.x-loc.x, 2.0f));
else {
distanceFormLocation = (loc.x-startCoordinate.x) * (endCoordinate.x-startCoordinate.x) + (loc.y-startCoordinate.y) * (endCoordinate.y-startCoordinate.y);
distanceFormLocation /= dbEdgeLength;
if( distanceFormLocation <= 0 )
distanceFormLocation = Math.sqrt(Math.pow(startCoordinate.y-loc.y, 2.0f) + Math.pow(startCoordinate.x-loc.x, 2.0f));
else if( distanceFormLocation >= dbEdgeLength )
distanceFormLocation = Math.sqrt(Math.pow(endCoordinate.y-loc.y, 2.0f) + Math.pow(endCoordinate.x-loc.x, 2.0f));
else
distanceFormLocation = Math.abs( (-1)*(loc.x-startCoordinate.x)*(endCoordinate.y-startCoordinate.y)+(loc.y-startCoordinate.y)*(endCoordinate.x-startCoordinate.x)) / dbEdgeLength;
}
// New shortest?
if( distanceFormLocation < dbShortestDist ) {
dbShortestDist = distanceFormLocation;
nearestStart = startCoordinate;
nearestEnd = endCoordinate;
}
}
// 2) Projection onto the line going through both nearestStart and nearestEnd...
if( nearestStart != null && nearestEnd != null ) {
// GoogleMapFragment.setTempMarker1(new LatLng(nearestStart.y/1000000.0f, nearestStart.x/1000000.0f));
// GoogleMapFragment.setTempMarker2(new LatLng(nearestEnd.y/1000000.0f, nearestEnd.x/1000000.0f));
// I do know this is not pretty but it works..
double dbSlope = 0.0f;
if( nearestEnd.x == nearestStart.x )
dbSlope = 1.0f;
else
dbSlope = ((double)(nearestEnd.y-nearestStart.y)) / ((double)(nearestEnd.x-nearestStart.x));
// Little filtering here...
if( dbSlope == Double.POSITIVE_INFINITY )
dbSlope = 1/0.0000001f;
else if( dbSlope == Double.NEGATIVE_INFINITY )
dbSlope = -1/0.0000001f;
else if( dbSlope == 0.0f )
dbSlope = 0.0000001f;
// Calculate a line equation which cross the edge (nearestStart, neartestEnd)..
// Equation: (dbSlope)x - C = y
double C = dbSlope*nearestStart.x - nearestStart.y;
double a = loc.x;
double b = loc.y;
double c = (a + b*dbSlope + C*dbSlope) / (Math.pow(dbSlope, 2) + 1.0f);
double d = (a*dbSlope + b*Math.pow(dbSlope, 2) + C*Math.pow(dbSlope, 2)) / (Math.pow(dbSlope, 2)+1.0f) - C;
// 3) Range check... depending on slope s...
double dbMin = 0.0f;
double dbMax = 0.0f;
if( dbSlope == 1.0f ) {
c = nearestStart.x;
dbMin = nearestStart.y;
dbMax = nearestEnd.y;
// GoogleMapFragment.setTempMarker1(new LatLng(dbMinD / 1000000.0f, nearestStart.x / 1000000.0f));
// GoogleMapFragment.setTempMarker2(new LatLng(dbMaxD / 1000000.0f, nearestEnd.x / 1000000.0f));
// Normalize!
if( dbMin > dbMax ) {
double temp = dbMin;
dbMin = dbMax;
dbMax = temp;
}
// Line segment range check...
if( dbMin > d || dbMax < d ) {
double dbDistanceFromStart = ModifiedCoordinate.distance(nearestStart, loc);
double dbDistanceFromEnd = ModifiedCoordinate.distance(nearestEnd, loc);
if( dbDistanceFromStart > dbDistanceFromEnd ) {
c = nearestEnd.x;
d = nearestEnd.y;
} else {
c = nearestStart.x;
d = nearestStart.y;
}
}
} else if( dbSlope == 0.0f ) {
d = nearestStart.y;
dbMin = nearestStart.x;
dbMax = nearestEnd.x;
// Normalize..
if( dbMin > dbMax ) {
double temp = dbMin;
dbMin = dbMax;
dbMax = temp;
}
// GoogleMapFragment.setTempMarker1(new LatLng(nearestStart.y / 1000000.0f, dbMinC / 1000000.0f));
// GoogleMapFragment.setTempMarker2(new LatLng(nearestEnd.y / 1000000.0f, dbMaxC / 1000000.0f));
// Line segment range check...
if( dbMin > c || dbMax < c ) {
double dbDistanceFromStart = ModifiedCoordinate.distance(nearestStart, loc);
double dbDistanceFromEnd = ModifiedCoordinate.distance(nearestEnd, loc);
if( dbDistanceFromStart > dbDistanceFromEnd ) {
c = nearestEnd.x;
d = nearestEnd.y;
} else {
c = nearestStart.x;
d = nearestStart.y;
}
}
} else {
dbMin = nearestStart.x * dbSlope - C;
dbMax = nearestEnd.x * dbSlope - C;
// GoogleMapFragment.setTempMarker1(new LatLng(dbMinD / 1000000.0f, nearestStart.x / 1000000.0f));
// GoogleMapFragment.setTempMarker2(new LatLng(dbMaxD / 1000000.0f, nearestEnd.x / 1000000.0f));
if( dbMin > dbMax ) {
double temp = dbMin;
dbMin = dbMax;
dbMax = temp;
}
// Line segment range check...
if( dbMin > d || dbMax < d ) {
double dbDistanceFromStart = ModifiedCoordinate.distance(nearestStart, loc);
double dbDistanceFromEnd = ModifiedCoordinate.distance(nearestEnd, loc);
if( dbDistanceFromStart > dbDistanceFromEnd ) {
c = nearestEnd.x;
d = nearestEnd.y;
} else {
c = nearestStart.x;
d = nearestStart.y;
}
}
}
projectedLocation.setLatitude(d/1000000.0f);
projectedLocation.setLongitude(c/1000000.0f);
// GoogleMapFragment.setTempMarker(new LatLng(d/1000000.0f, c/1000000.0f));
}
return projectedLocation;
}
public static String getDepartureFloorID() {
if( m_lstFloorPath == null || m_lstFloorPath.size() == 0 )
return "";
FloorPath pathOnDepartureFloor = m_lstFloorPath.get(0);
if( pathOnDepartureFloor == null || pathOnDepartureFloor.getPath() == null || pathOnDepartureFloor.getPath().size() == 0 )
return "";
return pathOnDepartureFloor.getPath().get(0).getFloorID();
}
public static String getDestinationFloorID() {
if( m_lstFloorPath == null || m_lstFloorPath.size() == 0 )
return "";
FloorPath pathOnDestinationFloor = m_lstFloorPath.get(m_lstFloorPath.size()-1);
if( pathOnDestinationFloor == null || pathOnDestinationFloor.getPath() == null || pathOnDestinationFloor.getPath().size() == 0 )
return "";
return pathOnDestinationFloor.getPath().get(0).getFloorID();
}
public static ArrayList<RouteVertex> getDepartureFloorVertexList() {
if( m_lstFloorPath == null || m_lstFloorPath.size() == 0 )
return null;
FloorPath pathOnFloor = m_lstFloorPath.get(0);
if( pathOnFloor == null || pathOnFloor.getPath() == null || pathOnFloor.getPath().size() == 0 )
return null;
return pathOnFloor.getPath();
}
public static ArrayList<RouteVertex> getDestinationFloorVertexList() {
if( m_lstFloorPath == null || m_lstFloorPath.size() == 0 )
return null;
FloorPath pathOnFloor = m_lstFloorPath.get(m_lstFloorPath.size()-1);
if( pathOnFloor == null || pathOnFloor.getPath() == null || pathOnFloor.getPath().size() == 0 )
return null;
return pathOnFloor.getPath();
}
public static ArrayList<RouteVertex> getOutdoorVertexList() {
if( m_lstEntirePath == null || m_lstEntirePath.size() == 0 )
return null;
ArrayList<RouteVertex> lstRet = new ArrayList<RouteVertex>();
Iterator<RouteVertex> iter = m_lstEntirePath.iterator();
while( iter.hasNext() ) {
RouteVertex vertex = iter.next();
lstRet.add(vertex);
if( vertex.getFloorID().compareTo("") == 0 )
break;
}
return lstRet;
}
public static boolean AreDepartureAndDestinationOnTheSameBuilding() {
if( m_lstEntirePath == null )
return false;
boolean bRet = false;
for(int i=0; i<m_lstEntirePath.size(); i++) {
RouteVertex vertex = m_lstEntirePath.get(i);
if( vertex.getFloorID().compareTo("") == 0 ) {
bRet = true;
break;
}
}
return bRet;
}
public static ArrayList<RouteVertex> getRoutesOnFloor(String strFloorID) {
if( m_lstFloorPath == null || strFloorID == null )
return null;
for(int i=0; i<m_lstFloorPath.size(); i++) {
FloorPath floorPath = m_lstFloorPath.get(i);
if( floorPath.getFloorID().compareTo(strFloorID) == 0 )
return floorPath.getPath();
}
return null;
}
public static ArrayList<FloorPath> getPathGroupedByFloorID() {
return m_lstFloorPath;
}
public static double distanceToDestination(EstimatedLocation currentLocation) {
float fDistance[] = new float[1];
Location.distanceBetween(m_poiDestination.getLatitude(), m_poiDestination.getLongitude(), currentLocation.getLatitude(), currentLocation.getLongitude(), fDistance);
return fDistance[0];
}
private static class ModifiedCoordinate {
public int x;
public int y;
public static double distance(ModifiedCoordinate x, ModifiedCoordinate y) {
return Math.sqrt(Math.pow(x.x - y.x, 2.0f) + Math.pow(x.y - y.y, 2.0f));
}
}
}
| [
"snm114@kaist.ac.kr"
] | snm114@kaist.ac.kr |
a657f0733e553bd4760d88fd8e8111c8f9677ada | a5857cc3f63699f1bbc44581b6dc4dd71bb54552 | /src/br/com/alura/loja/pedido/GeraPedidoHandler.java | b54ed5c668228055b7199246199ffac10f842a74 | [
"MIT"
] | permissive | VanessaSwerts/alura-design-patterns-II | 7c2527bbc3e4ff67df9e895092a2273899a92b6e | 7b8d2e7f966f8a0e291b855c9a4729782cb59cfe | refs/heads/master | 2023-06-06T19:59:21.168100 | 2021-07-14T18:47:15 | 2021-07-14T18:47:15 | 384,454,746 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 703 | java | package br.com.alura.loja.pedido;
import java.time.LocalDateTime;
import java.util.List;
import br.com.alura.loja.orcamento.ItemOrcamento;
import br.com.alura.loja.orcamento.Orcamento;
import br.com.alura.loja.pedido.acao.AcaoAposGerarPedido;
public class GeraPedidoHandler {
private List<AcaoAposGerarPedido> acoes;
public GeraPedidoHandler(List<AcaoAposGerarPedido> acoes) {
this.acoes = acoes;
}
public void executa(GeraPedido dados) {
Orcamento orcamento = new Orcamento();
orcamento.adicionarItem(new ItemOrcamento(dados.getValorOrcamento()));
Pedido pedido = new Pedido(dados.getCliente(), LocalDateTime.now(), orcamento);
acoes.forEach(a -> a.executarAcao(pedido));
}
}
| [
"vanessaswerts@gec.inatel.br"
] | vanessaswerts@gec.inatel.br |
8a8fc5774951eba0df90f3e11d8c1458f108d592 | 86cf6f618df134056cbf91e29a6b0c725f9c4b7a | /gen/com/example/collegecalendar/R.java | b7b0df3c0e5ee6b4f1ac6f47f0fb0b8bd38b698e | [] | no_license | JHochscheidt/CollegeCalendar | 513c0e7032b8bd4c1603f3c64fc3e1b130cef31b | c6469657e014b4e582c2912ffacab976d3208b39 | refs/heads/master | 2021-05-29T21:20:52.463936 | 2015-06-25T02:29:29 | 2015-06-25T02:29:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,987 | java | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.example.collegecalendar;
public final class R {
public static final class attr {
}
public static final class dimen {
/** Default screen margins, per the Android Design guidelines.
Example customization of dimensions originally defined in res/values/dimens.xml
(such as screen margins) for screens with more than 820dp of available width. This
would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively).
*/
public static final int activity_horizontal_margin=0x7f040000;
public static final int activity_vertical_margin=0x7f040001;
}
public static final class drawable {
public static final int ic_launcher=0x7f020000;
}
public static final class id {
public static final int action_settings=0x7f080004;
public static final int button1=0x7f080000;
public static final int button2=0x7f080001;
public static final int button3=0x7f080002;
public static final int button4=0x7f080003;
}
public static final class layout {
public static final int main=0x7f030000;
}
public static final class menu {
public static final int main=0x7f070000;
}
public static final class string {
public static final int action_settings=0x7f050002;
public static final int app_name=0x7f050000;
public static final int cadastrar_avaliacao_trabalho=0x7f050003;
public static final int cadastrar_dev_livro=0x7f050004;
public static final int hello_world=0x7f050001;
public static final int vis_aval_trab=0x7f050006;
public static final int vis_livro=0x7f050005;
}
public static final class style {
/**
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
API 11 theme customizations can go here.
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
API 14 theme customizations can go here.
*/
public static final int AppBaseTheme=0x7f060000;
/** Application theme.
All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f060001;
}
}
| [
"jackson94h@gmail.com"
] | jackson94h@gmail.com |
72c4e34744e61707aa522d50e44d41761bb7c91e | 502e9e48915f476bcc3dbbb9e13674add8d1bffb | /PXApp-master/PXApp/app/src/main/java/com/example/pxapp/PlaylistsAdapter.java | 6cfb5638dd6fad02a8dcd062ad7b6e6679890395 | [] | no_license | musicfordementia/app | cea2b37aef4a30918e28196dc81c99382b8bd0f0 | 16f64c9661c1deb4bae44ff1268185889708f6b2 | refs/heads/master | 2023-01-20T04:00:45.366244 | 2020-01-06T01:53:49 | 2020-01-06T01:53:49 | 231,870,874 | 0 | 0 | null | 2023-01-07T13:24:51 | 2020-01-05T05:13:56 | Java | UTF-8 | Java | false | false | 2,499 | java | package com.example.pxapp;
import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.pxapp.server.PXPlaylist;
import java.util.ArrayList;
public class PlaylistsAdapter extends RecyclerView.Adapter<PlaylistsAdapter.ViewHolder> {
private Context ctx;
private ArrayList<PXPlaylist> playlists;
public PlaylistsAdapter(Context ctx, ArrayList<PXPlaylist> playlists) {
this.ctx = ctx;
this.playlists = playlists;
}
@Override
public PlaylistsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(ctx);
View row = inflater.inflate(R.layout.rvplaylists_child, parent, false);
return new PlaylistsAdapter.ViewHolder(row);
}
@Override
public void onBindViewHolder(final PlaylistsAdapter.ViewHolder holder, final int pos) {
final PXPlaylist playlist = playlists.get(pos);
holder.row.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentTransaction ft = ((FragmentActivity)ctx).getSupportFragmentManager()
.beginTransaction();
ft.replace(R.id.fragment_content, FragmentSongs.newInstance(playlist.songs))
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(null)
.commit();
}
});
holder.txtName.setText(playlist.name);
holder.txtDescription.setText(playlist.description);
holder.txtSongCount.setText(String.format("%d songs", playlist.songs.size()));
}
@Override
public int getItemCount() {
return playlists.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public View row;
public TextView txtName, txtDescription, txtSongCount;
public ViewHolder(View v) {
super(v);
row = v;
txtName = v.findViewById(R.id.txtName);
txtDescription = v.findViewById(R.id.txtDescription);
txtSongCount = v.findViewById(R.id.txtSongCount);
}
}
}
| [
"bassace4000@gmail.com"
] | bassace4000@gmail.com |
46d0b61db64206de4bbc7008cfd9a8f7aef90135 | d2286e898713089f03debeabf6c3aabf8f50acd4 | /paylib/src/main/java/com/julyzeng/paylib/unionpay/UnionpayRequest.java | 940a7e3293ba6c022463e7755314c5b465f6a330 | [] | no_license | liuhuajian/WorkHouse | 5ea81d0b5b5846bedc6b0ed9a40525c2cf1ccc03 | e71f28cd4c91ffb4ff8ec6ab59c31f2fd988659b | refs/heads/master | 2020-04-07T09:27:28.611571 | 2018-11-19T16:48:31 | 2018-11-19T16:48:31 | 158,252,761 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,027 | java | package com.julyzeng.paylib.unionpay;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
/**
* 项目:原产地
* 作 者:julyzeng (曾招林) 364298140@qq.com
* 版 本:1.0
* 创建日期:2017/7/13 15:31
* 描 述:银联支付请求
* 修订历史:
*/
public class UnionpayRequest {
// 00 正式 01测试
public static final String mMode = "00";
/**
* 获取tn号之后 调用此方法
* @param activity 上下文
* @param tn 流水号
* @param mode mMode参数解释: "00" - 启动银联正式环境 "01" - 连接银联测试环境
*/
public void pay(final Context activity, String tn, String mode) {
// if(!UPPayAssistEx.checkInstalled(activity))
// {
// 需要重新安装控件
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("提示");
builder.setMessage("完成购买需要安装银联支付控件,是否安装?");
builder.setNegativeButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// UPPayAssistEx.installUPPayPlugin(activity);
dialog.dismiss();
}
});
builder.setPositiveButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
// }
// else{
// UPPayAssistEx.startPay(activity, null, null, tn, mode);
// }
}
/*
* 支付回调接口 在activity的 onActivityResult(int requestCode, int resultCode, Intent data)调用
* @param data
*/
public static void payResult(Intent data, UnionResult result) {
if (data == null) {
return;
}
String str = data.getExtras().getString("pay_result");
if (str.equalsIgnoreCase("success")) {
if(result!=null){
result.onSuccess();
}
} else if (str.equalsIgnoreCase("fail")) {
if(result!=null){
result.onFail();
}
} else if (str.equalsIgnoreCase("cancel")) {
if(result!=null){
result.onCancel();
}
}
}
/**
* 银联结果回调
*/
public interface UnionResult{
/**
* 成功回调
*/
void onSuccess();
/**
* 失败回调
*/
void onFail();
/**
* 取消回调
*/
void onCancel();
}
}
| [
"liuhuajian_lhj@163.com"
] | liuhuajian_lhj@163.com |
343f14d5a2412ba78ad25af84e1754d8b86fd987 | 8191bea395f0e97835735d1ab6e859db3a7f8a99 | /f737922a0ddc9335bb0fc2f3ae5ffe93_source_from_JADX/com/google/android/gms/measurement/internal/ai.java | 19df38e059cd0320c7dff7fc7678cd511a9883f8 | [] | no_license | msmtmsmt123/jadx-1 | 5e5aea319e094b5d09c66e0fdb31f10a3238346c | b9458bb1a49a8a7fba8b9f9a6fb6f54438ce03a2 | refs/heads/master | 2021-05-08T19:21:27.870459 | 2017-01-28T04:19:54 | 2017-01-28T04:19:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 54,420 | java | package com.google.android.gms.measurement.internal;
import afq;
import agl;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.text.TextUtils;
import android.util.Pair;
import com.google.android.gms.internal.hs;
import com.google.android.gms.internal.ht.b;
import com.google.android.gms.internal.ht.c;
import com.google.android.gms.internal.ht.d;
import com.google.android.gms.internal.ht.e;
import com.google.android.gms.internal.ht.g;
import com.google.android.gms.internal.m;
import com.google.android.gms.measurement.AppMeasurement;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import l;
public class ai {
private static volatile ai DW;
private int BT;
private final l EQ;
private final Context FH;
private final o Hw;
private final ab J0;
private final afq J8;
private final i Mr;
private final r QX;
private final n U2;
private final ah VH;
private final d Ws;
private final c XL;
private final aa Zo;
private final boolean a8;
private final y aM;
private FileLock er;
private List<Long> gW;
private final f gn;
private final ac j3;
public final agl j6;
private boolean lg;
private Boolean rN;
private final AppMeasurement tp;
private final ag u7;
private final ae v5;
private int vy;
private final p we;
private FileChannel yS;
class 1 implements Runnable {
final /* synthetic */ ai j6;
1(ai aiVar) {
this.j6 = aiVar;
}
public void run() {
this.j6.FH();
}
}
class 2 implements a {
final /* synthetic */ ai j6;
2(ai aiVar) {
this.j6 = aiVar;
}
public void j6(String str, int i, Throwable th, byte[] bArr, Map<String, List<String>> map) {
this.j6.j6(i, th, bArr);
}
}
class 3 implements a {
final /* synthetic */ ai j6;
3(ai aiVar) {
this.j6 = aiVar;
}
public void j6(String str, int i, Throwable th, byte[] bArr, Map<String, List<String>> map) {
this.j6.j6(str, i, th, bArr, map);
}
}
private class a implements b {
List<Long> DW;
List<b> FH;
long Hw;
e j6;
final /* synthetic */ ai v5;
private a(ai aiVar) {
this.v5 = aiVar;
}
private long j6(b bVar) {
return ((bVar.FH.longValue() / 1000) / 60) / 60;
}
public void j6(e eVar) {
com.google.android.gms.common.internal.b.j6((Object) eVar);
this.j6 = eVar;
}
boolean j6() {
return this.FH == null || this.FH.isEmpty();
}
public boolean j6(long j, b bVar) {
com.google.android.gms.common.internal.b.j6((Object) bVar);
if (this.FH == null) {
this.FH = new ArrayList();
}
if (this.DW == null) {
this.DW = new ArrayList();
}
if (this.FH.size() > 0 && j6((b) this.FH.get(0)) != j6(bVar)) {
return false;
}
long VH = this.Hw + ((long) bVar.VH());
if (VH >= ((long) this.v5.Hw().sy())) {
return false;
}
this.Hw = VH;
this.FH.add(bVar);
this.DW.add(Long.valueOf(j));
return this.FH.size() < this.v5.Hw().aj();
}
}
ai(zzab com_google_android_gms_measurement_internal_zzab) {
com.google.android.gms.common.internal.b.j6((Object) com_google_android_gms_measurement_internal_zzab);
this.FH = com_google_android_gms_measurement_internal_zzab.j6;
this.J8 = com_google_android_gms_measurement_internal_zzab.we(this);
this.Hw = com_google_android_gms_measurement_internal_zzab.j6(this);
ae DW = com_google_android_gms_measurement_internal_zzab.DW(this);
DW.Hw();
this.v5 = DW;
aa FH = com_google_android_gms_measurement_internal_zzab.FH(this);
FH.Hw();
this.Zo = FH;
Zo().vy().j6("App measurement is starting up, version", Long.valueOf(Hw().sG()));
Zo().vy().j6("To enable debug logging run: adb shell setprop log.tag.FA VERBOSE");
Zo().P8().j6("Debug logging enabled");
Zo().P8().j6("AppMeasurement singleton hash", Integer.valueOf(System.identityHashCode(this)));
this.EQ = com_google_android_gms_measurement_internal_zzab.u7(this);
r J8 = com_google_android_gms_measurement_internal_zzab.J8(this);
J8.Hw();
this.QX = J8;
y Ws = com_google_android_gms_measurement_internal_zzab.Ws(this);
Ws.Hw();
this.aM = Ws;
p tp = com_google_android_gms_measurement_internal_zzab.tp(this);
tp.Hw();
this.we = tp;
n aM = com_google_android_gms_measurement_internal_zzab.aM(this);
aM.Hw();
this.U2 = aM;
ab EQ = com_google_android_gms_measurement_internal_zzab.EQ(this);
EQ.Hw();
this.J0 = EQ;
d J0 = com_google_android_gms_measurement_internal_zzab.J0(this);
J0.Hw();
this.Ws = J0;
c gn = com_google_android_gms_measurement_internal_zzab.gn(this);
gn.Hw();
this.XL = gn;
i XL = com_google_android_gms_measurement_internal_zzab.XL(this);
XL.Hw();
this.Mr = XL;
this.j3 = com_google_android_gms_measurement_internal_zzab.QX(this);
this.tp = com_google_android_gms_measurement_internal_zzab.VH(this);
this.j6 = new agl(this);
f v5 = com_google_android_gms_measurement_internal_zzab.v5(this);
v5.Hw();
this.gn = v5;
ag Zo = com_google_android_gms_measurement_internal_zzab.Zo(this);
Zo.Hw();
this.u7 = Zo;
ah Hw = com_google_android_gms_measurement_internal_zzab.Hw(this);
Hw.Hw();
this.VH = Hw;
if (this.BT != this.vy) {
Zo().Zo().j6("Not all components initialized", Integer.valueOf(this.BT), Integer.valueOf(this.vy));
}
this.a8 = true;
if (!(this.Hw.ef() || vy())) {
if (!(this.FH.getApplicationContext() instanceof Application)) {
Zo().yS().j6("Application context is not an Application");
} else if (VERSION.SDK_INT >= 14) {
we().Zo();
} else {
Zo().P8().j6("Not tracking deep linking pre-ICS");
}
}
this.VH.j6(new 1(this));
}
private void DW(b bVar) {
if (bVar == null) {
throw new IllegalStateException("Component not created");
} else if (!bVar.j6()) {
throw new IllegalStateException("Component not initialized");
}
}
private void FH(AppMetadata appMetadata) {
Object obj = 1;
er();
j6();
com.google.android.gms.common.internal.b.j6((Object) appMetadata);
com.google.android.gms.common.internal.b.j6(appMetadata.DW);
a DW = Ws().DW(appMetadata.DW);
String DW2 = v5().DW(appMetadata.DW);
Object obj2 = null;
if (DW == null) {
a aVar = new a(this, appMetadata.DW);
aVar.j6(v5().Zo());
aVar.FH(DW2);
DW = aVar;
obj2 = 1;
} else if (!DW2.equals(DW.v5())) {
DW.FH(DW2);
DW.j6(v5().Zo());
int i = 1;
}
if (!(TextUtils.isEmpty(appMetadata.FH) || appMetadata.FH.equals(DW.Hw()))) {
DW.DW(appMetadata.FH);
obj2 = 1;
}
if (!(TextUtils.isEmpty(appMetadata.we) || appMetadata.we.equals(DW.Zo()))) {
DW.Hw(appMetadata.we);
obj2 = 1;
}
if (!(appMetadata.Zo == 0 || appMetadata.Zo == DW.we())) {
DW.Hw(appMetadata.Zo);
obj2 = 1;
}
if (!(TextUtils.isEmpty(appMetadata.Hw) || appMetadata.Hw.equals(DW.u7()))) {
DW.v5(appMetadata.Hw);
obj2 = 1;
}
if (appMetadata.EQ != DW.tp()) {
DW.FH(appMetadata.EQ);
obj2 = 1;
}
if (!(TextUtils.isEmpty(appMetadata.v5) || appMetadata.v5.equals(DW.EQ()))) {
DW.Zo(appMetadata.v5);
obj2 = 1;
}
if (appMetadata.VH != DW.J0()) {
DW.v5(appMetadata.VH);
obj2 = 1;
}
if (appMetadata.u7 != DW.J8()) {
DW.j6(appMetadata.u7);
} else {
obj = obj2;
}
if (obj != null) {
Ws().j6(DW);
}
}
private boolean cb() {
er();
return this.gW != null;
}
private boolean dx() {
er();
j6();
return Ws().KD() || !TextUtils.isEmpty(Ws().vy());
}
private long ef() {
long j6 = aM().j6();
long yO = Hw().yO();
long XX = Hw().XX();
long j62 = v5().FH.j6();
long j63 = v5().Hw.j6();
long max = Math.max(Ws().nw(), Ws().SI());
if (max == 0) {
return 0;
}
max = j6 - Math.abs(max - j6);
j63 = j6 - Math.abs(j63 - j6);
j6 = Math.max(j6 - Math.abs(j62 - j6), j63);
yO += max;
if (!J8().j6(j6, XX)) {
yO = j6 + XX;
}
if (j63 == 0 || j63 < max) {
return yO;
}
for (int i = 0; i < Hw().jJ(); i++) {
yO += ((long) (1 << i)) * Hw().XG();
if (yO > j63) {
return yO;
}
}
return 0;
}
public static ai j6(Context context) {
com.google.android.gms.common.internal.b.j6((Object) context);
com.google.android.gms.common.internal.b.j6(context.getApplicationContext());
if (DW == null) {
synchronized (ai.class) {
if (DW == null) {
DW = new zzab(context).j6();
}
}
}
return DW;
}
private void j6(int i, Throwable th, byte[] bArr) {
int i2 = 0;
er();
j6();
if (bArr == null) {
bArr = new byte[0];
}
List<Long> list = this.gW;
this.gW = null;
if ((i == 200 || i == 204) && th == null) {
v5().FH.j6(aM().j6());
v5().Hw.j6(0);
sG();
Zo().ei().j6("Successful upload. Got network response. code, size", Integer.valueOf(i), Integer.valueOf(bArr.length));
Ws().Zo();
try {
for (Long longValue : list) {
Ws().j6(longValue.longValue());
}
Ws().VH();
if (QX().Zo() && dx()) {
KD();
} else {
sG();
}
} finally {
Ws().yS();
}
} else {
Zo().ei().j6("Network upload failed. Will retry later. code, error", Integer.valueOf(i), th);
v5().Hw.j6(aM().j6());
if (i == 503 || i == 429) {
i2 = 1;
}
if (i2 != 0) {
v5().v5.j6(aM().j6());
}
sG();
}
}
private void j6(ak akVar) {
if (akVar == null) {
throw new IllegalStateException("Component not created");
}
}
private void j6(List<Long> list) {
com.google.android.gms.common.internal.b.DW(!list.isEmpty());
if (this.gW != null) {
Zo().Zo().j6("Set uploading progress before finishing the previous upload");
} else {
this.gW = new ArrayList(list);
}
}
private boolean j6(String str, long j) {
Ws().Zo();
try {
ai aiVar = this;
b aVar = new a();
Ws().j6(str, j, aVar);
if (aVar.j6()) {
Ws().VH();
Ws().yS();
return false;
}
int i;
e eVar = aVar.j6;
eVar.DW = new b[aVar.FH.size()];
int i2 = 0;
int i3 = 0;
while (i3 < aVar.FH.size()) {
if (tp().DW(aVar.j6.QX, ((b) aVar.FH.get(i3)).DW)) {
Zo().yS().j6("Dropping blacklisted raw event", ((b) aVar.FH.get(i3)).DW);
J8().j6(11, "_ev", ((b) aVar.FH.get(i3)).DW);
i = i2;
} else {
int i4;
if (tp().FH(aVar.j6.QX, ((b) aVar.FH.get(i3)).DW)) {
int i5;
Object obj;
c cVar;
if (((b) aVar.FH.get(i3)).j6 == null) {
((b) aVar.FH.get(i3)).j6 = new c[0];
}
for (c cVar2 : ((b) aVar.FH.get(i3)).j6) {
if ("_c".equals(cVar2.j6)) {
cVar2.FH = Long.valueOf(1);
obj = 1;
break;
}
}
obj = null;
if (obj == null) {
Zo().ei().j6("Marking event as conversion", ((b) aVar.FH.get(i3)).DW);
c[] cVarArr = (c[]) Arrays.copyOf(((b) aVar.FH.get(i3)).j6, ((b) aVar.FH.get(i3)).j6.length + 1);
cVar = new c();
cVar.j6 = "_c";
cVar.FH = Long.valueOf(1);
cVarArr[cVarArr.length - 1] = cVar;
((b) aVar.FH.get(i3)).j6 = cVarArr;
}
boolean j6 = l.j6(((b) aVar.FH.get(i3)).DW);
if (j6 && Ws().j6(ei(), aVar.j6.QX, false, j6, false).FH - ((long) Hw().j6(aVar.j6.QX)) > 0) {
Zo().yS().j6("Too many conversions. Not logging as conversion.");
b bVar = (b) aVar.FH.get(i3);
Object obj2 = null;
c cVar3 = null;
c[] cVarArr2 = ((b) aVar.FH.get(i3)).j6;
int length = cVarArr2.length;
int i6 = 0;
while (i6 < length) {
Object obj3;
cVar = cVarArr2[i6];
if ("_c".equals(cVar.j6)) {
obj3 = obj2;
} else if ("_err".equals(cVar.j6)) {
c cVar4 = cVar3;
int i7 = 1;
cVar = cVar4;
} else {
cVar = cVar3;
obj3 = obj2;
}
i6++;
obj2 = obj3;
cVar3 = cVar;
}
if (obj2 != null && cVar3 != null) {
c[] cVarArr3 = new c[(bVar.j6.length - 1)];
i4 = 0;
cVarArr2 = bVar.j6;
length = cVarArr2.length;
i5 = 0;
while (i5 < length) {
c cVar5 = cVarArr2[i5];
if (cVar5 != cVar3) {
i = i4 + 1;
cVarArr3[i4] = cVar5;
} else {
i = i4;
}
i5++;
i4 = i;
}
((b) aVar.FH.get(i3)).j6 = cVarArr3;
} else if (cVar3 != null) {
cVar3.j6 = "_err";
cVar3.FH = Long.valueOf(10);
} else {
Zo().Zo().j6("Did not find conversion parameter. Error not tracked");
}
}
}
i4 = i2 + 1;
eVar.DW[i2] = (b) aVar.FH.get(i3);
i = i4;
}
i3++;
i2 = i;
}
if (i2 < aVar.FH.size()) {
eVar.DW = (b[]) Arrays.copyOf(eVar.DW, i2);
}
eVar.BT = j6(aVar.j6.QX, aVar.j6.FH, eVar.DW);
eVar.v5 = eVar.DW[0].FH;
eVar.Zo = eVar.DW[0].FH;
for (i = 1; i < eVar.DW.length; i++) {
b bVar2 = eVar.DW[i];
if (bVar2.FH.longValue() < eVar.v5.longValue()) {
eVar.v5 = bVar2.FH;
}
if (bVar2.FH.longValue() > eVar.Zo.longValue()) {
eVar.Zo = bVar2.FH;
}
}
String str2 = aVar.j6.QX;
a DW = Ws().DW(str2);
if (DW == null) {
Zo().Zo().j6("Bundling raw events w/o app info");
} else {
long gn = DW.gn();
eVar.gn = gn != 0 ? Long.valueOf(gn) : null;
long VH = DW.VH();
if (VH != 0) {
gn = VH;
}
eVar.VH = gn != 0 ? Long.valueOf(gn) : null;
DW.aM();
eVar.rN = Integer.valueOf((int) DW.Ws());
DW.j6(eVar.v5.longValue());
DW.DW(eVar.Zo.longValue());
Ws().j6(DW);
}
eVar.er = Zo().nw();
Ws().j6(eVar);
Ws().j6(aVar.DW);
Ws().gn(str2);
Ws().VH();
return true;
} finally {
Ws().yS();
}
}
private com.google.android.gms.internal.ht.a[] j6(String str, g[] gVarArr, b[] bVarArr) {
com.google.android.gms.common.internal.b.j6(str);
return rN().j6(str, bVarArr, gVarArr);
}
private void sG() {
er();
j6();
if (!sh()) {
return;
}
if (DW() && dx()) {
long ef = ef();
if (ef == 0) {
a8().DW();
lg().Zo();
return;
} else if (QX().Zo()) {
long j6 = v5().v5.j6();
long br = Hw().br();
if (!J8().j6(j6, br)) {
ef = Math.max(ef, j6 + br);
}
a8().DW();
ef -= aM().j6();
if (ef <= 0) {
lg().j6(1);
return;
}
Zo().ei().j6("Upload scheduled in approximately ms", Long.valueOf(ef));
lg().j6(ef);
return;
} else {
a8().j6();
lg().Zo();
return;
}
}
a8().DW();
lg().Zo();
}
boolean BT() {
er();
try {
this.yS = new RandomAccessFile(new File(XL().getFilesDir(), this.we.BT()), "rw").getChannel();
this.er = this.yS.tryLock();
if (this.er != null) {
Zo().ei().j6("Storage concurrent access okay");
return true;
}
Zo().Zo().j6("Storage concurrent data access panic");
return false;
} catch (FileNotFoundException e) {
Zo().Zo().j6("Failed to acquire storage lock", e);
} catch (IOException e2) {
Zo().Zo().j6("Failed to access storage lock file", e2);
}
}
public void DW(AppMetadata appMetadata) {
er();
j6();
com.google.android.gms.common.internal.b.j6((Object) appMetadata);
com.google.android.gms.common.internal.b.j6(appMetadata.DW);
if (!TextUtils.isEmpty(appMetadata.FH)) {
if (appMetadata.u7) {
long j6 = aM().j6();
Ws().Zo();
try {
j6(appMetadata, j6);
FH(appMetadata);
if (Ws().j6(appMetadata.DW, "_f") == null) {
j6(new UserAttributeParcel("_fot", j6, Long.valueOf((1 + (j6 / 3600000)) * 3600000), "auto"), appMetadata);
DW(appMetadata, j6);
FH(appMetadata, j6);
} else if (appMetadata.tp) {
Hw(appMetadata, j6);
}
Ws().VH();
} finally {
Ws().yS();
}
} else {
FH(appMetadata);
}
}
}
void DW(AppMetadata appMetadata, long j) {
Bundle bundle = new Bundle();
bundle.putLong("_c", 1);
j6(new EventParcel("_f", new EventParams(bundle), "auto", j), appMetadata);
}
void DW(UserAttributeParcel userAttributeParcel, AppMetadata appMetadata) {
er();
j6();
if (!TextUtils.isEmpty(appMetadata.FH)) {
if (appMetadata.u7) {
Zo().P8().j6("Removing user property", userAttributeParcel.DW);
Ws().Zo();
try {
FH(appMetadata);
Ws().DW(appMetadata.DW, userAttributeParcel.DW);
Ws().VH();
Zo().P8().j6("User property removed", userAttributeParcel.DW);
} finally {
Ws().yS();
}
} else {
FH(appMetadata);
}
}
}
protected boolean DW() {
j6();
er();
if (this.rN == null) {
boolean z = J8().u7("android.permission.INTERNET") && J8().u7("android.permission.ACCESS_NETWORK_STATE") && af.j6(XL()) && e.j6(XL());
this.rN = Boolean.valueOf(z);
if (this.rN.booleanValue() && !Hw().ef()) {
this.rN = Boolean.valueOf(J8().Zo(U2().VH()));
}
}
return this.rN.booleanValue();
}
public byte[] DW(EventParcel eventParcel, String str) {
j6();
er();
SI();
com.google.android.gms.common.internal.b.j6((Object) eventParcel);
com.google.android.gms.common.internal.b.j6(str);
d dVar = new d();
Ws().Zo();
try {
a DW = Ws().DW(str);
byte[] bArr;
if (DW == null) {
Zo().P8().j6("Log and bundle not available. package_name", str);
bArr = new byte[0];
return bArr;
} else if (DW.J8()) {
long j;
e eVar = new e();
dVar.j6 = new e[]{eVar};
eVar.j6 = Integer.valueOf(1);
eVar.u7 = "android";
eVar.QX = DW.DW();
eVar.Ws = DW.EQ();
eVar.XL = DW.u7();
eVar.P8 = Integer.valueOf((int) DW.tp());
eVar.aM = Long.valueOf(DW.we());
eVar.yS = DW.Hw();
eVar.lg = Long.valueOf(DW.J0());
Pair j6 = v5().j6(DW.DW());
if (!(j6 == null || TextUtils.isEmpty((CharSequence) j6.first))) {
eVar.Mr = (String) j6.first;
eVar.U2 = (Boolean) j6.second;
}
eVar.EQ = Mr().Zo();
eVar.tp = Mr().VH();
eVar.J0 = Integer.valueOf((int) Mr().yS());
eVar.we = Mr().gW();
eVar.a8 = DW.FH();
eVar.vy = DW.Zo();
List j62 = Ws().j6(DW.DW());
eVar.FH = new g[j62.size()];
for (int i = 0; i < j62.size(); i++) {
g gVar = new g();
eVar.FH[i] = gVar;
gVar.DW = ((k) j62.get(i)).DW;
gVar.j6 = Long.valueOf(((k) j62.get(i)).FH);
J8().j6(gVar, ((k) j62.get(i)).Hw);
}
Bundle DW2 = eventParcel.FH.DW();
if ("_iap".equals(eventParcel.DW)) {
DW2.putLong("_c", 1);
}
DW2.putString("_o", eventParcel.Hw);
t j63 = Ws().j6(str, eventParcel.DW);
if (j63 == null) {
Ws().j6(new t(str, eventParcel.DW, 1, 0, eventParcel.v5));
j = 0;
} else {
j = j63.v5;
Ws().j6(j63.j6(eventParcel.v5).j6());
}
s sVar = new s(this, eventParcel.Hw, str, eventParcel.DW, eventParcel.v5, j, DW2);
b bVar = new b();
eVar.DW = new b[]{bVar};
bVar.FH = Long.valueOf(sVar.Hw);
bVar.DW = sVar.DW;
bVar.Hw = Long.valueOf(sVar.v5);
bVar.j6 = new c[sVar.Zo.j6()];
Iterator it = sVar.Zo.iterator();
int i2 = 0;
while (it.hasNext()) {
String str2 = (String) it.next();
c cVar = new c();
int i3 = i2 + 1;
bVar.j6[i2] = cVar;
cVar.j6 = str2;
J8().j6(cVar, sVar.Zo.j6(str2));
i2 = i3;
}
eVar.BT = j6(DW.DW(), eVar.FH, eVar.DW);
eVar.v5 = bVar.FH;
eVar.Zo = bVar.FH;
long gn = DW.gn();
eVar.gn = gn != 0 ? Long.valueOf(gn) : null;
long VH = DW.VH();
if (VH != 0) {
gn = VH;
}
eVar.VH = gn != 0 ? Long.valueOf(gn) : null;
DW.aM();
eVar.rN = Integer.valueOf((int) DW.Ws());
eVar.j3 = Long.valueOf(Hw().sG());
eVar.Hw = Long.valueOf(aM().j6());
eVar.gW = Boolean.TRUE;
DW.j6(eVar.v5.longValue());
DW.DW(eVar.Zo.longValue());
Ws().j6(DW);
Ws().VH();
Ws().yS();
try {
bArr = new byte[dVar.VH()];
m j64 = m.j6(bArr);
dVar.j6(j64);
j64.DW();
return J8().j6(bArr);
} catch (IOException e) {
Zo().Zo().j6("Data loss. Failed to bundle and serialize", e);
return null;
}
} else {
Zo().P8().j6("Log and bundle disabled. package_name", str);
bArr = new byte[0];
Ws().yS();
return bArr;
}
} finally {
Ws().yS();
}
}
ah EQ() {
return this.VH;
}
protected void FH() {
er();
if (!vy() || (this.VH.j6() && !this.VH.DW())) {
Ws().P8();
if (DW()) {
if (!(Hw().ef() || TextUtils.isEmpty(U2().VH()))) {
String gW = v5().gW();
if (gW == null) {
v5().FH(U2().VH());
} else if (!gW.equals(U2().VH())) {
Zo().vy().j6("Rechecking which service to use due to a GMP App Id change");
v5().vy();
this.Ws.vy();
this.Ws.gW();
v5().FH(U2().VH());
}
}
if (!(Hw().ef() || vy() || TextUtils.isEmpty(U2().VH()))) {
we().VH();
}
} else if (P8()) {
if (!J8().u7("android.permission.INTERNET")) {
Zo().Zo().j6("App is missing INTERNET permission");
}
if (!J8().u7("android.permission.ACCESS_NETWORK_STATE")) {
Zo().Zo().j6("App is missing ACCESS_NETWORK_STATE permission");
}
if (!af.j6(XL())) {
Zo().Zo().j6("AppMeasurementReceiver not registered/enabled");
}
if (!e.j6(XL())) {
Zo().Zo().j6("AppMeasurementService not registered/enabled");
}
Zo().Zo().j6("Uploading is not possible. App measurement disabled");
}
sG();
return;
}
Zo().Zo().j6("Scheduler shutting down before Scion.start() called");
}
void FH(AppMetadata appMetadata, long j) {
Bundle bundle = new Bundle();
bundle.putLong("_et", 1);
j6(new EventParcel("_e", new EventParams(bundle), "auto", j), appMetadata);
}
public o Hw() {
return this.Hw;
}
void Hw(AppMetadata appMetadata, long j) {
j6(new EventParcel("_cd", new EventParams(new Bundle()), "auto", j), appMetadata);
}
public AppMeasurement J0() {
return this.tp;
}
public l J8() {
j6(this.EQ);
return this.EQ;
}
public void KD() {
Map map = null;
int i = 0;
er();
j6();
if (!Hw().ef()) {
Boolean BT = v5().BT();
if (BT == null) {
Zo().yS().j6("Upload data called on the client side before use of service was decided");
return;
} else if (BT.booleanValue()) {
Zo().Zo().j6("Upload called in the client side when service should be used");
return;
}
}
if (cb()) {
Zo().yS().j6("Uploading requested multiple times");
} else if (QX().Zo()) {
long j6 = aM().j6();
j6(j6 - Hw().OW());
long j62 = v5().FH.j6();
if (j62 != 0) {
Zo().P8().j6("Uploading events. Elapsed time since last upload attempt (ms)", Long.valueOf(Math.abs(j6 - j62)));
}
String vy = Ws().vy();
if (TextUtils.isEmpty(vy)) {
String DW = Ws().DW(j6 - Hw().OW());
if (!TextUtils.isEmpty(DW)) {
a DW2 = Ws().DW(DW);
if (DW2 != null) {
String j63 = Hw().j6(DW2.Hw(), DW2.FH());
try {
URL url = new URL(j63);
Zo().ei().j6("Fetching remote configuration", DW2.DW());
hs.b j64 = tp().j6(DW2.DW());
CharSequence DW3 = tp().DW(DW2.DW());
if (!(j64 == null || TextUtils.isEmpty(DW3))) {
map = new l();
map.put("If-Modified-Since", DW3);
}
QX().j6(DW, url, map, new 3(this));
return;
} catch (MalformedURLException e) {
Zo().Zo().j6("Failed to parse config URL. Not fetching", j63);
return;
}
}
return;
}
return;
}
List<Pair> j65 = Ws().j6(vy, Hw().Hw(vy), Hw().v5(vy));
if (!j65.isEmpty()) {
e eVar;
Object obj;
List subList;
for (Pair pair : j65) {
eVar = (e) pair.first;
if (!TextUtils.isEmpty(eVar.Mr)) {
obj = eVar.Mr;
break;
}
}
obj = null;
if (obj != null) {
for (int i2 = 0; i2 < j65.size(); i2++) {
eVar = (e) ((Pair) j65.get(i2)).first;
if (!TextUtils.isEmpty(eVar.Mr) && !eVar.Mr.equals(obj)) {
subList = j65.subList(0, i2);
break;
}
}
}
subList = j65;
d dVar = new d();
dVar.j6 = new e[subList.size()];
List arrayList = new ArrayList(subList.size());
while (i < dVar.j6.length) {
dVar.j6[i] = (e) ((Pair) subList.get(i)).first;
arrayList.add((Long) ((Pair) subList.get(i)).second);
dVar.j6[i].j3 = Long.valueOf(Hw().sG());
dVar.j6[i].Hw = Long.valueOf(j6);
dVar.j6[i].gW = Boolean.valueOf(Hw().ef());
i++;
}
Object DW4 = Zo().j6(2) ? l.DW(dVar) : null;
byte[] j66 = J8().j6(dVar);
String lp = Hw().lp();
try {
URL url2 = new URL(lp);
j6(arrayList);
v5().Hw.j6(j6);
Object obj2 = "?";
if (dVar.j6.length > 0) {
obj2 = dVar.j6[0].QX;
}
Zo().ei().j6("Uploading data. app, uncompressed size, data", obj2, Integer.valueOf(j66.length), DW4);
QX().j6(vy, url2, j66, null, new 2(this));
} catch (MalformedURLException e2) {
Zo().Zo().j6("Failed to parse upload URL. Not uploading", lp);
}
}
} else {
Zo().yS().j6("Network not connected, ignoring upload request");
sG();
}
}
public r Mr() {
DW(this.QX);
return this.QX;
}
public boolean P8() {
boolean z = false;
er();
j6();
if (Hw().vJ()) {
return false;
}
Boolean g3 = Hw().g3();
if (g3 != null) {
z = g3.booleanValue();
} else if (!Hw().Mz()) {
z = true;
}
return v5().FH(z);
}
public ab QX() {
DW(this.J0);
return this.J0;
}
void SI() {
if (!Hw().ef()) {
throw new IllegalStateException("Unexpected call on client side");
}
}
public y U2() {
DW(this.aM);
return this.aM;
}
public aa VH() {
return (this.Zo == null || !this.Zo.j6()) ? null : this.Zo;
}
public p Ws() {
DW(this.we);
return this.we;
}
public Context XL() {
return this.FH;
}
public aa Zo() {
DW(this.Zo);
return this.Zo;
}
public ac a8() {
if (this.j3 != null) {
return this.j3;
}
throw new IllegalStateException("Network broadcast receiver not created");
}
public afq aM() {
return this.J8;
}
void cn() {
er();
j6();
if (!this.lg) {
Zo().vy().j6("This instance being marked as an uploader");
gW();
}
this.lg = true;
}
long ei() {
return ((((aM().j6() + v5().yS()) / 1000) / 60) / 60) / 24;
}
public void er() {
gn().tp();
}
void gW() {
er();
j6();
if (sh() && BT()) {
j6(j6(yS()), U2().gW());
}
}
public ah gn() {
DW(this.VH);
return this.VH;
}
public d j3() {
DW(this.Ws);
return this.Ws;
}
int j6(FileChannel fileChannel) {
int i = 0;
er();
if (fileChannel == null || !fileChannel.isOpen()) {
Zo().Zo().j6("Bad chanel to read from");
} else {
ByteBuffer allocate = ByteBuffer.allocate(4);
try {
fileChannel.position(0);
int read = fileChannel.read(allocate);
if (read != 4) {
Zo().yS().j6("Unexpected data length or empty data in channel. Bytes read", Integer.valueOf(read));
} else {
allocate.flip();
i = allocate.getInt();
}
} catch (IOException e) {
Zo().Zo().j6("Failed to read from channel", e);
}
}
return i;
}
void j6() {
if (!this.a8) {
throw new IllegalStateException("AppMeasurement is not initialized");
}
}
void j6(AppMetadata appMetadata) {
er();
j6();
com.google.android.gms.common.internal.b.j6(appMetadata.DW);
FH(appMetadata);
}
void j6(AppMetadata appMetadata, long j) {
a DW = Ws().DW(appMetadata.DW);
if (!(DW == null || DW.Hw() == null || DW.Hw().equals(appMetadata.FH))) {
Zo().yS().j6("New GMP App Id passed in. Removing cached database data.");
Ws().VH(DW.DW());
DW = null;
}
if (DW != null && DW.u7() != null && !DW.u7().equals(appMetadata.Hw)) {
Bundle bundle = new Bundle();
bundle.putString("_pv", DW.u7());
j6(new EventParcel("_au", new EventParams(bundle), "auto", j), appMetadata);
}
}
void j6(EventParcel eventParcel, AppMetadata appMetadata) {
long nanoTime = System.nanoTime();
er();
j6();
String str = appMetadata.DW;
com.google.android.gms.common.internal.b.j6(str);
if (!TextUtils.isEmpty(appMetadata.FH)) {
if (!appMetadata.u7) {
FH(appMetadata);
} else if (tp().DW(str, eventParcel.DW)) {
Zo().yS().j6("Dropping blacklisted event", eventParcel.DW);
J8().j6(11, "_ev", eventParcel.DW);
} else {
if (Zo().j6(2)) {
Zo().ei().j6("Logging event", eventParcel);
}
Ws().Zo();
try {
Bundle DW = eventParcel.FH.DW();
FH(appMetadata);
if ("_iap".equals(eventParcel.DW) || "ecommerce_purchase".equals(eventParcel.DW)) {
long round;
Object string = DW.getString("currency");
if ("ecommerce_purchase".equals(eventParcel.DW)) {
double d = DW.getDouble("value") * 1000000.0d;
if (d == 0.0d) {
d = ((double) DW.getLong("value")) * 1000000.0d;
}
if (d > 9.223372036854776E18d || d < -9.223372036854776E18d) {
Zo().yS().j6("Data lost. Currency value is too big", Double.valueOf(d));
Ws().VH();
Ws().yS();
return;
}
round = Math.round(d);
} else {
round = DW.getLong("value");
}
if (!TextUtils.isEmpty(string)) {
String toUpperCase = string.toUpperCase(Locale.US);
if (toUpperCase.matches("[A-Z]{3}")) {
k kVar;
String valueOf = String.valueOf("_ltv_");
toUpperCase = String.valueOf(toUpperCase);
String concat = toUpperCase.length() != 0 ? valueOf.concat(toUpperCase) : new String(valueOf);
k FH = Ws().FH(str, concat);
if (FH == null || !(FH.Hw instanceof Long)) {
Ws().j6(str, Hw().FH(str) - 1);
kVar = new k(str, concat, aM().j6(), Long.valueOf(round));
} else {
kVar = new k(str, concat, aM().j6(), Long.valueOf(round + ((Long) FH.Hw).longValue()));
}
if (!Ws().j6(kVar)) {
Zo().Zo().j6("Too many unique user properties are set. Ignoring user property.", kVar.DW, kVar.Hw);
J8().j6(9, null, null);
}
}
}
}
boolean j6 = l.j6(eventParcel.DW);
l.j6(DW);
boolean equals = "_err".equals(eventParcel.DW);
com.google.android.gms.measurement.internal.p.a j62 = Ws().j6(ei(), str, j6, false, equals);
long vy = j62.DW - Hw().vy();
if (vy > 0) {
if (vy % 1000 == 1) {
Zo().Zo().j6("Data loss. Too many events logged. count", Long.valueOf(j62.DW));
}
J8().j6(16, "_ev", eventParcel.DW);
Ws().VH();
return;
}
t j63;
if (j6) {
vy = j62.j6 - Hw().P8();
if (vy > 0) {
if (vy % 1000 == 1) {
Zo().Zo().j6("Data loss. Too many public events logged. count", Long.valueOf(j62.j6));
}
J8().j6(16, "_ev", eventParcel.DW);
Ws().VH();
Ws().yS();
return;
}
}
if (equals) {
vy = j62.Hw - Hw().ei();
if (vy > 0) {
if (vy == 1) {
Zo().Zo().j6("Too many error events logged. count", Long.valueOf(j62.Hw));
}
Ws().VH();
Ws().yS();
return;
}
}
J8().j6(DW, "_o", eventParcel.Hw);
long FH2 = Ws().FH(str);
if (FH2 > 0) {
Zo().yS().j6("Data lost. Too many events stored on disk, deleted", Long.valueOf(FH2));
}
s sVar = new s(this, eventParcel.Hw, str, eventParcel.DW, eventParcel.v5, 0, DW);
t j64 = Ws().j6(str, sVar.DW);
if (j64 != null) {
sVar = sVar.j6(this, j64.v5);
j63 = j64.j6(sVar.Hw);
} else if (Ws().u7(str) >= ((long) Hw().BT())) {
Zo().Zo().j6("Too many event names used, ignoring event. name, supported count", sVar.DW, Integer.valueOf(Hw().BT()));
J8().j6(8, null, null);
Ws().yS();
return;
} else {
j63 = new t(str, sVar.DW, 0, 0, sVar.Hw);
}
Ws().j6(j63);
j6(sVar, appMetadata);
Ws().VH();
if (Zo().j6(2)) {
Zo().ei().j6("Event recorded", sVar);
}
Ws().yS();
sG();
Zo().ei().j6("Background event processing time, ms", Long.valueOf(((System.nanoTime() - nanoTime) + 500000) / 1000000));
} finally {
Ws().yS();
}
}
}
}
void j6(EventParcel eventParcel, String str) {
a DW = Ws().DW(str);
if (DW == null || TextUtils.isEmpty(DW.u7())) {
Zo().P8().j6("No app data available; dropping event", str);
return;
}
try {
String str2 = XL().getPackageManager().getPackageInfo(str, 0).versionName;
if (!(DW.u7() == null || DW.u7().equals(str2))) {
Zo().yS().j6("App version does not match; dropping event", str);
return;
}
} catch (NameNotFoundException e) {
if (!"_ui".equals(eventParcel.DW)) {
Zo().yS().j6("Could not find package", str);
}
}
EventParcel eventParcel2 = eventParcel;
j6(eventParcel2, new AppMetadata(str, DW.Hw(), DW.u7(), DW.tp(), DW.EQ(), DW.we(), DW.J0(), null, DW.J8(), false, DW.Zo()));
}
void j6(UserAttributeParcel userAttributeParcel, AppMetadata appMetadata) {
er();
j6();
if (!TextUtils.isEmpty(appMetadata.FH)) {
if (appMetadata.u7) {
int FH = J8().FH(userAttributeParcel.DW);
if (FH != 0) {
J8().j6(FH, "_ev", J8().j6(userAttributeParcel.DW, Hw().Hw(), true));
return;
}
FH = J8().FH(userAttributeParcel.DW, userAttributeParcel.j6());
if (FH != 0) {
J8().j6(FH, "_ev", J8().j6(userAttributeParcel.DW, Hw().Hw(), true));
return;
}
Object Hw = J8().Hw(userAttributeParcel.DW, userAttributeParcel.j6());
if (Hw != null) {
k kVar = new k(appMetadata.DW, userAttributeParcel.DW, userAttributeParcel.FH, Hw);
Zo().P8().j6("Setting user property", kVar.DW, Hw);
Ws().Zo();
try {
FH(appMetadata);
boolean j6 = Ws().j6(kVar);
Ws().VH();
if (j6) {
Zo().P8().j6("User property set", kVar.DW, kVar.Hw);
} else {
Zo().Zo().j6("Too many unique user properties are set. Ignoring user property.", kVar.DW, kVar.Hw);
J8().j6(9, null, null);
}
Ws().yS();
return;
} catch (Throwable th) {
Ws().yS();
}
} else {
return;
}
}
FH(appMetadata);
}
}
void j6(b bVar) {
this.BT++;
}
void j6(s sVar, AppMetadata appMetadata) {
er();
j6();
com.google.android.gms.common.internal.b.j6((Object) sVar);
com.google.android.gms.common.internal.b.j6((Object) appMetadata);
com.google.android.gms.common.internal.b.j6(sVar.j6);
com.google.android.gms.common.internal.b.DW(sVar.j6.equals(appMetadata.DW));
e eVar = new e();
eVar.j6 = Integer.valueOf(1);
eVar.u7 = "android";
eVar.QX = appMetadata.DW;
eVar.Ws = appMetadata.v5;
eVar.XL = appMetadata.Hw;
eVar.P8 = Integer.valueOf((int) appMetadata.EQ);
eVar.aM = Long.valueOf(appMetadata.Zo);
eVar.yS = appMetadata.FH;
eVar.lg = appMetadata.VH == 0 ? null : Long.valueOf(appMetadata.VH);
Pair j6 = v5().j6(appMetadata.DW);
if (j6 != null && !TextUtils.isEmpty((CharSequence) j6.first)) {
eVar.Mr = (String) j6.first;
eVar.U2 = (Boolean) j6.second;
} else if (!Mr().j6(this.FH)) {
String string = Secure.getString(this.FH.getContentResolver(), "android_id");
if (string == null) {
Zo().yS().j6("null secure ID");
string = "null";
} else if (string.isEmpty()) {
Zo().yS().j6("empty secure ID");
}
eVar.SI = string;
}
eVar.EQ = Mr().Zo();
eVar.tp = Mr().VH();
eVar.J0 = Integer.valueOf((int) Mr().yS());
eVar.we = Mr().gW();
eVar.j3 = null;
eVar.Hw = null;
eVar.v5 = null;
eVar.Zo = null;
a DW = Ws().DW(appMetadata.DW);
if (DW == null) {
DW = new a(this, appMetadata.DW);
DW.j6(v5().Zo());
DW.Hw(appMetadata.we);
DW.DW(appMetadata.FH);
DW.FH(v5().DW(appMetadata.DW));
DW.Zo(0);
DW.j6(0);
DW.DW(0);
DW.v5(appMetadata.Hw);
DW.FH(appMetadata.EQ);
DW.Zo(appMetadata.v5);
DW.Hw(appMetadata.Zo);
DW.v5(appMetadata.VH);
DW.j6(appMetadata.u7);
Ws().j6(DW);
}
eVar.a8 = DW.FH();
eVar.vy = DW.Zo();
List j62 = Ws().j6(appMetadata.DW);
eVar.FH = new g[j62.size()];
for (int i = 0; i < j62.size(); i++) {
g gVar = new g();
eVar.FH[i] = gVar;
gVar.DW = ((k) j62.get(i)).DW;
gVar.j6 = Long.valueOf(((k) j62.get(i)).FH);
J8().j6(gVar, ((k) j62.get(i)).Hw);
}
try {
Ws().j6(sVar, Ws().DW(eVar));
} catch (IOException e) {
Zo().Zo().j6("Data loss. Failed to insert raw event metadata", e);
}
}
void j6(String str, int i, Throwable th, byte[] bArr, Map<String, List<String>> map) {
int i2 = 0;
er();
j6();
com.google.android.gms.common.internal.b.j6(str);
if (bArr == null) {
bArr = new byte[0];
}
Ws().Zo();
try {
a DW = Ws().DW(str);
int i3 = ((i == 200 || i == 204 || i == 304) && th == null) ? 1 : 0;
if (DW == null) {
Zo().yS().j6("App does not exist in onConfigFetched", str);
} else if (i3 != 0 || i == 404) {
List list = map != null ? (List) map.get("Last-Modified") : null;
String str2 = (list == null || list.size() <= 0) ? null : (String) list.get(0);
if (i == 404 || i == 304) {
if (tp().j6(str) == null && !tp().j6(str, null, null)) {
Ws().yS();
return;
}
} else if (!tp().j6(str, bArr, str2)) {
Ws().yS();
return;
}
DW.VH(aM().j6());
Ws().j6(DW);
if (i == 404) {
Zo().yS().j6("Config not found. Using empty config");
} else {
Zo().ei().j6("Successfully fetched config. Got network response. code, size", Integer.valueOf(i), Integer.valueOf(bArr.length));
}
if (QX().Zo() && dx()) {
KD();
} else {
sG();
}
} else {
DW.gn(aM().j6());
Ws().j6(DW);
Zo().ei().j6("Fetching config failed. code, error", Integer.valueOf(i), th);
tp().FH(str);
v5().Hw.j6(aM().j6());
if (i == 503 || i == 429) {
i2 = 1;
}
if (i2 != 0) {
v5().v5.j6(aM().j6());
}
sG();
}
Ws().VH();
} finally {
Ws().yS();
}
}
public void j6(boolean z) {
sG();
}
boolean j6(int i, int i2) {
er();
if (i > i2) {
Zo().Zo().j6("Panic: can't downgrade version. Previous, current version", Integer.valueOf(i), Integer.valueOf(i2));
return false;
}
if (i < i2) {
if (j6(i2, yS())) {
Zo().ei().j6("Storage version upgraded. Previous, current version", Integer.valueOf(i), Integer.valueOf(i2));
} else {
Zo().Zo().j6("Storage version upgrade failed. Previous, current version", Integer.valueOf(i), Integer.valueOf(i2));
return false;
}
}
return true;
}
boolean j6(int i, FileChannel fileChannel) {
er();
if (fileChannel == null || !fileChannel.isOpen()) {
Zo().Zo().j6("Bad chanel to read from");
return false;
}
ByteBuffer allocate = ByteBuffer.allocate(4);
allocate.putInt(i);
allocate.flip();
try {
fileChannel.truncate(0);
fileChannel.write(allocate);
fileChannel.force(true);
if (fileChannel.size() == 4) {
return true;
}
Zo().Zo().j6("Error writing to channel. Bytes written", Long.valueOf(fileChannel.size()));
return true;
} catch (IOException e) {
Zo().Zo().j6("Failed to write to channel", e);
return false;
}
}
boolean j6(long j) {
return j6(null, j);
}
public i lg() {
DW(this.Mr);
return this.Mr;
}
void nw() {
if (Hw().ef()) {
throw new IllegalStateException("Unexpected call on package side");
}
}
public n rN() {
DW(this.U2);
return this.U2;
}
void ro() {
this.vy++;
}
boolean sh() {
er();
j6();
return this.lg || vy();
}
public ag tp() {
DW(this.u7);
return this.u7;
}
public f u7() {
DW(this.gn);
return this.gn;
}
public ae v5() {
j6(this.v5);
return this.v5;
}
protected boolean vy() {
return false;
}
public c we() {
DW(this.XL);
return this.XL;
}
FileChannel yS() {
return this.yS;
}
}
| [
"eggfly@qq.com"
] | eggfly@qq.com |
bec6825fe8d8985740a0adccdd1ce521066653d4 | a12c2d978392a90071c953cb99f67303b24795c6 | /src/main/java/com/questhelper/quests/theslugmenace/PuzzleStep.java | 76a3b53aae9cde1e7b7412f375d1b856e6180a6b | [
"BSD-2-Clause"
] | permissive | Ranarrr/quest-helper | 7fbbbb2b4be1740d9ae7178b163e8bd62c62a030 | 21160ee67072c26cae3aa74344fa3880b1de0988 | refs/heads/master | 2023-01-08T00:47:40.948149 | 2020-11-11T16:23:35 | 2020-11-11T16:23:35 | 312,025,028 | 0 | 0 | BSD-2-Clause | 2020-11-11T16:23:36 | 2020-11-11T16:21:19 | null | UTF-8 | Java | false | false | 6,850 | java | package com.questhelper.quests.theslugmenace;
import com.questhelper.QuestHelperPlugin;
import com.questhelper.questhelpers.QuestHelper;
import com.questhelper.steps.QuestStep;
import java.awt.Color;
import java.awt.Graphics2D;
import java.util.HashMap;
import java.util.Map;
import net.runelite.api.events.VarbitChanged;
import net.runelite.api.widgets.Widget;
import net.runelite.client.eventbus.Subscribe;
public class PuzzleStep extends QuestStep
{
private final int FLIP_BUTTON = 33;
private final int DOWN_BUTTON = 32;
private final int LEFT_BUTTON = 31;
private final int RIGHT_BUTTON = 30;
private final int UP_BUTTON = 29;
private final int ROTATE_BUTTON = 28;
private final int HORIZONTAL = 0;
private final int VERTICAL = 1;
private final int FLIP = 2;
private final int ROTATE = 3;
private final int SELECTED = 4;
private final int SELECT_BUTTON = 5;
private HashMap<Integer, Integer> highlightButtons = new HashMap<>();
private final HashMap<Integer, Integer>[] pieces = new HashMap[3];
private final HashMap<Integer, Integer>[] solvedPieces = new HashMap[3];
public PuzzleStep(QuestHelper questHelper)
{
super(questHelper, "Click the highlighted boxes to move the pieces to the correct spots.");
pieces[0] = new HashMap<>();
pieces[0].put(HORIZONTAL, 876);
pieces[0].put(VERTICAL, 877);
pieces[0].put(FLIP, 878);
pieces[0].put(ROTATE, 879);
pieces[0].put(SELECTED, 261);
pieces[0].put(SELECT_BUTTON, 22);
solvedPieces[0] = new HashMap<>();
solvedPieces[0].put(HORIZONTAL, 40);
solvedPieces[0].put(VERTICAL, 30);
solvedPieces[0].put(FLIP, 1);
solvedPieces[0].put(ROTATE, 1);
pieces[1] = new HashMap<>();
pieces[1].put(HORIZONTAL, 880);
pieces[1].put(VERTICAL, 881);
pieces[1].put(FLIP, 882);
pieces[1].put(ROTATE, 883);
pieces[1].put(SELECTED, 262);
pieces[1].put(SELECT_BUTTON, 23);
solvedPieces[1] = new HashMap<>();
solvedPieces[1].put(HORIZONTAL, 35);
solvedPieces[1].put(VERTICAL, 35);
solvedPieces[1].put(FLIP, 1);
solvedPieces[1].put(ROTATE, 1);
pieces[2] = new HashMap<>();
pieces[2].put(HORIZONTAL, 884);
pieces[2].put(VERTICAL, 885);
pieces[2].put(FLIP, 886);
pieces[2].put(ROTATE, 887);
pieces[2].put(SELECTED, 263);
pieces[2].put(SELECT_BUTTON, 24);
solvedPieces[2] = new HashMap<>();
solvedPieces[2].put(HORIZONTAL, 35);
solvedPieces[2].put(VERTICAL, 35);
solvedPieces[2].put(FLIP, 1);
solvedPieces[2].put(ROTATE, 1);
highlightButtons.put(FLIP_BUTTON, 0);
highlightButtons.put(DOWN_BUTTON, 0);
highlightButtons.put(LEFT_BUTTON, 0);
highlightButtons.put(RIGHT_BUTTON, 0);
highlightButtons.put(UP_BUTTON, 0);
highlightButtons.put(ROTATE_BUTTON, 0);
int SELECT_1_BUTTON = 22;
highlightButtons.put(SELECT_1_BUTTON, 0);
int SELECT_2_BUTTON = 23;
highlightButtons.put(SELECT_2_BUTTON, 0);
int SELECT_3_BUTTON = 24;
highlightButtons.put(SELECT_3_BUTTON, 0);
}
@Override
public void startUp()
{
updateSolvedPositionState();
}
@Subscribe
public void onVarbitChanged(VarbitChanged varbitChanged)
{
updateSolvedPositionState();
}
private void updateSolvedPositionState()
{
int currentPiece;
HashMap<Integer, Integer>[] piecesCurrentState = new HashMap[3];
HashMap<Integer, Integer> highlightButtonsTmp = new HashMap<>();
piecesCurrentState[0] = new HashMap<>();
piecesCurrentState[0].put(HORIZONTAL, client.getVarpValue(pieces[0].get(HORIZONTAL)));
piecesCurrentState[0].put(VERTICAL, client.getVarpValue(pieces[0].get(VERTICAL)));
piecesCurrentState[0].put(FLIP, client.getVarpValue(pieces[0].get(FLIP)));
piecesCurrentState[0].put(ROTATE, client.getVarpValue(pieces[0].get(ROTATE)));
piecesCurrentState[1] = new HashMap<>();
piecesCurrentState[1].put(HORIZONTAL, client.getVarpValue(pieces[1].get(HORIZONTAL)));
piecesCurrentState[1].put(VERTICAL, client.getVarpValue(pieces[1].get(VERTICAL)));
piecesCurrentState[1].put(FLIP, client.getVarpValue(pieces[1].get(FLIP)));
piecesCurrentState[1].put(ROTATE, client.getVarpValue(pieces[1].get(ROTATE)));
piecesCurrentState[2] = new HashMap<>();
piecesCurrentState[2].put(HORIZONTAL, client.getVarpValue(pieces[2].get(HORIZONTAL)));
piecesCurrentState[2].put(VERTICAL, client.getVarpValue(pieces[2].get(VERTICAL)));
piecesCurrentState[2].put(FLIP, client.getVarpValue(pieces[2].get(FLIP)));
piecesCurrentState[2].put(ROTATE, client.getVarpValue(pieces[2].get(ROTATE)));
if (!piecesCurrentState[0].equals(solvedPieces[0]))
{
currentPiece = 0;
}
else if (!piecesCurrentState[1].equals(solvedPieces[1]))
{
currentPiece = 1;
}
else
{
currentPiece = 2;
}
boolean onlyCurrentSelected = true;
if (client.getVarpValue(pieces[currentPiece].get(SELECTED)) == 0)
{
highlightButtonsTmp.put(pieces[currentPiece].get(SELECT_BUTTON), 1);
onlyCurrentSelected = false;
}
if (client.getVarpValue(pieces[(currentPiece + 1) % 3].get(SELECTED)) == 1)
{
highlightButtonsTmp.put(pieces[(currentPiece + 1) % 3].get(SELECT_BUTTON), 1);
onlyCurrentSelected = false;
}
if (client.getVarpValue(pieces[Math.floorMod(currentPiece - 1, 3)].get(SELECTED)) == 1)
{
highlightButtonsTmp.put(pieces[Math.floorMod(currentPiece - 1, 3)].get(SELECT_BUTTON), 1);
onlyCurrentSelected = false;
}
if (onlyCurrentSelected)
{
if (!piecesCurrentState[currentPiece].get(FLIP).equals(solvedPieces[currentPiece].get(FLIP)))
{
highlightButtonsTmp.put(FLIP_BUTTON, 1);
}
else if (!piecesCurrentState[currentPiece].get(ROTATE).equals(solvedPieces[currentPiece].get(ROTATE)))
{
highlightButtonsTmp.put(ROTATE_BUTTON, 1);
}
else if (piecesCurrentState[currentPiece].get(HORIZONTAL) < solvedPieces[currentPiece].get(HORIZONTAL))
{
highlightButtonsTmp.put(RIGHT_BUTTON, 1);
}
else if (piecesCurrentState[currentPiece].get(HORIZONTAL) > solvedPieces[currentPiece].get(HORIZONTAL))
{
highlightButtonsTmp.put(LEFT_BUTTON, 1);
}
else if (piecesCurrentState[currentPiece].get(VERTICAL) > solvedPieces[currentPiece].get(VERTICAL))
{
highlightButtonsTmp.put(UP_BUTTON, 1);
}
else if (piecesCurrentState[currentPiece].get(VERTICAL) < solvedPieces[currentPiece].get(VERTICAL))
{
highlightButtonsTmp.put(DOWN_BUTTON, 1);
}
}
highlightButtons = highlightButtonsTmp;
}
@Override
public void makeWidgetOverlayHint(Graphics2D graphics, QuestHelperPlugin plugin)
{
super.makeWidgetOverlayHint(graphics, plugin);
for (Map.Entry<Integer, Integer> entry : highlightButtons.entrySet())
{
if (entry.getValue() == 0)
{
continue;
}
Widget widget = client.getWidget(462, entry.getKey());
if (widget != null)
{
graphics.setColor(new Color(0, 255, 255, 65));
graphics.fill(widget.getBounds());
graphics.setColor(Color.CYAN);
graphics.draw(widget.getBounds());
}
}
}
}
| [
"zoinkwiz@hotmail.co.uk"
] | zoinkwiz@hotmail.co.uk |
fe8fdeec2071ab418acbb15ff677b535a4501837 | a48519d35f10c8a895298da5d4a20c652f5e4684 | /MyWebsite/src/java/Dao1/OrderDAO.java | b48c3f94669f7d887ce388ecb786159f2d43d10a | [] | no_license | thanhphatsainin/code-THKHANH | ef95d3310d980b11e5fb65afabb1455322d5c7ba | aad0b91da2e0d293c0b6b1a1964e0ebafd368ed3 | refs/heads/master | 2023-05-04T13:01:48.793832 | 2021-05-23T14:02:38 | 2021-05-23T14:02:38 | 370,067,517 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,061 | java | /*
* 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 Dao1;
import Model.Article;
import Model.Cart;
import Model.Order;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
/**
*
* @author DELL
*/
public class OrderDAO extends DAO {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public OrderDAO() {
super();
}
public Order getOrderById(int key) {
Order order = new Order();
String sql = "SELECT * from `order` where id = ?";
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, key);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
order.setId(rs.getInt("id"));
Cart cart = new Cart();
CartDAO cartDAO = new CartDAO();
cart = cartDAO.getCartById(rs.getInt("cartId"));
order.setCart(cart);
order.setDateOder(rs.getDate("dateOrder"));
order.setTotal(cart.getTotal());
}
} catch (Exception e) {
e.printStackTrace();
}
return order;
}
public ArrayList<Order> getAllOrder() {
ArrayList<Order> result = new ArrayList<Order>();
//String sql = "SELECT * FROM article";
String sql = "SELECT * from `order`";
try {
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Order order = new Order();
order.setId(rs.getInt("id"));
Cart cart = new Cart();
CartDAO cartDAO = new CartDAO();
cart = cartDAO.getCartById(rs.getInt("cartId"));
order.setCart(cart);
order.setDateOder(rs.getDate("dateOrder"));
order.setTotal(cart.getTotal());
result.add(order);
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public void addOrder(Order Order) {
String sql = "INSERT INTO `order`(cartId, dateOrder) VALUES(?, ?)";
try {
PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setInt(1, Order.getCart().getId());
ps.setString(2, sdf.format(Order.getDateOder()));
ps.executeUpdate();
//get id of the new inserted Order
ResultSet generatedKeys = ps.getGeneratedKeys();
if (generatedKeys.next()) {
Order.setId(generatedKeys.getInt(1));
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* update the @Order
*
* @param Order
*/
public void editOrder(Order Order) {
String sql = "UPDATE `order` SET cartId=?, dateOrder=? WHERE id=?";
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, Order.getCart().getId());
ps.setString(2, sdf.format(Order.getDateOder()));
ps.setInt(3, Order.getId());
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* delete the Order whose id is @id
*
* @param id
*/
public void deleteOrder(int id) {
//String sql = "DELETE order, product FROM order, product WHERE order.id = product.orderId and order.id=?"; //sai
String sql1 ="Delete from `order` where id =?;";
try {
// sql1
PreparedStatement ps1 = con.prepareStatement(sql1);
ps1.setInt(1, id);
ps1.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| [
"namtc101099@gmail.com"
] | namtc101099@gmail.com |
0e50d19be986fefc55a65c92e6e9dec8642bc63f | 5f0230494255f093786a8d9fd486f044ccead5aa | /src/de/htw/grischa/chess/ChessBoard.java | 20dead63f5063c5539b61174276f24ee341989da | [] | no_license | jeins/grischa | dcb7701411a5e4e1a0d150e3eef1c1f9ccd7612a | 2906c56d32820b6d82ae05b6812f3179571771f8 | refs/heads/master | 2021-03-22T04:30:38.150037 | 2017-03-02T21:20:06 | 2017-03-02T21:20:06 | 105,343,335 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 74,138 | java | package de.htw.grischa.chess;
import de.htw.grischa.chess.database.client.DatabaseEntry;
import org.apache.log4j.Logger;
import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
/**
* Chessboard implementation, implements IChessGame
* <h3>Version History</h3>
* <ul>
* <li> 1.0 - 12/09 - Heim - Initial Version</li>
* <li> 1.? - 05/10 - Heim - ???</li>
* <li> 1.3 - 06/14 - Karsten Kochan - Added toDatabase method, added parent</li>
* </ul>
*
* @author Heim
* @version 1.3
* @see de.htw.grischa.chess.IChessGame
*/
public class ChessBoard implements IChessGame, Serializable {
public static final byte EMPTY_FIELD = 0;
public static final byte ILLEGAL_FIELD = -1;
public static final byte BLACK_PAWN = 2;
public static final byte BLACK_ROOK = 5;
public static final byte BLACK_KNIGHT = 3;
public static final byte BLACK_BISHOP = 4;
public static final byte BLACK_QUEEN = 6;
public static final byte BLACK_KING = 7;
public static final byte WHITE_PAWN = 12;
public static final byte WHITE_ROOK = 15;
public static final byte WHITE_KNIGHT = 13;
public static final byte WHITE_BISHOP = 14;
public static final byte WHITE_QUEEN = 16;
public static final byte WHITE_KING = 17;
/**
* Logger
*/
private final static Logger log = Logger.getLogger(ChessBoard.class);
private static final String[] NAMES = {"x", "", "B", "S", "L", "T", "D", "K", "", "", "", "",
"b", "s", "l", "t", "d", "k"};
private static final short[] QUALITIES = {0, 0, -1, -3, -3, -5, -9, -100, 0, 0, 0, 0, 1, 3, 3, 5, 9, 100};
private static final int[] ROOK_DIRECTIONS = {-10, -1, 1, 10};
private static final int[] KNIGHT_DIRECTIONS = {-21, -19, -8, 12, 21, 19, 8, -12};
private static final int[] BISHOP_DIRECTIONS = {-11, -9, 9, 11};
private static final int[] QUEEN_DIRECTIONS = {-11, -10, -9, -1, 1, 9, 10, 11};
public byte[] fields;
public boolean BlackCanLongRochade;
public boolean BlackCanShortRochade;
public boolean WhiteCanLongRochade;
public boolean WhiteCanShortRochade;
private Player playerToMakeTurn;
private ArrayList<IChessGame> entPassent;
//private ArrayList<IChessGame> nextTurns;
private int heuristicValue;
private String TurnNotation;
private int round_counter;
private boolean WhiteLost = false;
private boolean BlackLost = false;
private IChessGame parent;
/**
* Constructor
*/
public ChessBoard() {
fields = new byte[120];
this.initializeFields();
this.round_counter = 0;
playerToMakeTurn = Player.WHITE;
WhiteCanLongRochade = true;
WhiteCanShortRochade = true;
BlackCanLongRochade = true;
BlackCanShortRochade = true;
entPassent = new ArrayList<IChessGame>();
//BlackCanRochade=true;
//WhiteCanRochade=true;
}
/**
* Constructor from existing board
*
* @param oldBoard Chessboard to clone
*/
private ChessBoard(ChessBoard oldBoard) {
this.fields = oldBoard.fields.clone();
entPassent = new ArrayList<IChessGame>();
this.BlackCanLongRochade = oldBoard.BlackCanLongRochade;
this.BlackCanShortRochade = oldBoard.BlackCanShortRochade;
this.WhiteCanLongRochade = oldBoard.WhiteCanLongRochade;
this.WhiteCanShortRochade = oldBoard.WhiteCanShortRochade;
this.round_counter = oldBoard.round_counter + 1;
this.BlackLost = oldBoard.BlackLost;
this.WhiteLost = oldBoard.WhiteLost;
if (oldBoard.playerToMakeTurn == Player.BLACK) playerToMakeTurn = Player.WHITE;
else playerToMakeTurn = Player.BLACK;
}
/**
* Provides the standard starting position as Chessboard
*
* @return ChessBoard with starting position
*/
public static ChessBoard getStandardChessBoard() {
ChessBoard board = new ChessBoard();
for (int i = 31; i < 39; i++) {
board.fields[i] = WHITE_PAWN;
board.fields[i + 50] = BLACK_PAWN;
}
board.fields[21] = WHITE_ROOK;
board.fields[28] = WHITE_ROOK;
board.fields[22] = WHITE_KNIGHT;
board.fields[27] = WHITE_KNIGHT;
board.fields[23] = WHITE_BISHOP;
board.fields[26] = WHITE_BISHOP;
board.fields[24] = WHITE_QUEEN;
board.fields[25] = WHITE_KING;
board.fields[91] = BLACK_ROOK;
board.fields[98] = BLACK_ROOK;
board.fields[92] = BLACK_KNIGHT;
board.fields[97] = BLACK_KNIGHT;
board.fields[93] = BLACK_BISHOP;
board.fields[96] = BLACK_BISHOP;
board.fields[95] = BLACK_KING;
board.fields[94] = BLACK_QUEEN;
board.round_counter = 0;
return board;
}
/**
* Convert String representation of field into int value
*
* @param in String to convert
* @return int representation
* @throws java.lang.IllegalArgumentException if input String is invalid
*/
public static int fieldNameToIndex(String in) throws IllegalArgumentException {
int fieldColumn;
int fieldRow;
fieldColumn = (int) in.toCharArray()[0] - 'a' + 1;
fieldRow = Integer.parseInt(Character.toString(in.toCharArray()[1])) + 1;
if (fieldColumn < 0 || fieldColumn >= 8) {
log.warn("Could not convert " + in.toCharArray()[0]);
throw new IllegalArgumentException();
}
if (fieldRow < 0 || fieldRow >= 8) {
log.warn("Could not convert " + in.toCharArray()[1]);
throw new IllegalArgumentException();
}
return fieldColumn + fieldRow * 10;
}
/**
* Convert field by index to String representation
*
* @param in field index
* @return String representation
*/
public static String indexToFieldName(int in) {
int fieldColumn;
int fieldRow;
String columnName = "";
String rowName = "";
fieldRow = (in / 10) - 1;
fieldColumn = (in % 10) - 1;
char c = (char) ('a' + fieldColumn);
columnName += c;
rowName = rowName + fieldRow;
return columnName + rowName;
}
public Player getPlayerToMakeTurn() {
return playerToMakeTurn;
}
/**
* Setter playerToMakeTurn
*
* @param playerToMakeTurn player to set to
*/
public void setPlayerToMakeTurn(Player playerToMakeTurn) {
this.playerToMakeTurn = playerToMakeTurn;
}
/**
* Stellt eine Figur auf das Brett
*
* @param position Das Feld der Figur zwischen 0-59
* @param piece Die Figur, die auf das Brett gestellt wird -
* am besten Konstanten dieser Klasse nutzen
*/
public void PutPiece(int position, byte piece) throws Exception {
//*** Ungueltiges Feld beruecksichtigen ******************************************
if (position < 0 || position >= 64) throw new Exception(position + " nicht im Feld");
//TODO @Daniel ungueltige Figur abfangen
//*** linken und rechten rand beruecksichtigen ***********************************
int realPosition = position / 8 * 10;
realPosition += position % 8 + 1;
//*** unteren Rand ueberspringen *************************************************
realPosition += 20;
//*** Figur setzen ***************************************************************
fields[realPosition] = piece;
}
/************************************************************************************/
/************************* Prozedur: initializeFields *******************************/
/**
* ********************************************************************************
*/
public int parseField(int position) {
//*** linken und rechten rand beruecksichtigen ***********************************
int realPosition = position / 8 * 10;
realPosition += position % 8 + 1;
//*** unteren Rand ueberspringen *************************************************
realPosition += 20;
return realPosition;
}
/************************************************************************************/
/************************** Funktion: getNextTurns **********************************/
/**
* Gibt ein halbwegs lesbares Brett zur�ck schwarze Figuren sind gro�, wei�e
* klein geschrieben
*/
public String getReadableString() {
//*** Variablen-Deklaration ******************************************************
String s = "";
int i = 0;
for (int dy = 10; dy > 1; dy--) {
if (dy == 10) s += " ";
else s += dy - 1 + " ";
for (int dx = 1; dx < 9; dx++) {
if (dy == 10) s += (char) ('A' + dx - 1) + " ";
i = dy * 10 + dx;
//*** Figuren eintragen ******************************************************
switch (fields[i]) {
case (EMPTY_FIELD):
s += " ";
break;
case (BLACK_PAWN):
s += "B ";
break;
case (BLACK_KNIGHT):
s += "S ";
break;
case (BLACK_BISHOP):
s += "L ";
break;
case (BLACK_ROOK):
s += "T ";
break;
case (BLACK_QUEEN):
s += "D ";
break;
case (BLACK_KING):
s += "K ";
break;
case (WHITE_PAWN):
s += "b ";
break;
case (WHITE_KNIGHT):
s += "s ";
break;
case (WHITE_BISHOP):
s += "l ";
break;
case (WHITE_ROOK):
s += "t ";
break;
case (WHITE_QUEEN):
s += "d ";
break;
case (WHITE_KING):
s += "k ";
break;
}
}
s += "\n";
}
//*** String zurueckgeben ********************************************************
return s;
}
/************************************************************************************/
/************************** Funktion: makeBlackMoves ********************************/
/**
* ********************************************************************************
*/
private void initializeFields() {
//*** Einzelne Felder initializieren *********************************************
//*** Unterer Rand ***************************************************************
for (int i = 0; i < 20; i++) {
fields[i] = ChessBoard.ILLEGAL_FIELD;
}
//*** Mittlerer Teil mit leeren Feldern ******************************************
for (int i = 20; i < 100; i++) {
if (i % 10 == 0 || i % 10 == 9) fields[i] = ChessBoard.ILLEGAL_FIELD;
else fields[i] = ChessBoard.EMPTY_FIELD;
}
//*** Oberer Rand ****************************************************************
for (int i = 100; i < 120; i++) {
fields[i] = ChessBoard.ILLEGAL_FIELD;
}
}
/************************************************************************************/
/************************** Funktion: makeWhiteMoves ********************************/
/**
* ********************************************************************************
*/
public ArrayList<IChessGame> getNextTurns() {
// if(nextTurns!=null) return nextTurns;
if (playerToMakeTurn == Player.WHITE) {
return this.makeWhiteMoves();
} else {
return this.makeBlackMoves();
}
}
/************************************************************************************/
/************************ Funktion: makeBlackPawnMove *******************************/
/**
* ********************************************************************************
*/
private ArrayList<IChessGame> makeWhiteMoves() {
//*** Variablen-Deklaration ******************************************************
int field;
byte piece;
ArrayList<IChessGame> moves;
//*** Liste initialisieren *******************************************************
moves = new ArrayList<IChessGame>();
//*** F�r alle legalen Felder ****************************************************
for (int y = 2; y < 10; y++)
for (int x = 1; x < 9; x++) {
//*** Feldindex bestimmen ****************************************************
field = y * 10 + x;
//*** Figur bestimmen ********************************************************
piece = fields[field];
//*** Auf Fels ist leer undgueltig und von schwarz besetzt ragieren **********
if (piece < WHITE_PAWN) continue;
//*** Bauern Zug machen ******************************************************
if (piece == WHITE_PAWN) {
moves.addAll(this.makeWhitePawnMove(field));
continue;
}
//*** Turm Zug machen ********************************************************
if (piece == WHITE_ROOK) {
moves.addAll(this.genericWhiteMoves(field, ROOK_DIRECTIONS, piece));
continue;
}
//*** Laeufer Zug machen *****************************************************
if (piece == WHITE_BISHOP) {
moves.addAll(this.genericWhiteMoves(field, BISHOP_DIRECTIONS, piece));
continue;
}
//*** Springer ziehen ********************************************************
if (piece == WHITE_KNIGHT) {
moves.addAll(this.whiteSingleMove(field, KNIGHT_DIRECTIONS, piece));
continue;
}
//*** Koenig ziehen **********************************************************
if (piece == WHITE_KING) {
moves.addAll(this.whiteSingleMove(field, QUEEN_DIRECTIONS, piece));
continue;
}
//*** Dame ziehen ************************************************************
if (piece == WHITE_QUEEN) {
moves.addAll(this.genericWhiteMoves(field, QUEEN_DIRECTIONS, piece));
}
}
moves.addAll(entPassent);
moves.addAll(this.getWhiteRochade());
//** Züge merken *******************************************************
//nextTurns=moves;
//*** Zuege zurueckgeben *********************************************************
return moves;
}
/************************************************************************************/
/************************ Funktion: makeWhitePawnMove *******************************/
/**
* ********************************************************************************
*/
private ArrayList<IChessGame> makeBlackMoves() {
//*** Variablen-Deklaration ******************************************************
int field;
byte piece;
ArrayList<IChessGame> moves;
//*** Liste initialisieren *******************************************************
moves = new ArrayList<IChessGame>();
//*** F�r alle legalen Felder ****************************************************
for (int y = 2; y < 10; y++)
for (int x = 1; x < 9; x++) {
//*** Feldindex bestimmen ****************************************************
field = y * 10 + x;
//*** Figur bestimmen ********************************************************
piece = fields[field];
//*** Auf Fels ist leer undgueltig und von wei� besetzt ragieren *************
if (piece < BLACK_PAWN && piece >= BLACK_KING) continue;
//*** Bauern Zug machen ******************************************************
if (piece == BLACK_PAWN) {
moves.addAll(this.makeBlackPawnMove(field));
continue;
}
//*** Turm ziehen ************************************************************
if (piece == BLACK_ROOK) {
moves.addAll(this.genericBlackMoves(field, ROOK_DIRECTIONS, piece));
continue;
}
//*** Laeufer Zug machen *****************************************************
if (piece == BLACK_BISHOP) {
moves.addAll(this.genericBlackMoves(field, BISHOP_DIRECTIONS, piece));
continue;
}
//*** Springer ziehen ********************************************************
if (piece == BLACK_KNIGHT) {
moves.addAll(this.blackSingleMove(field, KNIGHT_DIRECTIONS, piece));
continue;
}
//*** Koenig ziehen **********************************************************
if (piece == BLACK_KING) {
moves.addAll(this.blackSingleMove(field, QUEEN_DIRECTIONS, piece));
continue;
}
//*** Dame ziehen ************************************************************
if (piece == BLACK_QUEEN) {
moves.addAll(this.genericBlackMoves(field, QUEEN_DIRECTIONS, piece));
}
}
moves.addAll(entPassent);
moves.addAll(this.getBlackRochade());
//** Züge merken *******************************************************
// nextTurns=moves;
//*** Zuege zurueckgeben *********************************************************
return moves;
}
/************************************************************************************/
/************************* Funktion: genericWhiteMoves ******************************/
/**
* ********************************************************************************
*/
private ArrayList<ChessBoard> makeBlackPawnMove(int field) {
//*** Variablen-Deklaration ******************************************************
ArrayList<ChessBoard> followMoves;
ChessBoard board;
//*** Liste initialisieren *******************************************************
followMoves = new ArrayList<ChessBoard>();
//*** Bauer in vorletzter Reihe **************************************************
if (field < 40) {
//*** Wurf �berpr�fen ********************************************************
if (fields[field - 9] > ChessBoard.BLACK_KING) {
board = this.executeMove(field, field - 9, ChessBoard.BLACK_PAWN);
//*** Figurentausch durchf�hren ******************************************
ChessBoard b;
b = board.Clone();
b.fields[field - 9] = BLACK_BISHOP;
b.TurnNotation = ChessBoard.indexToFieldName(field) +
ChessBoard.indexToFieldName(field - 9) + "b";
followMoves.add(b);
b = board.Clone();
b.fields[field - 9] = BLACK_ROOK;
b.TurnNotation = ChessBoard.indexToFieldName(field) +
ChessBoard.indexToFieldName(field - 9) + "r";
followMoves.add(b);
b = board.Clone();
b.fields[field - 9] = BLACK_KNIGHT;
b.TurnNotation = ChessBoard.indexToFieldName(field) +
ChessBoard.indexToFieldName(field - 9) + "n";
followMoves.add(b);
b = board.Clone();
b.fields[field - 9] = BLACK_QUEEN;
b.TurnNotation = ChessBoard.indexToFieldName(field) +
ChessBoard.indexToFieldName(field - 9) + "q";
followMoves.add(b);
}
//*** Wurf in andere Richtung �berpr�fen *************************************
if (fields[field - 11] > ChessBoard.BLACK_KING) {
board = this.executeMove(field, field - 11, ChessBoard.BLACK_PAWN);
//*** Figurentausch durchf�hren ******************************************
ChessBoard b;
b = board.Clone();
b.fields[field - 11] = BLACK_BISHOP;
b.TurnNotation = ChessBoard.indexToFieldName(field) +
ChessBoard.indexToFieldName(field - 11) + "b";
followMoves.add(b);
b = board.Clone();
b.fields[field - 11] = BLACK_ROOK;
b.TurnNotation = ChessBoard.indexToFieldName(field) +
ChessBoard.indexToFieldName(field - 11) + "r";
followMoves.add(b);
b = board.Clone();
b.fields[field - 11] = BLACK_KNIGHT;
b.TurnNotation = ChessBoard.indexToFieldName(field) +
ChessBoard.indexToFieldName(field - 11) + "n";
followMoves.add(b);
b = board.Clone();
b.fields[field - 11] = BLACK_QUEEN;
b.TurnNotation = ChessBoard.indexToFieldName(field) +
ChessBoard.indexToFieldName(field - 11) + "q";
followMoves.add(b);
}
//*** Gerade aus Zug pr�fen **************************************************
if (fields[field - 10] == ChessBoard.EMPTY_FIELD) {
board = this.executeMove(field, field - 10, ChessBoard.BLACK_PAWN);
//*** Figurentausch durchf�hren ******************************************
ChessBoard b;
b = board.Clone();
b.fields[field - 10] = BLACK_BISHOP;
b.TurnNotation = ChessBoard.indexToFieldName(field) +
ChessBoard.indexToFieldName(field - 10) + "b";
followMoves.add(b);
b = board.Clone();
b.fields[field - 10] = BLACK_ROOK;
b.TurnNotation = ChessBoard.indexToFieldName(field) +
ChessBoard.indexToFieldName(field - 10) + "r";
followMoves.add(b);
b = board.Clone();
b.fields[field - 10] = BLACK_KNIGHT;
b.TurnNotation = ChessBoard.indexToFieldName(field) +
ChessBoard.indexToFieldName(field - 10) + "n";
followMoves.add(b);
b = board.Clone();
b.fields[field - 10] = BLACK_QUEEN;
b.TurnNotation = ChessBoard.indexToFieldName(field) +
ChessBoard.indexToFieldName(field - 10) + "q";
followMoves.add(b);
} else return followMoves;
} else {
//*** Wurf �berpr�fen ********************************************************
if (fields[field - 9] > ChessBoard.BLACK_KING) {
board = this.executeMove(field, field - 9, ChessBoard.BLACK_PAWN);
followMoves.add(board);
}
//*** Wurf in andere Richtung �berpr�fen *************************************
if (fields[field - 11] > ChessBoard.BLACK_KING) {
board = this.executeMove(field, field - 11, ChessBoard.BLACK_PAWN);
followMoves.add(board);
}
//*** Gerade aus Zug pr�fen **************************************************
if (fields[field - 10] == ChessBoard.EMPTY_FIELD) {
board = this.executeMove(field, field - 10, ChessBoard.BLACK_PAWN);
followMoves.add(board);
} else return followMoves;
}
//*** Wenn gerade aus Zug moeglich war auch doppelt geradeaus pruefen ************
if (field / 10 == 8 && fields[field - 20] == ChessBoard.EMPTY_FIELD) {
board = this.executeMove(field, field - 20, ChessBoard.BLACK_PAWN);
//*** En Passent schlagen bearbeiten *****************************************
if (fields[field - 19] == ChessBoard.WHITE_PAWN) {
ChessBoard newBoard = new ChessBoard(board);
newBoard.fields[field - 20] = ChessBoard.EMPTY_FIELD;
newBoard.fields[field - 19] = ChessBoard.EMPTY_FIELD;
newBoard.fields[field - 10] = ChessBoard.WHITE_PAWN;
newBoard.TurnNotation = ChessBoard.indexToFieldName(field - 19) +
ChessBoard.indexToFieldName(field - 10);
board.entPassent.add(newBoard);
}
if (fields[field - 21] == ChessBoard.WHITE_PAWN) {
ChessBoard newBoard = new ChessBoard(board);
newBoard.fields[field - 20] = ChessBoard.EMPTY_FIELD;
newBoard.fields[field - 21] = ChessBoard.EMPTY_FIELD;
newBoard.fields[field - 10] = ChessBoard.WHITE_PAWN;
newBoard.TurnNotation = ChessBoard.indexToFieldName(field - 21) +
ChessBoard.indexToFieldName(field - 10);
board.entPassent.add(newBoard);
}
followMoves.add(board);
}
//*** Liste zur�ckgeben **********************************************************
return followMoves;
}
/************************************************************************************/
/************************* Funktion: genericBlackMoves ******************************/
/**
* ********************************************************************************
*/
private ArrayList<ChessBoard> makeWhitePawnMove(int field) {
//*** Variablen-Deklaration ******************************************************
ArrayList<ChessBoard> followMoves;
ChessBoard board;
//*** Liste initialisieren *******************************************************
followMoves = new ArrayList<ChessBoard>();
//*** Bauer in vorletzter Reihe **************************************************
if (field > 79) {
//*** Wurf �berpr�fen ********************************************************
if (fields[field + 9] > ChessBoard.EMPTY_FIELD && fields[field + 9] < ChessBoard.WHITE_PAWN) {
board = this.executeMove(field, field + 9, ChessBoard.WHITE_PAWN);
//*** Figurentausch durchf�hren ******************************************
ChessBoard b;
b = board.Clone();
b.fields[field + 9] = WHITE_BISHOP;
b.TurnNotation = ChessBoard.indexToFieldName(field) +
ChessBoard.indexToFieldName(field + 9) + "b";
followMoves.add(b);
b = board.Clone();
b.fields[field + 9] = WHITE_ROOK;
b.TurnNotation = ChessBoard.indexToFieldName(field) +
ChessBoard.indexToFieldName(field + 9) + "r";
followMoves.add(b);
b = board.Clone();
b.fields[field + 9] = WHITE_KNIGHT;
b.TurnNotation = ChessBoard.indexToFieldName(field) +
ChessBoard.indexToFieldName(field + 9) + "n";
followMoves.add(b);
b = board.Clone();
b.fields[field + 9] = WHITE_QUEEN;
b.TurnNotation = ChessBoard.indexToFieldName(field) +
ChessBoard.indexToFieldName(field + 9) + "q";
followMoves.add(b);
}
//*** Wurf in andere Richtung �berpr�fen *************************************
if (fields[field + 11] > ChessBoard.EMPTY_FIELD && fields[field + 11] < ChessBoard.WHITE_PAWN) {
board = this.executeMove(field, field + 11, ChessBoard.WHITE_PAWN);
//*** Figurentausch durchf�hren ******************************************
ChessBoard b;
b = board.Clone();
b.fields[field + 11] = WHITE_BISHOP;
b.TurnNotation = ChessBoard.indexToFieldName(field) +
ChessBoard.indexToFieldName(field + 11) + "b";
followMoves.add(b);
b = board.Clone();
b.fields[field + 11] = WHITE_ROOK;
b.TurnNotation = ChessBoard.indexToFieldName(field) +
ChessBoard.indexToFieldName(field + 11) + "r";
followMoves.add(b);
b = board.Clone();
b.fields[field + 11] = WHITE_KNIGHT;
b.TurnNotation = ChessBoard.indexToFieldName(field) +
ChessBoard.indexToFieldName(field + 11) + "n";
followMoves.add(b);
b = board.Clone();
b.fields[field + 11] = WHITE_QUEEN;
b.TurnNotation = ChessBoard.indexToFieldName(field) +
ChessBoard.indexToFieldName(field + 11) + "q";
followMoves.add(b);
}
//*** Gerade aus Zug pr�fen **************************************************
if (fields[field + 10] == ChessBoard.EMPTY_FIELD) {
board = this.executeMove(field, field + 10, ChessBoard.WHITE_PAWN);
//*** Figurentausch durchf�hren ******************************************
ChessBoard b;
b = board.Clone();
b.fields[field + 10] = WHITE_BISHOP;
b.TurnNotation = ChessBoard.indexToFieldName(field) +
ChessBoard.indexToFieldName(field + 10) + "b";
followMoves.add(b);
b = board.Clone();
b.fields[field + 10] = WHITE_ROOK;
b.TurnNotation = ChessBoard.indexToFieldName(field) +
ChessBoard.indexToFieldName(field + 10) + "r";
followMoves.add(b);
b = board.Clone();
b.fields[field + 10] = WHITE_KNIGHT;
b.TurnNotation = ChessBoard.indexToFieldName(field) +
ChessBoard.indexToFieldName(field + 10) + "n";
followMoves.add(b);
b = board.Clone();
b.fields[field + 10] = WHITE_QUEEN;
b.TurnNotation = ChessBoard.indexToFieldName(field) +
ChessBoard.indexToFieldName(field + 10) + "q";
followMoves.add(b);
} else return followMoves;
} else {
//*** Wurf �berpr�fen ********************************************************
if (fields[field + 9] > EMPTY_FIELD && fields[field + 9] < ChessBoard.WHITE_PAWN) {
board = this.executeMove(field, field + 9, ChessBoard.WHITE_PAWN);
followMoves.add(board);
}
//*** Wurf in andere Richtung �berpr�fen *************************************
if (fields[field + 11] > EMPTY_FIELD && fields[field + 11] < ChessBoard.WHITE_PAWN) {
board = this.executeMove(field, field + 11, ChessBoard.WHITE_PAWN);
followMoves.add(board);
}
//*** Gerade aus Zug pr�fen **************************************************
if (fields[field + 10] == ChessBoard.EMPTY_FIELD) {
board = this.executeMove(field, field + 10, ChessBoard.WHITE_PAWN);
followMoves.add(board);
} else return followMoves;
}
//*** Wenn gerade aus Zug moeglich war auch doppelt geradeaus pruefen ************
if (field / 10 == 3 && fields[field + 20] == ChessBoard.EMPTY_FIELD) {
board = this.executeMove(field, field + 20, ChessBoard.WHITE_PAWN);
//*** En Passent schlagen bearbeiten *****************************************
if (fields[field + 19] == ChessBoard.BLACK_PAWN) {
ChessBoard newBoard = new ChessBoard(board);
newBoard.fields[field + 20] = ChessBoard.EMPTY_FIELD;
newBoard.fields[field + 19] = ChessBoard.EMPTY_FIELD;
newBoard.fields[field + 10] = ChessBoard.BLACK_PAWN;
newBoard.TurnNotation = ChessBoard.indexToFieldName(field + 19) +
ChessBoard.indexToFieldName(field + 10);
board.entPassent.add(newBoard);
}
if (fields[field + 21] == ChessBoard.BLACK_PAWN) {
ChessBoard newBoard = new ChessBoard(board);
newBoard.fields[field + 20] = ChessBoard.EMPTY_FIELD;
newBoard.fields[field + 21] = ChessBoard.EMPTY_FIELD;
newBoard.fields[field + 10] = ChessBoard.BLACK_PAWN;
newBoard.TurnNotation = ChessBoard.indexToFieldName(field + 21) +
ChessBoard.indexToFieldName(field + 10);
board.entPassent.add(newBoard);
}
followMoves.add(board);
}
//*** Liste zur�ckgeben **********************************************************
return followMoves;
}
/************************************************************************************/
/************************** Funktion: whiteSingleMove *******************************/
/**
* ********************************************************************************
*/
private ArrayList<ChessBoard> genericWhiteMoves(int field, int[] directions, byte piece) {
//*** Variablen-Deklaration ******************************************************
ArrayList<ChessBoard> followMoves;
ChessBoard board;
int i = 0;
int newField;
//*** Liste initialisieren *******************************************************
followMoves = new ArrayList<ChessBoard>();
//*** F�r alle Richtungen ********************************************************
while (i < directions.length) {
//*** n�chstes Feld bestimmen ************************************************
newField = field + directions[i];
//*** Solange n�chstes Feld frei ist *****************************************
while (fields[newField] == EMPTY_FIELD) {
//*** Zug ausf�hren ******************************************************
board = this.executeMove(field, newField, piece);
followMoves.add(board);
//*** n�chstes Feld bestimmen ********************************************
newField = newField + directions[i];
}
//*** Neues Feld ist kein leeres Feld mehr und weder illegal noch wei� *******
if (fields[newField] != ILLEGAL_FIELD && fields[newField] < WHITE_PAWN) {
board = this.executeMove(field, newField, piece);
followMoves.add(board);
}
//*** Richtungsz�hler erh�hen ************************************************
i++;
}
//*** Liste zur�ckgeben **********************************************************
return followMoves;
}
/************************************************************************************/
/************************* Funktion: blackSingleMove ********************************/
/**
* ********************************************************************************
*/
private ArrayList<ChessBoard> genericBlackMoves(int field, int[] directions, byte piece) {
//*** Variablen-Deklaration ******************************************************
ArrayList<ChessBoard> followMoves;
ChessBoard board;
int i = 0;
int newField;
//*** Liste initialisieren *******************************************************
followMoves = new ArrayList<ChessBoard>();
//*** F�r alle Richtungen ********************************************************
while (i < directions.length) {
//*** n�chstes Feld bestimmen ************************************************
newField = field + directions[i];
//*** Solange n�chstes Feld frei ist *****************************************
while (fields[newField] == EMPTY_FIELD) {
//*** Zug ausf�hren ******************************************************
board = this.executeMove(field, newField, piece);
followMoves.add(board);
//*** n�chstes Feld bestimmen ********************************************
newField = newField + directions[i];
}
//*** Neues Feld ist kein leeres Feld mehr und weder illegal noch schwarz ****
if (fields[newField] > BLACK_KING) {
board = this.executeMove(field, newField, piece);
followMoves.add(board);
}
//*** Richtungsz�hler erh�hen ************************************************
i++;
}
//*** Liste zur�ckgeben **********************************************************
return followMoves;
}
/************************************************************************************/
/*************************** Funktion: executeMove **********************************/
/**
* ********************************************************************************
*/
private ArrayList<ChessBoard> whiteSingleMove(int field, int[] directions, byte piece) {
//*** Variablen-Deklaration ******************************************************
ArrayList<ChessBoard> followMoves;
ChessBoard board;
int i = 0;
int newField;
//*** Liste initialisieren *******************************************************
followMoves = new ArrayList<ChessBoard>();
//*** F�r alle Richtungen ********************************************************
while (i < directions.length) {
//*** n�chstes Feld bestimmen ************************************************
newField = field + directions[i];
//*** Neues Feld ist kein leeres Feld und weder illegal noch wei� ************
if (fields[newField] != ILLEGAL_FIELD && fields[newField] < WHITE_PAWN) {
board = this.executeMove(field, newField, piece);
followMoves.add(board);
}
//*** Richtungsz�hler erh�hen ************************************************
i++;
}
//*** Liste zur�ckgeben **********************************************************
return followMoves;
}
/************************************************************************************/
/*************************** Funktion: getQuality ***********************************/
/**
* ********************************************************************************
*/
private ArrayList<ChessBoard> blackSingleMove(int field, int[] directions, byte piece) {
//*** Variablen-Deklaration ******************************************************
ArrayList<ChessBoard> followMoves;
ChessBoard board;
int i = 0;
int newField;
//*** Liste initialisieren *******************************************************
followMoves = new ArrayList<ChessBoard>();
//*** F�r alle Richtungen ********************************************************
while (i < directions.length) {
//*** n�chstes Feld bestimmen ************************************************
newField = field + directions[i];
//*** Neues Feld ist kein leeres Feld und weder illegal noch schwarz *********
if (fields[newField] > BLACK_KING || fields[newField] == EMPTY_FIELD) {
board = this.executeMove(field, newField, piece);
followMoves.add(board);
}
//*** Richtungsz�hler erh�hen ************************************************
i++;
}
//*** Liste zur�ckgeben **********************************************************
return followMoves;
}
/************************************************************************************/
/********************** Funktion: getStringRepresentation ***************************/
/**
* ********************************************************************************
*/
private ChessBoard executeMove(int oldField, int newField, byte piece) {
//*** Variablen-Deklaration ******************************************************
ChessBoard board;
//*** Zug vornehmen **************************************************************
board = new ChessBoard(this);
board.fields[oldField] = ChessBoard.EMPTY_FIELD;
if (board.fields[newField] == BLACK_KING) board.BlackLost = true;
if (board.fields[newField] == WHITE_KING) board.WhiteLost = true;
board.fields[newField] = piece;
board.TurnNotation = ChessBoard.indexToFieldName(oldField) +
ChessBoard.indexToFieldName(newField);
//*** Rochade m�glickeite testen *************************************************
if (piece == WHITE_ROOK) {
if (oldField == 21) board.WhiteCanLongRochade = false;
if (oldField == 28) board.WhiteCanShortRochade = false;
}
if (piece == WHITE_KING) {
board.WhiteCanLongRochade = false;
board.WhiteCanShortRochade = false;
}
if (piece == BLACK_ROOK) {
if (oldField == 91) board.BlackCanLongRochade = false;
if (oldField == 98) board.BlackCanShortRochade = false;
}
if (piece == BLACK_KING) {
board.BlackCanLongRochade = false;
board.BlackCanShortRochade = false;
}
//*** Brett zurueckgeben *********************************************************
return board;
}
/************************************************************************************/
/************************** Funktion: loadFromString ********************************/
/**
* ********************************************************************************
*/
public int getQuality(Player player) {
//*** Variablen-Deklaration ******************************************************
int field;
int quality = 0;
//*** Fuer alle legalen Felder ****************************************************
for (int y = 2; y < 10; y++)
for (int x = 1; x < 9; x++) {
//*** Feldindex bestimmen ****************************************************
field = y * 10 + x;
//*** Bei leerem oder ungueltigem Feld naechstes Feld ************************
if (fields[field] <= EMPTY_FIELD) continue;
//*** Qualitaet entsprechend der Figuren Qualiteat (Array Index) anpassen *****
quality += QUALITIES[fields[field]];
}
//*** Aus Sicht von Schwarz Qualitaets Vorzeichen aendern *************************
if (player == Player.BLACK) quality *= -1;
//*** Wert zurueckgeben **********************************************************
return quality;
}
/************************************************************************************/
/********************** Funktion: getHash *******************************************/
/**
* ********************************************************************************
*/
public String getStringRepresentation() {
String game = "";
int field;
for (int y = 2; y < 10; y++)
for (int x = 1; x < 9; x++) {
//*** Feldindex bestimmen ****************************************************
field = y * 10 + x;
game += NAMES[fields[field]];
}
if (playerToMakeTurn == Player.WHITE) game += "w";
else game += "S";
return game;
}
/************************************************************************************/
/****************************** Funktion: makeTurn **********************************/
/**
* ********************************************************************************
*/
public void loadFromString(String s) {
char[] c = new char[65];
c = s.toCharArray();
int j = 0;
if (c[64] == 'w') {
playerToMakeTurn = Player.WHITE;
c[64] = ' ';
} else {
playerToMakeTurn = Player.BLACK;
c[64] = ' ';
}
for (int i = 0; i < 120; i++) {
if (i > 98 || i < 21 || i % 10 == 0 || i % 10 == 9) {
fields[i] = ILLEGAL_FIELD;
} else
switch (c[j]) {
case ('x'):
fields[i] = EMPTY_FIELD;
j++;
break;
case ('b'):
fields[i] = WHITE_PAWN;
j++;
break;
case ('B'):
fields[i] = BLACK_PAWN;
j++;
break;
case ('t'):
fields[i] = WHITE_ROOK;
j++;
break;
case ('T'):
fields[i] = BLACK_ROOK;
j++;
break;
case ('s'):
fields[i] = WHITE_KNIGHT;
j++;
break;
case ('S'):
fields[i] = BLACK_KNIGHT;
j++;
break;
case ('l'):
fields[i] = WHITE_BISHOP;
j++;
break;
case ('L'):
fields[i] = BLACK_BISHOP;
j++;
break;
case ('d'):
fields[i] = WHITE_QUEEN;
j++;
break;
case ('D'):
fields[i] = BLACK_QUEEN;
j++;
break;
case ('k'):
fields[i] = WHITE_KING;
j++;
break;
case ('K'):
fields[i] = BLACK_KING;
j++;
break;
}
}
}
/************************************************************************************/
/*************************** Funktion: isLegalMove **********************************/
/**
* ********************************************************************************
*/
public String getHash() {
//*** Variablen-Deklaration ******************************************************
String hash = "";
int empty = 0;
int field;
//*** F�r alle legalen Felder ****************************************************
for (int y = 2; y < 10; y++)
for (int x = 1; x < 9; x++) {
//*** Feldindex bestimmen ****************************************************
field = y * 10 + x;
//*** Bei leerem oder ungueltigem Feld leere Felder **************************
if (fields[field] <= EMPTY_FIELD) empty++;
else {
if (empty >= 2) hash += empty + "m";
else if (empty == 1) hash += "l";
empty = 0;
hash += fields[field];
}
}
//*** Wert zurueckgeben **********************************************************
return hash;
}
/************************************************************************************/
/****************************** Funktion: equals ************************************/
/**
* ********************************************************************************
*/
public IChessGame makeTurn(String turn) throws Exception {
ArrayList<IChessGame> nextTurns = this.getNextTurns();
for (int i = 0; i < nextTurns.size(); i++) {
if (turn.equals(nextTurns.get(i).getTurnNotation())) {
return nextTurns.get(i);
}
}
throw new Exception(turn + " :Zug nicht in Liste legaler Z�ge gefunden;");
}
/************************************************************************************/
/****************************** Funktion: fieldNameToIndex **************************/
/**
* ********************************************************************************
*/
public boolean isLegalMove(ChessBoard board) {
//*** Variablen Deklaration ******************************************************
ArrayList<IChessGame> nextBoards;
//*** Folge Zuege berechnen ******************************************************
nextBoards = this.getNextTurns();
//*** Pr�fen ob Brett unter den Folge z�gen **************************************
for (int i = 0; i < nextBoards.size(); i++) {
if (((ChessBoard) nextBoards.get(i)).equals(board)) return true;
}
return false;
}
/************************************************************************************/
/****************************** Funktion: indexToFieldName ***************************/
/**
* ********************************************************************************
*/
public boolean equals(ChessBoard board) {
for (int i = 0; i < this.fields.length; i++) {
if (board.fields[i] != this.fields[i]) return false;
}
if (this.playerToMakeTurn != board.playerToMakeTurn) return false;
return true;
}
/************************************************************************************/
/******************************* Funktion: Clone ************************************/
/**
* ********************************************************************************
*/
private ChessBoard Clone() {
ChessBoard board = new ChessBoard();
board.fields = this.fields.clone();
board.playerToMakeTurn = this.playerToMakeTurn;
board.BlackCanLongRochade = this.BlackCanLongRochade;
board.BlackCanShortRochade = this.BlackCanShortRochade;
board.WhiteCanLongRochade = this.WhiteCanLongRochade;
board.WhiteCanShortRochade = this.WhiteCanShortRochade;
board.entPassent = new ArrayList<IChessGame>();
board.entPassent.addAll(this.entPassent);
return board;
}
/************************************************************************************/
/************************** Funktion: getWhiteRochade *******************************/
/**
* ********************************************************************************
*/
ArrayList<IChessGame> getWhiteRochade() {
//*** Variablen-Deklaration ******************************************************
ArrayList<IChessGame> rochadeList;
int field;
//*** Liste initialisieren *******************************************************
rochadeList = new ArrayList<IChessGame>();
//*** Testen ob kurze Rochade m�glich ********************************************
if (WhiteCanShortRochade) {
//*** Wenn Felder zwischen Turm und K�nig leer und Turm da ********************
if (fields[26] == EMPTY_FIELD && fields[27] == EMPTY_FIELD && fields[28] == WHITE_ROOK) {
field = 25;
//*** Testen ob ein Feld angegriffen wird ********************************
while (field < 28 && !IsFieldAttackedByBlack(field)) {
field++;
}
//*** Wenn kein Feld angegriffen wurde ***********************************
if (field == 28) {
//*** Rochieren ******************************************************
ChessBoard b = this.Clone();
b.fields[26] = ChessBoard.WHITE_ROOK;
b.fields[27] = ChessBoard.WHITE_KING;
b.fields[25] = ChessBoard.EMPTY_FIELD;
b.fields[28] = ChessBoard.EMPTY_FIELD;
b.TurnNotation = "e1g1";
b.WhiteCanLongRochade = false;
b.WhiteCanShortRochade = false;
b.playerToMakeTurn = Player.BLACK;
rochadeList.add(b);
}
}
}
if (WhiteCanLongRochade) {
//*** Wenn Felder zwischen Turm und K�nig leer und Turm da ************************
if (fields[24] == EMPTY_FIELD && fields[23] == EMPTY_FIELD && fields[22] == EMPTY_FIELD && fields[21] == WHITE_ROOK) {
field = 25;
//*** Testen ob ein Feld angegriffen wird ********************************
while (field > 22 && !IsFieldAttackedByBlack(field)) {
field--;
}
//*** Wenn kein Feld angegriffen wurde ***********************************
if (field == 22) {
//*** Rochieren ******************************************************
ChessBoard b = this.Clone();
b.fields[24] = ChessBoard.WHITE_ROOK;
b.fields[23] = ChessBoard.WHITE_KING;
b.fields[25] = ChessBoard.EMPTY_FIELD;
b.fields[21] = ChessBoard.EMPTY_FIELD;
b.TurnNotation = "e1c1";
b.WhiteCanLongRochade = false;
b.WhiteCanShortRochade = false;
b.playerToMakeTurn = Player.BLACK;
rochadeList.add(b);
}
}
}
//*** Liste zur�ckgeben **********************************************************
return rochadeList;
}
/************************************************************************************/
/*********************** Funktion: IsFieldAttackedByBlack ***************************/
/**
* ********************************************************************************
*/
public boolean IsFieldAttackedByBlack(int field) {
//*** Variablen-Deklaration ******************************************************
byte piece;
int u;
//*** Testen ob Bauer werfen kann ************************************************
if (fields[field + 9] == BLACK_PAWN || fields[field + 11] == BLACK_PAWN) return true;
//*** Testen ob Springer werfen kann *********************************************
for (int i = 0; i < KNIGHT_DIRECTIONS.length; i++) {
if (fields[field + KNIGHT_DIRECTIONS[i]] == BLACK_KNIGHT) return true;
}
//*** Turm Richtungen testen *****************************************************
for (int i = 0; i < ROOK_DIRECTIONS.length; i++) {
u = 1;
while ((piece = fields[field + ROOK_DIRECTIONS[i] * u]) == EMPTY_FIELD) u++;
//*** Wenn in Sicht von Turm oder Dame - wird angegriffen ********************
if (piece == BLACK_QUEEN || piece == BLACK_ROOK) return true;
//*** Wenn K�nig nur eins weit weg ist - wird angegriffen ********************
if (piece == BLACK_KING && u == 1) return true;
}
//*** Turm Richtungen testen *****************************************************
for (int i = 0; i < ChessBoard.BISHOP_DIRECTIONS.length; i++) {
u = 1;
while ((piece = fields[field + BISHOP_DIRECTIONS[i] * u]) == EMPTY_FIELD) u++;
//*** Wenn in Sicht von Turm oder Dame - wird angegriffen ********************
if (piece == BLACK_QUEEN || piece == BLACK_BISHOP) return true;
//*** Wenn K�nig nur eins weit weg ist - wird angegriffen ********************
if (piece == BLACK_KING && u == 1) return true;
}
//*** Default: false *************************************************************
return false;
}
/************************************************************************************/
/************************** Funktion: getBlackRochade *******************************/
/**
* ********************************************************************************
*/
ArrayList<IChessGame> getBlackRochade() {
//*** Variablen-Deklaration ******************************************************
ArrayList<IChessGame> rochadeList;
ChessBoard b;
int field;
//*** Liste initialisieren *******************************************************
rochadeList = new ArrayList<IChessGame>();
//*** Testen ob kurze Rochade m�glich ********************************************
if (BlackCanShortRochade) {
//*** Wenn Felder zwischen Turm und K�nig leer und Turm da **********************
if (fields[96] == EMPTY_FIELD && fields[97] == EMPTY_FIELD && fields[98] == BLACK_ROOK) {
field = 95;
//*** Testen ob ein Feld angegriffen wird ********************************
while (field < 98 && !IsFieldAttackedByWhite(field)) {
field++;
}
//*** Wenn kein Feld angegriffen wurde ***********************************
if (field == 98) {
//*** Rochieren ******************************************************
b = this.Clone();
b.fields[96] = ChessBoard.BLACK_ROOK;
b.fields[97] = ChessBoard.BLACK_KING;
b.fields[95] = ChessBoard.EMPTY_FIELD;
b.fields[98] = ChessBoard.EMPTY_FIELD;
b.TurnNotation = "e8g8";
b.BlackCanLongRochade = false;
b.BlackCanShortRochade = false;
b.playerToMakeTurn = Player.WHITE;
rochadeList.add(b);
}
}
}
if (BlackCanLongRochade) {
//*** Wenn Felder zwischen Turm und K�nig leer und Turm da **********************
if (fields[94] == EMPTY_FIELD && fields[93] == EMPTY_FIELD && fields[92] == EMPTY_FIELD && fields[91] == BLACK_ROOK) {
field = 95;
//*** Testen ob ein Feld angegriffen wird ********************************
while (field > 92 && !IsFieldAttackedByWhite(field)) {
field--;
}
//*** Wenn kein Feld angegriffen wurde ***********************************
if (field == 92) {
//*** Rochieren ******************************************************
b = this.Clone();
b.fields[94] = ChessBoard.BLACK_ROOK;
b.fields[93] = ChessBoard.BLACK_KING;
b.fields[95] = ChessBoard.EMPTY_FIELD;
b.fields[91] = ChessBoard.EMPTY_FIELD;
b.TurnNotation = "e8c8";
b.BlackCanLongRochade = false;
b.BlackCanShortRochade = false;
b.playerToMakeTurn = Player.WHITE;
rochadeList.add(b);
}
}
}
//*** Liste zur�ckgeben **********************************************************
return rochadeList;
}
/************************************************************************************/
/*********************** Funktion: IsFieldAttackedByWhite ***************************/
/**
* ********************************************************************************
*/
public boolean IsFieldAttackedByWhite(int field) {
//*** Variablen-Deklaration ******************************************************
byte piece;
int u;
//*** Testen ob Bauer werfen kann ************************************************
if (fields[field - 9] == WHITE_PAWN || fields[field - 11] == WHITE_PAWN) return true;
//*** Testen ob Springer werfen kann *********************************************
for (int i = 0; i < KNIGHT_DIRECTIONS.length; i++) {
if (fields[field + KNIGHT_DIRECTIONS[i]] == WHITE_KNIGHT) return true;
}
//*** Turm Richtungen testen *****************************************************
for (int i = 0; i < ROOK_DIRECTIONS.length; i++) {
u = 1;
while ((piece = fields[field + ROOK_DIRECTIONS[i] * u]) == EMPTY_FIELD) u++;
//*** Wenn in Sicht von Turm oder Dame - wird angegriffen ********************
if (piece == WHITE_QUEEN || piece == WHITE_ROOK) return true;
//*** Wenn K�nig nur eins weit weg ist - wird angegriffen ********************
if (piece == WHITE_KING && u == 1) return true;
}
//*** Turm Richtungen testen *****************************************************
for (int i = 0; i < ChessBoard.BISHOP_DIRECTIONS.length; i++) {
u = 1;
while ((piece = fields[field + BISHOP_DIRECTIONS[i] * u]) == EMPTY_FIELD) u++;
//*** Wenn in Sicht von Turm oder Dame - wird angegriffen ********************
if (piece == WHITE_QUEEN || piece == WHITE_BISHOP) return true;
//*** Wenn K�nig nur eins weit weg ist - wird angegriffen ********************
if (piece == WHITE_KING && u == 1) return true;
}
//*** Default: false *************************************************************
return false;
}
// private ArrayList<ChessBoard> makePawnMove(int field, Player owner)
// {
// //*** Variablen-Deklaration ******************************************************
// ArrayList<ChessBoard> followMoves;
//
// //*** Liste initialisieren *******************************************************
// followMoves=new ArrayList<ChessBoard>();
//
// //*** Liste zur�ckgeben **********************************************************
// return followMoves;
// }
public String ToDebug() {
String s = "";
for (int y = 0; y < 10; y++) {
for (int x = 0; x < 10; x++) {
s += fields[y * 10 + x] + " ";
}
s += "\n";
}
return s;
}
public int compareTo(IChessGame o) {
return this.heuristicValue - o.getHeuristicValue();
}
public int getHeuristicValue() {
return heuristicValue;
}
public String getTurnNotation() {
return this.TurnNotation;
}
public void addRound() {
this.round_counter++;
}
public int getRound() {
return round_counter;
}
//*** Liefert den Index des Feldes mit dem König der Übergebenen Farbe zurück
//*** Wenn der König nciht gefunden wurde -1;
private int getKing(Player player) {
for (int i = 19; i < 100; i++) {
if (fields[i] == WHITE_KING && player == Player.WHITE)
return i;
if (fields[i] == BLACK_KING && player == Player.BLACK)
return i;
}
return -1;
}
public GameState getGameState() {
//*** variablen initialisieren *****************************************
int kingsField;
ChessBoard nextTurn;
ArrayList<IChessGame> nextGames = new ArrayList<IChessGame>();
boolean isKingAttacked = false;
boolean hasEscape = false;
//*** Prüfen ob Stellung legal ist ***********************************************
if (!this.isLegalBoard()) return GameState.ILLEGAL;
//** Dafür sorgen dass nachfolge stellung bekannt sind *****************
nextGames = this.getNextTurns();
//*** Wenn keine Nachfolgebretter existieren ist draw ****************************
if (nextGames.size() == 0) return GameState.DRAW;
//*** Auf MAtt und Draw weiter prüfen ********************************************
//*** Prüfen ob der König angegriffen wird ***************************************
if (playerToMakeTurn == Player.WHITE) {
if (IsFieldAttackedByBlack(this.getKing(Player.WHITE)))
isKingAttacked = true;
} else {
if (IsFieldAttackedByWhite(this.getKing(Player.BLACK)))
isKingAttacked = true;
}
//*** Prüfe alle Felder ************************************************
for (int i = 0; i < nextGames.size(); i++) {
//*** nachfolger bestimmen *****************************************
nextTurn = (ChessBoard) (nextGames.get(i));
//*** KönigsFeld des Nachfolgers besorgen **************************
kingsField = nextTurn.getKing(this.playerToMakeTurn);
//*** Wenn der König schon weg ist weiter ************************************
if (kingsField == -1) continue;
//*** Wenn das KönigsFeld nicht vom Gegner angegriffen gibts ein escape
if (this.playerToMakeTurn == Player.WHITE) {
if (!nextTurn.IsFieldAttackedByBlack(kingsField)) hasEscape = true;
} else {
if (!nextTurn.IsFieldAttackedByWhite(kingsField)) hasEscape = true;
}
}
//*** Auswerten ******************************************************************
if (isKingAttacked && !hasEscape) return GameState.MATT;
if (!hasEscape) return GameState.DRAW;
//*** DEfault legal **************************************************************
return GameState.LEGAL;
}
public boolean isLegalBoard() {
int kingsField;
//*** Wenn weiß dran ist *********************************************************
if (this.playerToMakeTurn == Player.WHITE) {
kingsField = this.getKing(Player.BLACK);
//*** Wenn kein König vorhanden ist ist das Brett auch nicht legal ***********
if (kingsField == -1) return false;
//*** Wenn der König angegriffen wird ****************************************
if (this.IsFieldAttackedByWhite(kingsField)) return false;
} else {
kingsField = this.getKing(Player.WHITE);
//*** Wenn kein König vorhanden ist ist das Brett auch nicht legal ***********
if (kingsField == -1) return false;
//*** Wenn der König angegriffen wird auch nicht *****************************
if (this.IsFieldAttackedByBlack(kingsField)) return false;
}
return true;
}
public void setRochade(boolean k_Castling, boolean q_Castling, boolean K_Castling, boolean Q_Castling) {
BlackCanLongRochade = Q_Castling;
BlackCanShortRochade = K_Castling;
WhiteCanLongRochade = q_Castling;
WhiteCanShortRochade = k_Castling;
}
public int getQ() {
int q = 0;
int field;
//*** Für alle Spalten
for (int x = 1; x < 9; x++) {
//*** Für alle Reihen
for (int y = 2; y < 10; y++) {
field = y * 10 + x;
//*** fig quali geht ein
q += QUALITIES[this.fields[field]];
}
}
return q;
}
public int getTurnsMade() {
return round_counter;
}
/**
* Getter for hasBlackLost
*
* @return boolean hasBlackLost
*/
public boolean hasBlackLost() {
return BlackLost;
}
/**
* Getter for hasWhiteLost
*
* @return boolean hasWhiteLost
*/
public boolean hasWhiteLost() {
return WhiteLost;
}
/**
* Generates database-String for current board including hash, depth and value
* <p>
* Syntax: Hash#Depth#Value
* </p>
*
* @return Hashed Chessboard String with depth and value, null if MD5 missing
* http://www.avajava.com/tutorials/lessons/how-do-i-generate-an-md5-digest-for-a-string.html</a>
*/
public String toDatabase(Player current, int depth) {
String hash = this.getMD5Hash();
if (hash == null || hash.length() == 0) {
return null;
}
return hash + DatabaseEntry.SEGMENTS_DELIMITER + DatabaseEntry.convert(depth, 4) +
DatabaseEntry.SEGMENTS_DELIMITER + DatabaseEntry.convert(this.getQuality(current), 4);
}
/**
* Convert the chessboard to a database string containing figures, player and castling
* <p>
* MD5(Board+Active Player+WSR+WLR+BSR+BLR)
* </p>
*
* @return String representation of MD5-Hash from Board
* @see de.htw.grischa.chess.database.client.DatabaseEntry#DatabaseEntry(String)
* @see <a href="http://www.avajava.com/tutorials/lessons/how-do-i-generate-an-md5-digest-for-a-string.html">
*/
public String getMD5Hash() {
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
log.fatal("MD5 not available");
return null;
}
String original = this.getStringRepresentation() + String.valueOf(this.WhiteCanShortRochade) +
String.valueOf(this.WhiteCanLongRochade) + String.valueOf(this.BlackCanShortRochade) +
String.valueOf(this.BlackCanLongRochade);
md.update(original.getBytes());
byte[] digest = md.digest();
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
String temp = Integer.toHexString((b & 0xff));
sb.append(temp.length() == 1 ? DatabaseEntry.convert(0, 2 - temp.length()) + temp : temp);
}
return sb.toString();
}
/**
* Return the parent off the game
* <p>
* This method returns null if the parent is not set or does not exists. Beware that not every IChessGame needs
* to have an parent
* </p>
*
* @return IChessGame parent of the board
*/
@Override
public IChessGame getParent() {
if (this.parent == null) {
return null;
} else {
return this.parent;
}
}
/**
* Set the parent board to the IChessGame
* <p>
* You are able to set a chain of children of a board by setting a parent which having a parent itself
* </p>
*
* @param parent IChessGame parent
*/
@Override
public void setParent(IChessGame parent) {
this.parent = parent;
}
}
| [
"vicarious@mailbox.org"
] | vicarious@mailbox.org |
ba71726edef70f367ab134479c4c480c796f568e | 1672d7a13c85969e6e804b2e540f3120a2b07466 | /GalaxyMetalShop/src/com/thoughtworks/testcases/NumberSystemConversionTest.java | 920231d3ed3aacaaef637aba35d3bb4fc21ee7b0 | [] | no_license | knirbhay/Merchant-Guide-To-The-Galaxy | 22fb769177a5621b1affee3d26e6cdf3f3e35c8a | 6577a6d6b16e613d53f1933305bcb14b1ce962c4 | refs/heads/master | 2021-01-17T22:32:16.429918 | 2014-04-17T15:40:57 | 2014-04-17T15:40:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 881 | java | package com.thoughtworks.testcases;
import org.junit.Assert;
import org.junit.Test;
import com.thoughtworks.metalshop.NumberSytemConversion;
/**
* test cases for number system conversion.
*
* @author Kartik
*
*/
public class NumberSystemConversionTest {
@Test
public void convertRomanToIntegerTest() {
Assert.assertEquals(10,
NumberSytemConversion.convertRomanToInteger("X"));
Assert.assertEquals(1984,
NumberSytemConversion.convertRomanToInteger("MCMLXXXIV"));
Assert.assertEquals(1953,
NumberSytemConversion.convertRomanToInteger("MCMLIII"));
Assert.assertEquals(3303,
NumberSytemConversion.convertRomanToInteger("MMMCCCIII"));
Assert.assertEquals(1995,
NumberSytemConversion.convertRomanToInteger("MCMXCV"));
Assert.assertEquals(17,
NumberSytemConversion.convertRomanToInteger("XVII"));
}
}
| [
"bhatnagar.kartik@gmail.com"
] | bhatnagar.kartik@gmail.com |
9bacac43565a1dc091e295414eb19051fc52a444 | 0041ca6e09887ac37ed523aa19d36771e1ec8f4f | /app/src/main/java/com/gf169/gfwalk/PrivacyPolicyActivity.java | 1d1cc662a024ecf46cae9c95e43106020d2828b3 | [] | no_license | Gf16954/gfWalk | 1f3c126a1a3064975381a9ded58d799720087002 | c268e302d3125802a332b3ad811206b9215f9f5b | refs/heads/master | 2021-04-21T05:35:59.389392 | 2020-10-22T15:55:38 | 2020-10-22T15:55:38 | 249,745,944 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 864 | java | /**
* Created by gf on 20.09.2015.
*/
package com.gf169.gfwalk;
import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.widget.TextView;
public class PrivacyPolicyActivity extends Activity {
static final String TAG = "gfPrivacyPolicyActivity";
String s;
@Override
protected void onCreate(Bundle savedInstanceState) {
Utils.logD(TAG, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help);
setTitle(getResources().getString(R.string.app_name)+
" "+BuildConfig.VERSION_NAME+"("+BuildConfig.VERSION_CODE+")"+
" "+getResources().getString(R.string.app_copyright));
((TextView) findViewById(R.id.textViewHelp)).setText(
Html.fromHtml(getResources().getString(R.string.help)));
}
}
| [
"gf16954@gmail.com"
] | gf16954@gmail.com |
d8ef81266689fb8384005ae0afd6b444644d7d7c | 992b8cb0c8fec5f8f4baecf67d47385677ceb757 | /src/com/mictlan/math/legacy/geometry/Line.java | 9101361438290355dee010ede662185f7acc2508 | [] | no_license | jcarchive/PathPlanning | f3b8da12c5e3005415cc366d17c98e90270ead6f | bd684e199e9b0e6ef489c7c3736d21f48f84cb5c | refs/heads/master | 2023-03-12T18:06:56.727928 | 2021-02-26T11:18:12 | 2021-02-26T11:18:12 | 304,773,732 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,966 | java | package com.mictlan.math.legacy.geometry;
import com.mictlan.math.IRange;
import com.mictlan.math.RangeFloat;
import processing.core.PVector;
import static com.mictlan.math.utils.ComparatorsUtils.eq;
import static java.lang.Math.abs;
public class Line implements ILine{
private IPoint a;
private IPoint b;
private IPoint upper;
private IPoint lower;
private IPoint left;
private IPoint right;
public Line(IPoint a, IPoint b){
this.a = a;
this.b = b;
calculateRL();
calculateUL();
}
private void calculateUL(){
if(a.equalsY(b)){
if(a.isLeftOf(b)){
upper = a;
}else{
upper = b;
}
}else if(a.isAboveOf(b)){
upper = a;
}else{
upper = b;
}
lower = (a == upper)?b:a;
}
private void calculateRL(){
if(a.equalsX(b)){
if(a.isAboveOf(b)) left = a;
else left = b;
}else{
if(a.isLeftOf(b)) left = a;
else left = b;
}
right = (a == left)?b:a;
}
@Override
public IPoint getStart() {
return a;
}
@Override
public IPoint getEnd() {
return b;
}
@Override
public IPoint getUpper() {
return upper;
}
@Override
public IPoint getLower() {
return lower;
}
@Override
public IPoint getRight() {
return right;
}
@Override
public IPoint getLeft() {
return left;
}
@Override
public IRange<Float> getYRange() {
return new RangeFloat(getLower().getY(), getUpper().getY()) ;
}
@Override
public IRange<Float> getXRange() {
return new RangeFloat(getLeft().getX(), getRight().getX());
}
@Override
public IPoint getYIntersection() {
return new Point(0, getStart().getY() - getSlope()*getStart().getX());
}
@Override
public IPoint getXIntersection() {
return new Point( -getYIntersection().getY()/getSlope(),0);
}
@Override
public PVector getDirection() {
return (new PVector(getEnd().getX() - getStart().getX(), getEnd().getY() - getStart().getY())).normalize();
}
@Override
public PVector getNormal() {
return (new PVector(-getEnd().getY() + getStart().getY(),getEnd().getX() - getStart().getX()).normalize());
}
@Override
public float getSlope(){
float m = (getEnd().getY() - getStart().getY())/(getEnd().getX() - getStart().getX());
if (eq(m,0f)) return 0;
return m;
}
@Override
public float getH(){
float h = abs(getEnd().getY() - getStart().getY());
if (eq(h,0)) return 0;
return h;
}
@Override
public float getW(){
float w = abs(getEnd().getX() - getStart().getX());
if (eq(w,0)) return 0;
return w;
}
@Override
public boolean isHorizontal(){
return eq(getH(), 0);
}
@Override
public boolean isVertical(){
return eq(getW(),0);
}
@Override
public boolean contains(IPoint p) {
if(isVertical()) return eq(p.getX(), getStart().getX());
if(isHorizontal()) return eq(p.getY(), getStart().getY());
return eq(getSlope()*p.getX() + getYIntersection().getY(), p.getY());
}
@Override
public void sortByY() {
a = upper;
b = lower;
}
@Override
public void sortByX() {
a = left;
b = right;
}
@Override
public PointOrientation orientation(IPoint r) {
var p = getStart();
var q = getEnd();
var d1 = (p.getX() - q.getX())*(q.getY() - r.getY());
var d2 = (p.getY() - q.getY())*(q.getX() - r.getX());
if(eq(d1,d2)) return PointOrientation.COLLINEAR;
if( d1 > d2) return PointOrientation.LIES_RIGHT;
return PointOrientation.LIES_LEFT;
}
}
| [
"jcarchive96@protonmail.com"
] | jcarchive96@protonmail.com |
fdfe692a44ceded41a3d0c00e34e3f2f94c7dbf4 | d9ebc39bdf34031b67a82b7560e3930e634adca2 | /CW1-SET09117/src/RouteLength.java | fb3851e2cbef3cea403b7b23673321d20505f29d | [] | no_license | Danayal0902/ADS-CW1 | f0d286d02a8a5185df03895b90eb815ddd3ba5d7 | 23f6d00605acdf9d93421964ede323af9892603c | refs/heads/master | 2021-03-30T16:32:52.732805 | 2016-12-04T21:39:58 | 2016-12-04T21:39:58 | 71,291,469 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 675 | java | import java.awt.geom.Point2D;
import java.util.ArrayList;
public class RouteLength {
public static double routeLength(ArrayList<Point2D> cities) {
//calculate the length of a TSP route held in an arraylist as a set of points
double result = 0; //holds the route length
Point2D prev = cities.get(cities.size()-1);
//set the previous city as the last city in the arraylist as we
//need to measure length of the entire loop
for (Point2D city : cities) {
//go through each city in turn
result+= city.distance(prev);
//get distance from the previous city
prev = city;
//current city will be the previous city next time
}
return result;
}
}
| [
"danayal_94@hotmail.com"
] | danayal_94@hotmail.com |
ce664d51aec998c36e688b7028a7a681a3e3ce26 | b570498c047c6c0e321f07c8323a3b471e568335 | /fabric-chaincode-shim/src/test/java/org/hyperledger/fabric/contract/TransactionExceptionTest.java | ea8f732c7f9bc6daea0658fbc5ff476dd3e358ea | [
"CC-BY-4.0",
"Apache-2.0"
] | permissive | Vijaypunugubati/fabric-chaincode-java | 0f300de13860390a19a93353c75c80cae1c8c69b | 3007102b54cdee9d8fccaf6fc6cba890d7229ff7 | refs/heads/master | 2020-09-12T18:42:08.378738 | 2019-12-10T15:48:17 | 2019-12-10T15:48:17 | 222,514,002 | 0 | 0 | Apache-2.0 | 2019-12-09T19:31:17 | 2019-11-18T18:16:02 | Java | UTF-8 | Java | false | false | 3,764 | java | /*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.fabric.contract;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import org.hyperledger.fabric.shim.ChaincodeException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class TransactionExceptionTest {
class MyTransactionException extends ChaincodeException {
private static final long serialVersionUID = 1L;
private int errorCode;
public MyTransactionException(int errorCode) {
super("MyTransactionException");
this.errorCode = errorCode;
}
@Override
public byte[] getPayload() {
String payload = String.format("E%03d", errorCode);
return payload.getBytes();
}
}
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testNoArgConstructor() {
ChaincodeException e = new ChaincodeException();
assertThat(e.getMessage(), is(nullValue()));
assertThat(e.getPayload(), is(nullValue()));
}
@Test
public void testMessageArgConstructor() {
ChaincodeException e = new ChaincodeException("Failure");
assertThat(e.getMessage(), is("Failure"));
assertThat(e.getPayload(), is(nullValue()));
}
@Test
public void testCauseArgConstructor() {
ChaincodeException e = new ChaincodeException(new Error("Cause"));
assertThat(e.getMessage(), is("java.lang.Error: Cause"));
assertThat(e.getPayload(), is(nullValue()));
assertThat(e.getCause().getMessage(), is("Cause"));
}
@Test
public void testMessageAndCauseArgConstructor() {
ChaincodeException e = new ChaincodeException("Failure", new Error("Cause"));
assertThat(e.getMessage(), is("Failure"));
assertThat(e.getPayload(), is(nullValue()));
assertThat(e.getCause().getMessage(), is("Cause"));
}
@Test
public void testMessageAndPayloadArgConstructor() {
ChaincodeException e = new ChaincodeException("Failure", new byte[] { 'P', 'a', 'y', 'l', 'o', 'a', 'd' });
assertThat(e.getMessage(), is("Failure"));
assertThat(e.getPayload(), is(new byte[] { 'P', 'a', 'y', 'l', 'o', 'a', 'd' }));
}
@Test
public void testMessagePayloadAndCauseArgConstructor() {
ChaincodeException e = new ChaincodeException("Failure", new byte[] { 'P', 'a', 'y', 'l', 'o', 'a', 'd' }, new Error("Cause"));
assertThat(e.getMessage(), is("Failure"));
assertThat(e.getPayload(), is(new byte[] { 'P', 'a', 'y', 'l', 'o', 'a', 'd' }));
assertThat(e.getCause().getMessage(), is("Cause"));
}
@Test
public void testMessageAndStringPayloadArgConstructor() {
ChaincodeException e = new ChaincodeException("Failure", "Payload");
assertThat(e.getMessage(), is("Failure"));
assertThat(e.getPayload(), is(new byte[] { 'P', 'a', 'y', 'l', 'o', 'a', 'd' }));
}
@Test
public void testMessageStringPayloadAndCauseArgConstructor() {
ChaincodeException e = new ChaincodeException("Failure", "Payload", new Error("Cause"));
assertThat(e.getMessage(), is("Failure"));
assertThat(e.getPayload(), is(new byte[] { 'P', 'a', 'y', 'l', 'o', 'a', 'd' }));
assertThat(e.getCause().getMessage(), is("Cause"));
}
@Test
public void testSubclass() {
ChaincodeException e = new MyTransactionException(1);
assertThat(e.getMessage(), is("MyTransactionException"));
assertThat(e.getPayload(), is(new byte[] { 'E', '0', '0', '1' }));
}
}
| [
"jamest@uk.ibm.com"
] | jamest@uk.ibm.com |
f2fde406c48105a695ce1788f8b6e55648e38366 | 5ac47d6c948282eabe871112a8b4c0bfab6d2656 | /app/src/main/java/com/gsgd/live/data/model/Order.java | 3b47a524189b66f903aea67e61ce275ded2952a9 | [] | no_license | crxu/android-gsyVideoPlayer | 59cdf8621da0e5f03ce50ea6dd3e1b542b8a9fd3 | d4bbe3f86bdfbff21309f516e45ca2657ecc0939 | refs/heads/master | 2020-04-04T22:48:55.798989 | 2018-11-06T06:35:57 | 2018-11-06T06:35:57 | 156,336,848 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,475 | java | package com.gsgd.live.data.model;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
/**
* Created by andy on 2017/12/25.
*/
public class Order implements Comparable<Order>, Parcelable {
private String key;//channelId date showTime 组成
private String showTime;
private String date;
private String channelName;
private String channelType;
private long time;
private long channelId;
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getChannelName() {
return channelName;
}
public void setChannelName(String channelName) {
this.channelName = channelName;
}
public String getChannelType() {
return channelType;
}
public void setChannelType(String channelType) {
this.channelType = channelType;
}
@Override
public boolean equals(Object obj) {
return key.equals(((Order) obj).key);
}
@Override
public int compareTo(@NonNull Order o) {
return (int) (time - o.time);
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getShowTime() {
return showTime;
}
public void setShowTime(String showTime) {
this.showTime = showTime;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public long getChannelId() {
return channelId;
}
public void setChannelId(long channelId) {
this.channelId = channelId;
}
@Override
public String toString() {
return "Order{" +
"key='" + key + '\'' +
", showTime='" + showTime + '\'' +
", date='" + date + '\'' +
", channelName='" + channelName + '\'' +
", channelType='" + channelType + '\'' +
", time=" + time +
", channelId=" + channelId +
'}';
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.key);
dest.writeString(this.showTime);
dest.writeString(this.date);
dest.writeString(this.channelName);
dest.writeString(this.channelType);
dest.writeLong(this.time);
dest.writeLong(this.channelId);
dest.writeString(this.type);
}
public Order() {
}
protected Order(Parcel in) {
this.key = in.readString();
this.showTime = in.readString();
this.date = in.readString();
this.channelName = in.readString();
this.channelType = in.readString();
this.time = in.readLong();
this.channelId = in.readLong();
this.type = in.readString();
}
public static final Parcelable.Creator<Order> CREATOR = new Parcelable.Creator<Order>() {
@Override
public Order createFromParcel(Parcel source) {
return new Order(source);
}
@Override
public Order[] newArray(int size) {
return new Order[size];
}
};
}
| [
"286299340@qq.com"
] | 286299340@qq.com |
7d7b892b70cdf13175b21827e171896fb00ae82c | 728b61059a086916b0a189add800804f2f3c08bd | /_017_spring-security-jwt-authorization/src/main/java/com/mimaraslan/security/UserPrincipalDetailsService.java | 7fec9ffe1c1ef02f84dc8f51d1e4ce0c550cd2a5 | [
"MIT"
] | permissive | mimaraslan/spring-security | 20331992ff651c52638a72e658880a0d0397b448 | 65451be8d60035ce7c5e062e279735cf9994a02d | refs/heads/master | 2020-06-27T06:21:56.715063 | 2020-05-23T07:51:22 | 2020-05-23T07:51:22 | 199,867,649 | 10 | 2 | null | null | null | null | UTF-8 | Java | false | false | 856 | java | package com.mimaraslan.security;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.mimaraslan.model.User;
import com.mimaraslan.repository.UserRepository;
@Service
public class UserPrincipalDetailsService implements UserDetailsService {
private UserRepository userRepository;
public UserPrincipalDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
User user = this.userRepository.findByUsername(s);
UserPrincipal userPrincipal = new UserPrincipal(user);
return userPrincipal;
}
}
| [
"mimaraslan@gmail.com"
] | mimaraslan@gmail.com |
e23254766cff190a7f8785a6b0400f59210d944d | 2351dc848102f20adea24dfd447c74dc3b625279 | /Trie/src/main/java/com/dmg/datasource/KeyValueDataSource.java | 509ffa4f2f8baeb40e1e856cafb94c227ada13b3 | [] | no_license | huangjiehua/Dmg | bb803eb9a5a835857d803f94f19b3f61f29ff3b9 | 6e14815be98be274c6c89b17fbb223d254133232 | refs/heads/master | 2021-01-20T18:01:51.417153 | 2016-07-06T14:44:12 | 2016-07-06T14:44:12 | 61,260,392 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 365 | java | package com.dmg.datasource;
import java.util.Map;
import java.util.Set;
/**
* @author Roman Mandeleil
* @since 18.01.2015
*/
public interface KeyValueDataSource extends DataSource {
byte[] get(byte[] key);
byte[] put(byte[] key, byte[] value);
void delete(byte[] key);
Set<byte[]> keys();
void updateBatch(Map<byte[], byte[]> rows);
}
| [
"huangjiehua19@outlook.com"
] | huangjiehua19@outlook.com |
178d47836564e88820ceaefe9f706968b650532a | e8fc9684f2a4dc24bee850dbb22bf5288895e45f | /src/Domain/DataStructures/Stack/MyLibStack.java | 7eacf0716bd35e8108d7c8f2c13522c916bef5e0 | [] | no_license | patriciadamian/Interpreter_java | 28b1a04cbc9d0bdd0b937e5a74b07852909d232f | 4ebea3b5c8c5214c09ab4ba6dd9c22fb51488ad5 | refs/heads/master | 2021-01-10T05:24:24.983346 | 2016-03-24T17:09:26 | 2016-03-24T17:09:26 | 54,655,174 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 834 | java | package Domain.DataStructures.Stack;
import Domain.DataStructures.Stack.IStack;
import java.util.Stack;
/**
* Created by Patri on 11/9/2015.
*/
public class MyLibStack<T> implements IStack<T> {
private Stack<T> elems;
public MyLibStack(){
elems = new Stack<>();
}
@Override
public void push(T e) {
elems.push(e);
}
@Override
public T pop() throws EmptyStackException{
if (!this.isEmpty())
return elems.pop();
throw new EmptyStackException("Cannot pop! Stack is empty");
}
@Override
public boolean isEmpty() {
return elems.isEmpty();
}
@Override
public String toString() {
String res = "";
for (T elem : elems){
res = elem.toString() + " " + res;
}
return res;
}
}
| [
"patricia.damian13@gmail.com"
] | patricia.damian13@gmail.com |
c041d8337af219b9dd9f214881f6f71a155c68e4 | 6e41a23d56d6ef656ba2b28d2d551c2bffb26637 | /JunitMockitoLogging-Afternoon/MathApplicationTester/src/test/java/TesterRunner.java | 64f9d1dda9e60664755e7b0a79b2d5963d14878c | [] | no_license | DishaSurana/SAU-2021-Jan-Batch-Delhi | d2d5f4aa7b2ad6a46ee39d833079472d506ed878 | 0e77f0b8121485fb5f4308b762ebf9dd5b6c2b04 | refs/heads/main | 2023-02-25T16:38:26.783337 | 2021-01-31T17:25:05 | 2021-01-31T17:25:09 | 328,562,490 | 0 | 0 | null | 2021-01-11T05:53:13 | 2021-01-11T05:53:12 | null | UTF-8 | Java | false | false | 532 | java | import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TesterRunner {
public static void main(String[] args)
{
Result result = JUnitCore.runClasses(MathApplicationMockitoTester.class);
// Result result = JUnitCore.runClasses(MathApplicationJunitTester.class);
for(Failure f : result.getFailures())
{
System.out.println(f.toString());
}
System.out.println(result.wasSuccessful());
}
}
| [
"disha.surana@accolitedigital.com"
] | disha.surana@accolitedigital.com |
1962b29b2009515a5d0cf8c2c41226585c059dac | 658450d633d4601e667744de7e7471be21470c6b | /EHR/src/main/java/com/babifood/clocked/entrty/Holiday.java | 49f834337228e15d94fd139d1e1e3756341c6edf | [] | no_license | babifood/EHR_Repository | d1d3534d7db866c56af9f5556c861662f24c4734 | 08d23ac5b5e0aefcc23576cbd946e5092bc2e524 | refs/heads/master | 2021-07-22T10:34:48.097065 | 2018-12-07T06:04:16 | 2018-12-07T06:04:16 | 129,208,803 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,001 | java | package com.babifood.clocked.entrty;
import org.springframework.stereotype.Component;
/**
* 法定节假日实体类
* @author BABIFOOD
*
*/
@Component
public class Holiday {
// 年度
private Integer year;
// 开始日期
private String beginDate;
// 结束日期
private String endDate;
// 天数
private Double days;
// 备注
private String remark;
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getBeginDate() {
return beginDate;
}
public void setBeginDate(String beginDate) {
this.beginDate = beginDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public double getDays() {
return days;
}
public void setDays(double days) {
this.days = days;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
| [
"461348746@qq.com"
] | 461348746@qq.com |
f7a33e0b1b74f1ef0631e247c79149b10eb3755c | 899ea486c3e8597e1bf33df97f7ff02d965835c6 | /ubenchmark/src/main/java/org/postgresql/benchmark/statement/FinalizeStatement.java | bc95b4394264e38432d7280d08443c453c1f45c6 | [
"BSD-3-Clause"
] | permissive | matriv/pgjdbc | b200c0f5bf92c3ff4dfd401d96f1b0211a53140c | 56c04d0ec95ede31b5f13a70ab76f2b4df09aef5 | refs/heads/master | 2022-09-30T01:25:35.608490 | 2016-09-07T15:50:22 | 2016-09-07T15:50:22 | 64,402,085 | 1 | 0 | BSD-3-Clause | 2022-09-22T19:46:16 | 2016-07-28T14:25:58 | Java | UTF-8 | Java | false | false | 3,183 | java | package org.postgresql.benchmark.statement;
import org.postgresql.util.ConnectionUtil;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.profile.GCProfiler;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* Here we measure the time it takes to create and close a dummy statement.
*
* <p>To run this and other benchmarks (you can run the class from within IDE):
*
* <blockquote> <code>mvn package && java -classpath postgresql-driver.jar:target/benchmarks.jar
* -Duser=postgres -Dpassword=postgres -Dport=5433 -wi 10 -i 10 -f 1</code> </blockquote>
*
* <p>To run with profiling:
*
* <blockquote> <code>java -classpath postgresql-driver.jar:target/benchmarks.jar -prof gc -f 1 -wi
* 10 -i 10</code> </blockquote>
*/
@Fork(value = 1, jvmArgsPrepend = "-Xmx128m")
@Measurement(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS)
@Warmup(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class FinalizeStatement {
@Param({"0", "1", "10", "100"})
private int leakPct;
private float leakPctFloat;
private Connection connection;
//#if mvn.project.property.current.jdk < "1.7"
private Random random = new Random();
//#endif
@Setup(Level.Trial)
public void setUp() throws SQLException {
Properties props = ConnectionUtil.getProperties();
connection = DriverManager.getConnection(ConnectionUtil.getURL(), props);
leakPctFloat = 0.01f * leakPct;
}
@TearDown(Level.Trial)
public void tearDown() throws SQLException {
connection.close();
}
@Benchmark
public Statement createAndLeak() throws SQLException {
Statement statement = connection.createStatement();
Random rnd;
//#if mvn.project.property.current.jdk < "1.7"
rnd = random;
//#else
rnd = java.util.concurrent.ThreadLocalRandom.current();
//#endif
if (rnd.nextFloat() >= leakPctFloat) {
statement.close();
}
return statement;
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(FinalizeStatement.class.getSimpleName())
.addProfiler(GCProfiler.class)
.detectJvmArgs()
.build();
new Runner(opt).run();
}
}
| [
"sitnikov.vladimir@gmail.com"
] | sitnikov.vladimir@gmail.com |
68b3b1b3cb1045121e243bc705cc6342b7f07f34 | ad5b0c69804b3f901d7b3fa3247b4d74f198a736 | /src/main/java/com/cqrs/axon/sample/entity/Application.java | 5b69218b2bc8923483cad1f9f0b457c43b36e9b6 | [] | no_license | rahul33/cqrs-axon-rabbitmq-source | 64ff195a9d59135a211c31f5b3fac9eb6ec303fe | 9f9efdf74161172c8b9ba84c08134d7a56836495 | refs/heads/master | 2020-06-17T23:02:04.773627 | 2019-07-09T22:30:29 | 2019-07-09T22:30:29 | 196,091,355 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,293 | java | package com.cqrs.axon.sample.entity;
import com.cqrs.axon.sample.command.SubmitApplicationCommand;
import com.cqrs.axon.sample.event.ApplicationSubmittedEvent;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.eventsourcing.EventSourcingHandler;
import org.axonframework.modelling.command.AggregateIdentifier;
import org.axonframework.spring.stereotype.Aggregate;
import static org.axonframework.modelling.command.AggregateLifecycle.apply;
@Aggregate
public class Application {
@AggregateIdentifier
private String id;
private String name;
private String dob;
private String ssn;
@CommandHandler
public Application(SubmitApplicationCommand command) {
apply(new ApplicationSubmittedEvent(command.getId(), command.getName(), command.getDob(), command.getSsn()));
}
@EventSourcingHandler
public void on(ApplicationSubmittedEvent event) {
this.id = event.getId();
this.name = event.getName();
this.dob = event.getDob();
this.ssn = event.getSsn();
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getDob() {
return dob;
}
public String getSsn() {
return ssn;
}
}
| [
"ALL@rahulprasad.fios-router.home"
] | ALL@rahulprasad.fios-router.home |
10add20cc1313308ed230bf206bd45e98ae0d2a7 | f2566b970b3f44a061f5147056c7999aa6f78f3b | /app1/src/main/java/de/stytex/foobar/config/LoadBalancedResourceDetails.java | 14bba51f8715e2860d89a0cbc283a7bb1be8b242 | [] | no_license | earandap/jhipster-uaa-setup | fdd11c264c1192879cc857f79d122cc2ea9d984d | d430601b4db44517663d971f3c12cd929cd2b886 | refs/heads/master | 2021-01-17T22:45:53.946962 | 2016-06-04T10:25:12 | 2016-06-04T10:25:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,080 | java | package de.stytex.foobar.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
import org.springframework.stereotype.Component;
import java.net.URI;
import java.net.URISyntaxException;
/**
* Created on 31.05.16.
*
* @author David Steiman, K-TEL Communications GmbH
*/
@Component
public class LoadBalancedResourceDetails extends ClientCredentialsResourceDetails {
@Autowired
public LoadBalancedResourceDetails(JHipsterProperties jHipsterProperties) {
this.jHipsterProperties = jHipsterProperties;
setAccessTokenUri(jHipsterProperties.getSecurity().getClientAuthorization().getTokenUrl());
setClientId(jHipsterProperties.getSecurity().getClientAuthorization().getClientId());
setClientSecret(jHipsterProperties.getSecurity().getClientAuthorization().getClientSecret());
setGrantType("client_credentials");
}
private LoadBalancerClient loadBalancerClient;
private JHipsterProperties jHipsterProperties;
@Autowired(required = false)
public void setLoadBalancerClient(LoadBalancerClient loadBalancerClient) {
this.loadBalancerClient = loadBalancerClient;
}
@Override
public String getAccessTokenUri() {
String serviceName = jHipsterProperties.getSecurity().getClientAuthorization().getTokenServiceId();
if (loadBalancerClient != null && !serviceName.isEmpty()) {
String newUrl;
try {
newUrl = loadBalancerClient.reconstructURI(
loadBalancerClient.choose(serviceName),
new URI(super.getAccessTokenUri())
).toString();
return newUrl;
} catch (URISyntaxException e) {
e.printStackTrace();
return super.getAccessTokenUri();
}
} else {
return super.getAccessTokenUri();
}
}
}
| [
"d.steiman@ktel.de"
] | d.steiman@ktel.de |
ec960e20f4c78aa2d242c949482c268a1b10a462 | 532f686f17d2bbcaa3a46e0165b0e7c9f97bbd86 | /src/test/java/com/twilio/rest/supersim/v1/FleetTest.java | 6013d5e16709fa20e70b8255038b0b2eb2dacdf9 | [
"MIT"
] | permissive | cotigao/twilio-java | 46a2d80e5b116225889f1dc922e239aedaef008b | b3114554b01874e8d88596748fc4c57ccaf9707f | refs/heads/main | 2023-02-23T05:54:46.652638 | 2021-01-29T11:53:09 | 2021-01-29T11:53:09 | 322,249,123 | 0 | 0 | MIT | 2020-12-17T09:46:18 | 2020-12-17T09:46:18 | null | UTF-8 | Java | false | false | 8,687 | java | /**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
package com.twilio.rest.supersim.v1;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.twilio.Twilio;
import com.twilio.converter.DateConverter;
import com.twilio.converter.Promoter;
import com.twilio.exception.TwilioException;
import com.twilio.http.HttpMethod;
import com.twilio.http.Request;
import com.twilio.http.Response;
import com.twilio.http.TwilioRestClient;
import com.twilio.rest.Domains;
import mockit.Mocked;
import mockit.NonStrictExpectations;
import org.junit.Before;
import org.junit.Test;
import java.net.URI;
import static com.twilio.TwilioTest.serialize;
import static org.junit.Assert.*;
public class FleetTest {
@Mocked
private TwilioRestClient twilioRestClient;
@Before
public void setUp() throws Exception {
Twilio.init("AC123", "AUTH TOKEN");
}
@Test
public void testCreateRequest() {
new NonStrictExpectations() {{
Request request = new Request(HttpMethod.POST,
Domains.SUPERSIM.toString(),
"/v1/Fleets");
request.addPostParam("NetworkAccessProfile", serialize("HAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"));
twilioRestClient.request(request);
times = 1;
result = new Response("", 500);
twilioRestClient.getAccountSid();
result = "AC123";
}};
try {
Fleet.creator("HAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").create();
fail("Expected TwilioException to be thrown for 500");
} catch (TwilioException e) {}
}
@Test
public void testCreateResponse() {
new NonStrictExpectations() {{
twilioRestClient.request((Request) any);
result = new Response("{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"unique_name\": \"unique_name\",\"data_enabled\": true,\"data_limit\": 1000,\"data_metering\": \"payg\",\"date_created\": \"2019-07-30T20:00:00Z\",\"date_updated\": \"2019-07-30T20:00:00Z\",\"commands_enabled\": true,\"commands_method\": \"GET\",\"commands_url\": \"https://google.com\",\"network_access_profile_sid\": \"HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"sid\": \"HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"url\": \"https://supersim.twilio.com/v1/Fleets/HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}", TwilioRestClient.HTTP_STATUS_CODE_CREATED);
twilioRestClient.getObjectMapper();
result = new ObjectMapper();
}};
Fleet.creator("HAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").create();
}
@Test
public void testFetchRequest() {
new NonStrictExpectations() {{
Request request = new Request(HttpMethod.GET,
Domains.SUPERSIM.toString(),
"/v1/Fleets/HFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.request(request);
times = 1;
result = new Response("", 500);
twilioRestClient.getAccountSid();
result = "AC123";
}};
try {
Fleet.fetcher("HFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch();
fail("Expected TwilioException to be thrown for 500");
} catch (TwilioException e) {}
}
@Test
public void testFetchResponse() {
new NonStrictExpectations() {{
twilioRestClient.request((Request) any);
result = new Response("{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"unique_name\": \"unique_name\",\"data_enabled\": true,\"data_limit\": 1000,\"data_metering\": \"payg\",\"date_created\": \"2019-07-30T20:00:00Z\",\"date_updated\": \"2019-07-30T20:00:00Z\",\"commands_enabled\": true,\"commands_method\": \"POST\",\"commands_url\": null,\"network_access_profile_sid\": \"HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"sid\": \"HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"url\": \"https://supersim.twilio.com/v1/Fleets/HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}", TwilioRestClient.HTTP_STATUS_CODE_OK);
twilioRestClient.getObjectMapper();
result = new ObjectMapper();
}};
assertNotNull(Fleet.fetcher("HFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch());
}
@Test
public void testReadRequest() {
new NonStrictExpectations() {{
Request request = new Request(HttpMethod.GET,
Domains.SUPERSIM.toString(),
"/v1/Fleets");
twilioRestClient.request(request);
times = 1;
result = new Response("", 500);
twilioRestClient.getAccountSid();
result = "AC123";
}};
try {
Fleet.reader().read();
fail("Expected TwilioException to be thrown for 500");
} catch (TwilioException e) {}
}
@Test
public void testReadEmptyResponse() {
new NonStrictExpectations() {{
twilioRestClient.request((Request) any);
result = new Response("{\"fleets\": [],\"meta\": {\"first_page_url\": \"https://supersim.twilio.com/v1/Fleets?NetworkAccessProfile=HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0\",\"key\": \"fleets\",\"next_page_url\": null,\"page\": 0,\"page_size\": 50,\"previous_page_url\": null,\"url\": \"https://supersim.twilio.com/v1/Fleets?NetworkAccessProfile=HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0\"}}", TwilioRestClient.HTTP_STATUS_CODE_OK);
twilioRestClient.getObjectMapper();
result = new ObjectMapper();
}};
assertNotNull(Fleet.reader().read());
}
@Test
public void testReadFullResponse() {
new NonStrictExpectations() {{
twilioRestClient.request((Request) any);
result = new Response("{\"meta\": {\"first_page_url\": \"https://supersim.twilio.com/v1/Fleets?NetworkAccessProfile=HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0\",\"key\": \"fleets\",\"next_page_url\": null,\"page\": 0,\"page_size\": 50,\"previous_page_url\": null,\"url\": \"https://supersim.twilio.com/v1/Fleets?NetworkAccessProfile=HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&PageSize=50&Page=0\"},\"fleets\": [{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"unique_name\": \"Pilot Fleet\",\"data_enabled\": true,\"data_limit\": 1000,\"data_metering\": \"payg\",\"date_created\": \"2019-10-15T20:00:00Z\",\"date_updated\": \"2019-10-15T20:00:00Z\",\"commands_enabled\": true,\"commands_method\": \"POST\",\"commands_url\": null,\"network_access_profile_sid\": \"HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"sid\": \"HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"url\": \"https://supersim.twilio.com/v1/Fleets/HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}]}", TwilioRestClient.HTTP_STATUS_CODE_OK);
twilioRestClient.getObjectMapper();
result = new ObjectMapper();
}};
assertNotNull(Fleet.reader().read());
}
@Test
public void testUpdateRequest() {
new NonStrictExpectations() {{
Request request = new Request(HttpMethod.POST,
Domains.SUPERSIM.toString(),
"/v1/Fleets/HFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.request(request);
times = 1;
result = new Response("", 500);
twilioRestClient.getAccountSid();
result = "AC123";
}};
try {
Fleet.updater("HFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update();
fail("Expected TwilioException to be thrown for 500");
} catch (TwilioException e) {}
}
@Test
public void testUpdateUniqueNameResponse() {
new NonStrictExpectations() {{
twilioRestClient.request((Request) any);
result = new Response("{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"unique_name\": \"unique_name\",\"data_enabled\": true,\"data_limit\": 1000,\"data_metering\": \"payg\",\"date_created\": \"2019-10-15T20:00:00Z\",\"date_updated\": \"2019-10-15T20:00:00Z\",\"commands_enabled\": true,\"commands_method\": \"POST\",\"commands_url\": null,\"network_access_profile_sid\": \"HAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"sid\": \"HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"url\": \"https://supersim.twilio.com/v1/Fleets/HFaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}", TwilioRestClient.HTTP_STATUS_CODE_OK);
twilioRestClient.getObjectMapper();
result = new ObjectMapper();
}};
Fleet.updater("HFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update();
}
} | [
"twilio-ci@twilio.com"
] | twilio-ci@twilio.com |
17febfff85a28b9fea6fe567c1244d36bdf9f991 | d11449fea68cc795c5badaac744806643c111778 | /src/main/java/com/luqiancheng/controller/AccountDetailsServlet.java | 1c5d2f01cec26b823e82851f6b56e59c42ea8e75 | [] | no_license | 2019211001000906-LuQiancheng/2019211001000906_LuQiancheng | 4542cbd0af9096a415defdd2ca4386322a04c97b | c732bc050c06ddd4ff57499499636942ff70ba55 | refs/heads/master | 2023-05-15T13:19:47.407023 | 2021-06-15T04:11:44 | 2021-06-15T04:11:44 | 344,175,713 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,928 | java | package com.luqiancheng.controller;
import com.luqiancheng.dao.OrderDao;
import com.luqiancheng.dao.UserDao;
import com.luqiancheng.model.Order;
import com.luqiancheng.model.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
@WebServlet(name = "AccountDetailsServlet",value = "/accountDetails")
public class AccountDetailsServlet extends HttpServlet {
private Connection con = null;
public void init(){
con = (Connection) getServletContext().getAttribute("con");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session!=null&&session.getAttribute("user")!=null){
User user = (User) session.getAttribute("user");
int id = user.getId();
UserDao dao = new UserDao();
try {
user = dao.findById(con, id);
request.setAttribute("user",user);
OrderDao orderDao = new OrderDao();
List<Order> orderList = orderDao.findByUserId(con, id);
request.setAttribute("orderList",orderList);
request.getRequestDispatcher("WEB-INF/views/accountDetails.jsp").forward(request,response);
} catch (SQLException e) {
e.printStackTrace();
}
}else {
response.sendRedirect("login");
}
}
}
| [
"2360692431@qq.com"
] | 2360692431@qq.com |
3418ea4540f0e34a40312c45a8c2c88dd40f2ed9 | e5f813b13b6ebeb58817ffda4c578ffddcd5cb9f | /src/com/fordays/fdpay/agent/_entity/_AgentBind.java | 0d5e31429eec0cba3ab1c651bbd48e4934354861 | [] | no_license | liveqmock/TPP-AGENT | 8f9fb76d89b0229893b3b9b4845d23cc0e42743e | 14ecb73a24f0c3cb69b08edb2f4742a9f86edd18 | refs/heads/master | 2020-12-31T05:55:19.151400 | 2012-10-09T09:30:22 | 2012-10-09T09:30:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,003 | java | package com.fordays.fdpay.agent._entity;
/**
* AgentBind generated by hbm2java
*/
public class _AgentBind
extends org.apache.struts.action.ActionForm implements Cloneable
{
private static final long serialVersionUID = 1L;
// Fields
protected long id;
protected Long agentId;
protected Long bindAgentId;
protected java.sql.Timestamp createDate;
protected java.sql.Timestamp expireDate;
// Constructors
// Property accessors
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public Long getAgentId() {
return this.agentId;
}
public void setAgentId(Long agentId) {
this.agentId = agentId;
}
public Long getBindAgentId() {
return this.bindAgentId;
}
public void setBindAgentId(Long bindAgentId) {
this.bindAgentId = bindAgentId;
}
public java.sql.Timestamp getCreateDate() {
return this.createDate;
}
public void setCreateDate(java.sql.Timestamp createDate) {
this.createDate = createDate;
}
public java.sql.Timestamp getExpireDate() {
return this.expireDate;
}
public void setExpireDate(java.sql.Timestamp expireDate) {
this.expireDate = expireDate;
}
// The following is extra code specified in the hbm.xml files
public Object clone()
{
Object o = null;
try
{
o = super.clone();
}
catch (CloneNotSupportedException e)
{
e.printStackTrace();
}
return o;
}
private String thisAction="";
public String getThisAction()
{
return thisAction;
}
public void setThisAction(String thisAction)
{
this.thisAction=thisAction;
}
private int index=0;
public int getIndex()
{
return index;
}
public void setIndex(int index)
{
this.index=index;
}
// end of extra code specified in the hbm.xml files
}
| [
"yanrui@kurui.com"
] | yanrui@kurui.com |
3b091c23a6239f447331af7bb33c201fb37b75f2 | cd5b26d40c89cfbcc9aae13cd4a30d9579edca9c | /src/main/java/com/enigma/watchstore/Service/WatchDetailService.java | 9cd765b712afbc9f8be0576f0ce5f94316a41a81 | [] | no_license | WisnuCakraa/watch-store-api | 2fb5685d1df7b52a0e566e4a1e1a748ca2961776 | f490f8a8160a1239ed2a5e584db6f2c1027595cc | refs/heads/main | 2023-03-05T20:20:08.613182 | 2021-02-15T01:05:59 | 2021-02-15T01:05:59 | 337,810,017 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 400 | java | package com.enigma.watchstore.Service;
import java.util.List;
import com.enigma.watchstore.Entity.WatchDetailEntity;
public interface WatchDetailService {
WatchDetailEntity addWatchDetail(WatchDetailEntity watchDetailEntity);
WatchDetailEntity editWatchDetail(WatchDetailEntity watchDetailEntity);
List<WatchDetailEntity> getWatchDetail();
void deleteWatchDetail(String id);
} | [
"you@example.com"
] | you@example.com |
d6360ddd51287df986db860786379fb2bb2fe656 | 46cf62cbce562295874d66ff9c54375a0230ca19 | /src/main/java/com/juliano/cursomc/services/EmailService.java | 78ddcee410862ccdb8ae59857826d9ad5b21edc1 | [] | no_license | julianoamorim/CursoSpring | 9b73625fba294e1973f762104877446a59e98245 | e471d3d14e9b0e616f0260b66535d9fefbcc42cc | refs/heads/master | 2023-08-12T11:58:25.138647 | 2021-10-07T22:38:21 | 2021-10-07T22:38:21 | 365,043,577 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 369 | java | package com.juliano.cursomc.services;
import com.juliano.cursomc.domain.Cliente;
import com.juliano.cursomc.domain.Pedido;
import org.springframework.mail.SimpleMailMessage;
public interface EmailService {
void mandarEmailConfirmacao(Pedido obj);
void mandarEmail(SimpleMailMessage msg);
void mandarNovaSenhaEmail(Cliente cliente, String novaSenha);
}
| [
"julianoamorim89@outlook.com"
] | julianoamorim89@outlook.com |
53b8a6982101645214754a4f6e00a8f0c57808a7 | 0758e91f9e55d303b2989e2416e3a38543d2418a | /FER_JSP/src/com/rs/fer/main/EditExpenseMain.java | 64a10bb5babc1335c05cdc738b3e70621529ecea | [] | no_license | prithiraj123/Java | bebb2186676d33a49c2a2828103cdb6a7e98bce8 | 78b0b2d110ab4f051480be9baebe32bb6a719e25 | refs/heads/master | 2020-03-26T05:41:14.793585 | 2018-08-13T11:47:04 | 2018-08-13T11:47:04 | 144,569,274 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 755 | java | package com.rs.fer.main;
import com.rs.fer.bean.Expense;
import com.rs.fer.service.FERService;
import com.rs.fer.service.FERServiceImpl;
public class EditExpenseMain {
public static void main(String[] args) {
FERService ferservice = new FERServiceImpl();
Expense expense = new Expense();
expense.setExpenseType("function");
expense.setDate("20/12/17");
expense.setPrice(1005);
expense.setNoOfItems(5);
expense.setTotalAmount(6000);
expense.setByWhom("ramesh");
expense.setUserId("4");
expense.setId(5);
boolean isUpdated = ferservice.editExpense(expense);
if (isUpdated) {
System.out.println("Expense edited successfully");
} else {
System.out.println("Expense not edited");
}
}
} | [
"admin@DESKTOP-4RLG0JM"
] | admin@DESKTOP-4RLG0JM |
a5bf40ff740edbfc9a1fdc7890efbf035375624f | a3caa6439679d267550ae337f11ca2a1e6aae19a | /Shike/src/com/yshow/shike/fragments/TeaContentFragment.java | dc93f8fa62f87c53a8c113abe86d2eb20904194c | [] | no_license | Nodeer/shike_github | ebe349e7def93eeae413effc950635fc5bf04ecf | f463e423d0293435a57fbe027b909282be7dfe21 | refs/heads/master | 2020-05-20T12:58:12.621453 | 2014-11-21T14:40:48 | 2014-11-21T14:40:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,904 | java | package com.yshow.shike.fragments;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.yshow.shike.activities.MessageActivity;
import com.yshow.shike.activities.WebViewActivity;
import com.yshow.shike.entity.HomeImgModel;
import com.yshow.shike.service.MySKService;
import com.yshow.shike.utils.ImageLoadOption;
import com.yshow.shike.utils.MyAsyncHttpResponseHandler;
import com.yshow.shike.utils.SKAsyncApiController;
import com.yshow.shike.utils.SKResolveJsonUtil;
import com.yshow.shike.widget.GalleryView;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
import com.yshow.shike.R;
import com.yshow.shike.widget.MyPagerAdapter;
import java.util.ArrayList;
/**
* Created by Administrator on 2014-10-16.
* 老师首页
*/
public class TeaContentFragment extends Fragment implements View.OnClickListener {
ImageView mMessRedIcon;
RelativeLayout mMakeTopicBtn, mTikuButton;
private TextView mOnlineTextView;
private ImageView mTitleRight;
private AnimationDrawable ani;
private String[] urls = {
"http://www.shikeke.com/news.php?id=4",
"http://www.shikeke.com/news.php?id=5",
"http://www.shikeke.com/news.php?id=6"
};
GalleryView gallery;
public Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case MySKService.HAVE_NEW_MESSAGE:
ani.stop();
ani.start();
mMessRedIcon.setVisibility(View.VISIBLE);
break;
}
}
};
private ArrayList<HomeImgModel> list;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tea_content_layout, null);
gallery = (GalleryView) view.findViewById(R.id.gallery);
mTitleRight = (ImageView) view.findViewById(R.id.title_right);
mTitleRight.setOnClickListener(this);
ani = (AnimationDrawable) mTitleRight.getDrawable();
ani.start();
ImageView mTitleLeft = (ImageView) view.findViewById(R.id.title_left);
mTitleLeft.setOnClickListener(this);
mMessRedIcon = (ImageView) view.findViewById(R.id.mess_red);
mMakeTopicBtn = (RelativeLayout) view.findViewById(R.id.make_topic_btn);
mMakeTopicBtn.setOnClickListener(this);
mTikuButton = (RelativeLayout) view.findViewById(R.id.tiku_btn);
mTikuButton.setOnClickListener(this);
mOnlineTextView = (TextView) view.findViewById(R.id.now_online);
SKAsyncApiController.getHomePageImgs(new MyAsyncHttpResponseHandler(getActivity(), true) {
@Override
public void onSuccess(String s) {
super.onSuccess(s);
boolean issuccess = SKResolveJsonUtil.getInstance().resolveIsSuccess(s);
if (issuccess) {
list = SKResolveJsonUtil.getInstance().getHomePageImgs(s);
ArrayList<String> imgs = new ArrayList<String>();
for (HomeImgModel model : list) {
imgs.add(model.pic);
}
gallery.setData(imgs);
gallery.setOnItemClickListaner(new MyPagerAdapter.OnMyClickListener() {
@Override
public void clickItem(int position) {
Intent it = new Intent(getActivity(), WebViewActivity.class);
it.putExtra("url", list.get(position).url);
startActivity(it);
}
});
} else {
gallery.setData(new int[]{R.drawable.blackboard_ad_img, R.drawable.blackboard_ad_img}, false);
gallery.setOnItemClickListaner(new MyPagerAdapter.OnMyClickListener() {
@Override
public void clickItem(int position) {
Intent it = new Intent(getActivity(), WebViewActivity.class);
it.putExtra("url", urls[position]);
startActivity(it);
}
});
}
}
});
return view;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.title_left:
Activity activity = getActivity();
if (activity instanceof SlidingFragmentActivity) {
((SlidingFragmentActivity) activity).showMenu();
}
break;
case R.id.title_right:
mMessRedIcon.setVisibility(View.GONE);
goMessageActivity();
break;
case R.id.make_topic_btn:
mMessRedIcon.setVisibility(View.GONE);
goMessageActivity();
break;
case R.id.tiku_btn:
Toast.makeText(getActivity(), "即将推出", Toast.LENGTH_SHORT).show();
break;
}
}
@Override
public void onResume() {
super.onResume();
MySKService.handler = handler;
}
private void goMessageActivity() {
Intent it = new Intent(getActivity(), MessageActivity.class);
getActivity().startActivity(it);
}
}
| [
"icemansuccess@163.com"
] | icemansuccess@163.com |
fb312a22730a1e4b04c4668b15d6837ac8a2f955 | 470f87fd23895bc9d88551f38abd8b51a2aa99cb | /android/rajawali/src/main/java/org/rajawali3d/materials/textures/Etc2Texture.java | bc14500c0bf6a79fcb9ef0fda3504f53fcce98da | [
"Apache-2.0"
] | permissive | staticmukesh/headouthackathon | d248bd4a8a928a596692a04c47b8b183f63a622a | a42a6ff78e86f3a04d122f6cc7e546d9138228ab | refs/heads/master | 2021-01-10T03:29:27.898494 | 2016-02-11T13:54:34 | 2016-02-11T13:54:34 | 51,232,784 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 7,294 | java | package org.rajawali3d.materials.textures;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.opengl.ETC1;
import android.opengl.GLES11Ext;
import android.opengl.GLES30;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import org.rajawali3d.materials.textures.utils.ETC2Util;
import org.rajawali3d.util.RajLog;
/**
* Rajawali container for an ETC2 texture. Due to the nature of ETC2 textures, you may also use this to load
* an ETC1 texture.
*
* The following GL internal formats are supported:
* - {@link GLES11Ext#GL_ETC1_RGB8_OES}
* - {@link GLES30#GL_COMPRESSED_RGB8_ETC2}
* - {@link GLES30#GL_COMPRESSED_RGBA8_ETC2_EAC}
* - {@link GLES30#GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2}
* - {@link GLES30#GL_COMPRESSED_R11_EAC}
* - {@link GLES30#GL_COMPRESSED_RG11_EAC}
* - {@link GLES30#GL_COMPRESSED_SIGNED_R11_EAC}
* - {@link GLES30#GL_COMPRESSED_SIGNED_RG11_EAC}
*
* In theory, the sRGB types {@link GLES30#GL_COMPRESSED_SRGB8_ETC2}, {@link GLES30#GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC},
* and {@link GLES30#GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2} are also supported, but they will currently fail the
* header check because no source was available to determine their internal type codes.
*
* //TODO: Find internal type codes for sRGB formats.
*
* @author Jared Woolston (jwoolston@tenkiv.com)
*/
public class Etc2Texture extends ACompressedTexture {
protected int mResourceId;
protected Bitmap mBitmap;
public Etc2Texture(String textureName) {
super(textureName);
mCompressionType = CompressionType.ETC2;
}
public Etc2Texture(int resourceId) {
this(TextureManager.getInstance().getContext().getResources().getResourceName(resourceId));
setResourceId(resourceId);
}
public Etc2Texture(String textureName, int resourceId, Bitmap fallbackTexture) {
this(textureName);
Context context = TextureManager.getInstance().getContext();
setInputStream(context.getResources().openRawResource(resourceId), fallbackTexture);
}
public Etc2Texture(String textureName, int[] resourceIds) {
this(textureName);
setResourceIds(resourceIds);
}
public Etc2Texture(String textureName, ByteBuffer byteBuffer) {
this(textureName);
setByteBuffer(byteBuffer);
}
public Etc2Texture(String textureName, ByteBuffer[] byteBuffers) {
this(textureName);
setByteBuffers(byteBuffers);
}
public Etc2Texture(String textureName, InputStream compressedTexture, Bitmap fallbackTexture) {
this(textureName);
setInputStream(compressedTexture, fallbackTexture);
}
public Etc2Texture(Etc1Texture other) {
super();
setFrom(other);
}
@Override
public ATexture clone() {
return null;
}
@Override
void add() throws TextureException {
super.add();
if (mShouldRecycle) {
if (mBitmap != null) {
mBitmap.recycle();
mBitmap = null;
}
}
}
@Override
void reset() throws TextureException {
super.reset();
if (mBitmap != null) {
mBitmap.recycle();
mBitmap = null;
}
}
public void setResourceId(int resourceId) {
mResourceId = resourceId;
Resources resources = TextureManager.getInstance().getContext().getResources();
try {
ETC2Util.ETC2Texture texture = ETC2Util.createTexture(resources.openRawResource(resourceId));
mByteBuffers = new ByteBuffer[]{texture.getData()};
setWidth(texture.getWidth());
setHeight(texture.getHeight());
setCompressionFormat(texture.getCompressionFormat());
} catch (IOException e) {
RajLog.e(e.getMessage());
e.printStackTrace();
}
}
public int getResourceId() {
return mResourceId;
}
public void setResourceIds(int[] resourceIds) {
ByteBuffer[] mipmapChain = new ByteBuffer[resourceIds.length];
Resources resources = TextureManager.getInstance().getContext().getResources();
int mip_0_width = 1, mip_0_height = 1;
try {
for (int i = 0, length = resourceIds.length; i < length; i++) {
ETC2Util.ETC2Texture texture = ETC2Util.createTexture(resources.openRawResource(resourceIds[i]));
if (i == 0) {
setCompressionFormat(texture.getCompressionFormat());
} else {
if (getCompressionFormat() != texture.getCompressionFormat()) {
throw new IllegalArgumentException("The ETC2 compression formats of all textures in the chain much match");
}
}
mipmapChain[i] = texture.getData();
if (i == 0) {
mip_0_width = texture.getWidth();
mip_0_height = texture.getHeight();
}
}
setWidth(mip_0_width);
setHeight(mip_0_height);
} catch (IOException e) {
RajLog.e(e.getMessage());
e.printStackTrace();
}
mByteBuffers = mipmapChain;
}
public void setInputStream(InputStream compressedTexture, Bitmap fallbackTexture) {
ETC2Util.ETC2Texture texture = null;
try {
texture = ETC2Util.createTexture(compressedTexture);
} catch (IOException e) {
RajLog.e("addEtc2Texture:" + e.getMessage());
} finally {
if (texture == null) {
setBitmap(fallbackTexture);
if (RajLog.isDebugEnabled())
RajLog.d("Falling back to ETC1 texture from fallback texture.");
} else {
setCompressionFormat(texture.getCompressionFormat());
setByteBuffer(texture.getData());
setWidth(texture.getWidth());
setHeight(texture.getHeight());
if (RajLog.isDebugEnabled())
RajLog.d("ETC2 texture load successful");
}
}
}
private void setBitmap(Bitmap bitmap) {
mBitmap = bitmap;
int imageSize = bitmap.getRowBytes() * bitmap.getHeight();
ByteBuffer uncompressedBuffer = ByteBuffer.allocateDirect(imageSize);
bitmap.copyPixelsToBuffer(uncompressedBuffer);
uncompressedBuffer.position(0);
ByteBuffer compressedBuffer = ByteBuffer.allocateDirect(
ETC1.getEncodedDataSize(bitmap.getWidth(), bitmap.getHeight())).order(ByteOrder.nativeOrder());
ETC1.encodeImage(uncompressedBuffer, bitmap.getWidth(), bitmap.getHeight(), 2, 2 * bitmap.getWidth(),
compressedBuffer);
setCompressionFormat(ETC1.ETC1_RGB8_OES);
mByteBuffers = new ByteBuffer[]{compressedBuffer};
setWidth(bitmap.getWidth());
setHeight(bitmap.getHeight());
}
}
| [
"sharma.mukesh439@gmail.com"
] | sharma.mukesh439@gmail.com |
a63d75d06be125abc4254dfbd1c252ec476bca9e | 288e5b9a50108b2c29641e7f050a0dd147621c54 | /src/com/oyster/DBandContentProviderEx/data/ToDo.java | 9b3cea8ac6ef49b683411ba5fdf25c0f14315dfe | [
"Apache-2.0"
] | permissive | AndriyBas/android_example_todo | f9693ad9627ee9d4a1cb661cf54281f7e782b27f | e88bd860eaa543e9334bcff62482412f9e5d3843 | refs/heads/master | 2020-05-17T23:59:59.684860 | 2014-04-18T21:16:23 | 2014-04-18T21:16:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,460 | java | package com.oyster.DBandContentProviderEx.data;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import com.oyster.DBandContentProviderEx.data.contentprovider.TodoContentProvider;
import com.oyster.DBandContentProviderEx.data.table.TodoTable;
import com.oyster.DBandContentProviderEx.utils.Utils;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* @author bamboo
* @since 4/11/14 5:10 PM
*/
public class ToDo implements Serializable {
private long mId = -1;
private long mProjectId = -1;
private String mSummary = "";
private String mDescription = "";
private Category mCategory = Category.Remainder;
private long mUpdatedAt = 0;
public ToDo() {
}
public ToDo(long id, long projectId, String summary, String description, Category category) {
this();
mId = id;
mProjectId = projectId;
mSummary = summary;
mDescription = description;
mCategory = category;
}
public ToDo(long id, long projectId, String summary, String description, Category category, long updatedAt) {
this(id, projectId, summary, description, category);
mUpdatedAt = updatedAt;
}
/**
* Convert data from cursor to new _ToDo
*
* @param c
* @return
*/
private static ToDo fromCursor(Cursor c) {
if (c == null) {
return null;
}
ToDo toDo = new ToDo(
c.getLong(c.getColumnIndexOrThrow(TodoTable.COLUMN_ID)),
c.getLong(c.getColumnIndexOrThrow(TodoTable.COLUMN_PROJECT_ID)),
c.getString(c.getColumnIndexOrThrow(TodoTable.COLUMN_SUMMARY)),
c.getString(c.getColumnIndexOrThrow(TodoTable.COLUMN_DESCRIPTION)),
Category.valueOf(c.getString(c.getColumnIndexOrThrow(TodoTable.COLUMN_CATEGORY))),
c.getLong(c.getColumnIndexOrThrow(TodoTable.COLUMN_UPDATED_AT))
);
return toDo;
}
/**
* puts all values int ContentValues class
*
* @return
*/
private ContentValues toContentValues() {
ContentValues values = new ContentValues();
// if (getId() != -1) {
// values.put(TodoTable.COLUMN_ID, getId());
// }
values.put(TodoTable.COLUMN_SUMMARY, getSummary());
values.put(TodoTable.COLUMN_DESCRIPTION, getDescription());
values.put(TodoTable.COLUMN_CATEGORY, getCategory().toString());
values.put(TodoTable.COLUMN_UPDATED_AT, getUpdatedAt());
values.put(TodoTable.COLUMN_PROJECT_ID, getProjectId());
return values;
}
/**
* find cursor by it's id in the database
*
* @param id
* @return
*/
public static ToDo getById(long projectId, long id) {
Uri uri = Uri.parse(TodoContentProvider.CONTENT_TODO_URI + "/" + projectId + "/toDoId/" + id);
Cursor c = Utils.getAppContext().getContentResolver().query(
uri, // Uri
null, // projection
null, // selection
null, // selectionArgs
null // sortOrder
);
if (c == null) {
return null;
}
c.moveToFirst();
if (c.isBeforeFirst() || c.isAfterLast()) {
return null;
}
return fromCursor(c);
}
/**
* find all ToDos in current project
*
* @param projectId
* @return
*/
public static List<ToDo> getByProjectId(long projectId) {
Uri uri = Uri.parse(TodoContentProvider.CONTENT_TODO_URI + "/" + projectId);
Cursor c = Utils.getAppContext().getContentResolver().query(
uri, // Uri
null, // projection
null, // selection
null, // selectionArgs
null // sortOrder
);
ArrayList<ToDo> toDos = new ArrayList<ToDo>();
if (c == null) {
return toDos;
}
c.moveToFirst();
while (!c.isAfterLast()) {
toDos.add(fromCursor(c));
c.moveToNext();
}
return toDos;
}
/**
* saves current _ToDo to the database, or updates if it was saved before
*/
public void save() {
onUpdated();
if (getId() == -1) {
Uri uri = Uri.parse(TodoContentProvider.CONTENT_TODO_URI + "/" + getProjectId());
Uri resUri = Utils.getAppContext().getContentResolver().insert(uri, toContentValues());
setId(Long.parseLong(resUri.getLastPathSegment()));
} else {
Uri uri = Uri.parse(TodoContentProvider.CONTENT_TODO_URI + "/" + getProjectId() + "/toDoId/" + getId());
Utils.getAppContext().getContentResolver().update(
uri, // Uri
toContentValues(), // ContentValues
null, // selection
null // selectionArgs
);
}
}
/**
* deletes the _ToDo from the database
*/
public void delete() {
onUpdated();
// if never saved before
if (getId() == -1) {
return;
}
Uri uri = Uri.parse(TodoContentProvider.CONTENT_TODO_URI + "/" + getProjectId() + "/toDoId/" + getId());
Utils.getAppContext().getContentResolver().delete(
uri, // Uri
null, // selection
null // selectionArgs
);
}
private void onUpdated() {
mUpdatedAt = System.currentTimeMillis();
}
public long getId() {
return mId;
}
public void setId(long id) {
mId = id;
}
public String getSummary() {
return mSummary;
}
public void setSummary(String summary) {
mSummary = summary;
}
public String getDescription() {
return mDescription;
}
public void setDescription(String description) {
mDescription = description;
}
public Category getCategory() {
return mCategory;
}
public void setCategory(Category category) {
mCategory = category;
}
public long getUpdatedAt() {
return mUpdatedAt;
}
public long getProjectId() {
return mProjectId;
}
public void setProjectId(long projectId) {
mProjectId = projectId;
}
}
| [
"avikbascra@gmail.com"
] | avikbascra@gmail.com |
0693e6869d7d82719bd31a5b587529701285bea0 | 00cbdf3e300c1dc54443dcfc7016a87a972d6531 | /Exams/Mid/Main.java | 3521e8d7dc23d4feada64cb8a03b11b9ca12d44d | [] | no_license | ValeriDimov/JavaProgrammingFundamentals | 83a884a061a550c7b81a750a4fcc93cef43e3cae | 6e7e6ba4566be9529108394f82f78a30d4cebd5e | refs/heads/main | 2023-07-15T13:38:49.171917 | 2021-08-27T13:25:13 | 2021-08-27T13:25:13 | 400,170,779 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 243 | java | package Exams.Mid;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int test = 4 % 3;
System.out.println(test);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
6e8360b81f1c95d50271ea65bbc1be7c2fc9c07d | 3ebe740d46970e8f84ec9e86fde23a129f971598 | /src/com/jframe/java/test.java | 74a846affe4bed95048f0827ae12931ded53c5b8 | [] | no_license | 2685818880/GUI_JFrame | e76d49daa0717a8e46f0eab1bfe5e8a1c809d0a1 | 642ec179291c28cbbe8dd5cd81b84b17c3eb3166 | refs/heads/master | 2021-01-01T03:54:55.195120 | 2016-05-10T04:43:36 | 2016-05-10T04:43:36 | 58,430,250 | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 3,702 | java | package com.jframe.java;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyVetoException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
/***
* 桌面面板和内部窗体
* ***/
@SuppressWarnings("serial")
public class test extends JFrame {
JDesktopPane desktopPane = null;
InternalFrame plnFrame=null;
InternalFrame rlnFrame=null;
InternalFrame tlnFrame=null;
public static void main(String[] args) {
test t=new test();
t.setVisible(true);
//t.setSize(800, 600);
//t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public test(){
super();
setTitle("报销");
setBounds(100,100,570,470);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
desktopPane=new JDesktopPane();//创建桌面面板
desktopPane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);//设置内部窗体的拖拽方式
getContentPane().add(desktopPane,BorderLayout.CENTER);//为桌面面板添加背景图片
/*final JButton addButton1 = new JButton("Project_mast");
addButton1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
new Project_mast();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
final JButton addButton2 = new JButton("Bx_mast");
addButton2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
new Bx_mast();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
desktopPane.add(addButton1,new Integer(Integer.MIN_VALUE));
desktopPane.add(addButton2,new Integer(Integer.MIN_VALUE));*/
final JLabel backLabel=new JLabel();
URL resource =this.getClass().getResource("/image/1.jpg");
ImageIcon icon=new ImageIcon(resource);//创建背景图片对象
backLabel.setIcon(icon);
backLabel.setBounds(0, 0, 800, 700);
desktopPane.add(backLabel,new Integer(Integer.MIN_VALUE));
///添加按钮的代码
}
}
class BAListener implements ActionListener{
JDesktopPane desktopPane = null;
InternalFrame inFrame;
String title;
public BAListener(InternalFrame inFrame,String title){
this.inFrame=inFrame;
this.title=title;
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(inFrame==null||inFrame.isClosable()){
JInternalFrame[]allFrames=desktopPane.getAllFrames();
int titleBarHight=30*allFrames.length;
int x=10+titleBarHight,y=x;
int width=250,height=180;
inFrame=new InternalFrame(title);
inFrame.setBounds(x, y, width, height);
inFrame.setVisible(true);
desktopPane.add(inFrame);
}
try {
inFrame.setSelected(true);
} catch (PropertyVetoException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
@SuppressWarnings("serial")
class InternalFrame extends JInternalFrame{
public InternalFrame(String title){
super();
setTitle(title);//设置内部窗体的标题
setResizable(true);//设置准许自由调整大小
setClosable(true);//设置提供“关闭”按钮
setIconifiable(true);//设置提供“最小化”按钮
setMaximizable(true);//设置提供“最大化”按钮
URL resource =this.getClass().getResource("/image/1.jpg");//获得图片的路径
ImageIcon icon=new ImageIcon(resource);//创建图片对象
setFrameIcon(icon);//设置窗体图标
}
} | [
"2685818880@qq.com"
] | 2685818880@qq.com |
a2d753318ca9e3d77ccb35ae1610d0d0797ca9b1 | 4b5d5dc67970d34e7cb55040e849a9de9d77b612 | /part6_spring_aop/src/robin_permission_check/aspect/CustomerAspectCheckPermission.java | a415bea4dac9d57b3c0fe1e89438b414a2dfe5de | [] | no_license | robin2017/cete28 | 9b74b36bda8139b59394e861b5ab0e446d7cfa2c | 4fe0feb2e890eadceed8d9f858fc55ee8649d1d1 | refs/heads/master | 2021-09-12T14:28:41.993102 | 2018-04-17T16:03:06 | 2018-04-17T16:03:06 | 100,281,174 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,666 | java | package robin_permission_check.aspect;
import robin_permission_check.proxyfactory.GeneralDynamicProxyBefore;
import robin_permission_check.data.PermissionData;
import robin_permission_check.service.CustomerServiceImpl;
import java.lang.reflect.Method;
import java.util.List;
/**
* Created by robin on 2017/8/21.
*/
public class CustomerAspectCheckPermission implements GeneralDynamicProxyBefore {
private Method method;
private String name;
public CustomerAspectCheckPermission(String name){
this.name=name;
}
@Override
public void setMethod(Method method) {
this.method=method;
}
@Override
public boolean before() {
boolean isContinue=true;
try {
Method targetMethod= CustomerServiceImpl.class.getDeclaredMethod(method.getName(),
method.getParameterTypes());
if(targetMethod.isAnnotationPresent(RequestPermission.class)){
if(!PermissionData.maps.containsKey(name))
throw new RuntimeException("请登陆");
List<String> permissions=PermissionData.maps.get(name);
RequestPermission permission=targetMethod.getAnnotation(RequestPermission.class);
String per=permission.value();
if(!permissions.contains(per))
throw new RuntimeException("没有权限:"+method.getName());
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
catch (RuntimeException e){
isContinue=false;
System.out.println(e.getMessage());
}
return isContinue;
}
}
| [
"robin.seu@foxmail.com"
] | robin.seu@foxmail.com |
1edc63d1a3109502d4ac545809f458f139a5439f | 490a79c073c9ed9dddbd96612b6b744dcf538ea6 | /encrypt-utils/src/main/java/com/cldt/encrypt/utils/RSA.java | ff891bcf94292aac914eb7a2f3da9d69df7e272c | [
"Apache-2.0"
] | permissive | andy-chau/incubator-std | 184e748d7a1dcf2a8ed04aba17a724f65d848541 | d3a4600cbd291ff52ba1f292cb8eb21430c96a55 | refs/heads/master | 2022-03-13T13:41:16.898575 | 2019-11-29T06:17:07 | 2019-11-29T06:17:07 | 182,928,365 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,545 | java | package com.cldt.encrypt.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import sun.misc.BASE64Decoder;
public class RSA {
public static String ALGORITHM = "RSA";
public static String SIGN_ALGORITHMS = "SHA1WithRSA";// 摘要加密算饭
private static String log = "RSAUtil";
public static String CHAR_SET = "UTF-8";
/** *//**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/** *//**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128;
/**
* 数据签名
*
* @param content
* 签名内容
* @param privateKey
* 私钥
* @return 返回签名数据
*/
public static String sign(String content, String privateKey) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature
.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(CHAR_SET));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 签名验证
*
* @param content
* @param sign
* @param lakala_public_key
* @return
*/
public static boolean verify(String content, String sign,
String lakala_public_key) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] encodedKey = Base64.decode(lakala_public_key);
PublicKey pubKey = keyFactory
.generatePublic(new X509EncodedKeySpec(encodedKey));
java.security.Signature signature = java.security.Signature
.getInstance(SIGN_ALGORITHMS);
signature.initVerify(pubKey);
signature.update(content.getBytes(CHAR_SET));
boolean bverify = signature.verify(Base64.decode(sign));
return bverify;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 通过公钥解密
*
* @param content待解密数据
* @param pk公钥
* @return 返回 解密后的数据
*/
protected static byte[] decryptByPublicKey(String content, PublicKey pk) {
try {
Cipher ch = Cipher.getInstance(ALGORITHM);
ch.init(Cipher.DECRYPT_MODE, pk);
InputStream ins = new ByteArrayInputStream(Base64.decode(content));
ByteArrayOutputStream writer = new ByteArrayOutputStream();
// rsa解密的字节大小最多是128,将需要解密的内容,按128位拆开解密
byte[] buf = new byte[128];
int bufl;
while ((bufl = ins.read(buf)) != -1) {
byte[] block = null;
if (buf.length == bufl) {
block = buf;
} else {
block = new byte[bufl];
for (int i = 0; i < bufl; i++) {
block[i] = buf[i];
}
}
writer.write(ch.doFinal(block));
}
return writer.toByteArray();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 通过私钥加密
*
* @param content
* @param pk
* @return,加密数据,未进行base64进行加密
*/
protected static byte[] encryptByPrivateKey(String content, PrivateKey pk) {
try {
Cipher ch = Cipher.getInstance(ALGORITHM);
ch.init(Cipher.ENCRYPT_MODE, pk);
return ch.doFinal(content.getBytes(CHAR_SET));
} catch (Exception e) {
e.printStackTrace();
System.out.println("通过私钥加密出错");
}
return null;
}
/**
* 解密数据,接收端接收到数据直接解密
*
* @param content
* @param key
* @return
*/
public static String decrypt(String content, String key) {
System.out.println(log + ":decrypt方法中key=" + key);
if (null == key || "".equals(key)) {
System.out.println(log + ":decrypt方法中key=" + key);
return null;
}
String res = null;
try {
PublicKey pk = getPublicKeyByString(key);
byte[] data = decryptByPublicKey(content, pk);
res = new String(data, CHAR_SET);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
/**
* 对内容进行加密
*
* @param content
* @param key私钥
* @return
*/
public static String encrypt(String content, String key) {
String res = null;
try {
PrivateKey pk = getPrivateKeyByString(key);
byte[] data = encryptByPrivateKey(content, pk);
res = Base64.encode(data);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
/** *//**
* <p>
* 公钥加密
* </p>
*
* @param data 源数据
* @param publicKey 公钥(BASE64编码)
* @return
* @throws Exception
*/
public static byte[] encryptByPublicKey(byte[] data, String publicKey)
throws Exception {
byte[] keyBytes = Base64.decode(publicKey);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
Key publicK = keyFactory.generatePublic(x509KeySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicK);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
}
/**
* <p>
* 私钥加密
* </p>
*
* @param data 源数据
* @param privateKey 私钥(BASE64编码)
* @return
* @throws Exception
*/
public static byte[] encryptByPrivateKey(byte[] data, String privateKey)
throws Exception {
byte[] keyBytes = Base64.decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateK);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
}
/**
* <P>
* 私钥解密
* </p>
*
* @param encryptedData 已加密数据
* @param privateKey 私钥(BASE64编码)
* @return
* @throws Exception
*/
public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey)
throws Exception {
byte[] keyBytes = Base64.decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateK);
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
}
public static String decryptByPrivateKey(String encryptedData, String privateKey)
throws Exception {
return new String(decryptByPrivateKey(Base64.decode(encryptedData),privateKey));
}
// 公钥转换
@SuppressWarnings("restriction")
public static PublicKey getPublicKeyByString(String key) throws Exception {
byte[] keyBytes;
keyBytes = (new BASE64Decoder()).decodeBuffer(key);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}
// 私钥转换
@SuppressWarnings("restriction")
public static PrivateKey getPrivateKeyByString(String key) throws Exception {
byte[] keyBytes;
keyBytes = (new BASE64Decoder()).decodeBuffer(key);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
}
public static void main(String[] args) {
String str = Base64.encode("test".getBytes());
System.out.println("Base64加密-->" + str);
String aaa = sign(
str,
"MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKWmOMF5zQBqc8xA41zq9BKHI8GUdZdJR8qP57mv8y2N7T/TD1YeNEx3UH7cSWpsZpdzV5BWKAhH7sTOWfhIU+EhrXrWbQWAndWcT2+ZDYlI0ctJ5Bo1gM0MEU01+g3mhOf70I9DJrYGvoVYV815m+F46bjq8qVEL06zZZLEKCTPAgMBAAECgYEAjZl3rrvFp/NXpWRadtVJaoUm5ZVYp8g2nEtDVJG5mFlYU1TCKWWMY0kjAC6ie1zKnfA1C+b6NYn36zhR5FE/kTSwUYT1P6INT4rD7JUEiwE8hi4MTvWIDCyqeUmb2H+abHpBo9VZymmh5wmwRTi1PgPQGTDq5uP519lgD00DzEECQQDZzHPSvgy0GztmD6Uip1mHDI9j7syIEVCEPtuIsNzH63GQdR5jLH7hZn0WRXEgrZa+f3gKZnFIew+lj6Ip1lPRAkEAwrQrwe6dcioJHdc0PsW/In5TOBTY+ppVKhrkJ6x9UOzZT/BYuXUFVJL8kiKGIK0wihOzMhHK57HjoN5fT5w2nwJBAJ5D4npmXgbWrxAYGFCZOQZYyy28DmZl5pNitdabZqPj5A8r/Bvm7oBOIGF5rp4nZh4htJIiJPmdax5MxHMQarECQH8yMPvqpJT2fSovcwQnL2ybVkZm6DEfLc/p7W81slBxyq38eBoAJtFPjQzy3Ojv+6vYntJw6Ttf7TMk0uMxTEUCQDw1ZXU5jiKoktSYjHjFL2EfqtfT9F8xTHVyaruKL+R67Z0OvxMNlM0j77ADUS/BAFlwF2bCsSkMT3PLvcNtpPk=");
System.out.println("加签-->" + aaa);
System.out
.println("验签-->"
+ verify(
str,
aaa,
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQClpjjBec0AanPMQONc6vQShyPBlHWXSUfKj+e5r/Mtje0/0w9WHjRMd1B+3ElqbGaXc1eQVigIR+7Ezln4SFPhIa161m0FgJ3VnE9vmQ2JSNHLSeQaNYDNDBFNNfoN5oTn+9CPQya2Br6FWFfNeZvheOm46vKlRC9Os2WSxCgkzwIDAQAB"));
System.out.println("原文-->" + new String(Base64.decode(str)));
String key = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQChHEP4d896wdubHz+m8TjoExgrNYMlKsW87+vMZ3smzwiIqGoIG5EQShZqydsgB2JOXn+9s5jVHPEJxHea2Nbn08VP8BAh4Hb4q6VpsKCXkfdstgsS8+Rh+nJzpTxElW+osUBOA+5i4N7i+ut/NXgsxmCxqlJrrYIJI24LFvQHQkAio0qBjp4K9otm6EAF50EZGteBUTWmZa/VuQxUbcix57PYAAZGQHGdEuxxyNuL/qogfNFt9rfpCgMR4xdRZvrDwRwAX6EVWob/Q/iD+GrU4efHv6tBWSh6Esv8Jt/ZnYL3fSR4P5+m7KUuy9gK+X5c5vZEdy4tNH3Y61rR3VvJAgMBAAECggEAfa8FP3KIA2X0IcFw8JVCJZmvwxWN55LEi65HL0CTDCV6rNFlVknbEvAZKNmr/gKEqEqEMMNIuQhI6avA+qWqkVPdm4zVqPfpF/kfo6HMxjFy6fXiEbj+M4kjfCAtMfu6DcmpNrNOZwiyGDRTPvvBcnyXtkH+5k2HIgXntPMFEBtWPdh3poQwJsHnqWpUifCFiQnR5LvBJQZH4ceAwsvGeWIUSCoWhppkh4NRvAaUDon/k4t0aEy1CPzSpS/uQN4Y/N27m8v2/jk8Z0u8Joe+Q03hpEMr7dfSs3bqkIgQX9ZP4d8AEMtzze8Z423PF1yRW9OlUNOX5CF+BT5TP4h6AQKBgQD1mvsJH/J9hIkTjdXYeRq9trsP4RPS/G/wYtBbektUAxk2K9wPm0byU2HQuqEib8VU4VFdkUuiw0+emQ+2BBNunMy1/+d5cn1huKyiR3kH0uaRzVBL1p3qHG+sqZKWE6e/EhoE9WvqQc3Ry9At9pNCzdD2jQwHUtGbzdMMoS/gaQKBgQCn7dJExXHppqyG9pMXOPjwp4b95tBEr8qPluJPFEvE5ypQt1rW43OeORk+FqGwXz2UHCJKIgXgjYnxvHDHxrM02eZTYyTj+jqeGQO8fics38/JxmAwmBu1144pczF4iAbuclYlB7EBY02iX4eS8L1Qng1zaU0VsIyDLCvH94Q0YQKBgQC0Trf3RfXvAgrkSR9yUc448tq32KSGI39GejS+w7Rjk/bBV0eySWu3YVGRPEIplubG3reuOonNjxd3tqTbGnjtnr2G670S4uN7h2ltpY0MGl/dMF6/nmrGQWQW3VLZTMq8slxZwZcdHnwshjVqWPhZdeHv7zKiecGaYWuMfRU56QKBgQCZEzTE86au8fv62vGiDZD+7fcjoy7eLdBbq5KHu1yGFKKCCWGI2LUf2bSk4ERrXaXoSO0I3pK06tB/xuKXeQ0KdEZ8ZLfQCN0+GFdLj0NuqGXk7Cvqn/1CeUdhiVvjHzwSR682+hfjx/2QsbwHueMYhbqFJcvapaCwQad3FK0ygQKBgQC2gK2KQ2GNzkpOSzQh82d1ofyLwNrFl+fFxYycsHWvxpP2yWj/NDqlzRVBzEQv18DKNvtF6PmtV065b0KOpvcpy6kcKjX1ct9HaxL/LcEMo4dUPD7+PGJcZjeisFw2Fn7fh6g3r3qsS0aFGvgdTirjH6IuuGXOPMBw8at6286xjw==";
String content = "PsgMreZA64WcuFoFYEq4y0/BmIaNI+tSoLLtxPGuESqEC7GGuvzUWxMPwTdL9oXWbR6A/5bSPsRbzt3OeB4sLlpp98D9ft7H3rY5iroxfcMIaBDC4us2TUbmO8RvRMLwhyRbGqQ8ODip03H85a+UPb84ILSx5HNDxHxDqkCslSPZiZM7gioVWEiLiHltJs9eYfaCDhuu+hbsmsbjQx32KgGKAHvutiqZiOGI6GAavtE2Z5atZ3hd8bqOzpgipHb4SUGnc9aNtcnTx7zIh0DvSYhDx8dIC9kQHQATsIWhQp6SBmMg9JE/b1VENECMtFPTJNNCVQLCzvWVKZL0gaFCPw==";
try {
System.out.println(decryptByPrivateKey(content, key));
} catch (Exception e) {
e.printStackTrace();
}
}
}
| [
"zhoukaijin@lakala.com"
] | zhoukaijin@lakala.com |
8780deb6a15169d95e02e10f67a09259928d8999 | bfb22064506d435d4165bd99603e34a151fbafb4 | /java8features/src/com/ustglobal/java8features/supplier/Student.java | e92f268ab929757a357d30026511b32ac9f4b7a8 | [] | no_license | Harshamukund/UST-Global-16-SEP-19-Harshamukund | 402bfdae2ffcf1652f6b17820159ad70664bec38 | e69fe4f08779f1d14ef636e7d29bd73394df2f87 | refs/heads/master | 2023-01-10T13:44:54.931405 | 2019-12-22T02:44:47 | 2019-12-22T02:44:47 | 224,569,475 | 0 | 0 | null | 2023-01-07T13:04:47 | 2019-11-28T04:25:54 | Java | UTF-8 | Java | false | false | 272 | java | package com.ustglobal.java8features.supplier;
public class Student {
int id;
String name;
double percentage;
public Student(int id, String name, double percentage) {
super();
this.id = id;
this.name = name;
this.percentage = percentage;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
b7cb9130df28c1dc65596982e6fb205edd98eced | 66a4188732238a72d08e46eae61bd75cf20e8b19 | /src/main/java/seedu/dietbook/person/Person.java | eb85de0f983c3b4b7c3d5b2ebe6c37fc76f410b8 | [] | no_license | snowbanana12345/tp | 6a7865744a2d22ef1a816a44ea7a0d072fa5c9dd | 7a008687a2ba85ebb29172563785beec30e63454 | refs/heads/master | 2023-01-05T22:22:57.161636 | 2020-10-22T06:10:33 | 2020-10-22T06:10:33 | 300,172,122 | 0 | 0 | null | 2020-10-28T12:08:24 | 2020-10-01T06:32:03 | Java | UTF-8 | Java | false | false | 7,590 | java | package seedu.dietbook.person;
/**
* Represents a Person.
* A <code>Person</code> has a name, gender, age, height, certain activity level, original and desired weight.
*/
public class Person {
/* The height of the person in cm */
private int height;
/* The original weight of the person in kg */
private int originalWeight;
/* The target weight of the person in kg */
private int targetWeight;
private int age;
private ActivityLevel activityLevel;
private Gender gender;
private String name;
/**
* Constructs a <code>Person</code> with the given name, gender, age, height, original weight, target
* weight and activity level.
*
* @param name The name of the person.
* @param gender The gender of the person.
* @param age The age of the person.
* @param height The height of the person.
* @param originalWeight The original weight of the person.
* @param targetWeight The target/desired weight that the person wants to achieve.
* @param activityLevel The activity level of the person or in other words, the amount of exercise the
* person engages in.
*/
public Person(String name, Gender gender, int age, int height, int originalWeight, int targetWeight,
ActivityLevel activityLevel) {
assert name != null : "Name of person should not be null";
assert name.trim().length() > 0 : "Name of person should not be an empty string";
assert gender != null : "Gender of person should not be null";
assert age > 0 : "Age of person should be greater than 0";
assert age < 125 : "Age of person should be less than 125";
assert height > 0 : "Height of person should be greater than 0";
assert height < 273 : "Height of person should be less than 273";
assert originalWeight > 0 : "Original weight of person should be greater than 0";
assert originalWeight < 443 : "Original weight of person should be less than 443";
assert targetWeight > 0 : "Target weight of person should be greater than 0";
assert targetWeight < 443 : "Target weight of person should be less than 443";
assert activityLevel != null : "Activity level of person should not be null";
this.name = name.trim();
this.gender = gender;
this.age = age;
this.height = height;
this.originalWeight = originalWeight;
this.targetWeight = targetWeight;
this.activityLevel = activityLevel;
}
/**
* Returns the name of the person.
*
* @return The name of the person.
*/
public String getName() {
return name;
}
/**
* Sets the name of the person to the new name given.
*
* @param newName The new/revised name of the person.
*/
public void setName(String newName) {
assert newName != null : "The revised name of person should not be null";
assert newName.trim().length() > 0 : "The revised name of person should not be an empty string";
name = newName.trim();
}
/**
* Returns the gender of the person.
*
* @return The gender of the person.
*/
public Gender getGender() {
return gender;
}
/**
* Sets the gender of the person to the new gender given.
*
* @param newGender The new/revised gender of the person.
*/
public void setGender(Gender newGender) {
assert newGender != null : "The revised gender of person should not be null";
gender = newGender;
}
/**
* Returns the age of the person.
*
* @return The age of the person.
*/
public int getAge() {
return age;
}
/**
* Sets the age of the person to the new age that is given.
*
* @param newAge The new/revised age of the person.
*/
public void setAge(int newAge) {
assert newAge > 0 : "The revised age of person should be greater than 0";
assert newAge < 125 : "The revised age of person should be lesser than 125";
age = newAge;
}
/**
* Returns the height of the person.
*
* @return The height of the person.
*/
public int getHeight() {
return height;
}
/**
* Sets the height of the person to the new height given.
*
* @param newHeight The new/revised height of the person.
*/
public void setHeight(int newHeight) {
assert newHeight > 0 : "The revised height of person should be greater than 0";
assert newHeight < 273 : "The revised height of person should be lesser than 273";
height = newHeight;
}
/**
* Returns the original weight of the person.
*
* @return The original weight of the person.
*/
public int getOriginalWeight() {
return originalWeight;
}
/**
* Sets the original weight of the person to the new original weight given.
*
* @param newOriginalWeight The new/revised original weight of the person.
*/
public void setOriginalWeight(int newOriginalWeight) {
assert newOriginalWeight > 0 : "The revised original weight of person should be greater than 0";
assert newOriginalWeight < 443 : "The revised original weight of person should be lesser than 443";
originalWeight = newOriginalWeight;
}
/**
* Returns the target weight the person the person wants to achieve.
*
* @return The target weight the person wants to achieve.
*/
public int getTargetWeight() {
return targetWeight;
}
/**
* Sets the target weight of the person to the new target weight given.
*
* @param newTargetWeight The new/revised target weight of the person.
*/
public void setTargetWeight(int newTargetWeight) {
assert newTargetWeight > 0 : "The revised target weight of person should be greater than 0";
assert newTargetWeight < 443 : "The revised target weight of person should be lesser than 443";
targetWeight = newTargetWeight;
}
/**
* Returns the activity level of the person.
*
* @return The activity level of the person.
*/
public ActivityLevel getActivityLevel() {
return activityLevel;
}
/**
* Sets the activity level of the person to the new activity level given.
*
* @param newActivityLevel The new/revised activity level of the person.
*/
public void setActivityLevel(ActivityLevel newActivityLevel) {
assert newActivityLevel != null : "The revised activity level of person should not be null";
activityLevel = newActivityLevel;
}
/**
* Returns a string representation of all information related to the user.
* Information includes name, gender, age, height, original weight, target weight and activity level.
*
* @return A string representation of all information related to the user.
*/
@Override
public String toString() {
String userInformation = " Name: " + name + System.lineSeparator()
+ " Gender: " + gender.getDescription() + System.lineSeparator()
+ " Age: " + age + System.lineSeparator()
+ " Height: " + height + "cm" + System.lineSeparator()
+ " Original weight: " + originalWeight + "kg" + System.lineSeparator()
+ " Target weight: " + targetWeight + "kg" + System.lineSeparator()
+ " Activity level: " + activityLevel.getDescription();
return userInformation;
}
}
| [
"heng.fu.yuen@gmail.com"
] | heng.fu.yuen@gmail.com |
c37838a083860dcc96c3c59cfbfe8d103649f07a | 79a6c4056ac33f762fc3a09c2a3c7aab5aae7205 | /backend/spring-ddd/src/main/java/com/tanjie/demo/domain/ExeciseEntry.java | 0a6e71d44e9c4ff4c26c55b1a7b9d9347b6f15c9 | [] | no_license | lstq-lab/jhipster-labs | 812bbf557b5d13c0b0a3114a88d9efdfb4803ce4 | aac5daa6ffba961e45dbb6005a1cfd909ec0eb17 | refs/heads/master | 2023-01-09T02:35:20.289983 | 2019-07-16T10:00:37 | 2019-07-16T10:00:37 | 213,600,832 | 0 | 0 | null | 2023-01-07T10:31:35 | 2019-10-08T09:25:48 | Java | UTF-8 | Java | false | false | 4,216 | java | package com.tanjie.demo.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
/**
* A ExeciseEntry.
*/
@Entity
@Table(name = "execise_entry")
//@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class ExeciseEntry implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "target")
private Integer target;
@Column(name = "is_finished")
private Boolean isFinished;
@OneToMany(fetch=FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "execiseEntry")
// @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<ExeciseEntryGroup> execiseEntryGroups = new HashSet<>();
@ManyToOne(targetEntity=ExeciseProject.class, optional=false)
@JsonIgnoreProperties("execiseEntries")
private ExeciseProject execiseProject;
@ManyToOne(targetEntity = ExecisePlan.class ,optional = false)
@JsonIgnoreProperties("execiseEntries")
private ExecisePlan execisePlan;
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getTarget() {
return target;
}
public ExeciseEntry target(Integer target) {
this.target = target;
return this;
}
public void setTarget(Integer target) {
this.target = target;
}
public Boolean isIsFinished() {
return isFinished;
}
public ExeciseEntry isFinished(Boolean isFinished) {
this.isFinished = isFinished;
return this;
}
public void setIsFinished(Boolean isFinished) {
this.isFinished = isFinished;
}
public Set<ExeciseEntryGroup> getExeciseEntryGroups() {
return execiseEntryGroups;
}
public ExeciseEntry execiseEntryGroups(Set<ExeciseEntryGroup> execiseEntryGroups) {
this.execiseEntryGroups = execiseEntryGroups;
return this;
}
public ExeciseEntry addExeciseEntryGroup(ExeciseEntryGroup execiseEntryGroup) {
this.execiseEntryGroups.add(execiseEntryGroup);
execiseEntryGroup.setExeciseEntry(this);
return this;
}
public ExeciseEntry removeExeciseEntryGroup(ExeciseEntryGroup execiseEntryGroup) {
this.execiseEntryGroups.remove(execiseEntryGroup);
execiseEntryGroup.setExeciseEntry(null);
return this;
}
public void setExeciseEntryGroups(Set<ExeciseEntryGroup> execiseEntryGroups) {
this.execiseEntryGroups = execiseEntryGroups;
}
public ExeciseProject getExeciseProject() {
return execiseProject;
}
public ExeciseEntry execiseProject(ExeciseProject execiseProject) {
this.execiseProject = execiseProject;
return this;
}
public void setExeciseProject(ExeciseProject execiseProject) {
this.execiseProject = execiseProject;
}
public ExecisePlan getExecisePlan() {
return execisePlan;
}
public ExeciseEntry execisePlan(ExecisePlan execisePlan) {
this.execisePlan = execisePlan;
return this;
}
public void setExecisePlan(ExecisePlan execisePlan) {
this.execisePlan = execisePlan;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ExeciseEntry)) {
return false;
}
return id != null && id.equals(((ExeciseEntry) o).id);
}
@Override
public int hashCode() {
return 31;
}
@Override
public String toString() {
return "ExeciseEntry{" +
"id=" + getId() +
", target=" + getTarget() +
", isFinished='" + isIsFinished() + "'" +
"}";
}
}
| [
"tanjie@deepexi.com"
] | tanjie@deepexi.com |
ef00d197bb8f902bfa9e5cfd8ed666e421f61fc9 | 8646cd4b5b4b12e436f8f1b2a0b675f29765d348 | /src/pset1/C.java | 4396583a492d2da0b0a3725b4c88f1f300b2316a | [] | no_license | JavierPalomares90/software-testing-pset1 | 97d21f5d1e9deba82d147b4cdea038e1ec13a4f5 | c45c12d28c1957c2710ff0c5a6ecf3db0a2da0bf | refs/heads/master | 2022-01-05T15:39:03.134605 | 2018-06-20T01:52:50 | 2018-06-20T01:52:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 383 | java | package pset1;
public class C
{
int f;
public C(int f)
{
this.f = f;
}
@Override
public boolean equals(Object o)
{
// assume this method is implemented for you
return super.equals(o);
}
@Override
public int hashCode()
{
// assume this method is implemented for you
return super.hashCode();
}
}
| [
"javier.palomares.90@gmail.com"
] | javier.palomares.90@gmail.com |
b7325eefe7f722ef6bb6fbf71ce279a5d0e8a50d | 0af8b92686a58eb0b64e319b22411432aca7a8f3 | /large-multiproject/project35/src/test/java/org/gradle/test/performance35_1/Test35_94.java | d5ccb439e5fad6bb4a02c371119dbf1f4e45d7ad | [] | no_license | gradle/performance-comparisons | b0d38db37c326e0ce271abebdb3c91769b860799 | e53dc7182fafcf9fedf07920cbbea8b40ee4eef4 | refs/heads/master | 2023-08-14T19:24:39.164276 | 2022-11-24T05:18:33 | 2022-11-24T05:18:33 | 80,121,268 | 17 | 15 | null | 2022-09-30T08:04:35 | 2017-01-26T14:25:33 | null | UTF-8 | Java | false | false | 289 | java | package org.gradle.test.performance35_1;
import static org.junit.Assert.*;
public class Test35_94 {
private final Production35_94 production = new Production35_94("value");
@org.junit.Test
public void test() {
assertEquals(production.getProperty(), "value");
}
} | [
"cedric.champeau@gmail.com"
] | cedric.champeau@gmail.com |
8a3bf5c2fb4da182d36c1f5aaed5821bbdd67d33 | e14fd9b2579565ace194a5a292a27c868b16a396 | /algorithm/src/dynamic_plan/C6.java | 0b20e4a619d521030e0ea370bfdb4981f342f943 | [] | no_license | weilulu/study | dc606dad8990c238a7b06009956153185665d451 | 49db940bf9c85a942e5286bdfc4791eaf12d23c3 | refs/heads/master | 2022-12-25T12:53:01.670609 | 2022-07-10T15:07:22 | 2022-07-10T15:07:22 | 193,913,511 | 0 | 1 | null | 2022-12-16T08:58:15 | 2019-06-26T13:48:00 | Java | UTF-8 | Java | false | false | 3,871 | java | package dynamic_plan;
import java.util.Arrays;
import java.util.HashMap;
/**
* 数组中的最长连续序列
* 给定无序数组arr,返回其中最长的连续序列的长度
* 如:arr=[100,4,200,1,3,2],最长的连续序列为[1,2,3,4],返回4
* 时间复杂度为O(n),空间复杂度为:O(n)
*/
public class C6 {
/**
* 这个是左程云的方法,但merge方法里的开始两行不理解
* @param arr
* @return
*/
public int longestConsecutive(int[] arr){
if (arr == null || arr.length == 0){
return 0;
}
int max =1;
//key:遍历过的某个数,value:这个数所在的最长连续序列的长度
HashMap<Integer,Integer> map = new HashMap<>();
for (int i=0;i<arr.length;i++){
if(!map.containsKey(arr[i])){
map.put(arr[i],1);//在没拼接之前,放进去的数对应的都是最短值1,随着这个数与前面的数(-1)或后面的数(+1)拼接后会形成最长值。
if(map.containsKey(arr[i]-1)){
max = Math.max(max,merge(map,arr[i]-1,arr[i]));
}
if(map.containsKey(arr[i]+1)){
max = Math.max(max,merge(map,arr[i],arr[i]+1));
}
}
}
return max;
}
public int merge(HashMap<Integer,Integer> map,int less,int more){
int left = less - map.get(less) + 1;//子序列的左边界元素
int right = more + map.get(more) - 1;//子序列的右边界元素
int len = right - left + 1;
map.put(left,len);
map.put(right,len);
return len;
}
public static void main(String[] args) {
C6 c6 = new C6();
int[] arr = {100,4,200,1,3,2};
int i = c6.m3(arr);
System.out.println(i);
}
/**
* 这个是网上的方法:https://blog.nowcoder.net/n/8c71b5ca85a64af39e9ca2601671a74e
* @param nums
* @return
* {100,4,200,1,3,2}
*/
public int m2(int[] nums) {
//map中保存着子序列当前左侧元素,当前右侧元素,当前元素及子序列长度
HashMap<Integer, Integer> map = new HashMap<>();
int max = 0;
for (int x : nums) {
if (!map.containsKey(x)) {
int left = map.getOrDefault(x - 1, 0);//前一元素所在序列长度
int right = map.getOrDefault(x + 1, 0);//后一元素所在序列长度
int sum = left + right + 1;//前面元素所在的序列长度+后面元素所在序列长度+当前元素序列长度(当前元素是一个长度为1的子序列)
map.put(x, sum);
map.put(x - left, sum);//x-left 序列的左边界
map.put(x + right, sum);//x+right 序列的右边界
max = Math.max(max, sum);
}
}
return max;
}
/**
* 1,先进行排序
* 2,统计连续序列长度:遇到重复元素跳过;遇到不连续元素重置;遇到连续元素加一并更新max
* @param arr
* @return
*/
public int m3(int[] arr) {
Arrays.sort(arr);
int length = 1;//每次遍历中子序列的长度,遍历过程中如果发现当前元素与已形成的子序列连续,则子序列长度加1;如果不连续则子序列长度置为1
int max = 1;//记录所有子序列中最长的长度
for (int i=1;i<arr.length;i++){
if(arr[i] == arr[i-1]+1){//说明是连续的,将
length = length + 1;
max = Math.max(max,length);
}else if(arr[i] == arr[i-1]){//遇到重复的元素,直接跳过
continue;
}else{//说明不连续,将子序列置为1
length = 1;
}
}
return max;
}
}
| [
"762990029@qq.com"
] | 762990029@qq.com |
b8e9c5e87659f7983694f51a90c53652e2781721 | b50f46bd76634a9815e3422bb9d0adeedc8d442f | /ScanMoudle/app/src/androidTest/java/scan/scanmoudle/ExampleInstrumentedTest.java | 5d636a6829fb7b437af9d3ab2804add6c3ab0246 | [] | no_license | ZHENGZX123/Scan | 512a6273e9bf159d3b645e6189c8eb95bfd31bd7 | 22f808f9f5fc68ba491862f801934fbb91a379ac | refs/heads/master | 2021-01-01T19:35:34.620854 | 2017-07-28T06:31:43 | 2017-07-28T06:31:43 | 98,616,433 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 734 | java | package scan.scanmoudle;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("scan.scanmoudle", appContext.getPackageName());
}
}
| [
"656701179@qq.com"
] | 656701179@qq.com |
d581aa0882e0d931a654628c5690e7f9d249f51e | 12512635babd74cd21de0a6429518f95e5062852 | /JAVA&J2EE/Swings/Text Fields/TextFieldExample1.java | 551d428a19d7585cc8e928b40d97377fcbd9d569 | [
"MIT"
] | permissive | vybhavjain/6thSemIse | d068aea97090fe8361484fa45fedddc49c61810d | 64278d5dc0b625e9d9ade45d6e59a57e695ccba3 | refs/heads/master | 2021-07-13T05:21:14.960666 | 2020-06-26T14:14:27 | 2020-06-26T14:14:27 | 171,490,444 | 1 | 3 | MIT | 2020-06-26T14:14:28 | 2019-02-19T14:41:10 | Java | UTF-8 | Java | false | false | 1,400 | java | import javax.swing.*;
import java.awt.event.*;
public class TextFieldExample1 implements ActionListener{
JTextField tf1,tf2,tf3;
JButton b1,b2;
TextFieldExample1(){
JFrame f= new JFrame();
tf1=new JTextField();
tf1.setBounds(50,50,150,20);
tf2=new JTextField();
tf2.setBounds(50,100,150,20);
tf3=new JTextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new JButton("+");
b1.setBounds(50,200,50,50);
b2=new JButton("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s1=tf1.getText();
String s2=tf2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1){
c=a+b;
}else if(e.getSource()==b2){
c=a-b;
}
String result=String.valueOf(c);
tf3.setText(result);
}
public static void main(String[] args) {
new TextFieldExample1();
} } | [
"noreply@github.com"
] | noreply@github.com |
10f707ebf3e5bf2dca0e13b9b7cc367df89a1902 | ec1a0d22f56d5f364a74d6c8598f588a232847a7 | /Speech Processing - Maori/src/com/a03/game/Level.java | ebaaf872f380c028e617b930e0cb97bedf376402 | [
"MIT"
] | permissive | mfrost433/Tatai | eb6c0f12a63814885cf403aaf22ce4254745b66c | da3c8b5ba2c6037a7d21e0ce0156e72c5165ac57 | refs/heads/master | 2020-03-20T12:53:23.117308 | 2018-06-15T05:37:18 | 2018-06-15T05:37:18 | 137,442,792 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,009 | java | package com.a03.game;
import java.util.ArrayList;
import java.util.List;
import com.a03.speech.VoiceData;
/**
* Data structure for the level info; contains all relevant level info
* and allows for practise levels to be played
* @author Matthew
*
*/
public class Level {
// todo: change MaoriNumbers to allow for 1-99.
private int _attempts = 0, _number;
private boolean pass = false;
private List<MaoriNumbers> m;
private String equationString;
private boolean _add = true,
_minus= true,
_multiply= true,
_divide= true;
/*
* This constructor is for regular games, not practise games.
* determines whether to start an easy or hard level.
*/
public Level(int i){
_add = true;
_minus= true;
_multiply= true;
_divide= true;
_number = i;
m = MaoriNumberFactory.createNumber(_number);
if( i < 10 ) {
equationString = easyEquation();
}else {
equationString = hardEquation();
}
}
/*
* This constructor is for practise levels, allows customization of the
* math operations.
*/
public Level(int start, int finish, boolean add, boolean minus, boolean multiply, boolean divide){
_add = add;
_minus = minus;
_multiply = multiply;
_divide = divide;
_number = (int)((finish - start)*Math.random())+ start;
m = MaoriNumberFactory.createNumber(_number);
equationString = hardEquation();
}
/*
* converts a boolean to an int (1 = true, 0 = false)
*/
int boolToInt( boolean b ){
if ( b )
return 1;
return 0;
}
public enum Operation {
ADDITION, SUBTRACTION, MULTIPLICATION, DIVISION
}
/*
* This defines logic for producing a practice level with
* a changing number of operations being played.
* The number of operations being played is summed, and then
* 1 / the sum provides the probability bracket for each
* operation being generated.
*/
private String hardEquation() {
ArrayList<Operation> operations = new ArrayList<Operation>();
int num;
//Adding relevant possible operations to operations list
if(_add) {
operations.add(Operation.ADDITION);
}
if(_minus) {
operations.add(Operation.SUBTRACTION);
}
if( !isPrime(_number) && _multiply) {
//Does not try to multiply to primes
//Double weighting to counter conditions
operations.add(Operation.MULTIPLICATION);
operations.add(Operation.MULTIPLICATION);
}
if( _number < 60 && _divide ) {
//Does not try to divide to large numbers
//Double weighting to counter conditions
operations.add(Operation.DIVISION);
operations.add(Operation.DIVISION);
}
Operation operator = operations.get( (int) ( Math.random()*( (double)operations.size() ) ) );
//Choosing a random operation
//Logic for generating an equation string from the given operation
switch (operator) {
case ADDITION:
num = ((int)(Math.random()*100))%_number;
return Integer.toString(_number - num) + " + " + Integer.toString(num);
case SUBTRACTION:
num = ((int)(Math.random()*100))%(1000-_number);
return Integer.toString(_number + num) + " - " + Integer.toString(num);
case MULTIPLICATION:
List<Integer> factorList = findFactors(_number);
num = factorList.get( ((int)((factorList.size()*Math.random()))) );
return Integer.toString(_number / num) + " x " + Integer.toString(num);
case DIVISION:
num = (int)(Math.random()* ( 150.0 / ((double)_number)) + 1);
return Integer.toString(_number * num) + " / " + Integer.toString(num);
}
return "" + _number;
//Otherwise return lone number
}
/*
* defines easy level generation - 50/50 chance of producing a
* subtraction or addition question
*/
private String easyEquation() {
double rand1 = Math.random();
double deciderNum = Math.random();
if( deciderNum < 0.5) {
//Addition question
int num = ((int)(rand1*_number));
return Integer.toString(_number - num) + " + " + Integer.toString(num);
}else {
//Subtraction question
int num = ((int)(rand1*_number));
return Integer.toString(_number + num) + " - " + Integer.toString(num);
}
}
public List<MaoriNumbers> getWord(){
return m;
}
public void passed() {
pass = true;
}
public boolean getPass(){
return pass;
}
public int getAttempt(){
if(_attempts == 2) {
_attempts = 0;
return 2;
}
return _attempts;
}
public int getNumber(){
return _number;
}
public void attempted() {
_attempts++;
}
public String getEquationString() {
return equationString;
}
/*
* used for find factors for multiplication questions
*/
public List<Integer> findFactors(int n){
ArrayList<Integer> list = new ArrayList<Integer>();
for( int i = 1; i <= n; i ++) {
if( n % i == 0 ) {
list.add(i);
}
}
return list;
}
/*
* Avoids prime numbers from becoming multiplication questions.
*/
private boolean isPrime(int num) {
if (num % 2 == 0) return false;
for (int i = 3; i * i < num; i += 2)
if (num % i == 0) return false;
return true;
}
}
| [
"death2502@yahoo.co.nz"
] | death2502@yahoo.co.nz |
090984ce319838ea5a5cb7571b83b0e196a02a56 | 32db8c99853048df598779e5c9de0230696359df | /app/build/generated/not_namespaced_r_class_sources/debug/r/android/support/coreutils/R.java | da3d65aeac9a4e69db3419978ea27dcbe1d2c051 | [
"Apache-2.0"
] | permissive | clacosta/android-espresso-testes-complexos | 7efb8bce69f8fa24b8e9d7350c9d12650bceeb1b | 68e0eee772f325a2de67acecdb0e15e12635dd53 | refs/heads/master | 2020-08-31T04:43:40.597897 | 2019-11-01T00:06:18 | 2019-11-01T00:06:18 | 218,591,750 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,456 | java | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package android.support.coreutils;
public final class R {
private R() {}
public static final class attr {
private attr() {}
public static final int alpha = 0x7f030027;
public static final int font = 0x7f0300d7;
public static final int fontProviderAuthority = 0x7f0300d9;
public static final int fontProviderCerts = 0x7f0300da;
public static final int fontProviderFetchStrategy = 0x7f0300db;
public static final int fontProviderFetchTimeout = 0x7f0300dc;
public static final int fontProviderPackage = 0x7f0300dd;
public static final int fontProviderQuery = 0x7f0300de;
public static final int fontStyle = 0x7f0300df;
public static final int fontVariationSettings = 0x7f0300e0;
public static final int fontWeight = 0x7f0300e1;
public static final int ttcIndex = 0x7f030208;
}
public static final class color {
private color() {}
public static final int notification_action_color_filter = 0x7f05006a;
public static final int notification_icon_bg_color = 0x7f05006b;
public static final int ripple_material_light = 0x7f050075;
public static final int secondary_text_default_material_light = 0x7f050077;
}
public static final class dimen {
private dimen() {}
public static final int compat_button_inset_horizontal_material = 0x7f06004e;
public static final int compat_button_inset_vertical_material = 0x7f06004f;
public static final int compat_button_padding_horizontal_material = 0x7f060050;
public static final int compat_button_padding_vertical_material = 0x7f060051;
public static final int compat_control_corner_material = 0x7f060052;
public static final int compat_notification_large_icon_max_height = 0x7f060053;
public static final int compat_notification_large_icon_max_width = 0x7f060054;
public static final int notification_action_icon_size = 0x7f0600c0;
public static final int notification_action_text_size = 0x7f0600c1;
public static final int notification_big_circle_margin = 0x7f0600c2;
public static final int notification_content_margin_start = 0x7f0600c3;
public static final int notification_large_icon_height = 0x7f0600c4;
public static final int notification_large_icon_width = 0x7f0600c5;
public static final int notification_main_column_padding_top = 0x7f0600c6;
public static final int notification_media_narrow_margin = 0x7f0600c7;
public static final int notification_right_icon_size = 0x7f0600c8;
public static final int notification_right_side_padding_top = 0x7f0600c9;
public static final int notification_small_icon_background_padding = 0x7f0600ca;
public static final int notification_small_icon_size_as_large = 0x7f0600cb;
public static final int notification_subtext_size = 0x7f0600cc;
public static final int notification_top_pad = 0x7f0600cd;
public static final int notification_top_pad_large_text = 0x7f0600ce;
}
public static final class drawable {
private drawable() {}
public static final int notification_action_background = 0x7f07006e;
public static final int notification_bg = 0x7f07006f;
public static final int notification_bg_low = 0x7f070070;
public static final int notification_bg_low_normal = 0x7f070071;
public static final int notification_bg_low_pressed = 0x7f070072;
public static final int notification_bg_normal = 0x7f070073;
public static final int notification_bg_normal_pressed = 0x7f070074;
public static final int notification_icon_background = 0x7f070075;
public static final int notification_template_icon_bg = 0x7f070076;
public static final int notification_template_icon_low_bg = 0x7f070077;
public static final int notification_tile_bg = 0x7f070078;
public static final int notify_panel_notification_icon_bg = 0x7f070079;
}
public static final class id {
private id() {}
public static final int action_container = 0x7f08000d;
public static final int action_divider = 0x7f08000f;
public static final int action_image = 0x7f080010;
public static final int action_text = 0x7f080016;
public static final int actions = 0x7f080017;
public static final int async = 0x7f08001d;
public static final int blocking = 0x7f080021;
public static final int chronometer = 0x7f080029;
public static final int forever = 0x7f080049;
public static final int icon = 0x7f080054;
public static final int icon_group = 0x7f080055;
public static final int info = 0x7f080058;
public static final int italic = 0x7f08005a;
public static final int line1 = 0x7f08006c;
public static final int line3 = 0x7f08006d;
public static final int normal = 0x7f08007e;
public static final int notification_background = 0x7f08007f;
public static final int notification_main_column = 0x7f080080;
public static final int notification_main_column_container = 0x7f080081;
public static final int right_icon = 0x7f08008e;
public static final int right_side = 0x7f08008f;
public static final int tag_transition_group = 0x7f0800bb;
public static final int tag_unhandled_key_event_manager = 0x7f0800bc;
public static final int tag_unhandled_key_listeners = 0x7f0800bd;
public static final int text = 0x7f0800be;
public static final int text2 = 0x7f0800bf;
public static final int time = 0x7f0800c7;
public static final int title = 0x7f0800c8;
}
public static final class integer {
private integer() {}
public static final int status_bar_notification_info_maxnum = 0x7f09000e;
}
public static final class layout {
private layout() {}
public static final int notification_action = 0x7f0b0033;
public static final int notification_action_tombstone = 0x7f0b0034;
public static final int notification_template_custom_big = 0x7f0b0035;
public static final int notification_template_icon_group = 0x7f0b0036;
public static final int notification_template_part_chronometer = 0x7f0b0037;
public static final int notification_template_part_time = 0x7f0b0038;
}
public static final class string {
private string() {}
public static final int status_bar_notification_info_overflow = 0x7f0e003a;
}
public static final class style {
private style() {}
public static final int TextAppearance_Compat_Notification = 0x7f0f0115;
public static final int TextAppearance_Compat_Notification_Info = 0x7f0f0116;
public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0f0117;
public static final int TextAppearance_Compat_Notification_Time = 0x7f0f0118;
public static final int TextAppearance_Compat_Notification_Title = 0x7f0f0119;
public static final int Widget_Compat_NotificationActionContainer = 0x7f0f01bf;
public static final int Widget_Compat_NotificationActionText = 0x7f0f01c0;
}
public static final class styleable {
private styleable() {}
public static final int[] ColorStateListItem = { 0x10101a5, 0x101031f, 0x7f030027 };
public static final int ColorStateListItem_android_color = 0;
public static final int ColorStateListItem_android_alpha = 1;
public static final int ColorStateListItem_alpha = 2;
public static final int[] FontFamily = { 0x7f0300d9, 0x7f0300da, 0x7f0300db, 0x7f0300dc, 0x7f0300dd, 0x7f0300de };
public static final int FontFamily_fontProviderAuthority = 0;
public static final int FontFamily_fontProviderCerts = 1;
public static final int FontFamily_fontProviderFetchStrategy = 2;
public static final int FontFamily_fontProviderFetchTimeout = 3;
public static final int FontFamily_fontProviderPackage = 4;
public static final int FontFamily_fontProviderQuery = 5;
public static final int[] FontFamilyFont = { 0x1010532, 0x1010533, 0x101053f, 0x101056f, 0x1010570, 0x7f0300d7, 0x7f0300df, 0x7f0300e0, 0x7f0300e1, 0x7f030208 };
public static final int FontFamilyFont_android_font = 0;
public static final int FontFamilyFont_android_fontWeight = 1;
public static final int FontFamilyFont_android_fontStyle = 2;
public static final int FontFamilyFont_android_ttcIndex = 3;
public static final int FontFamilyFont_android_fontVariationSettings = 4;
public static final int FontFamilyFont_font = 5;
public static final int FontFamilyFont_fontStyle = 6;
public static final int FontFamilyFont_fontVariationSettings = 7;
public static final int FontFamilyFont_fontWeight = 8;
public static final int FontFamilyFont_ttcIndex = 9;
public static final int[] GradientColor = { 0x101019d, 0x101019e, 0x10101a1, 0x10101a2, 0x10101a3, 0x10101a4, 0x1010201, 0x101020b, 0x1010510, 0x1010511, 0x1010512, 0x1010513 };
public static final int GradientColor_android_startColor = 0;
public static final int GradientColor_android_endColor = 1;
public static final int GradientColor_android_type = 2;
public static final int GradientColor_android_centerX = 3;
public static final int GradientColor_android_centerY = 4;
public static final int GradientColor_android_gradientRadius = 5;
public static final int GradientColor_android_tileMode = 6;
public static final int GradientColor_android_centerColor = 7;
public static final int GradientColor_android_startX = 8;
public static final int GradientColor_android_startY = 9;
public static final int GradientColor_android_endX = 10;
public static final int GradientColor_android_endY = 11;
public static final int[] GradientColorItem = { 0x10101a5, 0x1010514 };
public static final int GradientColorItem_android_color = 0;
public static final int GradientColorItem_android_offset = 1;
}
}
| [
"claudio@imaginaction.com.br"
] | claudio@imaginaction.com.br |
893328639dfdc714c760d7b69f990179c910939c | 654ec03bdb659820abcc26e785968e7562b63944 | /src/sample/Roads/Road130.java | 82ac684bf2b30afbe596d87a4fd3fa1f44031fe4 | [] | no_license | Eraddak/ProjectJTraffic | 39742863fedb87d89a7c7d816531c121ddcff1f9 | c1a4644464323d7cc3217bb1d5d2a04544c386fa | refs/heads/master | 2020-05-04T15:24:58.208428 | 2019-05-24T07:59:13 | 2019-05-24T07:59:13 | 179,239,893 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 375 | java | package sample.Roads;
import javafx.scene.paint.Color;
import sample.Intersection;
import sample.Ville;
public class Road130 extends Road {
public Road130(Intersection start, Intersection end) {
super(start, end);
this.vitesseMax = 130d;
this.nbVoies = 6d;
this.line.setStroke(Color.RED);
this.line.setStrokeWidth(60d);
}
}
| [
"kabotin5693@gmail.com"
] | kabotin5693@gmail.com |
f195a1e3004896ddd614bffb0af9168b1a61cea8 | 86647ab1dce23875b27988750c23b8455829f489 | /app/src/main/java/com/dudu/voice/window/BaseWindowManager.java | 13eaf34aa92309145f57782e06ba2fac8124dc8b | [] | no_license | BAT6188/DuDuHome_Home | 1fab41f8fd0456c6fdecb901dc2ee94c269ec516 | 08fa399406a1e19e7738c6767260db4153593f38 | refs/heads/master | 2023-05-28T18:38:36.377138 | 2016-07-25T06:48:06 | 2016-07-25T06:48:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,795 | java | package com.dudu.voice.window;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import com.dudu.android.launcher.LauncherApplication;
import com.dudu.voice.VoiceManagerProxy;
/**
* Created by Administrator on 2016/1/4.
*/
public abstract class BaseWindowManager implements FloatWindowManager {
protected WindowManager mWindowManager;
protected WindowManager.LayoutParams mLayoutParams;
protected View mFloatWindowView;
protected Context mContext;
protected boolean mShowFloatWindow;
protected VoiceManagerProxy mVoiceManager;
public BaseWindowManager() {
mContext = LauncherApplication.getContext();
mVoiceManager = VoiceManagerProxy.getInstance();
mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
mFloatWindowView = LayoutInflater.from(mContext).inflate(getFloatWindowLayout(), null);
initWindow();
}
public boolean isShowFloatWindow() {
return mShowFloatWindow;
}
public abstract void initWindow();
public abstract int getFloatWindowLayout();
protected void addFloatView() {
if (mShowFloatWindow) {
return;
}
try {
mWindowManager.addView(mFloatWindowView, mLayoutParams);
mShowFloatWindow = true;
} catch (Exception e) {
mShowFloatWindow = false;
}
}
protected void removeFloatView() {
mVoiceManager.onStop();
if (!mShowFloatWindow) {
return;
}
if (mWindowManager != null && mFloatWindowView != null) {
mWindowManager.removeView(mFloatWindowView);
}
mShowFloatWindow = false;
}
}
| [
"angcyo@126.com"
] | angcyo@126.com |
229b54b8f24de5e10481f1c82aa5095b41b0f280 | bb2439d2a3f9c6c1bc46abaaf2114f767853d141 | /src/main/java/me/karakelley/http/server/HttpServer.java | 0ec9c3c38283b494cb90e89241af91b7b7b91183 | [] | no_license | klkelley/http-java | 143a0ff6ffa4094ee54f570a7dd3e066432102d8 | 0b72eab2200a642ecceac3f88204a211b14142a6 | refs/heads/master | 2021-01-25T12:19:15.623594 | 2018-05-14T21:40:52 | 2018-05-14T21:40:52 | 123,458,007 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,547 | java | package me.karakelley.http.server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.CompletableFuture;
public class HttpServer {
private final int port;
private final static Logger logger = LoggerFactory.getLogger(HttpServer.class);
private final Handler handler;
private final ConnectionHandler connectionHandler;
private ServerSocket serverSocket;
private RequestReaderFactory readerFactory;
public HttpServer(ServerConfiguration serverConfiguration, ConnectionHandler connectionHandler, RequestReaderFactory readerFactory) {
this.connectionHandler = connectionHandler;
this.port = serverConfiguration.getPort();
this.handler = serverConfiguration.getHandler();
this.readerFactory = readerFactory;
}
public void start() {
try {
serverSocket = new ServerSocket(port);
logger.info("Started on port {}", getPortNumber());
while (true) {
Socket socket = serverSocket.accept();
CompletableFuture.runAsync(() -> connectionHandler.startConnection(socket, handler, readerFactory));
}
} catch (Exception e) {
logger.info("Ouch!", e);
} finally {
shutDown();
}
}
public Integer getPortNumber() {
return serverSocket.getLocalPort();
}
private void shutDown() {
if (serverSocket != null && !serverSocket.isClosed()) try {
serverSocket.close();
} catch (IOException e) {
logger.info("Ouch!", e);
}
}
}
| [
"kelley.15@gmail.com"
] | kelley.15@gmail.com |
0397fd8a0145a42b08ca5a201e7e83143953aed0 | 447520f40e82a060368a0802a391697bc00be96f | /apks/banking_set2_qark/com.advantage.RaiffeisenBank/classes_dex2jar/com/thinkdesquared/banking/transfers/treasury/CreateTreasuryVerifyFragment.java | 78b206994629cefb312d670d81abab955349923a | [
"Apache-2.0"
] | permissive | iantal/AndroidPermissions | 7f3343a9c29d82dbcd4ecd98b3a50ddf8d179465 | d623b732734243590b5f004d167e542e2e2ae249 | refs/heads/master | 2023-07-19T01:29:26.689186 | 2019-09-30T19:01:42 | 2019-09-30T19:01:42 | 107,239,248 | 0 | 0 | Apache-2.0 | 2023-07-16T07:41:38 | 2017-10-17T08:22:57 | null | UTF-8 | Java | false | false | 8,663 | java | package com.thinkdesquared.banking.transfers.treasury;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import com.hannesdorfmann.fragmentargs.annotation.Arg;
import com.hannesdorfmann.fragmentargs.annotation.FragmentWithArgs;
import com.path.android.jobqueue.JobManager;
import com.thinkdesquared.banking.VerifyFragment;
import com.thinkdesquared.banking.VerifyFragment.VerifyFragmentListener;
import com.thinkdesquared.banking.core.SmartMobileApplication;
import com.thinkdesquared.banking.core.store.AibasStore;
import com.thinkdesquared.banking.core.store.AibasStore.LoggedInState;
import com.thinkdesquared.banking.helpers.DSQHelper;
import com.thinkdesquared.banking.helpers.LogHelper;
import com.thinkdesquared.banking.models.TransactionAmountModel;
import com.thinkdesquared.banking.models.TreasuryData;
import com.thinkdesquared.banking.models.response.CreateTreasuryVerifyResponse;
import com.thinkdesquared.banking.models.response.GenericResultResponse;
import com.thinkdesquared.banking.transfers.treasury.events.CreateTreasuryResultResponseEvent;
import com.thinkdesquared.banking.transfers.treasury.events.CreateTreasuryVerifyResponseEvent;
import com.thinkdesquared.banking.transfers.treasury.jobs.CreateTreasuryResultJob;
import com.thinkdesquared.banking.transfers.treasury.jobs.CreateTreasuryVerifyJob;
import java.util.ArrayList;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
@FragmentWithArgs
public class CreateTreasuryVerifyFragment
extends VerifyFragment
{
private static final String BUGETUL_DE_STAT = "Bugetul de Stat";
private CreateTreasuryVerifyResponse mVerifyResponse;
@Arg
TreasuryData passedData;
private String template;
public CreateTreasuryVerifyFragment() {}
private void initWithVerifyResponse()
{
boolean bool = true;
if (!"S".equalsIgnoreCase(this.mVerifyResponse.resultCode))
{
DSQHelper.showErrorDialog(getActivity(), this.mVerifyResponse, bool, false);
return;
}
ArrayList localArrayList1 = new ArrayList();
ArrayList localArrayList2 = new ArrayList();
TreasuryData localTreasuryData = this.mVerifyResponse.getVerifiedData();
String str1;
String str2;
if ((localTreasuryData == null) || (DSQHelper.isEmpty(localTreasuryData.getTemplateId())))
{
str1 = null;
this.template = str1;
if (localTreasuryData != null)
{
localArrayList1.add("VERIFY_TITLE");
localArrayList2.add(getString(2131166074));
localArrayList1.add(getString(2131165603));
if (!DSQHelper.isEmpty(this.mVerifyResponse.getFromAccountNickname())) {
break label556;
}
str2 = localTreasuryData.getFromAccount() + " - " + this.mVerifyResponse.getAmountCurrency();
label163:
localArrayList2.add(str2);
localArrayList1.add(getString(2131166159));
localArrayList2.add(localTreasuryData.getTreasuryPaymentDescription());
localArrayList1.add(getString(2131165351));
localArrayList2.add(localTreasuryData.getTreasuryPaymentCode());
localArrayList1.add(getString(2131165345));
if ((AibasStore.getInstance().getLoggedInState() != AibasStore.LoggedInState.LoggedInState_DEMO) || ("Bugetul de Stat".equalsIgnoreCase(localTreasuryData.getTreasuryPaymentBeneficiaryName()))) {
break label609;
}
label248:
if (bool) {
this.mVerifyResponse.setBenCounty(localTreasuryData.getTreasuryBenCounty());
}
if (((!DSQHelper.isNotEmpty(this.mVerifyResponse.getBenCounty())) || (!DSQHelper.isNotEmpty(localTreasuryData.getTreasuryPaymentBeneficiaryType())) || (!"TOWN_HALL".equalsIgnoreCase(localTreasuryData.getTreasuryPaymentBeneficiaryType()))) && (!bool)) {
break label614;
}
}
}
label556:
label609:
label614:
for (String str3 = localTreasuryData.getTreasuryPaymentBeneficiaryName() + " - " + this.mVerifyResponse.getBenCounty();; str3 = localTreasuryData.getTreasuryPaymentBeneficiaryName())
{
localArrayList2.add(str3);
localArrayList1.add(getString(2131165894));
localArrayList2.add(localTreasuryData.getDetailsOfPayment());
if ((DSQHelper.isNotEmpty(localTreasuryData.getThirdParty())) && ("1".equals(localTreasuryData.getThirdParty())) && (DSQHelper.isNotEmpty(localTreasuryData.getTaxPayerCNP())))
{
localArrayList1.add(getString(2131166029));
localArrayList2.add(localTreasuryData.getTaxPayerCNP());
}
if (DSQHelper.isNotEmpty(localTreasuryData.getFiscalRegistrationNumber()))
{
localArrayList1.add(getString(2131165901));
localArrayList2.add(localTreasuryData.getFiscalRegistrationNumber());
}
TransactionAmountModel localTransactionAmountModel = new TransactionAmountModel(localTreasuryData.getTransactionAmount(), this.mVerifyResponse.getAmountCurrency());
localArrayList1.add(getString(2131165308));
localArrayList2.add(localTransactionAmountModel.toString(getActivity()));
localArrayList1.add(getString(2131165873));
localArrayList2.add(localTreasuryData.getTransactionDate());
this.mLabels = localArrayList1;
this.mValues = localArrayList2;
hideLoadingOrError();
showLayoutForVerifyResponse(this.mVerifyResponse);
return;
str1 = localTreasuryData.getTemplateId();
break;
str2 = this.mVerifyResponse.getFromAccountNickname() + " (" + localTreasuryData.getFromAccount() + ") - " + this.mVerifyResponse.getAmountCurrency();
break label163;
bool = false;
break label248;
}
}
public void executeResultTask()
{
this.mProgressDialog.show();
SmartMobileApplication.getDefaultJobManager().addJob(new CreateTreasuryResultJob(getSessionIdForJob(), this.workflowId, this.template, getAuthorizationElements()));
}
public void onActivityCreated(Bundle paramBundle)
{
super.onActivityCreated(paramBundle);
setHasOptionsMenu(true);
setRetainInstance(true);
ActionBar localActionBar = ((AppCompatActivity)getActivity()).getSupportActionBar();
DSQHelper.setActionBarTitle(getActivity(), localActionBar, getString(2131166113));
if (this.mVerifyResponse == null)
{
startLoading();
return;
}
initWithVerifyResponse();
}
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
EventBus.getDefault().register(this);
}
public void onDestroy()
{
super.onDestroy();
EventBus.getDefault().unregister(this);
}
@Subscribe(threadMode=ThreadMode.MAIN)
public void onEventMainThread(CreateTreasuryResultResponseEvent paramCreateTreasuryResultResponseEvent)
{
this.mProgressDialog.dismiss();
LogHelper.d("VerifyFragment", "Create Treasury Result Received");
GenericResultResponse localGenericResultResponse = paramCreateTreasuryResultResponseEvent.getResponse();
if ("S".equalsIgnoreCase(localGenericResultResponse.resultCode))
{
EventBus.getDefault().unregister(this);
String str2 = getString(2131166151);
this.mListener.onReceivedSuccessfullResultResponse(str2, true, localGenericResultResponse, 2131166241);
return;
}
if ((localGenericResultResponse.resultCode.equals("AUTH_ERROR")) || (localGenericResultResponse.resultCode.equals("CLIENT_ERROR")))
{
DSQHelper.showErrorDialog(getActivity(), localGenericResultResponse, false, true);
return;
}
String str1 = localGenericResultResponse.getErrors();
this.mListener.onReceivedSuccessfullResultResponse(str1, true, localGenericResultResponse, 2131166241);
}
@Subscribe(threadMode=ThreadMode.MAIN)
public void onEventMainThread(CreateTreasuryVerifyResponseEvent paramCreateTreasuryVerifyResponseEvent)
{
this.mVerifyResponse = paramCreateTreasuryVerifyResponseEvent.getResponse();
initWithVerifyResponse();
}
protected void restartLoading()
{
if (this.mVerifyResponse != null) {
this.mVerifyResponse = null;
}
showLoading();
SmartMobileApplication.getDefaultJobManager().addJob(new CreateTreasuryVerifyJob(getSessionIdForJob(), this.workflowId, this.passedData, getActivity()));
}
protected boolean shouldReAdjustLayoutToCenter()
{
return false;
}
protected void startLoading()
{
showLoading();
SmartMobileApplication.getDefaultJobManager().addJob(new CreateTreasuryVerifyJob(getSessionIdForJob(), this.workflowId, this.passedData, getActivity()));
}
}
| [
"antal.micky@yahoo.com"
] | antal.micky@yahoo.com |
19e7d09d1eb694a20207a84b2053be064245ccf0 | dc9aa6951c5fa1d6986ee0e60bfc4652c3af66c5 | /src/main/java/com/codecool/service/dataManipulation/ILogicalOperationEvaluator.java | b64583923ab025b99990c0ffb87efb9ee5dafeae | [] | no_license | Paprok/sheetql-webapp | 2b5c34109a02fd5ba62211bc42b6ccc922c68a6b | 1ba34cc3f4f771e43b40e06d0b24dd909aa07ecf | refs/heads/master | 2020-04-07T23:18:57.574336 | 2018-10-18T21:17:07 | 2018-10-18T21:17:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 261 | java | package com.codecool.service.dataManipulation;
import com.codecool.exception.MalformedQueryException;
public interface ILogicalOperationEvaluator {
boolean isTrue(String operation);
String prepareQuery(String query) throws MalformedQueryException;
}
| [
"wojciech.m1997@gmail.com"
] | wojciech.m1997@gmail.com |
303a879e13a05b1ba8f9a2f950beac94a3174ea8 | 5d059d98ffd879095d503f8db0bc701fab13ed11 | /sfm/src/main/java/org/sfm/map/mapper/AbstractColumnDefinitionProvider.java | 171bc483b14567517dd418e5a21724d82d3f13ce | [
"MIT"
] | permissive | sripadapavan/SimpleFlatMapper | c74cce774b0326d5ea5ea141ee9f3caf07a98372 | 8359a08abb3a321b3a47f91cd4046ca1a88590fd | refs/heads/master | 2021-01-17T08:11:57.463205 | 2016-02-06T14:38:44 | 2016-02-07T16:50:53 | 51,313,393 | 1 | 0 | null | 2016-02-08T17:23:12 | 2016-02-08T17:23:12 | null | UTF-8 | Java | false | false | 2,619 | java | package org.sfm.map.mapper;
import org.sfm.map.FieldKey;
import org.sfm.map.column.ColumnProperty;
import org.sfm.tuples.Tuple2;
import org.sfm.utils.Predicate;
import org.sfm.utils.UnaryFactory;
import java.util.ArrayList;
import java.util.List;
public abstract class AbstractColumnDefinitionProvider<C extends ColumnDefinition<K, C>, K extends FieldKey<K>> implements ColumnDefinitionProvider<C, K> {
protected final List<Tuple2<Predicate<? super K>, C>> definitions;
protected final List<Tuple2<Predicate<? super K>, UnaryFactory<? super K, ColumnProperty>>> properties;
public AbstractColumnDefinitionProvider() {
definitions = new ArrayList<Tuple2<Predicate<? super K>, C>>();
properties = new ArrayList<Tuple2<Predicate<? super K>, UnaryFactory<? super K, ColumnProperty>>>();
}
public AbstractColumnDefinitionProvider(List<Tuple2<Predicate<? super K>, C>> definitions,
List<Tuple2<Predicate<? super K>, UnaryFactory<? super K, ColumnProperty>>> properties) {
this.definitions = definitions;
this.properties = properties;
}
public void addColumnDefinition(Predicate<? super K> predicate, C definition) {
definitions.add(new Tuple2<Predicate<? super K>, C>(predicate, definition));
}
public void addColumnProperty(Predicate<? super K> predicate, UnaryFactory<? super K, ColumnProperty> propertyFactory) {
properties.add(new Tuple2<Predicate<? super K>, UnaryFactory<? super K, ColumnProperty>>(predicate, propertyFactory));
}
@Override
public C getColumnDefinition(K key) {
C definition = identity();
for(Tuple2<Predicate<? super K>, C> def : definitions) {
if (def.first().test(key)) {
definition = compose(definition, def.second());
}
}
for (Tuple2<Predicate<? super K>, UnaryFactory<? super K, ColumnProperty>> tuple2 : properties) {
if (tuple2.first().test(key)) {
ColumnProperty columnProperty = tuple2.second().newInstance(key);
if (columnProperty != null) {
definition = definition.add(columnProperty);
}
}
}
return definition;
}
protected abstract C compose(C definition, C second);
protected abstract C identity();
public List<Tuple2<Predicate<? super K>, C>> getDefinitions() {
return definitions;
}
public List<Tuple2<Predicate<? super K>, UnaryFactory<? super K, ColumnProperty>>> getProperties() {
return properties;
}
}
| [
"arnaud.roger@gmail.com"
] | arnaud.roger@gmail.com |
c9fcbb273cb5203f65f17490fa4d1950e15dfd79 | d20fdbf38869da345b1cba1a7dd7aab5818bbf63 | /clock/src/main/java/com/yiju/ClassClockRoom/bean/MoreStoreBean.java | 4ba0cce9ec856cd83868ba50b23cb067609ce81e | [] | no_license | xxchenqi/clockclassroom | 28902afe11d9bed667f85fdc33825049318e7ed6 | 7c5dedbb237d01b1cc7deb85f2a16e2f121d32a2 | refs/heads/master | 2021-01-23T04:29:50.159212 | 2017-03-26T04:58:04 | 2017-03-26T04:58:08 | 86,203,308 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,928 | java | package com.yiju.ClassClockRoom.bean;
import java.util.List;
/**
* ----------------------------------------
* 注释:更多门店列表
* <p>
* 作者: cq
* <p>
* 时间: on 2016/9/5 10:56
* ----------------------------------------
*/
public class MoreStoreBean {
/**
* code : 0
* msg : 查询成功
* obj : [{"address":"人民广场XXX","addressgeo":"","area":"黄浦区","available_table":"","contract_code":"","create_time":0,"detail":"","dist_id":0,"end_time":0,"end_time_afternoon":1800,"end_time_day":0,"end_time_evening":2100,"end_time_morning":0,"id":46,"ip":"","is_available":0,"lat":0,"lat_g":31.198819,"lng":0,"lng_g":121.454819,"name":"人广测试店0818","phone":"","pic_big":"http://get.file.dc.cric.com/SZJSa1ec2fc60b36a2ea6aa2a9bbcfe151d8_639X360_0_0_3.jpg","pic_small":"http://get.file.dc.cric.com/SZJSa1ec2fc60b36a2ea6aa2a9bbcfe151d8_314X236_0_0_3.jpg","praise":0,"rate_device":0,"rate_room":0,"start_time":0,"start_time_afternoon":1200,"start_time_day":0,"start_time_evening":1800,"start_time_morning":0,"tags":"","traffic":"","type_desc":"","update_time":0,"use":"","video_ip":"","video_password":"","video_port":"","video_username":""}]
*/
private int code;
private String msg;
/**
* address : 人民广场XXX
* addressgeo :
* area : 黄浦区
* available_table :
* contract_code :
* create_time : 0
* detail :
* dist_id : 0
* end_time : 0
* end_time_afternoon : 1800
* end_time_day : 0
* end_time_evening : 2100
* end_time_morning : 0
* id : 46
* ip :
* is_available : 0
* lat : 0
* lat_g : 31.198819
* lng : 0
* lng_g : 121.454819
* name : 人广测试店0818
* phone :
* pic_big : http://get.file.dc.cric.com/SZJSa1ec2fc60b36a2ea6aa2a9bbcfe151d8_639X360_0_0_3.jpg
* pic_small : http://get.file.dc.cric.com/SZJSa1ec2fc60b36a2ea6aa2a9bbcfe151d8_314X236_0_0_3.jpg
* praise : 0
* rate_device : 0
* rate_room : 0
* start_time : 0
* start_time_afternoon : 1200
* start_time_day : 0
* start_time_evening : 1800
* start_time_morning : 0
* tags :
* traffic :
* type_desc :
* update_time : 0
* use :
* video_ip :
* video_password :
* video_port :
* video_username :
*/
private List<MoreStoreEntity> obj;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public List<MoreStoreEntity> getObj() {
return obj;
}
public void setObj(List<MoreStoreEntity> obj) {
this.obj = obj;
}
public class MoreStoreEntity {
/**
* address : 上海市静安区共和新路2395弄宝华商业街35号
* addressgeo :
* area : 静安区
* available_table :
* can_schedule : 0
* contract_code :
* create_time : 0
* detail :
* dist_id : 0
* distances : 0.36
* end_time : 0
* end_time_afternoon : 1800
* end_time_day : 0
* end_time_evening : 2100
* end_time_morning : 0
* id : 299
* ip :
* is_available : 0
* lat : 31.28634546508
* lat_g : 31.280147
* lng : 121.45991762838
* lng_g : 121.453891
* name : 秦汉胡同国学大宁分院
* phone :
* pic_big : http://get.file.dc.cric.com/SZJSc9570a49e974cac0ebc0b0c2be4f7045_639X446_0_0_1.jpg
* pic_small : http://get.file.dc.cric.com/SZJSc9570a49e974cac0ebc0b0c2be4f7045_314X236_0_0_1.jpg
* praise : 0
* rate_device : 0
* rate_room : 0
* school_type : 2
* start_time : 0
* start_time_afternoon : 1200
* start_time_day : 0
* start_time_evening : 1800
* start_time_morning : 0
* tags : 国学 茶道 琴棋书画 交通便利
* traffic :
* type_desc :
* update_time : 0
* use : 国学 茶道 琴棋书画 交通便利
* video_ip :
* video_password :
* video_port :
* video_username :
*/
private String address;
private String addressgeo;
private String area;
private String available_table;
private String can_schedule;
private String contract_code;
private int create_time;
private String detail;
private int dist_id;
private double distances;
private int end_time;
private int end_time_afternoon;
private int end_time_day;
private int end_time_evening;
private int end_time_morning;
private int id;
private String ip;
private int is_available;
private double lat;
private double lat_g;
private double lng;
private double lng_g;
private String name;
private String phone;
private String pic_big;
private String pic_small;
private int praise;
private int rate_device;
private int rate_room;
private String school_type;
private int start_time;
private int start_time_afternoon;
private int start_time_day;
private int start_time_evening;
private int start_time_morning;
private String tags;
private String traffic;
private String type_desc;
private int update_time;
private String use;
private String video_ip;
private String video_password;
private String video_port;
private String video_username;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAddressgeo() {
return addressgeo;
}
public void setAddressgeo(String addressgeo) {
this.addressgeo = addressgeo;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getAvailable_table() {
return available_table;
}
public void setAvailable_table(String available_table) {
this.available_table = available_table;
}
public String getCan_schedule() {
return can_schedule;
}
public void setCan_schedule(String can_schedule) {
this.can_schedule = can_schedule;
}
public String getContract_code() {
return contract_code;
}
public void setContract_code(String contract_code) {
this.contract_code = contract_code;
}
public int getCreate_time() {
return create_time;
}
public void setCreate_time(int create_time) {
this.create_time = create_time;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public int getDist_id() {
return dist_id;
}
public void setDist_id(int dist_id) {
this.dist_id = dist_id;
}
public double getDistances() {
return distances;
}
public void setDistances(double distances) {
this.distances = distances;
}
public int getEnd_time() {
return end_time;
}
public void setEnd_time(int end_time) {
this.end_time = end_time;
}
public int getEnd_time_afternoon() {
return end_time_afternoon;
}
public void setEnd_time_afternoon(int end_time_afternoon) {
this.end_time_afternoon = end_time_afternoon;
}
public int getEnd_time_day() {
return end_time_day;
}
public void setEnd_time_day(int end_time_day) {
this.end_time_day = end_time_day;
}
public int getEnd_time_evening() {
return end_time_evening;
}
public void setEnd_time_evening(int end_time_evening) {
this.end_time_evening = end_time_evening;
}
public int getEnd_time_morning() {
return end_time_morning;
}
public void setEnd_time_morning(int end_time_morning) {
this.end_time_morning = end_time_morning;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getIs_available() {
return is_available;
}
public void setIs_available(int is_available) {
this.is_available = is_available;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLat_g() {
return lat_g;
}
public void setLat_g(double lat_g) {
this.lat_g = lat_g;
}
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
public double getLng_g() {
return lng_g;
}
public void setLng_g(double lng_g) {
this.lng_g = lng_g;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPic_big() {
return pic_big;
}
public void setPic_big(String pic_big) {
this.pic_big = pic_big;
}
public String getPic_small() {
return pic_small;
}
public void setPic_small(String pic_small) {
this.pic_small = pic_small;
}
public int getPraise() {
return praise;
}
public void setPraise(int praise) {
this.praise = praise;
}
public int getRate_device() {
return rate_device;
}
public void setRate_device(int rate_device) {
this.rate_device = rate_device;
}
public int getRate_room() {
return rate_room;
}
public void setRate_room(int rate_room) {
this.rate_room = rate_room;
}
public String getSchool_type() {
return school_type;
}
public void setSchool_type(String school_type) {
this.school_type = school_type;
}
public int getStart_time() {
return start_time;
}
public void setStart_time(int start_time) {
this.start_time = start_time;
}
public int getStart_time_afternoon() {
return start_time_afternoon;
}
public void setStart_time_afternoon(int start_time_afternoon) {
this.start_time_afternoon = start_time_afternoon;
}
public int getStart_time_day() {
return start_time_day;
}
public void setStart_time_day(int start_time_day) {
this.start_time_day = start_time_day;
}
public int getStart_time_evening() {
return start_time_evening;
}
public void setStart_time_evening(int start_time_evening) {
this.start_time_evening = start_time_evening;
}
public int getStart_time_morning() {
return start_time_morning;
}
public void setStart_time_morning(int start_time_morning) {
this.start_time_morning = start_time_morning;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getTraffic() {
return traffic;
}
public void setTraffic(String traffic) {
this.traffic = traffic;
}
public String getType_desc() {
return type_desc;
}
public void setType_desc(String type_desc) {
this.type_desc = type_desc;
}
public int getUpdate_time() {
return update_time;
}
public void setUpdate_time(int update_time) {
this.update_time = update_time;
}
public String getUse() {
return use;
}
public void setUse(String use) {
this.use = use;
}
public String getVideo_ip() {
return video_ip;
}
public void setVideo_ip(String video_ip) {
this.video_ip = video_ip;
}
public String getVideo_password() {
return video_password;
}
public void setVideo_password(String video_password) {
this.video_password = video_password;
}
public String getVideo_port() {
return video_port;
}
public void setVideo_port(String video_port) {
this.video_port = video_port;
}
public String getVideo_username() {
return video_username;
}
public void setVideo_username(String video_username) {
this.video_username = video_username;
}
}
}
| [
"812046652@qq.com"
] | 812046652@qq.com |
bdc97dd04c5b569a1299cd1e4fbbf10f684283e1 | f1078c3b9fdd57de71cf74ef915750828518afbd | /afirma-signfolder-proxy/src/main/java/es/gob/afirma/signfolder/server/proxy/ConfigurationRequestParser.java | 77a99493ef252f9771347e14e1a333ccd49d82c3 | [] | no_license | ctt-gob-es/portafirmas-proxy | eb9900ea955139e41e60a32f1f8dd31142f66b2e | 401cf8606c76ea96ee100d0bfd15ca768ace6e61 | refs/heads/master | 2023-03-07T02:57:18.140867 | 2023-03-03T11:11:13 | 2023-03-03T11:11:13 | 55,968,686 | 4 | 1 | null | 2023-03-03T11:17:37 | 2016-04-11T12:03:59 | Java | UTF-8 | Java | false | false | 1,295 | java | package es.gob.afirma.signfolder.server.proxy;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Analiza un documento XML para obtener una petición de previsualización
* de documento.
* @author Carlos Gamuci
*/
public class ConfigurationRequestParser {
private static final String CONFIGURATION_REQUEST_NODE = "rqtconf"; //$NON-NLS-1$
private ConfigurationRequestParser() {
// Se evita el uso del constructor
}
/** Analiza un documento XML y, en caso de tener el formato correcto, obtiene de él
* un identificador de documento.
* @param doc Documento XML.
* @return Identificador de documento.
* @throws IllegalArgumentException Cuando el XML no tiene el formato esperado. */
static ConfigurationRequest parse(final Document doc) {
if (doc == null) {
throw new IllegalArgumentException("El documento proporcionado no puede ser nulo"); //$NON-NLS-1$
}
final Element rootElement = doc.getDocumentElement();
if (!CONFIGURATION_REQUEST_NODE.equalsIgnoreCase(rootElement.getNodeName())) {
throw new IllegalArgumentException("El elemento raiz del XML debe ser '" + //$NON-NLS-1$
CONFIGURATION_REQUEST_NODE + "' y aparece: " + //$NON-NLS-1$
rootElement.getNodeName());
}
return new ConfigurationRequest();
}
}
| [
"carlos.gamuci@gmail.com"
] | carlos.gamuci@gmail.com |
e96b75b83687a3456854f6fdf066d6a78d10906f | 87fb5958a149cde061523b408a3331afa58056df | /src/com/cn/mojita/design/Test1.java | b32aa7b73a75d90a0b09c2962b9145e2fdc2e9b0 | [] | no_license | mojita/LamdaTest | 94b6c17389c9c9da41e63a51ac7c861c6d02c6c3 | 130c53c4eda1ecb8b85bd36e2b143a69a006d8ce | refs/heads/master | 2021-06-27T14:14:27.766257 | 2017-09-17T17:09:58 | 2017-09-17T17:09:58 | 103,747,658 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 521 | java | package com.cn.mojita.design;
import org.junit.Test;
/**
* Created by lijunhong on 17/9/17.
*/
public class Test1 {
@Test
public void test1() {
//简单工厂创建实例演示
//创建工厂
ElectronFactory factory = new ElectronFactory();
//创建电脑实例
USBElectron computer = factory.creatDevice("computer");
computer.function();
//创建鼠标实例
USBElectron mouse = factory.creatDevice("mouse");
mouse.function();
}
}
| [
"rsystem392@gmail.com"
] | rsystem392@gmail.com |
346909c182a4adde741bf30876fc793dc850d7a8 | 4e516583021b884f45c1763698d38996fed326f6 | /pcgen/code/src/java/plugin/lsttokens/subclass/SubclasslevelToken.java | 965bc340c83a5ff6a3a20eded12b5ba1ba3d7840 | [] | no_license | Manichee/pcgen | d993d04e75a8398b8cb9d577a717698a5ae8e3e9 | 5fb3937e5e196d2c0b244e9b4dacab2aecca381f | refs/heads/master | 2020-04-09T01:55:53.634379 | 2016-04-11T03:41:50 | 2016-04-11T03:41:50 | 23,060,834 | 0 | 0 | null | 2014-08-18T22:37:19 | 2014-08-18T06:20:19 | Java | UTF-8 | Java | false | false | 379 | java | package plugin.lsttokens.subclass;
import pcgen.core.SubClass;
import pcgen.persistence.lst.SubClassLstToken;
/**
* Class deals with SUBCLASS Token
*/
public class SubclasslevelToken implements SubClassLstToken {
public String getTokenName() {
return "SUBCLASS";
}
public boolean parse(SubClass subclass, String value) {
subclass.setName(value);
return true;
}
}
| [
"tladdjr@gmail.com"
] | tladdjr@gmail.com |
130e14e076d345b221f58cf1109ecc52ac448d2e | 7e40b0b5c8a51743277628126a2e4291e79ea2ea | /src/com/xywztech/bcrm/sales/service/MktBusiOpporOperationService.java | 7acbb530c24704c320573ff322c5ae233988d1d5 | [] | no_license | hctwgl/xywzweb | 40b99f38355b9f648d5de1f24278a21edae1c102 | 9845c9d3fbfc31f0d253e17dc0c6f904e18cff8f | refs/heads/master | 2020-03-09T10:03:10.264961 | 2018-03-16T08:07:42 | 2018-03-16T08:07:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 49,608 | java | package com.xywztech.bcrm.sales.service;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.xywztech.bcrm.customer.model.OcrmFCiCustDesc;
import com.xywztech.bcrm.custview.model.OcrmFCiBelongCustmgr;
import com.xywztech.bcrm.custview.model.OcrmFCiBelongOrg;
import com.xywztech.bcrm.sales.model.OcrmFMmMktBusiOppor;
import com.xywztech.bcrm.sales.model.OcrmFMmMktBusiOpporHisS;
import com.xywztech.bcrm.system.model.AdminAuthAccount;
import com.xywztech.bcrm.system.model.AdminAuthOrg;
import com.xywztech.bob.vo.AuthUser;
/**
* @描述:营销管理->商机管理->商机池功能操作Service
* @author wzy
* @date:2013-02-22
*/
@Service
@Transactional(value = "postgreTransactionManager")
public class MktBusiOpporOperationService {
private EntityManager em;
@PersistenceContext
public void setEntityManager(EntityManager em) {
this.em = em;
}
public OcrmFMmMktBusiOppor find(long id) {
return em.find(OcrmFMmMktBusiOppor.class, id);
}
// 保存(新增)商机记录
@SuppressWarnings("unchecked")
public void saveBusiOppor(OcrmFMmMktBusiOppor ofmbo, AuthUser auth) {
OcrmFMmMktBusiOppor ofmbo_h = null;
String[] prod_id_arr = null;
String[] prod_name_arr = null;
String prod_id = ofmbo.getProdId();
String prod_name = ofmbo.getProdName();
if (prod_id != null && !"".equals(prod_id)) {
prod_id_arr = prod_id.split(",");
}
if (prod_name != null && !"".equals(prod_name)) {
prod_name_arr = prod_name.split(",");
}
if (prod_id_arr != null && prod_id_arr.length > 0) {
for (int i = 0; i < prod_id_arr.length; i++) {// 如果选择了多个产品,循环产生商机(一个产品对应一个商机)
ofmbo_h = new OcrmFMmMktBusiOppor();
BeanUtils.copyProperties(ofmbo, ofmbo_h);
// 设置部分特殊字段值
ofmbo_h.setProdId(prod_id_arr[i]);// 产品ID
ofmbo_h.setProdName(prod_name_arr[i]);// 产品名称
ofmbo_h.setOpporStat("0");// 状态(0-暂存)
ofmbo_h.setOpporSource("0");// 商机来源(0-手动创建)
ofmbo_h.setCreaterId(auth.getUserId());// 创建人ID
ofmbo_h.setCreaterName(auth.getUsername());// 创建人名称
ofmbo_h.setCreateOrgId(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("ID"));// 创建人所在机构ID
ofmbo_h.setCreateOrgName(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("UNITNAME"));// 创建人所在机构名称
ofmbo_h.setCreateDateTime(new Timestamp(System
.currentTimeMillis()));// 创建时间
ofmbo_h.setUpdateUserId(auth.getUserId());// 更新人ID
ofmbo_h.setUpdateUserName(auth.getUsername());// 更新人名称
ofmbo_h.setUpdateOrgId(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("ID"));// 更新人所在机构ID
ofmbo_h.setUpdateOrgName(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("UNITNAME"));// 更新人所在机构名称
ofmbo_h.setUpdateDateTime(new Timestamp(System
.currentTimeMillis()));// 更新时间
// 保存商机数据
em.persist(ofmbo_h);
}
}
}
// 更新(修改)商机记录
@SuppressWarnings("unchecked")
public void updateBusiOppor(OcrmFMmMktBusiOppor ofmbo, AuthUser auth) {
OcrmFMmMktBusiOppor ofmbo_h = null;
OcrmFMmMktBusiOpporHisS ofmboh = null;
if (ofmbo != null && ofmbo.getOpporId() != null) {
ofmbo_h = em.find(OcrmFMmMktBusiOppor.class, ofmbo.getOpporId());
if (ofmbo_h != null) {
// 设置要更新的字段值
ofmbo_h.setOpporName(ofmbo.getOpporName());// 商机名称
ofmbo_h.setOpporType(ofmbo.getOpporType());// 商机类型
ofmbo_h.setOpporDueDate(ofmbo.getOpporDueDate());// 商机有效期
ofmbo_h.setOpporStage(ofmbo.getOpporStage());// 商机阶段
ofmbo_h.setOpporStartDate(ofmbo.getOpporStartDate());// 商机开始日期
ofmbo_h.setOpporEndDate(ofmbo.getOpporEndDate());// 商机结束日期
ofmbo_h.setMktActivId(ofmbo.getMktActivId());// 营销活动ID
ofmbo_h.setMktActivName(ofmbo.getMktActivName());// 营销活动名称
ofmbo_h.setMktTargetId(ofmbo.getMktTargetId());// 营销任务指标ID
ofmbo_h.setMktTargetName(ofmbo.getMktTargetName());// 营销任务指标名称
ofmbo_h.setProdId(ofmbo.getProdId());// 商机产品ID
ofmbo_h.setProdName(ofmbo.getProdName());// 商机产品名称
ofmbo_h.setCustId(ofmbo.getCustId());// 客户ID
ofmbo_h.setCustName(ofmbo.getCustName());// 客户名称
ofmbo_h.setCustCategory(ofmbo.getCustCategory());// 客户类型
ofmbo_h.setCustType(ofmbo.getCustType());// 客户状态
ofmbo_h.setCustContactName(ofmbo.getCustContactName());// 客户联系人
ofmbo_h.setPlanAmount(ofmbo.getPlanAmount());// 预计金额
ofmbo_h.setPlanCost(ofmbo.getPlanCost());// 费用预算
ofmbo_h.setOpporContent(ofmbo.getOpporContent());// 商机内容
ofmbo_h.setMemo(ofmbo.getMemo());// 商机备注
// 设置部分特殊字段值
ofmbo_h.setUpdateUserId(auth.getUserId());// 更新人ID
ofmbo_h.setUpdateUserName(auth.getUsername());// 更新人名称
ofmbo_h.setUpdateOrgId(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("ID"));// 更新人所在机构ID
ofmbo_h.setUpdateOrgName(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("UNITNAME"));// 更新人所在机构名称
ofmbo_h.setUpdateDateTime(new Timestamp(System
.currentTimeMillis()));// 更新时间
// 更新商机数据
em.merge(ofmbo_h);
// 新增商机操作历史记录
ofmboh = new OcrmFMmMktBusiOpporHisS();
ofmboh.setOpporId(ofmbo_h.getOpporId());
ofmboh.setOprDateTime(new Timestamp(System.currentTimeMillis()));
ofmboh.setOprOrgId(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("ID"));
ofmboh.setOprOrgName(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("UNITNAME"));
ofmboh.setOprUserId(auth.getUserId());
ofmboh.setOprUserName(auth.getUsername());
ofmboh.setOprContent("“" + auth.getUsername() + "”更新商机。");
this.saveBusiOpporOperationHis(ofmboh);
}
}
}
// 提交商机信息
public void submitBusiOppor(OcrmFMmMktBusiOppor ofmbo, AuthUser auth,
HttpServletResponse response) {
String alertMsg = "";
OcrmFMmMktBusiOppor ofmmbo_h = null;
if (ofmbo != null) {
if (ofmbo.getOpporId() == null || "".equals(ofmbo.getOpporId())) {
// 1、在页面填写了商机信息,没保存到数据库,就直接提交的情况
this.addAndSubmit(ofmbo, auth);
ofmmbo_h = ofmbo;
} else {
// 2、在页面填写了商机信息,并已保存到数据库,然后提交的情况
ofmmbo_h = this.updateAndSubmit(ofmbo, auth);
}
// 设置返回信息
if (ofmmbo_h.getExecuteUserName() != null
&& !"".equals(ofmmbo_h.getExecuteUserName())) {
alertMsg = "0" + ofmmbo_h.getExecuteUserName();
} else if (ofmmbo_h.getAssignOrgName() != null
&& !"".equals(ofmmbo_h.getAssignOrgName())) {
alertMsg = "1" + ofmmbo_h.getAssignOrgName();
}
try {
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(alertMsg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 新增商机并且提交操作
@SuppressWarnings("unchecked")
private void addAndSubmit(OcrmFMmMktBusiOppor ofmbo, AuthUser auth) {
AdminAuthOrg aao = null;
OcrmFCiBelongOrg ofcbo = null;
OcrmFCiBelongCustmgr ofcbc = null;
OcrmFMmMktBusiOppor ofmbo_h = null;
String[] prod_id_arr = null;
String[] prod_name_arr = null;
String prod_id = ofmbo.getProdId();
String prod_name = ofmbo.getProdName();
if (prod_id != null && !"".equals(prod_id)) {
prod_id_arr = prod_id.split(",");
}
if (prod_name != null && !"".equals(prod_name)) {
prod_name_arr = prod_name.split(",");
}
if (prod_id_arr != null && prod_id_arr.length > 0) {
ofcbc = this.getBelongCustmgr(ofmbo);
ofcbo = this.getBelongOrg(ofmbo);
aao = this.getTopOrg();
for (int i = 0; i < prod_id_arr.length; i++) {// 如果选择了多个产品,循环产生商机(一个产品对应一个商机)
ofmbo_h = new OcrmFMmMktBusiOppor();
BeanUtils.copyProperties(ofmbo, ofmbo_h);
if (ofcbc != null) {
// 1、如果客户有归属客户经理,将商机状态置成“4-执行中”,执行人就是对应的客户经理,执行机构就是对应客户经理所在机构
ofmbo_h.setOpporStat("4");// 商机状态置成“4-执行中”
ofmbo_h.setExecuteUserId(ofcbc.getMgrId());// 执行人ID置成“归属客户经理ID”
ofmbo_h.setExecuteUserName(ofcbc.getMgrName());// 执行人名称置成“归属客户经理名称”
ofmbo_h.setExecuteOrgId(ofcbc.getInstitution());// 执行机构ID置成“归属客户经理所属机构ID”
ofmbo_h.setExecuteOrgName(ofcbc.getInstitutionName());// 执行机构名称置成“归属客户经理所属机构名称”
} else if (ofcbo != null) {
// 2、如果客户没有归属客户经理,但有归属机构,将商机状态置成“1-待分配”,将待分配机构设置成客户对应的归属机构
ofmbo_h.setOpporStat("1");// 商机状态置成“1-待分配”
ofmbo_h.setAssignOgrId(ofcbo.getInstitutionCode());// 待分配机构ID置成“归属机构代码”
ofmbo_h.setAssignOrgName(ofcbo.getInstitutionName());// 待分配机构名称置成“归属机构名称”
} else {
// 3、如果客户既没有归属客户经理,也没有归属机构,将商机状态置成“1-待分配”,将待分配机构设置成总行
ofmbo_h.setOpporStat("1");// 商机状态置成“1-待分配”
ofmbo_h.setAssignOgrId(aao.getOrgId());// 待分配机构ID置成“总行机构代码”
ofmbo_h.setAssignOrgName(aao.getOrgName());// 待分配机构名称置成“总行机构名称”
}
ofmbo_h.setProdId(prod_id_arr[i]);// 产品ID
ofmbo_h.setProdName(prod_name_arr[i]);// 产品名称
ofmbo_h.setOpporSource("0");// 商机来源(0-手动创建)
ofmbo_h.setCreaterId(auth.getUserId());// 创建人ID
ofmbo_h.setCreaterName(auth.getUsername());// 创建人名称
ofmbo_h.setCreateOrgId(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("ID"));// 创建人所在机构ID
ofmbo_h.setCreateOrgName(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("UNITNAME"));// 创建人所在机构名称
ofmbo_h.setCreateDateTime(new Timestamp(System
.currentTimeMillis()));// 创建时间
ofmbo_h.setUpdateUserId(auth.getUserId());// 更新人ID
ofmbo_h.setUpdateUserName(auth.getUsername());// 更新人名称
ofmbo_h.setUpdateOrgId(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("ID"));// 更新人所在机构ID
ofmbo_h.setUpdateOrgName(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("UNITNAME"));// 更新人所在机构名称
ofmbo_h.setUpdateDateTime(new Timestamp(System
.currentTimeMillis()));// 更新时间
// 保存商机数据
em.persist(ofmbo_h);
}
}
}
// 修改商机并且提交操作
@SuppressWarnings("unchecked")
private OcrmFMmMktBusiOppor updateAndSubmit(OcrmFMmMktBusiOppor ofmbo,
AuthUser auth) {
AdminAuthOrg aao = null;
OcrmFCiBelongOrg ofcbo = null;
OcrmFCiBelongCustmgr ofcbc = null;
OcrmFMmMktBusiOppor ofmbo_h = null;
if (ofmbo != null && ofmbo.getOpporId() != null) {
ofmbo_h = em.find(OcrmFMmMktBusiOppor.class, ofmbo.getOpporId());
if (ofmbo_h != null) {
ofcbc = this.getBelongCustmgr(ofmbo);
ofcbo = this.getBelongOrg(ofmbo);
aao = this.getTopOrg();
if (ofcbc != null) {
// 1、如果客户有归属客户经理,将商机状态置成“4-执行中”,执行人就是对应的客户经理,执行机构就是对应客户经理所在机构
ofmbo_h.setOpporStat("4");// 商机状态置成“4-执行中”
ofmbo_h.setExecuteUserId(ofcbc.getMgrId());// 执行人ID置成“归属客户经理ID”
ofmbo_h.setExecuteUserName(ofcbc.getMgrName());// 执行人名称置成“归属客户经理名称”
ofmbo_h.setExecuteOrgId(ofcbc.getInstitution());// 执行机构ID置成“归属客户经理所属机构ID”
ofmbo_h.setExecuteOrgName(ofcbc.getInstitutionName());// 执行机构名称置成“归属客户经理所属机构名称”
} else if (ofcbo != null) {
// 2、如果客户没有归属客户经理,但有归属机构,将商机状态置成“1-待分配”,将待分配机构设置成客户对应的归属机构
ofmbo_h.setOpporStat("1");// 商机状态置成“1-待分配”
ofmbo_h.setAssignOgrId(ofcbo.getInstitutionCode());// 待分配机构ID置成“归属机构代码”
ofmbo_h.setAssignOrgName(ofcbo.getInstitutionName());// 待分配机构名称置成“归属机构名称”
} else {
// 3、如果客户既没有归属客户经理,也没有归属机构,将商机状态置成“1-待分配”,将待分配机构设置成总行
ofmbo_h.setOpporStat("1");// 商机状态置成“1-待分配”
ofmbo_h.setAssignOgrId(aao.getOrgId());// 待分配机构ID置成“总行机构代码”
ofmbo_h.setAssignOrgName(aao.getOrgName());// 待分配机构名称置成“总行机构名称”
}
// 设置要更新的字段值
ofmbo_h.setOpporName(ofmbo.getOpporName());// 商机名称
ofmbo_h.setOpporType(ofmbo.getOpporType());// 商机类型
ofmbo_h.setOpporDueDate(ofmbo.getOpporDueDate());// 商机有效期
ofmbo_h.setOpporStage(ofmbo.getOpporStage());// 商机阶段
ofmbo_h.setOpporStartDate(ofmbo.getOpporStartDate());// 商机开始日期
ofmbo_h.setOpporEndDate(ofmbo.getOpporEndDate());// 商机结束日期
ofmbo_h.setMktActivId(ofmbo.getMktActivId());// 营销活动ID
ofmbo_h.setMktActivName(ofmbo.getMktActivName());// 营销活动名称
ofmbo_h.setMktTargetId(ofmbo.getMktTargetId());// 营销任务指标ID
ofmbo_h.setMktTargetName(ofmbo.getMktTargetName());// 营销任务指标名称
ofmbo_h.setProdId(ofmbo.getProdId());// 商机产品ID
ofmbo_h.setProdName(ofmbo.getProdName());// 商机产品名称
ofmbo_h.setCustId(ofmbo.getCustId());// 客户ID
ofmbo_h.setCustName(ofmbo.getCustName());// 客户名称
ofmbo_h.setCustCategory(ofmbo.getCustCategory());// 客户类型
ofmbo_h.setCustType(ofmbo.getCustType());// 客户状态
ofmbo_h.setCustContactName(ofmbo.getCustContactName());// 客户联系人
ofmbo_h.setPlanAmount(ofmbo.getPlanAmount());// 预计金额
ofmbo_h.setPlanCost(ofmbo.getPlanCost());// 费用预算
ofmbo_h.setOpporContent(ofmbo.getOpporContent());// 商机内容
ofmbo_h.setMemo(ofmbo.getMemo());// 商机备注
// 设置部分特殊字段值
ofmbo_h.setUpdateUserId(auth.getUserId());// 更新人ID
ofmbo_h.setUpdateUserName(auth.getUsername());// 更新人名称
ofmbo_h.setUpdateOrgId(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("ID"));// 更新人所在机构ID
ofmbo_h.setUpdateOrgName(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("UNITNAME"));// 更新人所在机构名称
ofmbo_h.setUpdateDateTime(new Timestamp(System
.currentTimeMillis()));// 更新时间
// 更新商机数据
em.merge(ofmbo_h);
}
}
return ofmbo_h;
}
// 根据客户ID,查询客户归属的主办客户经理对象
@SuppressWarnings("rawtypes")
private OcrmFCiBelongCustmgr getBelongCustmgr(OcrmFMmMktBusiOppor ofmbo) {
List list = null;
String jql = null;
OcrmFCiBelongCustmgr ofcbc = null;
jql = "select t from OcrmFCiBelongCustmgr t where t.custId = '"
+ ofmbo.getCustId() + "' and t.mainType = '1'";
list = em.createQuery(jql).getResultList();
if (list != null && list.size() > 0) {
ofcbc = (OcrmFCiBelongCustmgr) list.get(0);
}
return ofcbc;
}
// 根据客户ID,查询客户归属的主办机构对象
@SuppressWarnings("rawtypes")
private OcrmFCiBelongOrg getBelongOrg(OcrmFMmMktBusiOppor ofmbo) {
List list = null;
String jql = null;
OcrmFCiBelongOrg ofcbo = null;
jql = "select t from OcrmFCiBelongOrg t where t.custId = '"
+ ofmbo.getCustId() + "' and t.mainType = '1'";
list = em.createQuery(jql).getResultList();
if (list != null && list.size() > 0) {
ofcbo = (OcrmFCiBelongOrg) list.get(0);
}
return ofcbo;
}
// 查询总行对象
@SuppressWarnings("rawtypes")
private AdminAuthOrg getTopOrg() {
List list = null;
String jql = null;
AdminAuthOrg aao = null;
jql = "select t from AdminAuthOrg t where t.orgLevel = '1' or t.upOrgId is null";
list = em.createQuery(jql).getResultList();
if (list != null && list.size() > 0) {
aao = (AdminAuthOrg) list.get(0);
}
return aao;
}
// 分配商机信息
public void allocatBusiOppor(OcrmFMmMktBusiOppor ofmbo, AuthUser auth) {
if (ofmbo != null && ofmbo.getOpporId() != null) {
// 根据“执行机构”和“执行人”进行区分:是分配到执行机构还是分配到执行人
if (ofmbo.getAssignOgrId() != null
&& !"".equals(ofmbo.getAssignOgrId())) {
// 分配到机构
this.allocatBusiOpporOrg(ofmbo, auth);
// 保存操作历史记录
this.addOpHis(ofmbo, auth, 0);
} else if (ofmbo.getExecuteUserId() != null
&& !"".equals(ofmbo.getExecuteUserId())) {
// 分配到执行人
this.allocatBusiOpporUser(ofmbo, auth);
// 保存操作历史记录
this.addOpHis(ofmbo, auth, 1);
}
}
}
// 商机分配到机构
@SuppressWarnings("unchecked")
private void allocatBusiOpporOrg(OcrmFMmMktBusiOppor ofmbo, AuthUser auth) {
if (ofmbo != null && ofmbo.getOpporId() != null) {
OcrmFMmMktBusiOppor ofmbo_d = null;
ofmbo_d = em.find(OcrmFMmMktBusiOppor.class, ofmbo.getOpporId());
if (ofmbo_d != null) {
if ("6".equals(ofmbo_d.getOpporStat())) {// 如果是“到期退回”状态的分配,需要更新“商机有效期”
ofmbo_d.setOpporDueDate(ofmbo.getOpporDueDate());
}
ofmbo_d.setUpdateUserId(auth.getUserId());// 最近更新人ID
ofmbo_d.setUpdateUserName(auth.getUsername());// 最近更新人名称
ofmbo_d.setUpdateOrgId(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("ID"));// 最近更新机构ID
ofmbo_d.setUpdateOrgName(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("UNITNAME"));// 最近更新机构名称
ofmbo_d.setUpdateDateTime(new Timestamp(System
.currentTimeMillis()));// 最近更新时间
ofmbo_d.setAssignOgrId(ofmbo.getAssignOgrId());// 待分配机构ID
ofmbo_d.setAssignOrgName(ofmbo.getAssignOrgName());// 待分配机构
em.merge(ofmbo_d);
}
}
}
// 商机分配到客户经理
@SuppressWarnings("unchecked")
private void allocatBusiOpporUser(OcrmFMmMktBusiOppor ofmbo, AuthUser auth) {
if (ofmbo != null && ofmbo.getOpporId() != null) {
OcrmFMmMktBusiOppor ofmbo_d = null;
AdminAuthAccount aaa = null;
AdminAuthOrg aao = null;
ofmbo_d = em.find(OcrmFMmMktBusiOppor.class, ofmbo.getOpporId());
if (ofmbo_d != null) {
ofmbo_d.setOpporStat("4");// 商机状态变成“执行中(4)”
if ("6".equals(ofmbo_d.getOpporStat())) {// 如果是“到期退回”状态的分配,需要更新“商机有效期”
ofmbo_d.setOpporDueDate(ofmbo.getOpporDueDate());
}
ofmbo_d.setUpdateUserId(auth.getUserId());// 最近更新人ID
ofmbo_d.setUpdateUserName(auth.getUsername());// 最近更新人名称
ofmbo_d.setUpdateOrgId(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("ID"));// 最近更新机构ID
ofmbo_d.setUpdateOrgName(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("UNITNAME"));// 最近更新机构名称
ofmbo_d.setUpdateDateTime(new Timestamp(System
.currentTimeMillis()));// 最近更新时间
ofmbo_d.setExecuteUserId(ofmbo.getExecuteUserId());// 执行人ID
ofmbo_d.setExecuteUserName(ofmbo.getExecuteUserName());// 执行人名称
aaa = this.getUserOrg(ofmbo.getExecuteUserId());
ofmbo_d.setExecuteOrgId(aaa == null ? "" : aaa.getOrgId());// 执行人所在机构ID
aao = this.getOrg(aaa.getOrgId());
ofmbo_d.setExecuteOrgName(aao == null ? "" : aao.getOrgName());// 执行人所在机构名称
em.merge(ofmbo_d);
}
}
}
// 根据用户登录账号,查询对应的用户对象
@SuppressWarnings("rawtypes")
private AdminAuthAccount getUserOrg(String userAccout) {
AdminAuthAccount aaa = null;
String jql = null;
List list = null;
jql = "select t from AdminAuthAccount t where t.accountName = '"
+ userAccout + "'";
list = em.createQuery(jql).getResultList();
if (list != null && list.size() > 0) {
aaa = (AdminAuthAccount) list.get(0);
}
return aaa;
}
// 根据机构ID,查询对应的机构对象
@SuppressWarnings("rawtypes")
private AdminAuthOrg getOrg(String orgId) {
AdminAuthOrg aao = null;
String jql = null;
List list = null;
jql = "select t from AdminAuthOrg t where t.orgId = '" + orgId + "'";
list = em.createQuery(jql).getResultList();
if (list != null && list.size() > 0) {
aao = (AdminAuthOrg) list.get(0);
}
return aao;
}
// 分配商机操作时,新增商机操作历史记录
@SuppressWarnings("unchecked")
private void addOpHis(OcrmFMmMktBusiOppor ofmbo, AuthUser auth, int flag) {
OcrmFMmMktBusiOpporHisS ofmboh = null;
if (ofmbo != null && ofmbo.getOpporId() != null) {
ofmboh = new OcrmFMmMktBusiOpporHisS();
ofmboh.setOpporId(ofmbo.getOpporId());// 商机ID
// 操作内容
if (flag == 0) {// 分配到机构
ofmboh.setOprContent("商机由“" + auth.getUsername() + "”分配给“"
+ ofmbo.getAssignOrgName() + "("
+ ofmbo.getAssignOgrId() + ")”。");
} else if (flag == 1) {// 分配到客户经理
ofmboh.setOprContent("商机由“" + auth.getUsername() + "”分配给“"
+ "“" + ofmbo.getExecuteUserName() + "("
+ ofmbo.getExecuteUserId() + ")”。");
}
ofmboh.setOprDateTime(new Timestamp(System.currentTimeMillis()));// 操作时间
ofmboh.setOprOrgId(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("ID"));// 操作机构ID
ofmboh.setOprOrgName(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("UNITNAME"));// 操作机构名称
ofmboh.setOprUserId(auth.getUserId());// 操作人ID
ofmboh.setOprUserName(auth.getUsername());// 操作人名称
this.saveBusiOpporOperationHis(ofmboh);
}
}
// 退回商机
// 由于现在数据结构不支持层层回退,所以,执行回退操作时,
// 直接根据客户归属情况,进行重新分配,规则和提交商机一致
// 并且清空“执行人”、“执行机构”、“待分配机构”、“认领人”、“认领人机构”
@SuppressWarnings("unchecked")
public int backBusiOppor(OcrmFMmMktBusiOppor ofmbo, AuthUser auth) {
int result = 0;
AdminAuthOrg aao = null;
String[] oppor_id_arr = null;
OcrmFCiBelongOrg ofcbo = null;
OcrmFMmMktBusiOppor ofmbo_d = null;
OcrmFMmMktBusiOpporHisS ofmboh = null;
if (ofmbo != null && ofmbo.getOpporId() != null) {
oppor_id_arr = ofmbo.getOpporId().split(",");
if (oppor_id_arr != null && oppor_id_arr.length > 0) {
for (int i = 0; i < oppor_id_arr.length; i++) {
ofmbo_d = em.find(OcrmFMmMktBusiOppor.class,
oppor_id_arr[i]);
// 判断“执行人”是否是当前用户
if (ofmbo_d.getExecuteUserId() != null
&& !ofmbo_d.getExecuteUserId().equals(
auth.getUserId())) {
result = 1;
}
if (result != 0) {
return result;
}
// 判断“待分配机构”是否是当前用户所在机构
if (ofmbo_d.getAssignOgrId() != null
&& !ofmbo_d
.getAssignOgrId()
.equals(((HashMap<String, String>) auth
.getPathOrgList().get(0)).get("ID"))) {
result = 1;
}
if (result != 0) {
return result;
}
if (ofmbo_d != null) {
ofcbo = this.getBelongOrg(ofmbo_d);
aao = this.getTopOrg();
// 执行回退操作
ofmbo_d.setExecuteUserId("");// 清空“执行人ID”
ofmbo_d.setExecuteUserName("");// 清空“执行人名称”
ofmbo_d.setExecuteOrgId("");// 清空“执行机构ID”
ofmbo_d.setExecuteOrgName("");// 清空“执行机构名称”
ofmbo_d.setAssignOgrId("");// 清空“待分配机构ID”
ofmbo_d.setAssignOrgName("");// 清空“待分配机构名称”
ofmbo_d.setClaimUserId("");// 清空“认领人ID”
ofmbo_d.setClaimUserName("");// 清空“认领人名称”
ofmbo_d.setClaimOrgId("");// 清空“认领机构ID”
ofmbo_d.setClaimOrgName("");// 清空“认领机构名称”
if (ofcbo != null) {
// 如果客户有归属机构,将商机状态置成“1-待分配”,将待分配机构设置成客户对应的归属机构
ofmbo_d.setOpporStat("1");// 商机状态置成“1-待分配”
ofmbo_d.setAssignOgrId(ofcbo.getInstitutionCode());// 待分配机构ID置成“归属机构代码”
ofmbo_d.setAssignOrgName(ofcbo.getInstitutionName());// 待分配机构名称置成“归属机构名称”
} else {
// 如果客户没有归属机构,将商机状态置成“1-待分配”,将待分配机构设置成总行
ofmbo_d.setOpporStat("1");// 商机状态置成“1-待分配”
ofmbo_d.setAssignOgrId(aao.getOrgId());// 待分配机构ID置成“总行机构代码”
ofmbo_d.setAssignOrgName(aao.getOrgName());// 待分配机构名称置成“总行机构名称”
}
ofmbo_d.setOpporStat("5");// 商机状态(退回(5))
ofmbo_d.setUpdateUserId(auth.getUserId());// 最近更新人ID
ofmbo_d.setUpdateUserName(auth.getUsername());// 最近更新人名称
ofmbo_d.setUpdateOrgId(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("ID"));// 最近更新机构ID
ofmbo_d.setUpdateOrgName(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("UNITNAME"));// 最近更新机构名称
ofmbo_d.setUpdateDateTime(new Timestamp(System
.currentTimeMillis()));// 最近更新时间
em.merge(ofmbo_d);
// 新增商机操作历史记录
ofmboh = new OcrmFMmMktBusiOpporHisS();
ofmboh.setOpporId(ofmbo_d.getOpporId());
ofmboh.setOprDateTime(new Timestamp(System
.currentTimeMillis()));
ofmboh.setOprOrgId(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("ID"));
ofmboh.setOprOrgName(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("UNITNAME"));
ofmboh.setOprUserId(auth.getUserId());
ofmboh.setOprUserName(auth.getUsername());
ofmboh.setOprContent("“" + auth.getUsername()
+ "”退回商机,退回原因:" + ofmbo.getMemo() + "。");
this.saveBusiOpporOperationHis(ofmboh);
}
}
}
}
return result;
}
// 根据商机ID集合,删除对应的商机记录
public String delBusiOpporByIdS(String opporIdS, AuthUser auth) {
String result = null;
if (opporIdS != null && !"".equals(opporIdS)) {
String[] idArr = opporIdS.split(",");
for (int i = 0; i < idArr.length; i++) {
result = delBusiOpporById(idArr[i], auth);
if (result != null && !"".equals(result)) {
break;
}
}
}
return result;
}
// 根据商机ID,删除对应的商机记录
public String delBusiOpporById(String opporId, AuthUser auth) {
String result = null;
String orgManagerId = null;
OcrmFMmMktBusiOppor ofmmbo = null;
if (opporId != null && !"".equals(opporId)) {
ofmmbo = em.find(OcrmFMmMktBusiOppor.class, opporId);
if (ofmmbo != null) {
// 根据商机的创建类型判断,当前用户是否有权限删除
if ("0".equals(ofmmbo.getOpporSource())) {
// 1、如果是手动创建,只能由创建人和执行人删除
if (!auth.getUserId().equals(ofmmbo.getExecuteUserId())
&& !auth.getUserId().equals(ofmmbo.getCreaterId())) {
result = "您没有权限删除当前选中的商机!";
return result;
}
} else {
// 2、如果非手动创建,只能由待分配机构主管删除
orgManagerId = this.getOrgManager(ofmmbo.getAssignOgrId());
if (!auth.getUserId().equals(orgManagerId)) {
result = "您没有权限删除当前选中的商机!";
return result;
}
}
em.remove(ofmmbo);
}
}
return result;
}
// 认领商机
public void claimBusiOppor(String opporIdS, String claimType, AuthUser auth) {
String[] id_arr = null;
if (opporIdS != null && !"".equals(opporIdS)) {
id_arr = opporIdS.split(",");
if ("0".equals(claimType)) {// 客户经理认领
this.claimUserManager(id_arr, auth);
} else if ("1".equals(claimType)) {// 机构认领
this.claimOrgManager(id_arr, auth);
}
}
}
// 客户经理认领商机
@SuppressWarnings("unchecked")
private void claimUserManager(String[] id_arr, AuthUser auth) {
OcrmFMmMktBusiOppor ofmbo = null;
OcrmFMmMktBusiOpporHisS ofmboh = null;
if (id_arr != null && id_arr.length > 0) {
for (int i = 0; i < id_arr.length; i++) {
ofmbo = em.find(OcrmFMmMktBusiOppor.class, id_arr[i]);
if (ofmbo != null) {
// 更新商机信息
ofmbo.setClaimUserId(auth.getUserId());// 认领人ID
ofmbo.setClaimUserName(auth.getUsername());// 认领人名称
ofmbo.setOpporStat("3");// 商机状态:待审批(3)
ofmbo.setUpdateUserId(auth.getUserId());// 最近更新人ID
ofmbo.setUpdateUserName(auth.getUsername());// 最近更新人名称
ofmbo.setUpdateOrgId(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("ID"));// 最近更新机构ID
ofmbo.setUpdateOrgName(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("UNITNAME"));// 最近更新机构名称
ofmbo.setUpdateDateTime(new Timestamp(System
.currentTimeMillis()));// 最近更新时间
ofmbo.setAssignOgrId("");// 待分配机构ID(清空)
ofmbo.setAssignOrgName("");// 待分配机构名称(清空)
em.merge(ofmbo);
// 写商机操作历史记录
ofmboh = new OcrmFMmMktBusiOpporHisS();
ofmboh.setOpporId(ofmbo.getOpporId());
ofmboh.setOprDateTime(new Timestamp(System
.currentTimeMillis()));
ofmboh.setOprOrgId(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("ID"));
ofmboh.setOprOrgName(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("UNITNAME"));
ofmboh.setOprUserId(auth.getUserId());
ofmboh.setOprUserName(auth.getUsername());
ofmboh.setOprContent("“" + auth.getUsername()
+ "(客户经理认领)”认领商机。");
this.saveBusiOpporOperationHis(ofmboh);
}
}
}
}
// 机构认领商机
@SuppressWarnings("unchecked")
private void claimOrgManager(String[] id_arr, AuthUser auth) {
OcrmFMmMktBusiOppor ofmbo = null;
OcrmFMmMktBusiOpporHisS ofmboh = null;
if (id_arr != null && id_arr.length > 0) {
for (int i = 0; i < id_arr.length; i++) {
ofmbo = em.find(OcrmFMmMktBusiOppor.class, id_arr[i]);
if (ofmbo != null) {
// 更新商机信息
ofmbo.setClaimOrgId(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("ID"));// 认领机构ID
ofmbo.setClaimOrgName(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("UNITNAME"));// 认领机构名称
ofmbo.setOpporStat("3");// 商机状态:待审批(3)
ofmbo.setUpdateUserId(auth.getUserId());// 最近更新人ID
ofmbo.setUpdateUserName(auth.getUsername());// 最近更新人名称
ofmbo.setUpdateOrgId(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("ID"));// 最近更新机构ID
ofmbo.setUpdateOrgName(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("UNITNAME"));// 最近更新机构名称
ofmbo.setUpdateDateTime(new Timestamp(System
.currentTimeMillis()));// 最近更新时间
ofmbo.setAssignOgrId("");// 待分配机构ID(清空)
ofmbo.setAssignOrgName("");// 待分配机构名称(清空)
em.merge(ofmbo);
// 写商机操作历史记录
ofmboh = new OcrmFMmMktBusiOpporHisS();
ofmboh.setOpporId(ofmbo.getOpporId());
ofmboh.setOprDateTime(new Timestamp(System
.currentTimeMillis()));
ofmboh.setOprOrgId(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("ID"));
ofmboh.setOprOrgName(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("UNITNAME"));
ofmboh.setOprUserId(auth.getUserId());
ofmboh.setOprUserName(auth.getUsername());
ofmboh.setOprContent("“" + auth.getUsername()
+ "(机构认领)”认领商机。");
this.saveBusiOpporOperationHis(ofmboh);
}
}
}
}
// 认领商机审批
public void claimAuditBusiOppor(String opporIdS, String auditResult,
AuthUser auth, OcrmFMmMktBusiOppor model) {
String[] id_arr = null;
if (opporIdS != null && !"".equals(opporIdS)) {
id_arr = opporIdS.split(",");
if ("0".equals(auditResult)) {// 审核通过
this.claimAuditBusiOpporPass(id_arr, auth, model);
} else if ("1".equals(auditResult)) {// 审核不通过
this.claimAuditBusiOpporBack(id_arr, auth, model);
}
}
}
// 认领商机审批:同意
@SuppressWarnings("unchecked")
public void claimAuditBusiOpporPass(String[] id_arr, AuthUser auth,
OcrmFMmMktBusiOppor model) {
AdminAuthOrg aao = null;
AdminAuthAccount aaa = null;
OcrmFMmMktBusiOppor ofmbo = null;
OcrmFMmMktBusiOpporHisS ofmboh = null;
if (id_arr != null && id_arr.length > 0) {
for (int i = 0; i < id_arr.length; i++) {
ofmbo = em.find(OcrmFMmMktBusiOppor.class, id_arr[i]);
if (ofmbo != null) {
// 更新商机信息
if (ofmbo.getClaimUserId() != null
&& !"".equals(ofmbo.getClaimUserId())) {
// 客户经理认领
aaa = this.getUserByAccountName(ofmbo.getClaimUserId());
aao = this.getOrg(aaa.getOrgId());
ofmbo.setExecuteUserId(ofmbo.getClaimUserId());// 将“执行人ID”设置成“认领人ID”
ofmbo.setExecuteUserName(ofmbo.getClaimUserName());// 将“执行人名称”设置成“认领人名称”
ofmbo.setOpporStat("4");// 商机状态:执行中(4)
ofmbo.setClaimUserId("");// 清空“认领人ID”
ofmbo.setClaimUserName("");// 清空“认领人名称”
ofmbo.setExecuteOrgId(aaa.getOrgId());// 执行人所在机构ID
ofmbo.setExecuteOrgName(aao.getOrgName());// 执行人所在机构名称
} else if (ofmbo.getClaimOrgId() != null
&& !"".equals(ofmbo.getClaimOrgId())) {
// 机构认领
ofmbo.setAssignOgrId(ofmbo.getClaimOrgId());// 将“认领机构ID”设置成“待分配机构ID”
ofmbo.setAssignOrgName(ofmbo.getClaimOrgName());// 将“认领机构名称”设置成“待分配机构名称”
ofmbo.setOpporStat("1");// 商机状态:待分配(1)
ofmbo.setClaimOrgId("");// 清空“待分配机构ID”
ofmbo.setClaimOrgName("");// 清空“待分配机构名称”
}
ofmbo.setUpdateUserId(auth.getUserId());// 最近更新人ID
ofmbo.setUpdateUserName(auth.getUsername());// 最近更新人名称
ofmbo.setUpdateOrgId(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("ID"));// 最近更新机构ID
ofmbo.setUpdateOrgName(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("UNITNAME"));// 最近更新机构名称
ofmbo.setUpdateDateTime(new Timestamp(System
.currentTimeMillis()));// 最近更新时间
em.merge(ofmbo);
// 写商机操作历史记录
ofmboh = new OcrmFMmMktBusiOpporHisS();
ofmboh.setOpporId(ofmbo.getOpporId());
ofmboh.setOprDateTime(new Timestamp(System
.currentTimeMillis()));
ofmboh.setOprOrgId(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("ID"));
ofmboh.setOprOrgName(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("UNITNAME"));
ofmboh.setOprUserId(auth.getUserId());
ofmboh.setOprUserName(auth.getUsername());
ofmboh.setOprContent("“" + auth.getUsername()
+ "”审批商机认领:同意。");
this.saveBusiOpporOperationHis(ofmboh);
}
}
}
}
// 认领商机审批:拒绝
@SuppressWarnings("unchecked")
public void claimAuditBusiOpporBack(String[] id_arr, AuthUser auth,
OcrmFMmMktBusiOppor model) {
AdminAuthOrg aao = null;
OcrmFCiBelongOrg ofcbo = null;
OcrmFMmMktBusiOppor ofmbo = null;
OcrmFMmMktBusiOpporHisS ofmboh = null;
if (id_arr != null && id_arr.length > 0) {
for (int i = 0; i < id_arr.length; i++) {
ofmbo = em.find(OcrmFMmMktBusiOppor.class, id_arr[i]);
if (ofmbo != null) {
ofcbo = this.getBelongOrg(ofmbo);
aao = this.getTopOrg();
// 更新商机信息
ofmbo.setClaimOrgId("");// 清空认领机构ID
ofmbo.setClaimOrgName("");// 清空认领机构名称
ofmbo.setClaimUserId("");// 清空认领人ID
ofmbo.setClaimUserName("");// 清空认领人名称
if (ofcbo != null) {
// 如果客户有归属机构,将商机状态置成“1-待分配”,将待分配机构设置成客户对应的归属机构
ofmbo.setOpporStat("1");// 商机状态置成“1-待分配”
ofmbo.setAssignOgrId(ofcbo.getInstitutionCode());// 待分配机构ID置成“归属机构代码”
ofmbo.setAssignOrgName(ofcbo.getInstitutionName());// 待分配机构名称置成“归属机构名称”
} else {
// 如果客户没有归属机构,将商机状态置成“1-待分配”,将待分配机构设置成总行
ofmbo.setOpporStat("1");// 商机状态置成“1-待分配”
ofmbo.setAssignOgrId(aao.getOrgId());// 待分配机构ID置成“总行机构代码”
ofmbo.setAssignOrgName(aao.getOrgName());// 待分配机构名称置成“总行机构名称”
}
ofmbo.setUpdateUserId(auth.getUserId());// 最近更新人ID
ofmbo.setUpdateUserName(auth.getUsername());// 最近更新人名称
ofmbo.setUpdateOrgId(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("ID"));// 最近更新机构ID
ofmbo.setUpdateOrgName(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("UNITNAME"));// 最近更新机构名称
ofmbo.setUpdateDateTime(new Timestamp(System
.currentTimeMillis()));// 最近更新时间
em.merge(ofmbo);
// 写商机操作历史记录
ofmboh = new OcrmFMmMktBusiOpporHisS();
ofmboh.setOpporId(ofmbo.getOpporId());
ofmboh.setOprDateTime(new Timestamp(System
.currentTimeMillis()));
ofmboh.setOprOrgId(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("ID"));
ofmboh.setOprOrgName(((HashMap<String, String>) (auth
.getPathOrgList().get(0))).get("UNITNAME"));
ofmboh.setOprUserId(auth.getUserId());
ofmboh.setOprUserName(auth.getUsername());
ofmboh.setOprContent("“" + auth.getUsername()
+ "”审批商机认领:拒绝,拒绝理由:" + model.getMemo() + "。");
this.saveBusiOpporOperationHis(ofmboh);
}
}
}
}
// 根据ID,查询对应的商机对象
public OcrmFMmMktBusiOppor find(String opporId) {
return em.find(OcrmFMmMktBusiOppor.class, opporId);
}
// 保存商机操作历史记录
public void saveBusiOpporOperationHis(OcrmFMmMktBusiOpporHisS ofmboh) {
em.persist(ofmboh);
}
// 根据机构ID,查询对应的机构主管
// 查询逻辑:
// 1、在用户表中,根据机构ID,查询出该机构下的所有用户
// 2、在用户和角色关联表中,根据用户和角色关联关系,找出角色为“主管”的用户
// 其中,“主管角色”编码,是在代码中写死的,在不同的行实施时,需要根据具体情况进行修改
@SuppressWarnings("rawtypes")
public String getOrgManager(String orgId) {
String jql = null;
List list = null;
StringBuffer sb = null;
String orgManager = null;
AdminAuthAccount aaa = null;
if (orgId == null || "".equals(orgId)) {
return orgManager;
}
// 定义机构主管角色编码(用于拼凑查询语句),在不同的银行实施时,需要根据系统实际情况进行更改
// zleader:总行管理人员
// 1234:总行业务主管
// zhbm:总行业务经理
// fhsystem:分行系统管理员
// fhbm:分行业务经理
// zhhz:支行行长
String orgManagerRoleCodeS = "('zleader','1234','zhbm','fhsystem','fhbm','zhhz')";
sb = new StringBuffer("");
sb.append("select a");
sb.append(" from AdminAuthAccount a");
sb.append(" where a.id in");
sb.append(" (select b.accountId");
sb.append(" from AdminAuthAccountRole b");
sb.append(" where b.accountId in (select c.id");
sb.append(" from AdminAuthAccount c");
sb.append(" where c.orgId = '" + orgId + "')");
sb.append(" and b.roleId in (select d.id");
sb.append(" from AdminAuthRole d");
sb.append(" where d.roleCode in " + orgManagerRoleCodeS + "))");
jql = sb.toString();
list = em.createQuery(jql).getResultList();
if (list != null && list.size() > 0) {
aaa = (AdminAuthAccount) list.get(0);
orgManager = aaa.getAccountName();
}
return orgManager;
}
// 判断当前用户是否能退回选中的商机
// 判断逻辑:
// 1、客户经理只能退回分配给自己的商机,客户只有当前一个归属客户经理时不能退回
// 2、客户主管可以退回分配给本机构的商机,并且只能退回客户没有归属机构的商机
public String canReturn(String userType, String opporIdS, AuthUser auth) {
String result = "true";
String[] id_arr = null;
OcrmFMmMktBusiOppor ofmbo = null;
if (opporIdS != null && !"".equals(opporIdS)) {
id_arr = opporIdS.split(",");
if (id_arr != null && id_arr.length > 0) {
for (int i = 0; i < id_arr.length; i++) {
ofmbo = em.find(OcrmFMmMktBusiOppor.class, id_arr[i]);
if (ofmbo != null) {
// userType,0:客户经理;1:机构主管;2:客户经理+机构主管
if ("0".equals(userType)) {
// 客户经理
if (ofmbo.getExecuteUserId() != null
&& !ofmbo.getExecuteUserId().equals(
auth.getUserId())) {
// 有执行人,并且不是当前用户,不能退回
result = "false";
return result;
} else if (ofmbo.getExecuteUserId() != null
&& this.isOnlyOneManager(ofmbo.getCustId())) {
// 有执行人,并且该客户只有一个归属客户经理,不能退回
result = "false";
return result;
}
} else if ("1".equals(opporIdS)) {
// 机构主管
if (ofmbo.getAssignOgrId() != null
&& !ofmbo.getAssignOgrId().equals(
auth.getUnitId())) {
// 有待分配机构,并且待分配机构不是当前用户所在机构,不能退回
result = "false";
return result;
} else if (ofmbo.getAssignOgrId() != null
&& ofmbo.getAssignOgrId().equals(
auth.getUnitId())
&& !this.isHadOrgManager(ofmbo.getCustId())) {
// 有待分配机构,并且待分配机构是当前用户所在机构,但客户没有归属机构,不能退回
result = "false";
return result;
}
} else if ("2".equals(opporIdS)) {
// 客户经理+机构主管
// 客户经理
if (ofmbo.getExecuteUserId() != null
&& !ofmbo.getExecuteUserId().equals(
auth.getUserId())) {
// 有执行人,并且不是当前用户,不能退回
result = "false";
return result;
} else if (ofmbo.getExecuteUserId() != null
&& this.isOnlyOneManager(ofmbo.getCustId())) {
// 有执行人,并且该客户只有一个归属客户经理,不能退回
result = "false";
return result;
}
// 机构主管
if (ofmbo.getAssignOgrId() != null
&& !ofmbo.getAssignOgrId().equals(
auth.getUnitId())) {
// 有待分配机构,并且待分配机构不是当前用户所在机构,不能退回
result = "false";
return result;
} else if (ofmbo.getAssignOgrId() != null
&& ofmbo.getAssignOgrId().equals(
auth.getUnitId())
&& !this.isHadOrgManager(ofmbo.getCustId())) {
// 有待分配机构,并且待分配机构是当前用户所在机构,但客户没有归属机构,不能退回
result = "false";
return result;
}
} else {
// 既不是客户经理,也不是结构主管,不能退回商机(wzy,20130422,add)
result = "false";
return result;
}
}
}
}
}
return result;
}
// 判断某一客户是否只有一个归属客户经理,是:返回true;否:返回false
@SuppressWarnings("rawtypes")
private boolean isOnlyOneManager(String custId) {
boolean result = false;
List list = null;
StringBuffer sb = null;
sb = new StringBuffer("");
sb.append("select a");
sb.append(" from OcrmFCiBelongCustmgr a");
sb.append(" where a.custId = '" + custId + "'");
list = em.createQuery(sb.toString()).getResultList();
if (list != null && list.size() == 1) {
result = true;
}
return result;
}
// 判断某一客户是否有归属机构,有:返回true;无:返回false
@SuppressWarnings("rawtypes")
private boolean isHadOrgManager(String custId) {
boolean result = false;
List list = null;
StringBuffer sb = null;
sb = new StringBuffer("");
sb.append("select a");
sb.append(" from OcrmFCiBelongOrg a");
sb.append(" where a.custId = '" + custId + "'");
list = em.createQuery(sb.toString()).getResultList();
if (list != null && list.size() > 0) {
result = true;
}
return result;
}
// 用户用户登录系统的账号,查询用户model对象
private AdminAuthAccount getUserByAccountName(String accountName) {
String jql = "";
AdminAuthAccount aaa = null;
try {
if (accountName != null && !"".equals(accountName)) {
jql = "select t from AdminAuthAccount t where t.accountName = '"
+ accountName + "'";
aaa = (AdminAuthAccount) em.createQuery(jql).getResultList()
.get(0);
}
} catch (Exception e) {
e.printStackTrace();
}
return aaa;
}
// 从客户群组功能点批量创建商机(新增保存)
public void pitchCreateBusiOpporFromCustGroup(OcrmFMmMktBusiOppor ofmbo,
AuthUser auth) {
String[] custIdArr = null;
String[] custNameArr = null;
OcrmFCiCustDesc ofccd = null;
if (ofmbo != null && ofmbo.getCustId() != null) {
custIdArr = ofmbo.getCustId().split(",");
custNameArr = ofmbo.getCustName().split(",");
if (custIdArr != null && custIdArr.length > 0) {
for (int i = 0; i < custIdArr.length; i++) {
ofccd = this.getCustByID(custIdArr[i]);
ofmbo.setCustId(custIdArr[i]);
ofmbo.setCustName(custNameArr[i]);
ofmbo.setCustType(ofccd.getCustStat());
ofmbo.setCustCategory(ofccd.getCustTyp());
this.saveBusiOppor(ofmbo, auth);
}
}
}
}
// 从客户群组功能点批量创建商机(新增提交)
public void pitchCreateSubmitBusiOpporFromCustGroup(
OcrmFMmMktBusiOppor ofmbo, AuthUser auth) {
String[] custIdArr = null;
String[] custNameArr = null;
OcrmFCiCustDesc ofccd = null;
if (ofmbo != null && ofmbo.getCustId() != null) {
custIdArr = ofmbo.getCustId().split(",");
custNameArr = ofmbo.getCustName().split(",");
if (custIdArr != null && custIdArr.length > 0) {
for (int i = 0; i < custIdArr.length; i++) {
ofccd = this.getCustByID(custIdArr[i]);
ofmbo.setCustId(custIdArr[i]);
ofmbo.setCustName(custNameArr[i]);
ofmbo.setCustType(ofccd.getCustStat());
ofmbo.setCustCategory(ofccd.getCustTyp());
this.addAndSubmit(ofmbo, auth);
}
}
}
}
// 根据客户ID查询客户对象
private OcrmFCiCustDesc getCustByID(String custId) {
return em.find(OcrmFCiCustDesc.class, custId);
}
} | [
"jack@jack-XPS-13-9343"
] | jack@jack-XPS-13-9343 |
ca330955bc8e021e18a745df32429a506b66918d | 36bbde826ff3e123716dce821020cf2a931abf6e | /plugin/makeMaker/src/main/java/com/perl5/lang/perl/makeMaker/PerlMakeMakerDirectoryConfigurationProvider.java | f757a6d0a551f36d73024e9760a38272f0d91b1a | [
"Apache-2.0"
] | permissive | Camelcade/Perl5-IDEA | 0332dd4794aab5ed91126a2c1ecd608f9c801447 | deecc3c4fcdf93b4ff35dd31b4c7045dd7285407 | refs/heads/master | 2023-08-08T07:47:31.489233 | 2023-07-27T05:18:40 | 2023-07-27T06:17:04 | 33,823,684 | 323 | 79 | NOASSERTION | 2023-09-13T04:36:15 | 2015-04-12T16:09:15 | Java | UTF-8 | Java | false | false | 1,763 | java | /*
* Copyright 2015-2023 Alexandr Evstigneev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.perl5.lang.perl.makeMaker;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.vfs.VirtualFile;
import com.perl5.lang.perl.idea.project.PerlDirectoryConfigurationProvider;
import com.perl5.lang.perl.idea.project.PerlDirectoryInfoCollector;
import org.jetbrains.annotations.NotNull;
public class PerlMakeMakerDirectoryConfigurationProvider implements PerlDirectoryConfigurationProvider {
@Override
public void configureContentRoot(@NotNull Module module,
@NotNull VirtualFile contentRoot,
@NotNull PerlDirectoryInfoCollector collector) {
var makeFilePl = contentRoot.findChild("Makefile.PL");
if (makeFilePl == null) {
return;
}
collector.addTestRoot(contentRoot.findChild("t"));
collector.addLibRoot(contentRoot.findChild("lib"));
var blibRoot = contentRoot.findChild("blib");
if (blibRoot != null) {
collector.addExcludedRoot(blibRoot);
var blibLibRoot = blibRoot.findChild("lib");
if (blibLibRoot != null) {
collector.addExternalLibRoot(blibRoot.findChild("arch"));
}
}
}
}
| [
"hurricup@gmail.com"
] | hurricup@gmail.com |
d596f632cc6288e4e0eee3ad5439e6a915db2386 | a8ac29989b58f4a8dc68478cd60cc927bcba7899 | /src/main/java/sawtooth/sdk/protobuf/ClientSortControlsOrBuilder.java | a701529a0b34ca2487eb0d3fa1d549e6c45f7739 | [
"Apache-2.0"
] | permissive | Remmeauth/remme-client-java | 6b2513e3ee099a9af66d785ef77680ed301237cd | 207786915bc8fc28833093081d9a7f690592da9e | refs/heads/master | 2020-04-06T11:13:05.599324 | 2019-02-13T12:10:18 | 2019-02-13T12:10:18 | 157,408,408 | 2 | 0 | Apache-2.0 | 2019-02-13T12:10:19 | 2018-11-13T16:10:04 | Java | UTF-8 | Java | false | true | 777 | java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: client_list_control.proto
package sawtooth.sdk.protobuf;
public interface ClientSortControlsOrBuilder extends
// @@protoc_insertion_point(interface_extends:ClientSortControls)
com.google.protobuf.MessageOrBuilder {
/**
* <code>repeated string keys = 1;</code>
*/
java.util.List<java.lang.String>
getKeysList();
/**
* <code>repeated string keys = 1;</code>
*/
int getKeysCount();
/**
* <code>repeated string keys = 1;</code>
*/
java.lang.String getKeys(int index);
/**
* <code>repeated string keys = 1;</code>
*/
com.google.protobuf.ByteString
getKeysBytes(int index);
/**
* <code>bool reverse = 2;</code>
*/
boolean getReverse();
}
| [
"marchello9307@gmail.com"
] | marchello9307@gmail.com |
b4bdc48b92f6911ca22410446d977f0cc1f4c21a | 441b412d2e334fa37cb617f4701e8a4c6e239d2f | /Customer/src/com/shashi/customer/GlobalApplication.java | 0941de5aa848cdc9f2b7b48b155403d51bbb4ae2 | [] | no_license | varuniiit/serviceme2 | 77c177efa306162a83a5da9072db5fd1ca57608f | 2bb93e0d926da2e7882b57c215bc30430392e501 | refs/heads/master | 2016-09-06T00:54:27.921111 | 2015-03-11T16:45:45 | 2015-03-11T16:45:45 | 28,478,809 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 922 | java | package com.shashi.customer;
import android.app.Application;
import com.parse.Parse;
import com.parse.ParseACL;
import com.parse.ParseInstallation;
import com.parse.ParseUser;
import com.parse.PushService;
public class GlobalApplication extends Application {
public static boolean isAppOpend = false;
public static String installationId;
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Parse.initialize(this, "pwuBEQ600d8CL0v8vu6GuVkndT2zgYee0odYktmQ",
"hZtz11BGcEwLofUZuKo1fVEN6emhE58tsoDp8OeR");
PushService.setDefaultPushCallback(this, MainActivity.class);
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
ParseInstallation installation = ParseInstallation
.getCurrentInstallation();
installationId = installation.getInstallationId();
}
}
| [
"sharathmk99@gmail.com"
] | sharathmk99@gmail.com |
882524623cf5147a92583eef954bb8834265f61b | bcd7c93f89adac49a8ddbe699f19e798d3507b63 | /eureka-getway/src/main/java/org/eureka/getway/conf/JsonExceptionHandler.java | 9f786ca6817f981f4593e5f68dea0902342bc8b0 | [] | no_license | gui-gui-maker/MyFrame | 3b37d7770617fb4438c4f97d79e58421a970000b | b03b38a26d591f16dca07cf2b3d24f129c5833ef | refs/heads/master | 2022-12-23T11:53:16.105726 | 2019-10-31T06:23:00 | 2019-10-31T06:23:00 | 218,462,486 | 1 | 0 | null | 2022-12-16T07:18:22 | 2019-10-30T06:56:36 | Java | UTF-8 | Java | false | false | 3,114 | java | package org.eureka.getway.conf;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.*;
import java.util.HashMap;
import java.util.Map;
/**
* 自定义异常处理
* SpringBoot 提供了默认的异常处理类,这显然不符合我们的预期
* 因此需要重写此类,返回统一的 JSON 格式
*/
public class JsonExceptionHandler extends DefaultErrorWebExceptionHandler {
public JsonExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties,
ErrorProperties errorProperties, ApplicationContext applicationContext) {
super(errorAttributes, resourceProperties, errorProperties, applicationContext);
}
/**
* 获取异常属性
*/
@Override
protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
int code = 500;
Throwable error = super.getError(request);
if (error instanceof org.springframework.cloud.gateway.support.NotFoundException) {
code = 404;
}
return response(code, this.buildMessage(request, error));
}
/**
* 指定响应处理方法为 JSON 处理的方法
* @param errorAttributes
*/
@Override
protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
}
/**
* 根据 code 获取对应的 HttpStatus
* @param errorAttributes
*/
@Override
protected HttpStatus getHttpStatus(Map<String, Object> errorAttributes) {
int statusCode = (int) errorAttributes.get("code");
return HttpStatus.valueOf(statusCode);
}
/**
* 构建异常信息
* @param request
* @param ex
* @return
*/
private String buildMessage(ServerRequest request, Throwable ex) {
StringBuilder message = new StringBuilder("Failed to handle request [");
message.append(request.methodName());
message.append(" ");
message.append(request.uri());
message.append("]");
if (ex != null) {
message.append(": ");
message.append(ex.getMessage());
}
return message.toString();
}
/**
* 构建返回的 JSON 数据格式
* @param status 状态码
* @param errorMessage 异常信息
* @return
*/
public static Map<String, Object> response(int status, String errorMessage) {
Map<String, Object> map = new HashMap<>();
map.put("code", status);
map.put("message", errorMessage);
map.put("data", null);
return map;
}
}
| [
"guidoz@163.com"
] | guidoz@163.com |
7aa18a46eb510492f4659929f426e0c9fc4ccb39 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/30/30_7bdfb134c6c1c4e3d4c5da61327e62bc38407c95/DownloadProvider/30_7bdfb134c6c1c4e3d4c5da61327e62bc38407c95_DownloadProvider_s.java | a9d861675fe037facce3a60e9c179458a564d7ea | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 43,189 | java | /*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.providers.downloads;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.UriMatcher;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.CrossProcessCursor;
import android.database.Cursor;
import android.database.CursorWindow;
import android.database.CursorWrapper;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.os.Binder;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.os.Process;
import android.provider.Downloads;
import android.util.Config;
import android.util.Log;
import com.google.common.annotations.VisibleForTesting;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
/**
* Allows application to interact with the download manager.
*/
public final class DownloadProvider extends ContentProvider {
/** Database filename */
private static final String DB_NAME = "downloads.db";
/** Current database version */
private static final int DB_VERSION = 102;
/** Name of table in the database */
private static final String DB_TABLE = "downloads";
/** MIME type for the entire download list */
private static final String DOWNLOAD_LIST_TYPE = "vnd.android.cursor.dir/download";
/** MIME type for an individual download */
private static final String DOWNLOAD_TYPE = "vnd.android.cursor.item/download";
/** URI matcher used to recognize URIs sent by applications */
private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
/** URI matcher constant for the URI of the entire download list */
private static final int DOWNLOADS = 1;
/** URI matcher constant for the URI of an individual download */
private static final int DOWNLOADS_ID = 2;
/** URI matcher constant for the URI of a download's request headers */
private static final int REQUEST_HEADERS_URI = 3;
static {
sURIMatcher.addURI("downloads", "download", DOWNLOADS);
sURIMatcher.addURI("downloads", "download/#", DOWNLOADS_ID);
sURIMatcher.addURI("downloads", "download/#/" + Downloads.Impl.RequestHeaders.URI_SEGMENT,
REQUEST_HEADERS_URI);
}
private static final String[] sAppReadableColumnsArray = new String[] {
Downloads.Impl._ID,
Downloads.Impl.COLUMN_APP_DATA,
Downloads.Impl._DATA,
Downloads.Impl.COLUMN_MIME_TYPE,
Downloads.Impl.COLUMN_VISIBILITY,
Downloads.Impl.COLUMN_DESTINATION,
Downloads.Impl.COLUMN_CONTROL,
Downloads.Impl.COLUMN_STATUS,
Downloads.Impl.COLUMN_LAST_MODIFICATION,
Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Downloads.Impl.COLUMN_TOTAL_BYTES,
Downloads.Impl.COLUMN_CURRENT_BYTES,
Downloads.Impl.COLUMN_TITLE,
Downloads.Impl.COLUMN_DESCRIPTION,
Downloads.Impl.COLUMN_URI,
};
private static HashSet<String> sAppReadableColumnsSet;
static {
sAppReadableColumnsSet = new HashSet<String>();
for (int i = 0; i < sAppReadableColumnsArray.length; ++i) {
sAppReadableColumnsSet.add(sAppReadableColumnsArray[i]);
}
}
/** The database that lies underneath this content provider */
private SQLiteOpenHelper mOpenHelper = null;
/** List of uids that can access the downloads */
private int mSystemUid = -1;
private int mDefContainerUid = -1;
@VisibleForTesting
SystemFacade mSystemFacade;
/**
* Creates and updated database on demand when opening it.
* Helper class to create database the first time the provider is
* initialized and upgrade it when a new version of the provider needs
* an updated version of the database.
*/
private final class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(final Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
/**
* Creates database the first time we try to open it.
*/
@Override
public void onCreate(final SQLiteDatabase db) {
if (Constants.LOGVV) {
Log.v(Constants.TAG, "populating new database");
}
onUpgrade(db, 0, DB_VERSION);
}
/**
* Updates the database format when a content provider is used
* with a database that was created with a different format.
*
* Note: to support downgrades, creating a table should always drop it first if it already
* exists.
*/
@Override
public void onUpgrade(final SQLiteDatabase db, int oldV, final int newV) {
if (oldV == 31) {
// 31 and 100 are identical, just in different codelines. Upgrading from 31 is the
// same as upgrading from 100.
oldV = 100;
} else if (oldV < 100) {
// no logic to upgrade from these older version, just recreate the DB
Log.i(Constants.TAG, "Upgrading downloads database from version " + oldV
+ " to version " + newV + ", which will destroy all old data");
oldV = 99;
} else if (oldV > newV) {
// user must have downgraded software; we have no way to know how to downgrade the
// DB, so just recreate it
Log.i(Constants.TAG, "Downgrading downloads database from version " + oldV
+ " (current version is " + newV + "), destroying all old data");
oldV = 99;
}
for (int version = oldV + 1; version <= newV; version++) {
upgradeTo(db, version);
}
}
/**
* Upgrade database from (version - 1) to version.
*/
private void upgradeTo(SQLiteDatabase db, int version) {
switch (version) {
case 100:
createDownloadsTable(db);
break;
case 101:
createHeadersTable(db);
break;
case 102:
addColumn(db, DB_TABLE, Downloads.Impl.COLUMN_IS_PUBLIC_API,
"INTEGER NOT NULL DEFAULT 0");
addColumn(db, DB_TABLE, Downloads.Impl.COLUMN_ALLOW_ROAMING,
"INTEGER NOT NULL DEFAULT 0");
addColumn(db, DB_TABLE, Downloads.Impl.COLUMN_ALLOWED_NETWORK_TYPES,
"INTEGER NOT NULL DEFAULT 0");
break;
default:
throw new IllegalStateException("Don't know how to upgrade to " + version);
}
}
/**
* Add a column to a table using ALTER TABLE.
* @param dbTable name of the table
* @param columnName name of the column to add
* @param columnDefinition SQL for the column definition
*/
private void addColumn(SQLiteDatabase db, String dbTable, String columnName,
String columnDefinition) {
db.execSQL("ALTER TABLE " + dbTable + " ADD COLUMN " + columnName + " "
+ columnDefinition);
}
/**
* Creates the table that'll hold the download information.
*/
private void createDownloadsTable(SQLiteDatabase db) {
try {
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
db.execSQL("CREATE TABLE " + DB_TABLE + "(" +
Downloads.Impl._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
Downloads.Impl.COLUMN_URI + " TEXT, " +
Constants.RETRY_AFTER_X_REDIRECT_COUNT + " INTEGER, " +
Downloads.Impl.COLUMN_APP_DATA + " TEXT, " +
Downloads.Impl.COLUMN_NO_INTEGRITY + " BOOLEAN, " +
Downloads.Impl.COLUMN_FILE_NAME_HINT + " TEXT, " +
Constants.OTA_UPDATE + " BOOLEAN, " +
Downloads.Impl._DATA + " TEXT, " +
Downloads.Impl.COLUMN_MIME_TYPE + " TEXT, " +
Downloads.Impl.COLUMN_DESTINATION + " INTEGER, " +
Constants.NO_SYSTEM_FILES + " BOOLEAN, " +
Downloads.Impl.COLUMN_VISIBILITY + " INTEGER, " +
Downloads.Impl.COLUMN_CONTROL + " INTEGER, " +
Downloads.Impl.COLUMN_STATUS + " INTEGER, " +
Constants.FAILED_CONNECTIONS + " INTEGER, " +
Downloads.Impl.COLUMN_LAST_MODIFICATION + " BIGINT, " +
Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE + " TEXT, " +
Downloads.Impl.COLUMN_NOTIFICATION_CLASS + " TEXT, " +
Downloads.Impl.COLUMN_NOTIFICATION_EXTRAS + " TEXT, " +
Downloads.Impl.COLUMN_COOKIE_DATA + " TEXT, " +
Downloads.Impl.COLUMN_USER_AGENT + " TEXT, " +
Downloads.Impl.COLUMN_REFERER + " TEXT, " +
Downloads.Impl.COLUMN_TOTAL_BYTES + " INTEGER, " +
Downloads.Impl.COLUMN_CURRENT_BYTES + " INTEGER, " +
Constants.ETAG + " TEXT, " +
Constants.UID + " INTEGER, " +
Downloads.Impl.COLUMN_OTHER_UID + " INTEGER, " +
Downloads.Impl.COLUMN_TITLE + " TEXT, " +
Downloads.Impl.COLUMN_DESCRIPTION + " TEXT, " +
Constants.MEDIA_SCANNED + " BOOLEAN);");
} catch (SQLException ex) {
Log.e(Constants.TAG, "couldn't create table in downloads database");
throw ex;
}
}
private void createHeadersTable(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + Downloads.Impl.RequestHeaders.HEADERS_DB_TABLE);
db.execSQL("CREATE TABLE " + Downloads.Impl.RequestHeaders.HEADERS_DB_TABLE + "(" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
Downloads.Impl.RequestHeaders.COLUMN_DOWNLOAD_ID + " INTEGER NOT NULL," +
Downloads.Impl.RequestHeaders.COLUMN_HEADER + " TEXT NOT NULL," +
Downloads.Impl.RequestHeaders.COLUMN_VALUE + " TEXT NOT NULL" +
");");
}
}
/**
* Initializes the content provider when it is created.
*/
@Override
public boolean onCreate() {
if (mSystemFacade == null) {
mSystemFacade = new RealSystemFacade(getContext());
}
mOpenHelper = new DatabaseHelper(getContext());
// Initialize the system uid
mSystemUid = Process.SYSTEM_UID;
// Initialize the default container uid. Package name hardcoded
// for now.
ApplicationInfo appInfo = null;
try {
appInfo = getContext().getPackageManager().
getApplicationInfo("com.android.defcontainer", 0);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (appInfo != null) {
mDefContainerUid = appInfo.uid;
}
return true;
}
/**
* Returns the content-provider-style MIME types of the various
* types accessible through this content provider.
*/
@Override
public String getType(final Uri uri) {
int match = sURIMatcher.match(uri);
switch (match) {
case DOWNLOADS: {
return DOWNLOAD_LIST_TYPE;
}
case DOWNLOADS_ID: {
return DOWNLOAD_TYPE;
}
default: {
if (Constants.LOGV) {
Log.v(Constants.TAG, "calling getType on an unknown URI: " + uri);
}
throw new IllegalArgumentException("Unknown URI: " + uri);
}
}
}
/**
* Inserts a row in the database
*/
@Override
public Uri insert(final Uri uri, final ContentValues values) {
checkInsertPermissions(values);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
if (sURIMatcher.match(uri) != DOWNLOADS) {
if (Config.LOGD) {
Log.d(Constants.TAG, "calling insert on an unknown/invalid URI: " + uri);
}
throw new IllegalArgumentException("Unknown/Invalid URI " + uri);
}
ContentValues filteredValues = new ContentValues();
copyString(Downloads.Impl.COLUMN_URI, values, filteredValues);
copyString(Downloads.Impl.COLUMN_APP_DATA, values, filteredValues);
copyBoolean(Downloads.Impl.COLUMN_NO_INTEGRITY, values, filteredValues);
copyString(Downloads.Impl.COLUMN_FILE_NAME_HINT, values, filteredValues);
copyString(Downloads.Impl.COLUMN_MIME_TYPE, values, filteredValues);
copyBoolean(Downloads.Impl.COLUMN_IS_PUBLIC_API, values, filteredValues);
boolean isPublicApi =
values.getAsBoolean(Downloads.Impl.COLUMN_IS_PUBLIC_API) == Boolean.TRUE;
Integer dest = values.getAsInteger(Downloads.Impl.COLUMN_DESTINATION);
if (dest != null) {
if (getContext().checkCallingPermission(Downloads.Impl.PERMISSION_ACCESS_ADVANCED)
!= PackageManager.PERMISSION_GRANTED
&& dest != Downloads.Impl.DESTINATION_EXTERNAL
&& dest != Downloads.Impl.DESTINATION_CACHE_PARTITION_PURGEABLE
&& dest != Downloads.Impl.DESTINATION_FILE_URI) {
throw new SecurityException("unauthorized destination code");
}
// for public API behavior, if an app has CACHE_NON_PURGEABLE permission, automatically
// switch to non-purgeable download
boolean hasNonPurgeablePermission =
getContext().checkCallingPermission(
Downloads.Impl.PERMISSION_CACHE_NON_PURGEABLE)
== PackageManager.PERMISSION_GRANTED;
if (isPublicApi && dest == Downloads.Impl.DESTINATION_CACHE_PARTITION_PURGEABLE
&& hasNonPurgeablePermission) {
dest = Downloads.Impl.DESTINATION_CACHE_PARTITION;
}
if (dest == Downloads.Impl.DESTINATION_FILE_URI) {
getContext().enforcePermission(
android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
Binder.getCallingPid(), Binder.getCallingUid(),
"need WRITE_EXTERNAL_STORAGE permission to use DESTINATION_FILE_URI");
checkFileUriDestination(values);
}
filteredValues.put(Downloads.Impl.COLUMN_DESTINATION, dest);
}
Integer vis = values.getAsInteger(Downloads.Impl.COLUMN_VISIBILITY);
if (vis == null) {
if (dest == Downloads.Impl.DESTINATION_EXTERNAL) {
filteredValues.put(Downloads.Impl.COLUMN_VISIBILITY,
Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
} else {
filteredValues.put(Downloads.Impl.COLUMN_VISIBILITY,
Downloads.Impl.VISIBILITY_HIDDEN);
}
} else {
filteredValues.put(Downloads.Impl.COLUMN_VISIBILITY, vis);
}
copyInteger(Downloads.Impl.COLUMN_CONTROL, values, filteredValues);
filteredValues.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_PENDING);
filteredValues.put(Downloads.Impl.COLUMN_LAST_MODIFICATION,
mSystemFacade.currentTimeMillis());
String pckg = values.getAsString(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE);
String clazz = values.getAsString(Downloads.Impl.COLUMN_NOTIFICATION_CLASS);
if (pckg != null && (clazz != null || isPublicApi)) {
int uid = Binder.getCallingUid();
try {
if (uid == 0 || mSystemFacade.userOwnsPackage(uid, pckg)) {
filteredValues.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE, pckg);
if (clazz != null) {
filteredValues.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS, clazz);
}
}
} catch (PackageManager.NameNotFoundException ex) {
/* ignored for now */
}
}
copyString(Downloads.Impl.COLUMN_NOTIFICATION_EXTRAS, values, filteredValues);
copyString(Downloads.Impl.COLUMN_COOKIE_DATA, values, filteredValues);
copyString(Downloads.Impl.COLUMN_USER_AGENT, values, filteredValues);
copyString(Downloads.Impl.COLUMN_REFERER, values, filteredValues);
if (getContext().checkCallingPermission(Downloads.Impl.PERMISSION_ACCESS_ADVANCED)
== PackageManager.PERMISSION_GRANTED) {
copyInteger(Downloads.Impl.COLUMN_OTHER_UID, values, filteredValues);
}
filteredValues.put(Constants.UID, Binder.getCallingUid());
if (Binder.getCallingUid() == 0) {
copyInteger(Constants.UID, values, filteredValues);
}
copyString(Downloads.Impl.COLUMN_TITLE, values, filteredValues);
copyString(Downloads.Impl.COLUMN_DESCRIPTION, values, filteredValues);
filteredValues.put(Downloads.Impl.COLUMN_TOTAL_BYTES, -1);
if (isPublicApi) {
copyInteger(Downloads.Impl.COLUMN_ALLOWED_NETWORK_TYPES, values, filteredValues);
copyBoolean(Downloads.Impl.COLUMN_ALLOW_ROAMING, values, filteredValues);
}
if (Constants.LOGVV) {
Log.v(Constants.TAG, "initiating download with UID "
+ filteredValues.getAsInteger(Constants.UID));
if (filteredValues.containsKey(Downloads.Impl.COLUMN_OTHER_UID)) {
Log.v(Constants.TAG, "other UID " +
filteredValues.getAsInteger(Downloads.Impl.COLUMN_OTHER_UID));
}
}
Context context = getContext();
context.startService(new Intent(context, DownloadService.class));
long rowID = db.insert(DB_TABLE, null, filteredValues);
insertRequestHeaders(db, rowID, values);
Uri ret = null;
if (rowID != -1) {
context.startService(new Intent(context, DownloadService.class));
ret = Uri.parse(Downloads.Impl.CONTENT_URI + "/" + rowID);
context.getContentResolver().notifyChange(uri, null);
} else {
if (Config.LOGD) {
Log.d(Constants.TAG, "couldn't insert into downloads database");
}
}
return ret;
}
/**
* Check that the file URI provided for DESTINATION_FILE_URI is valid.
*/
private void checkFileUriDestination(ContentValues values) {
String fileUri = values.getAsString(Downloads.Impl.COLUMN_FILE_NAME_HINT);
if (fileUri == null) {
throw new IllegalArgumentException(
"DESTINATION_FILE_URI must include a file URI under COLUMN_FILE_NAME_HINT");
}
Uri uri = Uri.parse(fileUri);
if (!uri.getScheme().equals("file")) {
throw new IllegalArgumentException("Not a file URI: " + uri);
}
File path = new File(uri.getSchemeSpecificPart());
String externalPath = Environment.getExternalStorageDirectory().getAbsolutePath();
if (!path.getPath().startsWith(externalPath)) {
throw new SecurityException("Destination must be on external storage: " + uri);
}
}
/**
* Apps with the ACCESS_DOWNLOAD_MANAGER permission can access this provider freely, subject to
* constraints in the rest of the code. Apps without that may still access this provider through
* the public API, but additional restrictions are imposed. We check those restrictions here.
*
* @param values ContentValues provided to insert()
* @throws SecurityException if the caller has insufficient permissions
*/
private void checkInsertPermissions(ContentValues values) {
if (getContext().checkCallingOrSelfPermission(Downloads.Impl.PERMISSION_ACCESS)
== PackageManager.PERMISSION_GRANTED) {
return;
}
getContext().enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET,
"INTERNET permission is required to use the download manager");
// ensure the request fits within the bounds of a public API request
// first copy so we can remove values
values = new ContentValues(values);
// check columns whose values are restricted
enforceAllowedValues(values, Downloads.Impl.COLUMN_IS_PUBLIC_API, Boolean.TRUE);
enforceAllowedValues(values, Downloads.Impl.COLUMN_DESTINATION,
Downloads.Impl.DESTINATION_CACHE_PARTITION_PURGEABLE,
Downloads.Impl.DESTINATION_FILE_URI);
if (getContext().checkCallingOrSelfPermission(Downloads.Impl.PERMISSION_NO_NOTIFICATION)
== PackageManager.PERMISSION_GRANTED) {
enforceAllowedValues(values, Downloads.Impl.COLUMN_VISIBILITY,
Downloads.Impl.VISIBILITY_HIDDEN, Downloads.Impl.VISIBILITY_VISIBLE);
} else {
enforceAllowedValues(values, Downloads.Impl.COLUMN_VISIBILITY,
Downloads.Impl.VISIBILITY_VISIBLE);
}
// remove the rest of the columns that are allowed (with any value)
values.remove(Downloads.Impl.COLUMN_URI);
values.remove(Downloads.Impl.COLUMN_TITLE);
values.remove(Downloads.Impl.COLUMN_DESCRIPTION);
values.remove(Downloads.Impl.COLUMN_MIME_TYPE);
values.remove(Downloads.Impl.COLUMN_FILE_NAME_HINT); // checked later in insert()
values.remove(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE); // checked later in insert()
values.remove(Downloads.Impl.COLUMN_ALLOWED_NETWORK_TYPES);
values.remove(Downloads.Impl.COLUMN_ALLOW_ROAMING);
Iterator<Map.Entry<String, Object>> iterator = values.valueSet().iterator();
while (iterator.hasNext()) {
String key = iterator.next().getKey();
if (key.startsWith(Downloads.Impl.RequestHeaders.INSERT_KEY_PREFIX)) {
iterator.remove();
}
}
// any extra columns are extraneous and disallowed
if (values.size() > 0) {
StringBuilder error = new StringBuilder("Invalid columns in request: ");
boolean first = true;
for (Map.Entry<String, Object> entry : values.valueSet()) {
if (!first) {
error.append(", ");
}
error.append(entry.getKey());
}
throw new SecurityException(error.toString());
}
}
/**
* Remove column from values, and throw a SecurityException if the value isn't within the
* specified allowedValues.
*/
private void enforceAllowedValues(ContentValues values, String column,
Object... allowedValues) {
Object value = values.get(column);
values.remove(column);
for (Object allowedValue : allowedValues) {
if (value == null && allowedValue == null) {
return;
}
if (value != null && value.equals(allowedValue)) {
return;
}
}
throw new SecurityException("Invalid value for " + column + ": " + value);
}
/**
* Starts a database query
*/
@Override
public Cursor query(final Uri uri, String[] projection,
final String selection, final String[] selectionArgs,
final String sort) {
Helpers.validateSelection(selection, sAppReadableColumnsSet);
SQLiteDatabase db = mOpenHelper.getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
int match = sURIMatcher.match(uri);
boolean emptyWhere = true;
switch (match) {
case DOWNLOADS: {
qb.setTables(DB_TABLE);
break;
}
case DOWNLOADS_ID: {
qb.setTables(DB_TABLE);
qb.appendWhere(Downloads.Impl._ID + "=");
qb.appendWhere(getDownloadIdFromUri(uri));
emptyWhere = false;
break;
}
case REQUEST_HEADERS_URI:
if (projection != null || selection != null || sort != null) {
throw new UnsupportedOperationException("Request header queries do not support "
+ "projections, selections or sorting");
}
return queryRequestHeaders(db, uri);
default: {
if (Constants.LOGV) {
Log.v(Constants.TAG, "querying unknown URI: " + uri);
}
throw new IllegalArgumentException("Unknown URI: " + uri);
}
}
if (shouldRestrictVisibility()) {
if (projection == null) {
projection = sAppReadableColumnsArray;
} else {
for (int i = 0; i < projection.length; ++i) {
if (!sAppReadableColumnsSet.contains(projection[i])) {
throw new IllegalArgumentException(
"column " + projection[i] + " is not allowed in queries");
}
}
}
if (!emptyWhere) {
qb.appendWhere(" AND ");
emptyWhere = false;
}
qb.appendWhere(getRestrictedUidClause());
}
if (Constants.LOGVV) {
java.lang.StringBuilder sb = new java.lang.StringBuilder();
sb.append("starting query, database is ");
if (db != null) {
sb.append("not ");
}
sb.append("null; ");
if (projection == null) {
sb.append("projection is null; ");
} else if (projection.length == 0) {
sb.append("projection is empty; ");
} else {
for (int i = 0; i < projection.length; ++i) {
sb.append("projection[");
sb.append(i);
sb.append("] is ");
sb.append(projection[i]);
sb.append("; ");
}
}
sb.append("selection is ");
sb.append(selection);
sb.append("; ");
if (selectionArgs == null) {
sb.append("selectionArgs is null; ");
} else if (selectionArgs.length == 0) {
sb.append("selectionArgs is empty; ");
} else {
for (int i = 0; i < selectionArgs.length; ++i) {
sb.append("selectionArgs[");
sb.append(i);
sb.append("] is ");
sb.append(selectionArgs[i]);
sb.append("; ");
}
}
sb.append("sort is ");
sb.append(sort);
sb.append(".");
Log.v(Constants.TAG, sb.toString());
}
Cursor ret = qb.query(db, projection, selection, selectionArgs,
null, null, sort);
if (ret != null) {
ret = new ReadOnlyCursorWrapper(ret);
}
if (ret != null) {
ret.setNotificationUri(getContext().getContentResolver(), uri);
if (Constants.LOGVV) {
Log.v(Constants.TAG,
"created cursor " + ret + " on behalf of " + Binder.getCallingPid());
}
} else {
if (Constants.LOGV) {
Log.v(Constants.TAG, "query failed in downloads database");
}
}
return ret;
}
private String getDownloadIdFromUri(final Uri uri) {
return uri.getPathSegments().get(1);
}
/**
* Insert request headers for a download into the DB.
*/
private void insertRequestHeaders(SQLiteDatabase db, long downloadId, ContentValues values) {
ContentValues rowValues = new ContentValues();
rowValues.put(Downloads.Impl.RequestHeaders.COLUMN_DOWNLOAD_ID, downloadId);
for (Map.Entry<String, Object> entry : values.valueSet()) {
String key = entry.getKey();
if (key.startsWith(Downloads.Impl.RequestHeaders.INSERT_KEY_PREFIX)) {
String headerLine = entry.getValue().toString();
if (!headerLine.contains(":")) {
throw new IllegalArgumentException("Invalid HTTP header line: " + headerLine);
}
String[] parts = headerLine.split(":", 2);
rowValues.put(Downloads.Impl.RequestHeaders.COLUMN_HEADER, parts[0].trim());
rowValues.put(Downloads.Impl.RequestHeaders.COLUMN_VALUE, parts[1].trim());
db.insert(Downloads.Impl.RequestHeaders.HEADERS_DB_TABLE, null, rowValues);
}
}
}
/**
* Handle a query for the custom request headers registered for a download.
*/
private Cursor queryRequestHeaders(SQLiteDatabase db, Uri uri) {
String where = Downloads.Impl.RequestHeaders.COLUMN_DOWNLOAD_ID + "="
+ getDownloadIdFromUri(uri);
String[] projection = new String[] {Downloads.Impl.RequestHeaders.COLUMN_HEADER,
Downloads.Impl.RequestHeaders.COLUMN_VALUE};
Cursor cursor = db.query(Downloads.Impl.RequestHeaders.HEADERS_DB_TABLE, projection, where,
null, null, null, null);
return new ReadOnlyCursorWrapper(cursor);
}
/**
* Delete request headers for downloads matching the given query.
*/
private void deleteRequestHeaders(SQLiteDatabase db, String where, String[] whereArgs) {
String[] projection = new String[] {Downloads.Impl._ID};
Cursor cursor = db.query(DB_TABLE, projection, where, whereArgs, null, null, null, null);
try {
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
long id = cursor.getLong(0);
String idWhere = Downloads.Impl.RequestHeaders.COLUMN_DOWNLOAD_ID + "=" + id;
db.delete(Downloads.Impl.RequestHeaders.HEADERS_DB_TABLE, idWhere, null);
}
} finally {
cursor.close();
}
}
/**
* @return true if we should restrict this caller to viewing only its own downloads
*/
private boolean shouldRestrictVisibility() {
int callingUid = Binder.getCallingUid();
return Binder.getCallingPid() != Process.myPid() &&
callingUid != mSystemUid &&
callingUid != mDefContainerUid &&
Process.supportsProcesses();
}
/**
* @return a SQL WHERE clause to restrict the query to downloads accessible to the caller's UID
*/
private String getRestrictedUidClause() {
return "( " + Constants.UID + "=" + Binder.getCallingUid() + " OR "
+ Downloads.Impl.COLUMN_OTHER_UID + "=" + Binder.getCallingUid() + " )";
}
/**
* Updates a row in the database
*/
@Override
public int update(final Uri uri, final ContentValues values,
final String where, final String[] whereArgs) {
Helpers.validateSelection(where, sAppReadableColumnsSet);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int count;
long rowId = 0;
boolean startService = false;
ContentValues filteredValues;
if (Binder.getCallingPid() != Process.myPid()) {
filteredValues = new ContentValues();
copyString(Downloads.Impl.COLUMN_APP_DATA, values, filteredValues);
copyInteger(Downloads.Impl.COLUMN_VISIBILITY, values, filteredValues);
Integer i = values.getAsInteger(Downloads.Impl.COLUMN_CONTROL);
if (i != null) {
filteredValues.put(Downloads.Impl.COLUMN_CONTROL, i);
startService = true;
}
copyInteger(Downloads.Impl.COLUMN_CONTROL, values, filteredValues);
copyString(Downloads.Impl.COLUMN_TITLE, values, filteredValues);
copyString(Downloads.Impl.COLUMN_DESCRIPTION, values, filteredValues);
} else {
filteredValues = values;
String filename = values.getAsString(Downloads.Impl._DATA);
if (filename != null) {
Cursor c = query(uri, new String[]
{ Downloads.Impl.COLUMN_TITLE }, null, null, null);
if (!c.moveToFirst() || c.getString(0) == null) {
values.put(Downloads.Impl.COLUMN_TITLE,
new File(filename).getName());
}
c.close();
}
}
int match = sURIMatcher.match(uri);
switch (match) {
case DOWNLOADS:
case DOWNLOADS_ID: {
String fullWhere = getWhereClause(uri, where);
if (filteredValues.size() > 0) {
count = db.update(DB_TABLE, filteredValues, fullWhere, whereArgs);
} else {
count = 0;
}
break;
}
default: {
if (Config.LOGD) {
Log.d(Constants.TAG, "updating unknown/invalid URI: " + uri);
}
throw new UnsupportedOperationException("Cannot update URI: " + uri);
}
}
getContext().getContentResolver().notifyChange(uri, null);
if (startService) {
Context context = getContext();
context.startService(new Intent(context, DownloadService.class));
}
return count;
}
private String getWhereClause(final Uri uri, final String where) {
StringBuilder myWhere = new StringBuilder();
if (where != null) {
myWhere.append("( " + where + " )");
}
if (sURIMatcher.match(uri) == DOWNLOADS_ID) {
String segment = getDownloadIdFromUri(uri);
long rowId = Long.parseLong(segment);
appendClause(myWhere, " ( " + Downloads.Impl._ID + " = " + rowId + " ) ");
}
if (shouldRestrictVisibility()) {
appendClause(myWhere, getRestrictedUidClause());
}
return myWhere.toString();
}
/**
* Deletes a row in the database
*/
@Override
public int delete(final Uri uri, final String where,
final String[] whereArgs) {
Helpers.validateSelection(where, sAppReadableColumnsSet);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int count;
int match = sURIMatcher.match(uri);
switch (match) {
case DOWNLOADS:
case DOWNLOADS_ID: {
String fullWhere = getWhereClause(uri, where);
deleteRequestHeaders(db, fullWhere, whereArgs);
count = db.delete(DB_TABLE, fullWhere, whereArgs);
break;
}
default: {
if (Config.LOGD) {
Log.d(Constants.TAG, "deleting unknown/invalid URI: " + uri);
}
throw new UnsupportedOperationException("Cannot delete URI: " + uri);
}
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
private void appendClause(StringBuilder whereClause, String newClause) {
if (whereClause.length() != 0) {
whereClause.append(" AND ");
}
whereClause.append(newClause);
}
/**
* Remotely opens a file
*/
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode)
throws FileNotFoundException {
if (Constants.LOGVV) {
Log.v(Constants.TAG, "openFile uri: " + uri + ", mode: " + mode
+ ", uid: " + Binder.getCallingUid());
Cursor cursor = query(Downloads.Impl.CONTENT_URI,
new String[] { "_id" }, null, null, "_id");
if (cursor == null) {
Log.v(Constants.TAG, "null cursor in openFile");
} else {
if (!cursor.moveToFirst()) {
Log.v(Constants.TAG, "empty cursor in openFile");
} else {
do {
Log.v(Constants.TAG, "row " + cursor.getInt(0) + " available");
} while(cursor.moveToNext());
}
cursor.close();
}
cursor = query(uri, new String[] { "_data" }, null, null, null);
if (cursor == null) {
Log.v(Constants.TAG, "null cursor in openFile");
} else {
if (!cursor.moveToFirst()) {
Log.v(Constants.TAG, "empty cursor in openFile");
} else {
String filename = cursor.getString(0);
Log.v(Constants.TAG, "filename in openFile: " + filename);
if (new java.io.File(filename).isFile()) {
Log.v(Constants.TAG, "file exists in openFile");
}
}
cursor.close();
}
}
// This logic is mostly copied form openFileHelper. If openFileHelper eventually
// gets split into small bits (to extract the filename and the modebits),
// this code could use the separate bits and be deeply simplified.
Cursor c = query(uri, new String[]{"_data"}, null, null, null);
int count = (c != null) ? c.getCount() : 0;
if (count != 1) {
// If there is not exactly one result, throw an appropriate exception.
if (c != null) {
c.close();
}
if (count == 0) {
throw new FileNotFoundException("No entry for " + uri);
}
throw new FileNotFoundException("Multiple items at " + uri);
}
c.moveToFirst();
String path = c.getString(0);
c.close();
if (path == null) {
throw new FileNotFoundException("No filename found.");
}
if (!Helpers.isFilenameValid(path)) {
throw new FileNotFoundException("Invalid filename.");
}
if (!"r".equals(mode)) {
throw new FileNotFoundException("Bad mode for " + uri + ": " + mode);
}
ParcelFileDescriptor ret = ParcelFileDescriptor.open(new File(path),
ParcelFileDescriptor.MODE_READ_ONLY);
if (ret == null) {
if (Constants.LOGV) {
Log.v(Constants.TAG, "couldn't open file");
}
throw new FileNotFoundException("couldn't open file");
} else {
ContentValues values = new ContentValues();
values.put(Downloads.Impl.COLUMN_LAST_MODIFICATION, mSystemFacade.currentTimeMillis());
update(uri, values, null, null);
}
return ret;
}
private static final void copyInteger(String key, ContentValues from, ContentValues to) {
Integer i = from.getAsInteger(key);
if (i != null) {
to.put(key, i);
}
}
private static final void copyBoolean(String key, ContentValues from, ContentValues to) {
Boolean b = from.getAsBoolean(key);
if (b != null) {
to.put(key, b);
}
}
private static final void copyString(String key, ContentValues from, ContentValues to) {
String s = from.getAsString(key);
if (s != null) {
to.put(key, s);
}
}
private class ReadOnlyCursorWrapper extends CursorWrapper implements CrossProcessCursor {
public ReadOnlyCursorWrapper(Cursor cursor) {
super(cursor);
mCursor = (CrossProcessCursor) cursor;
}
public boolean deleteRow() {
throw new SecurityException("Download manager cursors are read-only");
}
public boolean commitUpdates() {
throw new SecurityException("Download manager cursors are read-only");
}
public void fillWindow(int pos, CursorWindow window) {
mCursor.fillWindow(pos, window);
}
public CursorWindow getWindow() {
return mCursor.getWindow();
}
public boolean onMove(int oldPosition, int newPosition) {
return mCursor.onMove(oldPosition, newPosition);
}
private CrossProcessCursor mCursor;
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
d48963e19ea1bf374c538c835b1db0314ef1a0c1 | 74f04a9b6fb68ae9b85a2865a8a42c5d68d62997 | /app/src/test/java/tw/adouble/app/helloworld/myonbootservice170819002/ExampleUnitTest.java | 5edaaf8e6e858dc935e43779d597e4b9dc3d5e32 | [] | no_license | DoubleJen/MyOnBootService170819002 | 4674214d7ffabe2b6c35a6c4269e143e7848705b | 6a103e21f8ee3b5f229524088974443dda45d506 | refs/heads/master | 2021-01-19T12:21:49.900120 | 2017-08-20T08:41:55 | 2017-08-20T08:41:55 | 100,779,709 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 428 | java | package tw.adouble.app.helloworld.myonbootservice170819002;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"qoo2003654@gmail.com"
] | qoo2003654@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.