text
stringlengths 10
2.72M
|
|---|
public class linearsearch {
public int Search(int arr[],int data)
{
int length=arr.length;
if(arr.length!=0){
for(int i=0;i<length;i++){
if(arr[i]==data){
return i;
}
}
}
return -1;
}
public static void main(String[] args) {
int arr[]={1,2,3,5,6};
int data=5;
linearsearch ln=new linearsearch();
System.out.println(data+" founded at :"+ ln.Search(arr, data)+" index no");
}
}
|
/**
* encapTest1
*/
public class encapTest1 {
public static void main(String[] args) {
encapDemo1 encap = new encapDemo1();
encap.setName("Dobleh");
encap.setAge(19);
System.out.println("Name : "+encap.getName());
System.out.println("Age : "+encap.getAge());
}
}
|
package designer.ui.properties.renderer;
import specification.Properties;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
/**
* Created by Tomas Hanus on 4/15/2015.
*/
public class PropertiesCellRenderer extends DefaultTableCellRenderer {
public PropertiesCellRenderer() {
super();
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component comp = super.getTableCellRendererComponent(table, value, isSelected,
hasFocus, row, column);
((JLabel) comp).setOpaque(true);
if (value instanceof Properties) {
String textToDisplay = "No properties set";
Properties properties = (Properties) table.getModel().getValueAt(row, column);
if ((properties != null) && (properties.getProperties() != null)) {
if (properties.getProperties().size() == 1) {
textToDisplay = "1 property set";
} else {
textToDisplay = Integer.toString(properties.getProperties().size()) + " properties set";
}
}
((JLabel) comp).setText(textToDisplay);
}
return comp;
}
}
|
package chc;
import shared.GetEnv;
import shared.Inducer;
import java.util.StringTokenizer;
public class Population {
private static Inducer inducer;
private static FitnessMachine machine;
private Hypothesis[] population = new Hypothesis[0];
private Hypothesis[] parents = new Hypothesis[0];
private Hypothesis[] children = new Hypothesis[0];
private int popmarker=0;
private int parentpopmarker=0;
private int childpopmarker=0;
private MatingPair[] pairs;
private int pairmarker;
private int generationnumber;
private int currentthreshhold;
//statistic storage to be printed
private double[] averagegenerationfitness;
private Hypothesis[] bestspawnedofgeneration;
private Options options;
public Population(Inducer ind, Options options) {
this.options = options;
GetEnv getenv = new GetEnv();
String temp = getenv.get_option_string("FitnessDistribution");
StringTokenizer token = new StringTokenizer(temp, ",");
double[] fdist = new double[3];
for (int i = 0; i < fdist.length; i++) {
fdist[i] = Double.valueOf(token.nextToken()).doubleValue();
}
Hypothesis.setFDist(fdist);
inducer = ind;
machine = new FitnessMachine(ind, options.getDist());
generationnumber = 0;
currentthreshhold = 1 + options.getDist().getattrselectionsize()/4;
averagegenerationfitness = new double[0];
//Precalculate the size of the arrays
population = new Hypothesis[options.getPopArraySize()];
parents = new Hypothesis[options.populationsize];
children = new Hypothesis[options.populationsize];
}
/** nextGeneration sequentially goes through the steps necessary to complete
* one generation. It takes no arguments and returns nothing.
*/
public void nextGeneration() {
options.LOG(1, "Generation " + generationnumber + CHC.ENDL);
children=new Hypothesis[options.populationsize];
breed();
calculateFitness();
parents = CHC.sortDescendingFitness(parents);
children = CHC.sortDescendingFitness(children);
bestspawnedofgeneration = CHC.addHypo(bestspawnedofgeneration,
children[0], 1);
displayPopulation(CHC.GENERATIONPRINTING);
parents = getFit();
for (int i=0; i<parents.length;i++) {
parents[i].nextGeneration();
}
pairs = null;
generationnumber++;
}
/** getFit() returns an array with the most fit hypothesis from the
* parent and child population.
*/
public Hypothesis[] getFit() {
Hypothesis[] fithypo = new Hypothesis[parents.length+children.length];
int tempmarker=0;
int tempparentmarker = 0; //parents.length-1;
int tempchildmarker = 0; //children.length-1;
for (int i=0; i<parents.length;i++) {
fithypo[tempmarker++]=parents[i];
}
for (int i=0; i<children.length;i++) {
fithypo[tempmarker++]=children[i];
}
fithypo=CHC.sortDescendingFitness(fithypo);
double holdfitness = fithypo[options.populationsize-1].getFitness();
int holdindex=options.populationsize;
for (int i=options.populationsize;i<fithypo.length; i++) {
if (holdindex==options.populationsize && holdfitness < fithypo[i].getFitness()) {
holdindex = i;
}
}
Hypothesis[] temphypo = new Hypothesis[holdindex];
for (int i=0; i<holdindex;i++) {
temphypo[i] = fithypo[i];
}
return temphypo;
}
public Hypothesis[] sortDescendingHypothesis(Hypothesis[] hypo) {
return hypo;
}
public void calculateFitness() {
options.LOG(3, "Calculate Fitness Called"+CHC.ENDL);
machine.add(children);
machine.run();
// options.LOG(3, " Done" + CHC.ENDL);
}
public void breed() {
options.LOG(3, "Breeding "+CHC.ENDL);
Breeder b = new Breeder(parents);
children = b.breed(options.populationsize, currentthreshhold);
if (options.getMask("print_all_hypothesis")) {
population = CHC.addHypo(population, children, options.populationsize*10);
}
// Check to see if we need Cataclysmic Mutation
if (children.length < options.populationsize) {
options.LOG(3, "Using Cataclysimic Mutation to produce "+(options.populationsize-children.length)+" hypotheses"+CHC.ENDL);
Hypothesis[] hypo = Mutator.cataclysmicMutation(parents[0],options.populationsize-children.length);
for (int i=0;i<hypo.length;i++) {
addChild(hypo[i]);
}
}
}
private void addParent(Hypothesis[] hypo) {
for (int i = 0; i < hypo.length; i++) {
addParent(hypo[i]);
}
}
private void addParent(Hypothesis hypo) {
parents = CHC.addHypo(parents, hypo, 1);
if (options.getMask("print_all_hypothesis")) {
population = CHC.addHypo(population, hypo, options.populationsize*10);
}
}
private void addChild(Hypothesis hypo) {
children = CHC.addHypo(children, hypo, 1);
if (options.getMask("print_all_hypothesis")) {
population = CHC.addHypo(population, hypo, options.populationsize*10);
}
}
private void addMatingPair(MatingPair mp) {
if (pairmarker == pairs.length) {
MatingPair[] newpairs = new MatingPair[pairmarker + 1];
for (int i = 0; i < pairmarker; i++) {
newpairs[i] = pairs[i];
}
pairs = newpairs;
}
pairs[pairmarker++] = mp;
}
public void spawnPopulation() {
Spawner spawner = new Spawner(options.getDist().getattrselectionsize());
addParent(spawner.spawnPopulation(options.populationsize, generationnumber));
machine.add(parents);
machine.run();
}
public void displayPopulation(String depth) {
if (depth.equals(CHC.GENERATIONPRINTING)) {
options.LOG(4, "Generation "+generationnumber+".\nParents."+CHC.ENDL);
options.LOG(4, getHypothesisString(parents, 0));
options.LOG(4, "Children."+CHC.ENDL);
options.LOG(4, getHypothesisString(children, 0));
}
else if (depth.equals(CHC.TOTALPRINTING)) {
population = CHC.cleanHypo(population);
printHypothesis(population, popmarker-1);
}
options.LOG(4, CHC.ENDL);
}
private void printHypothesis(Hypothesis[] hypo, int maxprint) {
if (hypo == null) {
}
else {
for (int i = 0; i<((maxprint<=0)||(hypo.length<maxprint)?hypo.length:maxprint); i++) {
if (hypo[i] == null) {
}
else {
hypo[i].displayHypothesis();
}
}
}
}
public static String getHypothesisString(Hypothesis[] hypo, int maxprint) {
String result = "";
if (hypo == null) {
}
else {
for (int i = 0; i<((maxprint<=0)||(hypo.length<maxprint)?hypo.length:maxprint); i++) {
if (hypo[i] == null) {
}
else {
result += hypo[i].getHypothesisString();
}
}
}
return result;
}
public int getGenerationNumber() { return generationnumber; }
/* public void setmaxpopulation(int value) {
if (value > 1) {
int temp = value/2;
maxpopulation = temp*2;
}
}
*/
public void displayFinalHypothesisFitness(boolean bool) {
if (bool) {
Hypothesis[] newpopulation = CHC.cleanHypo(parents);
newpopulation = CHC.sortDescendingFitness(newpopulation);
int number = 0;
options.LOG(7, "newpopulation.length = " + newpopulation.length+CHC.ENDL);
if (newpopulation.length >= 10) {
number = 10;
}
else {
number = newpopulation.length;
}
for (int i = 0; i < number; i++ ) {
options.LOG(7, "newpop: i = "+ i+CHC.ENDL);
if (newpopulation[i] == null) {
}
else {
machine.add(newpopulation[i]);
}
}
machine.run();
options.LOG(0, "\n|||||||||||||||||Final Hypothesis Fitness||||||||||||||||||||||||||||||"+CHC.ENDL);
for (int i = 0; i < number; i++) {
if (newpopulation[i] == null) {
}
else {
options.LOG(0, newpopulation[i].getHypothesisString("|| ", " ||"+CHC.ENDL));
}
}
options.LOG(0, "|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||"+CHC.ENDL);
}
}
public void displayAverageFitnessPerGeneration(boolean bool) {
if (bool) {
options.LOG(0, "\nAverage Fitness by Generation"+CHC.ENDL);
for (int i = 0; i < averagegenerationfitness.length; i++) {
options.LOG(0, " " + i + ") " + averagegenerationfitness[i]
+CHC.ENDL);
}
options.LOG(0, CHC.ENDL);
}
}
public void set_log_level(int level) {
options.set_log_level(level);
}
public void displayBestSpawnedOfGeneration(boolean bool) {
if (bool) {
bestspawnedofgeneration = CHC.cleanHypo(bestspawnedofgeneration);
machine.add(bestspawnedofgeneration);
machine.run();
System.out.println("Best Spawned Hypothesis of Generation");
for (int i = 0 ; i < bestspawnedofgeneration.length; i++) {
System.out.println(i
+ bestspawnedofgeneration[i].getHypothesisString(" ", ""));
}
}
}
public int get_log_level() {
return options.get_log_level();
}
}
|
package net.unicornbox.fastuniqueinfolders;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
public class PageImageDimension {
private final Map<Integer, Integer> pageImageSize = new ConcurrentHashMap<>();
public PageImageDimension(Map<Integer, AtomicInteger> mimeTypes) {
mimeTypes.forEach((k, v) -> {
this.pageImageSize.put(k, v.intValue());
});
}
public PageImageDimension() {
}
public PageImageDimension addForeign(PageImageDimension other) {
other.pageImageSize.forEach((k, v) -> {
pageImageSize.put(k, pageImageSize.getOrDefault(k, 0) + v);
});
return this;
}
public String toString() {
StringBuilder sb = new StringBuilder();
// map first to a list of segments, 100 per 100
Map<Integer, Integer> steppedMap = new HashMap<>();
// compute total at the same time
AtomicLong total = new AtomicLong();
pageImageSize.forEach((key1, value) -> {
total.addAndGet(value);
final int step = 100;
int index = key1 / step;
int key = index * step;
final Integer steppedMapOrDefault = steppedMap.getOrDefault(key, 0);
steppedMap.put(key, steppedMapOrDefault + value);
});
List<Map.Entry<Integer, Integer>> values =
new LinkedList<>(steppedMap.entrySet());
values.sort(Map.Entry.comparingByValue(Integer::compareTo));
for (Map.Entry<Integer, Integer> entry : values) {
sb.append(entry.getKey()).append("-").append(entry.getKey() + 99).append(":").append(entry.getValue()/(total.floatValue()) * 100).append("%").append("\n");
}
final ArrayList<Integer> sizes = new ArrayList<>(pageImageSize.keySet());
sizes.sort(Integer::compareTo);
sb.append("max value ").append(sizes.get(sizes.size() - 1)).append("\n");
return sb.toString();
}
}
|
package com.tencent.mm.plugin.sns.ui;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.an.c;
import com.tencent.mm.bg.d;
import com.tencent.mm.g.a.gk;
import com.tencent.mm.g.a.js;
import com.tencent.mm.g.a.nk;
import com.tencent.mm.g.a.qu;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.plugin.sns.a.b.j;
import com.tencent.mm.plugin.sns.a.b.j.a;
import com.tencent.mm.plugin.sns.a.b.j.b;
import com.tencent.mm.plugin.sns.data.i;
import com.tencent.mm.plugin.sns.model.ae;
import com.tencent.mm.plugin.sns.model.af;
import com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.e;
import com.tencent.mm.plugin.sns.storage.n;
import com.tencent.mm.plugin.topstory.a.g;
import com.tencent.mm.plugin.websearch.api.p;
import com.tencent.mm.plugin.websearch.api.r;
import com.tencent.mm.protocal.c.ate;
import com.tencent.mm.protocal.c.avq;
import com.tencent.mm.protocal.c.bgx;
import com.tencent.mm.protocal.c.brh;
import com.tencent.mm.protocal.c.bsu;
import com.tencent.mm.protocal.c.cfn;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import java.io.IOException;
import java.util.List;
public final class bg {
Context context;
ae nMm;
public OnClickListener nZN = new OnClickListener() {
public final void onClick(View view) {
long currentTimeMillis = System.currentTimeMillis();
if (currentTimeMillis - bg.this.ohu >= 500) {
bg.this.ohu = currentTimeMillis;
if (view.getTag() instanceof r) {
r rVar = (r) view.getTag();
bsu bsu = rVar.nMH;
n Nl = af.byo().Nl(rVar.bKW);
if (bg.this.nMm != null) {
bg.this.nMm.bxT().v(Nl);
}
Intent intent;
ate ate;
String str;
if (bsu.sqc.ruz == 18) {
Context context = bg.this.context;
bsu bsu2 = rVar.nMH;
j.a(b.njU, a.njM, af.byo().Nl(rVar.bKW));
intent = new Intent();
ate = null;
if (bsu2.sqc.ruA.size() > 0) {
ate = (ate) bsu2.sqc.ruA.get(0);
}
intent.putExtra("IsAd", false);
intent.putExtra("KStremVideoUrl", bsu2.sqc.jPK);
intent.putExtra("KSta_SourceType", 2);
intent.putExtra("KSta_Scene", b.njU.value);
intent.putExtra("KSta_FromUserName", bsu2.hbL);
intent.putExtra("KSta_SnSId", bsu2.ksA);
if (ate == null) {
intent.putExtra("KMediaId", "fakeid_" + (ate == null ? bsu2.ksA : ate.ksA));
} else {
intent.putExtra("KMediaId", ate.ksA);
}
brh brh = bsu2.sqh;
if (brh != null) {
intent.putExtra("KMediaVideoTime", brh.dyK);
intent.putExtra("StreamWording", brh.dyM);
intent.putExtra("StremWebUrl", brh.dyN);
intent.putExtra("KMediaTitle", brh.dyL);
intent.putExtra("KStremVideoUrl", brh.dyJ);
intent.putExtra("KThumUrl", brh.dyO);
intent.putExtra("KSta_StremVideoAduxInfo", brh.dyP);
intent.putExtra("KSta_StremVideoPublishId", brh.dyQ);
}
intent.putExtra("KSta_SnsStatExtStr", bsu2.nNV);
d.b(context, "sns", ".ui.VideoAdPlayerUI", intent);
} else if (bsu.nsD == null || bi.oW(bsu.nsD.pLr)) {
String str2 = bsu.sqc.jPK;
str = bsu.sqb.ksA;
x.d("MicroMsg.TimeLineClickEvent", "url:" + str2);
String B = com.tencent.mm.plugin.sns.c.a.ezo.B(str2, "timeline");
if (B != null && B.length() != 0) {
Intent intent2 = new Intent();
Bundle bundle = null;
if (bsu != null) {
Bundle bundle2 = new Bundle();
bundle2.putString("KSnsStrId", bsu.ksA);
bundle2.putString("KSnsLocalId", rVar.bKW);
bundle2.putBoolean("KFromTimeline", true);
if (bsu.sqc != null && bsu.sqc.ruA.size() > 0) {
bundle2.putString("K_sns_thumb_url", ((ate) bsu.sqc.ruA.get(0)).rVE);
bundle2.putString("K_sns_raw_url", bsu.sqc.jPK);
x.i("MicroMsg.TimeLineClickEvent", "put the thumb url %s redirectUrl %s", new Object[]{((ate) bsu.sqc.ruA.get(0)).rVE, bsu.sqc.jPK});
}
bundle = bundle2;
}
bundle.putString("key_snsad_statextstr", bsu.nNV);
intent2.putExtra("rawUrl", B);
intent2.putExtra("shortUrl", B);
intent2.putExtra("useJs", true);
intent2.putExtra("type", -255);
if (bsu.sqd != null) {
intent2.putExtra("srcUsername", bsu.sqd);
intent2.putExtra("srcDisplayname", bsu.qIc);
x.i("MicroMsg.TimeLineClickEvent", "urlRedirectListener tlObj.sourceNickName: " + bsu.qIc + " tlObj.publicUserName: " + bsu.sqd);
}
intent2.putExtra("sns_local_id", rVar.bKW);
if (Nl != null) {
intent2.putExtra("KPublisherId", "sns_" + i.eF(Nl.field_snsId));
intent2.putExtra("pre_username", Nl.field_userName);
intent2.putExtra("prePublishId", "sns_" + i.eF(Nl.field_snsId));
intent2.putExtra("preUsername", Nl.field_userName);
intent2.putExtra("share_report_pre_msg_url", B);
intent2.putExtra("share_report_pre_msg_title", bsu.sqc.bHD);
intent2.putExtra("share_report_pre_msg_desc", bsu.sqc.jOS);
if (bsu.sqc.ruA != null && bsu.sqc.ruA.size() > 0) {
intent2.putExtra("share_report_pre_msg_icon_url", ((ate) bsu.sqc.ruA.get(0)).rVE);
}
intent2.putExtra("share_report_pre_msg_appid", "");
intent2.putExtra("share_report_from_scene", 1);
}
if (!(bsu == null || bsu.sqb == null)) {
intent2.putExtra("KAppId", bsu.sqb.ksA);
}
if (Nl != null && Nl.xb(32)) {
com.tencent.mm.plugin.sns.storage.a bAH = Nl.bAH();
if (bAH != null) {
intent2.putExtra("KsnsViewId", bAH.fvT);
}
}
if (!(Nl == null || bsu == null)) {
com.tencent.mm.modelsns.b io;
if (bg.this.scene == 0) {
io = com.tencent.mm.modelsns.b.io(718);
} else {
io = com.tencent.mm.modelsns.b.ip(718);
}
io.nb(i.g(Nl)).ir(Nl.field_type).bP(Nl.xb(32)).nb(Nl.bBo()).nb(bsu.sqd).nb(bsu.sqb == null ? "" : bsu.sqb.ksA).nb(bsu.sqc.jPK);
io.RD();
if (bg.this.scene == 0) {
io = com.tencent.mm.modelsns.b.io(743);
} else {
io = com.tencent.mm.modelsns.b.ip(743);
}
com.tencent.mm.modelsns.b nb = io.nb(i.g(Nl)).ir(Nl.field_type).bP(Nl.xb(32)).nb(Nl.bBo()).nb(bsu.sqd);
if (bsu.sqb == null) {
str = "";
} else {
str = bsu.sqb.ksA;
}
nb.nb(str).nb(bsu.sqc.jPK);
if (bundle != null) {
str = "intent_key_StatisticsOplog";
byte[] Lv = io.Lv();
if (Lv != null) {
bundle.putByteArray(str, Lv);
}
}
}
if (bundle != null) {
intent2.putExtra("jsapiargs", bundle);
}
intent2.putExtra("geta8key_scene", 2);
intent2.putExtra("from_scence", 3);
if (bi.oW(bsu.ogR) || !e.Nf(bsu.ogR)) {
intent2.addFlags(536870912);
com.tencent.mm.plugin.sns.c.a.ezn.j(intent2, bg.this.context);
str = null;
int i = 0;
if (!(bsu == null || bsu.sqb == null)) {
str = bsu.sqb.ksA;
i = bi.getInt(bsu.sqb.hcr, 0);
}
B = com.tencent.mm.plugin.sns.c.a.ezo.s(str, i);
if (!bi.oW(B) && com.tencent.mm.plugin.sns.c.a.ezo.cU(str)) {
String str3 = null;
if (!(bsu == null || bsu.nsB == null || bsu.nsB.raS == null)) {
str3 = bsu.nsB.raS.raM;
}
com.tencent.mm.plugin.sns.c.a.ezo.a(bg.this.context, str, B, bsu == null ? null : bsu.hbL, 5, 4, 1, str3, bsu.ksA);
}
h.mEJ.h(11105, new Object[]{bsu.hbL, bsu.sqc.jPK});
if (Nl != null && Nl.field_type == 4) {
ate = (ate) bsu.sqc.ruA.get(0);
h hVar = h.mEJ;
Object[] objArr = new Object[3];
objArr[0] = Integer.valueOf(1);
objArr[1] = ate == null ? "" : ate.jOS;
objArr[2] = bsu.sqb.ksA;
hVar.h(13043, objArr);
return;
}
return;
}
int[] iArr = new int[2];
if (view != null) {
view.getLocationInWindow(iArr);
}
int width = view.getWidth();
int height = view.getHeight();
intent = new Intent();
intent.putExtra("img_gallery_left", iArr[0]);
intent.putExtra("img_gallery_top", iArr[1]);
intent.putExtra("img_gallery_width", width);
intent.putExtra("img_gallery_height", height);
if (bsu != null) {
List list = bsu.sqc.ruA;
if (list.size() > 0) {
intent.putExtra("sns_landing_pages_share_thumb_url", ((ate) list.get(0)).rVE);
}
}
intent.putExtra("sns_landing_pages_share_sns_id", Nl.bAK());
intent.putExtra("sns_landing_pages_rawSnsId", Nl.bAJ().ksA);
intent.putExtra("sns_landing_pages_aid", Nl.bBj());
intent.putExtra("sns_landing_pages_traceid", Nl.bBk());
intent.putExtra("sns_landing_pages_ux_info", Nl.bBo());
intent.putExtra("sns_landig_pages_from_source", bg.this.scene == 0 ? 3 : 4);
intent.setClass(bg.this.context, SnsAdNativeLandingPagesUI.class);
intent.putExtra("sns_landing_pages_xml", bsu.ogR);
intent.putExtra("sns_landing_pages_rec_src", Nl.bBq());
intent.putExtra("sns_landing_pages_xml_prefix", "adxml");
e.y(intent, bg.this.context);
}
} else {
bg bgVar = bg.this;
cfn cfn = bsu.nsD;
if (cfn != null && !bi.oW(cfn.pLr)) {
Intent intent3 = new Intent();
try {
intent3.putExtra("key_context", g.a(cfn, 31, r.PX("discoverRecommendEntry").optString("wording")).toByteArray());
} catch (IOException e) {
}
p.c(bgVar.context, ".ui.video.TopStoryVideoStreamUI", intent3);
String str4 = bsu.qIb;
str = bsu.ksA;
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("isShareClick=1");
stringBuffer.append("&relevant_vid=");
stringBuffer.append(cfn.pLr);
stringBuffer.append("&relevant_pre_searchid=");
stringBuffer.append(cfn.pLt);
stringBuffer.append("&relevant_shared_openid=");
stringBuffer.append(cfn.pLu);
stringBuffer.append("&rec_category=");
stringBuffer.append(cfn.pLv);
stringBuffer.append("&source=");
stringBuffer.append(cfn.bhd);
stringBuffer.append("&fromUser=");
stringBuffer.append(str4);
stringBuffer.append("&fromScene=");
stringBuffer.append(3);
stringBuffer.append("&targetInfo=");
stringBuffer.append(str);
x.i("MicroMsg.TopStory.TopStoryReportApiLogic", "reportTopStoryClickShareItem 15371 %s", new Object[]{stringBuffer.toString()});
bgx bgx = new bgx();
bgx.shQ = stringBuffer.toString();
com.tencent.mm.kernel.g.DF().a(new com.tencent.mm.plugin.websearch.api.n(bgx), 0);
}
}
}
}
}
};
public OnClickListener ohA = new 13(this);
public OnClickListener ohB = new 14(this);
public OnClickListener ohC = new 15(this);
public OnClickListener ohD = new 2(this);
public OnClickListener ohE = new 3(this);
public OnClickListener ohF = new OnClickListener() {
public final void onClick(View view) {
x.i("MicroMsg.TimeLineClickEvent", "appbrandHomeRedirectListener");
if (view.getTag() instanceof bsu) {
bsu bsu = (bsu) view.getTag();
if (bsu.sqi == null) {
x.e("MicroMsg.TimeLineClickEvent", "appbrandRedirectListener username is null");
return;
}
String str = bsu.sqi.username;
qu quVar = new qu();
x.i("MicroMsg.TimeLineClickEvent", "username: " + str);
quVar.cbq.userName = str;
quVar.cbq.scene = 1009;
quVar.cbq.bGG = bsu.ksA + ":" + bsu.hbL;
com.tencent.mm.sdk.b.a.sFg.m(quVar);
}
}
};
public OnClickListener ohG = new OnClickListener() {
public final void onClick(View view) {
x.i("MicroMsg.TimeLineClickEvent", "hardMallProductRedirectListener");
if (view.getTag() instanceof r) {
r rVar = (r) view.getTag();
bsu bsu = rVar.nMH;
if (bsu.sqc.ruA.size() > 0) {
n Nl = af.byo().Nl(rVar.bKW);
if (bg.this.nMm != null) {
bg.this.nMm.bxT().v(Nl);
}
String str = ((ate) bsu.sqc.ruA.get(0)).nME;
Intent intent = new Intent();
intent.putExtra("key_product_scene", 2);
intent.putExtra("key_product_info", str);
d.b(bg.this.context, "product", ".ui.MallProductUI", intent);
}
}
}
};
public OnClickListener ohH = new OnClickListener() {
public final void onClick(View view) {
x.i("MicroMsg.TimeLineClickEvent", "cardRediretListener");
if (view.getTag() instanceof r) {
r rVar = (r) view.getTag();
bsu bsu = rVar.nMH;
if (bsu.sqc.ruA.size() > 0) {
n Nl = af.byo().Nl(rVar.bKW);
if (bg.this.nMm != null) {
bg.this.nMm.bxT().v(Nl);
}
String str = ((ate) bsu.sqc.ruA.get(0)).nME;
Intent intent = new Intent();
intent.putExtra("key_from_scene", 12);
if (TextUtils.isEmpty(str)) {
x.i("MicroMsg.TimeLineClickEvent", "cardRediretListener userData is empty");
return;
}
String[] split = str.split("#");
if (split.length >= 2) {
x.i("MicroMsg.TimeLineClickEvent", "cardRediretListener userData[0]:" + split[0]);
intent.putExtra("key_card_id", split[0]);
intent.putExtra("key_card_ext", split[1]);
d.b(bg.this.context, "card", ".ui.CardDetailUI", intent);
} else if (split.length == 1) {
x.i("MicroMsg.TimeLineClickEvent", "cardRediretListener userData not include cardExt");
x.i("MicroMsg.TimeLineClickEvent", "cardRediretListener card_id :" + str);
intent.putExtra("key_card_id", split[0]);
intent.putExtra("key_card_ext", "");
d.b(bg.this.context, "card", ".ui.CardDetailUI", intent);
} else {
x.i("MicroMsg.TimeLineClickEvent", "cardRediretListener userData not include card_id and cardExt");
x.i("MicroMsg.TimeLineClickEvent", "cardRediretListener userData :" + str);
}
}
}
}
};
public OnClickListener ohI = new 7(this);
a oht;
long ohu = 0;
public OnClickListener ohv = new OnClickListener() {
public final void onClick(View view) {
boolean z;
String str;
String str2 = null;
bg bgVar = bg.this;
if (view == null || !(view.getTag() instanceof bsu)) {
z = true;
} else {
str = ((bsu) view.getTag()).sqb.ksA;
Intent intent;
if ("wx485a97c844086dc9".equals(str)) {
d.b(view.getContext(), "shake", ".ui.ShakeReportUI", new Intent().putExtra("shake_music", true));
z = true;
} else if ("wx7fa037cc7dfabad5".equals(str)) {
com.tencent.mm.plugin.sport.b.d.kB(34);
com.tencent.mm.kernel.g.Ek();
if (com.tencent.mm.l.a.gd(((com.tencent.mm.plugin.messenger.foundation.a.i) com.tencent.mm.kernel.g.l(com.tencent.mm.plugin.messenger.foundation.a.i.class)).FR().Yg("gh_43f2581f6fd6").field_type)) {
intent = new Intent();
intent.putExtra("Chat_User", "gh_43f2581f6fd6");
intent.putExtra("finish_direct", true);
d.e(bgVar.context, ".ui.chatting.ChattingUI", intent);
} else {
intent = new Intent();
intent.putExtra("Contact_User", "gh_43f2581f6fd6");
d.b(bgVar.context, "profile", ".ui.ContactInfoUI", intent);
}
z = true;
} else if ("wx9181ed3f223e6d76".equals(str) || "wx2fe12a395c426fcf".equals(str)) {
x.i("MicroMsg.TimeLineClickEvent", "hy: shake new year closed. try to go to shake TV");
intent = new Intent();
intent.putExtra("shake_tv", true);
d.b(view.getContext(), "shake", ".ui.ShakeReportUI", intent);
z = true;
} else if ("wx751a1acca5688ba3".equals(str)) {
intent = new Intent();
intent.putExtra("BaseScanUI_select_scan_mode", 5);
if (!(com.tencent.mm.p.a.bx(bgVar.context) || com.tencent.mm.p.a.bw(bgVar.context))) {
d.b(bgVar.context, "scanner", ".ui.BaseScanUI", intent);
}
z = true;
} else if ("wxfbc915ff7c30e335".equals(str)) {
intent = new Intent();
intent.putExtra("BaseScanUI_select_scan_mode", 1);
if (!(com.tencent.mm.p.a.bx(bgVar.context) || com.tencent.mm.p.a.bw(bgVar.context))) {
d.b(bgVar.context, "scanner", ".ui.BaseScanUI", intent);
}
z = true;
} else if ("wx482a4001c37e2b74".equals(str)) {
intent = new Intent();
intent.putExtra("BaseScanUI_select_scan_mode", 2);
if (!(com.tencent.mm.p.a.bx(bgVar.context) || com.tencent.mm.p.a.bw(bgVar.context))) {
d.b(bgVar.context, "scanner", ".ui.BaseScanUI", intent);
}
z = true;
} else if (!"wxaf060266bfa9a35c".equals(str)) {
z = false;
} else if (c.Qf()) {
intent = new Intent();
intent.putExtra("shake_tv", true);
d.b(bgVar.context, "shake", ".ui.ShakeReportUI", intent);
z = true;
} else {
z = true;
}
}
if (!z && view != null && (view.getTag() instanceof bsu)) {
bsu bsu = (bsu) view.getTag();
if (bsu == null || bsu.sqb == null) {
x.e("MicroMsg.TimeLineClickEvent", "appInfo is null");
return;
}
String str3 = bsu.sqb.ksA;
String cS = com.tencent.mm.plugin.sns.c.a.ezo.cS(str3);
if (bi.oW(cS) || !com.tencent.mm.plugin.sns.c.a.ezo.cU(str3)) {
str = com.tencent.mm.plugin.sns.c.a.ezo.h(bg.this.context, str3, "timeline");
if (str != null && str.length() != 0) {
Intent intent2 = new Intent();
intent2.putExtra("rawUrl", str);
intent2.putExtra("shortUrl", str);
intent2.putExtra("useJs", true);
intent2.putExtra("type", -255);
intent2.putExtra("geta8key_scene", 2);
com.tencent.mm.plugin.sns.c.a.ezn.j(intent2, bg.this.context);
return;
}
return;
}
int i;
String str4 = bsu == null ? null : bsu.hbL;
if (bsu.sqc.ruz == 1) {
i = 2;
} else if (bsu.sqc.ruz == 3) {
i = 5;
} else {
i = 2;
}
if (!(bsu.nsB == null || bsu.nsB.raS == null)) {
str2 = bsu.nsB.raS.raM;
}
nk nkVar = new nk();
nkVar.bYs.context = bg.this.context;
nkVar.bYs.scene = 4;
nkVar.bYs.bPS = str3;
nkVar.bYs.packageName = cS;
nkVar.bYs.msgType = i;
nkVar.bYs.bSS = str4;
nkVar.bYs.mediaTagName = str2;
nkVar.bYs.bYt = 5;
nkVar.bYs.bYu = 0;
nkVar.bYs.bYv = bsu.ksA;
com.tencent.mm.sdk.b.a.sFg.m(nkVar);
gk gkVar = new gk();
gkVar.bPB.actionCode = 2;
gkVar.bPB.scene = 3;
gkVar.bPB.extMsg = "timeline_src=3";
gkVar.bPB.appId = str3;
gkVar.bPB.context = bg.this.context;
com.tencent.mm.sdk.b.a.sFg.m(gkVar);
}
}
};
public OnClickListener ohw = new 9(this);
public OnClickListener ohx = new 10(this);
public OnClickListener ohy = new 11(this);
public OnClickListener ohz = new 12(this);
int scene = 0;
com.tencent.mm.ui.base.p tipDialog;
public bg(Context context, a aVar, int i, ae aeVar) {
this.context = context;
this.oht = aVar;
this.scene = i;
this.nMm = aeVar;
}
protected static boolean KK(String str) {
js jsVar = new js();
jsVar.bTw.action = -2;
com.tencent.mm.sdk.b.a.sFg.m(jsVar);
avq avq = jsVar.bTx.bTy;
if (avq != null && com.tencent.mm.an.b.d(avq) && str.equals(avq.rsp) && com.tencent.mm.an.b.PY()) {
return true;
}
return false;
}
}
|
package org.study.core.collections;
import java.util.HashSet;
import java.util.Set;
/*
HashMap, HashSet may used objects without overridden equals()
However one will not be able to find item by other than initial object
*/
public class ClassWithoutEqualsInMap {
private final String name;
public ClassWithoutEqualsInMap(String name) {
this.name = name;
}
public static void main(String[] args) {
Set<ClassWithoutEqualsInMap> set = new HashSet<>();
String name = "test";
ClassWithoutEqualsInMap testObj = new ClassWithoutEqualsInMap(name);
ClassWithoutEqualsInMap newObj = new ClassWithoutEqualsInMap(name);
set.add(testObj);
System.out.println("is testObj in set? " + set.contains(testObj));
System.out.println("is newObj in set? " + set.contains(newObj));
}
}
|
package huang.da.fb.db;
import java.net.UnknownHostException;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
public class MongoAccessor {
MongoClient mongoClient;
DB db;
DBCollection collection;
public DB getDb() {
return db;
}
public DBCollection getCollection() {
return collection;
}
public void connectLocalDB(String dbName, String collectionName) {
try {
mongoClient = new MongoClient("192.168.56.121");
DB db = mongoClient.getDB(dbName);
collection = db.getCollection(collectionName);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void initDB(){
try {
mongoClient = new MongoClient("192.168.56.121");
DB db = mongoClient.getDB("fb");
collection = db.getCollection("bus_schedule");
BasicDBObject[] schedule = createStations();
collection.insert(schedule);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public BasicDBObject[] createStations(){
BasicDBObject f_01_schedule = new BasicDBObject();
f_01_schedule.put("bus_id", "F_01");
f_01_schedule.put("bus_status", "in time");
f_01_schedule.put("pass_station1", "12:00");
f_01_schedule.put("pass_station2", "12:05");
f_01_schedule.put("pass_station3", "12:07");
f_01_schedule.put("pass_station4", "12:09");
f_01_schedule.put("pass_station5", "12:10");
f_01_schedule.put("has_mechanical_failure", "true");
f_01_schedule.put("has_traffic_jam", "false");
BasicDBObject f_02_schedule = new BasicDBObject();
f_02_schedule.put("bus_id", "F_02");
f_02_schedule.put("bus_status", "in time");
f_02_schedule.put("pass_station1", "13:00");
f_02_schedule.put("pass_station2", "13:05");
f_02_schedule.put("pass_station3", "13:07");
f_02_schedule.put("pass_station4", "13:09");
f_02_schedule.put("pass_station5", "13:10");
f_02_schedule.put("has_mechanical_failure", "false");
f_02_schedule.put("has_traffic_jam", "false");
BasicDBObject f_03_schedule = new BasicDBObject();
f_03_schedule.put("bus_id", "F_03");
f_03_schedule.put("bus_status", "in time");
f_03_schedule.put("pass_station1", "14:00");
f_03_schedule.put("pass_station2", "14:05");
f_03_schedule.put("pass_station3", "14:07");
f_03_schedule.put("pass_station4", "14:09");
f_03_schedule.put("pass_station5", "14:10");
f_03_schedule.put("has_mechanical_failure", "false");
f_03_schedule.put("has_traffic_jam", "false");
BasicDBObject f_04_schedule = new BasicDBObject();
f_04_schedule.put("bus_id", "F_04");
f_04_schedule.put("bus_status", "in time");
f_04_schedule.put("pass_station1", "15:00");
f_04_schedule.put("pass_station2", "15:05");
f_04_schedule.put("pass_station3", "15:07");
f_04_schedule.put("pass_station4", "15:09");
f_04_schedule.put("pass_station5", "15:10");
f_04_schedule.put("has_mechanical_failure", "false");
f_04_schedule.put("has_traffic_jam", "false");
BasicDBObject f_05_schedule = new BasicDBObject();
f_05_schedule.put("bus_id", "F_05");
f_05_schedule.put("bus_status", "in time");
f_05_schedule.put("pass_station1", "16:00");
f_05_schedule.put("pass_station2", "16:05");
f_05_schedule.put("pass_station3", "16:07");
f_05_schedule.put("pass_station4", "16:09");
f_05_schedule.put("pass_station5", "16:10");
f_05_schedule.put("has_mechanical_failure", "false");
f_05_schedule.put("has_traffic_jam", "false");
BasicDBObject f_06_schedule = new BasicDBObject();
f_06_schedule.put("bus_id", "F_06");
f_06_schedule.put("bus_status", "in time");
f_06_schedule.put("pass_station1", "17:00");
f_06_schedule.put("pass_station2", "17:05");
f_06_schedule.put("pass_station3", "17:07");
f_06_schedule.put("pass_station4", "17:09");
f_06_schedule.put("pass_station5", "17:10");
f_06_schedule.put("has_mechanical_failure", "false");
f_06_schedule.put("has_traffic_jam", "false");
BasicDBObject[] schedule = {f_01_schedule, f_02_schedule, f_03_schedule,
f_04_schedule, f_05_schedule, f_06_schedule};
return schedule;
}
public void closeMongoClient() {
//collection.drop();
mongoClient.close();
}
}
|
package edu.uci.ics.sdcl.firefly.util.mturk;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import edu.uci.ics.sdcl.firefly.Microtask;
import edu.uci.ics.sdcl.firefly.WorkerSession;
import edu.uci.ics.sdcl.firefly.report.descriptive.FileSessionDTO;
/** Utility class to process the logs generated in the
* experiment run of July 2015.
*
* Objectives:
* Consolidate different workerIDs from same turkerID
* Differentiate sessionIDs with the name number but related to different sessions
*
* Load all Turkers with their Worker ID/BatchFile
* If two turkers have the same workerID, than replace their IDs in the Logs
*
* @author adrianoc
*
*/
public class TurkerWorkerMatcher {
//Alls maps, one indexed by turker other indexed by sessionsIDs
HashMap<String, Turker> hitsMapAll = new HashMap<String, Turker>();
HashMap<String, HashMap<String,Turker>>allTurkSessionsMap = new HashMap<String, HashMap<String,Turker>>();
//Matching sessions maps.
HashMap<String, Turker> hitsMap1 = new HashMap<String, Turker>();
HashMap<String, Turker> hitsMap2 = new HashMap<String, Turker>();
HashMap<String, WorkerSession> sessionMap = new HashMap<String, WorkerSession>();
MTurkSessions checker;
LogReadWriter logReadWriter;
private HashMap<String, HashMap<String, WorkerSession>> workerSessionsMap;
private HashMap<String, HashMap<String, WorkerSession>> missinHITSessionMap;
/** Constructor */
public TurkerWorkerMatcher(){
this.checker = new MTurkSessions();
this.logReadWriter = new LogReadWriter();
}
//-----------------------------------
public static void main(String[] args){
TurkerWorkerMatcher matcher = new TurkerWorkerMatcher();
matcher.listTurkersRunSessions();
}
/**
* Look at each workerID to see if it is associated with two different turkers.
* Prints the results in the console.
*/
public void checkTurkerHasSameWorkerID(){
this.loadHITs(checker.mturkLogs_S1,checker.mturkLogs_S2);
this.matchWorkerIDs(checker.crowddebugLogs[0],hitsMap1);
this.matchWorkerIDs(checker.crowddebugLogs[1],hitsMap2);
this.printTurkersWithSameWorkerID();//Session (1,2,TP1, TP2, etc.), same workerID: (TurkerID1:WorkerSession , TurkerID2:WorkerSession)
}
/**
* Look at same turker and check if this turker is associated with different workerIDs in different sessionLogs
* Prints the results in the console.
*
* Order of checking: Session (TP6 x TP5, TP65 x TP4, TP654x TP3, TP6453x TP1, TP x S1, TPS x S2)
*
* Order of checking: S1 x S2
*/
public void checkSameTurkerWithDifferentWorkerID(){
this.loadHITs(checker.mturkLogs_S1,checker.mturkLogs_S2);
this.matchWorkerIDs(checker.crowddebugLogs[0],hitsMap1);
this.matchWorkerIDs(checker.crowddebugLogs[1],hitsMap2);
this.printTurkerWithDifferentWorkerID();
}
/**
* Checks if:
* - the code in the HIT exists in the session-log
* - the worker associated with that code in the session-log is not associate with other codes
* that are actually from different workers
*/
public void checkHITLogConsistency(){
this.loadAllHITs();
this.hitsMap1 = loadHIT(this.checker.mturkLogs_S1);
this.loadSession(this.checker.crowddebugLogs[0]);
this.matchWorkerIDs(checker.crowddebugLogs[0],this.hitsMap1);
this.matchSessions(this.hitsMap1);
this.findMissingHITSessions();
checkAllNotClaimed();
}
/**
* List all turkers who have HITs across session logs.
*/
public HashMap<String, Turker> listTurkersRunSessions(){
this.loadAllHITs();
//For each turker, check if turker has
for(String turkerStr : hitsMapAll.keySet()){
Turker turker = hitsMapAll.get(turkerStr);
int nonEmptyRunSessions = 0;
int runSession = 0;
for(int i=0; i<checker.mturkAllLogs.size();i++) {
runSession++;
String[] turkLogs = checker.mturkAllLogs.get(i);
ArrayList<String> turkerHITList = getHITList(turker.turkerID, turkLogs);
if(turkerHITList.size()>0)
nonEmptyRunSessions++;
//gets both the runSession number as the HITs in which the worker participated
turker.runSessionMap.put(new Integer(runSession).toString(),turkerHITList);
}
turker.nonEmptyRunSessions = nonEmptyRunSessions;
hitsMapAll.put(turkerStr, turker);// saves turker back to the list
}
populateTurkerWorkerIDs();
consolidateTurkerIDs();
//printRunWorkerIDMap();
printTurkerRunSessions();
return this.hitsMapAll;
}
/** For each turker
* Obtain the sessionID associated with at a HITName (uses the Turker.runSessionMap)
* Obtains the sessionLog corresponding to the run
* Opens the log and extracts the workerID associated with the sessionID
* Instantiates a new datastructure in Turker.runWorkerIDMap
*/
private void populateTurkerWorkerIDs(){
//For each turker, check if turker has
for(String turkerStr : hitsMapAll.keySet()){
Turker turker = hitsMapAll.get(turkerStr);
for(String runID: turker.runSessionMap.keySet()){
ArrayList<String> sessionIDList = turker.runSessionMap.get(runID);
if(sessionIDList.size()>0){
String sessionID = sessionIDList.get(0); // The first element is sufficient to obtain the workerID.
Integer runIDInt = new Integer(runID);
HashMap<String, WorkerSession> workerSessionMap = checker.workerSessionMapList.get(runIDInt-1);
WorkerSession session = workerSessionMap.get(sessionID);
if(session!=null){
String workerID = session.getWorkerId();
turker.runWorkerIDMap.put(runID, workerID);
}
else{
System.out.println("Session is null! Should not be, sessionID:"+sessionID);
}
}
}
}
}
private void printRunWorkerIDMap(){
for(Turker turker : this.hitsMapAll.values()){
System.out.println();
System.out.print(turker.turkerID+";"+turker.nonEmptyRunSessions+";"+turker.turkerFinalWorkerID+";");
for(int i=1;i<9;i++){
String workerID = turker.runWorkerIDMap.get(new Integer(i).toString());
if(workerID==null)
System.out.print(i+";-");
else{
System.out.print(i+";");
System.out.print(workerID);
}
System.out.print(";");
}
}
}
private void consolidateTurkerIDs(){
for(String turkerStr : hitsMapAll.keySet()){
Turker turker = hitsMapAll.get(turkerStr);
turker.consolidadeID();
hitsMapAll.put(turkerStr,turker);
}
}
private ArrayList<String> getHITList(String turkerID, String[]turkerLogs){
ArrayList<String> HITList = new ArrayList<String>();
HashMap<String, Turker> hitMap = this.loadHIT(turkerLogs);
for(String turkID : hitMap.keySet()){
if(turkID.compareTo(turkerID)==0){
Turker turker = hitMap.get(turkID);
HITList.addAll(turker.sessionMap.keySet());
}
}
return HITList;
}
/**
* Prints for each turkerID the following string
* The HITnames are within curly brackets.
*
* TurkerID:1:{}2:{}:3:{}:4:{}:5:{}:6{}:7:{}:8:{}
*/
private void printTurkerRunSessions(){
for(Turker turker : this.hitsMapAll.values()){
System.out.print(turker.turkerID+":"+turker.nonEmptyRunSessions+":");
for(int i=1;i<9;i++){
ArrayList<String> list = turker.runSessionMap.get(new Integer(i).toString());
if(list==null)
System.out.print(i+":{}:");
else{
System.out.print(i+":{");
for(String hitname: list){
System.out.print(hitname+ ",");
}
System.out.print("}:");
}
}
System.out.println();
}
}
public HashMap<String, Turker> loadHIT(String[] sessionLog){
HashMap<String, Turker> hitMap = new HashMap<String,Turker>();
for(String batchFile: sessionLog){
hitMap= importHITCodes(batchFile, hitMap);
}
return hitMap;
}
public void loadHITs(String[] firstLogs, String[] secondLogs){
for(String batchFile: firstLogs){
this.hitsMap1= importHITCodes(batchFile, hitsMap1);
}
for(String batchFile: secondLogs){
this.hitsMap2= importHITCodes(batchFile, hitsMap2);
}
}
public void loadSession(String crowdLog){
FileSessionDTO sessionDTO = new FileSessionDTO(this.logReadWriter.getPath(2)+crowdLog);
this.sessionMap = (HashMap<String, WorkerSession>) sessionDTO.getSessions();
buildWorkerSessionsMap();
}
/** Builds a map with the following structure:
* Key: workerID
* Value: HashMap<sessionID,session>
*/
private void buildWorkerSessionsMap(){
this.workerSessionsMap = new HashMap<String, HashMap<String,WorkerSession>>();
for(WorkerSession session: sessionMap.values()){
String workerID = session.getWorkerId();
HashMap<String,WorkerSession> map = this.workerSessionsMap.get(workerID);
if(map==null)
map = new HashMap<String,WorkerSession>();
map.put(extract(session.getId()), session);
this.workerSessionsMap.put(workerID, map);
}
}
public void matchSessions(int firstSession, int secondSession){
matchWorkerIDs(checker.crowddebugLogs[firstSession],hitsMap1); //Load the sessions and populate turkers with respective workerIds.
matchWorkerIDs(checker.crowddebugLogs[secondSession],hitsMap2);
}
private void matchWorkerIDs(String crowdLog, HashMap<String, Turker> hitsMap){
for(Turker turker: hitsMap.values()){
for(String sessionID: turker.sessionMap.keySet()){
//System.out.println("Turker sessionID entered:"+sessionID);
String workerID = retrieveWorkerID(sessionMap, sessionID.trim());
if(workerID!=null && !this.workerHasExtraSessions(workerID, turker)){ //For merging, I will have to drop the workerHasExtraSessions condition.
System.out.println("MATCH, turkerID:"+turker.turkerID+": workerID:"+workerID+": sessionID:"+sessionID );
turker.setWorkerID(workerID,crowdLog);
hitsMap.put(turker.turkerID, turker);
}
else{
System.out.println("NOT FOUND VIABLE SESSION! turkerID:"+turker.turkerID+": sessionID:"+sessionID );
}
}
}
}
/** Look for the sessionID that matches the workerID */
private String retrieveWorkerID(HashMap<String, WorkerSession> sessionMap,
String sessionID) {
for(String composedSessionID: sessionMap.keySet()){
//System.out.println("composedSessionID: "+composedSessionID);
String sessionIDpart = composedSessionID.split(":")[0].trim();
String workerIDpart = composedSessionID.split(":")[1].trim();
if(sessionID.compareTo(sessionIDpart)==0){
if((sessionMap.get(composedSessionID).getMicrotaskListSize()>0)){
return workerIDpart;
}
else{
System.out.println("EMPTY SESSION: "+sessionID);
return workerIDpart;
}
}
}
return null;
}
public void matchSessions(HashMap<String, Turker> hitsMap){
//Get each turker list the sessions
for(Turker turker: hitsMap.values()){
//Accumulate all sessions in the log that are associated to a workerID
HashMap<String, WorkerSession> foundSessionsInLog = new HashMap<String, WorkerSession>();
HashMap<String, String> workerWithInvalidSession = new HashMap<String,String>();
for(String turkWorkerID: turker.workerIDMap.keySet()){
HashMap<String, WorkerSession> logSessionsMap = this.workerSessionsMap.get(turkWorkerID);
if(logSessionsMap==null){
workerWithInvalidSession.put(turker.turkerID,turkWorkerID);
System.out.println("NOT FOUND IN LOGS! turkerID:"+turker.turkerID+": turkWorkerID:"+turkWorkerID);
}
else{
//Accumulate all sessions found for that workerID
for(WorkerSession logSession : logSessionsMap.values()){
foundSessionsInLog.put(extract(logSession.getId()), logSession );
}
}
}
//Now compare the sessions accumulated against the sessions in the hitMap
for(String turkSession: turker.sessionMap.keySet()){
WorkerSession logSession = foundSessionsInLog.get(turkSession);
if(logSession==null){
System.out.println("Mismatching Session! turkerID:"+turker.turkerID+
": turkSession:"+turkSession);
}
else
foundSessionsInLog.remove(turkSession);
}
if(foundSessionsInLog.isEmpty()){
turker.printTurkerWorkerSessionLog();
}
else{
System.out.print("Turker incomplete, sessions not found in sessionLog HITMaps, turkerID :"+turker.turkerID+":");
for(String sessionID: foundSessionsInLog.keySet()){
System.out.print(sessionID+":");
}
System.out.println();
System.out.print("Turker incomplete, sessions not found in sessionLog HITMaps, turkerID :"+turker.turkerID+":");
for(String sessionID: foundSessionsInLog.keySet()){
WorkerSession session = foundSessionsInLog.get(sessionID);
System.out.print(session.getFileName()+":");
}
System.out.println();
System.out.print("Turker incomplete, sessions not found in sessionLog HITMaps, turkerID :"+turker.turkerID+":");
for(String sessionID: foundSessionsInLog.keySet()){
WorkerSession session = foundSessionsInLog.get(sessionID);
System.out.print(session.getWorkerId()+":");
}
System.out.println();
//Save the missing sessions to be inspected lated.
addMissingHITSessions(turker.turkerID, foundSessionsInLog);
}
}
}
private void addMissingHITSessions(String turkerID,
HashMap<String, WorkerSession> foundSessionsInLog) {
if (this.missinHITSessionMap == null)
this.missinHITSessionMap = new HashMap<String,HashMap<String, WorkerSession>>();
this.missinHITSessionMap.put(turkerID, foundSessionsInLog);
}
/** Search in the AllHITs for sessions that were in the log, but were not in the HITs of Sessions-2
*
* If not found, then turker did not reclaimed the sessionID
* If found a session in a HIT, check if it is from the worker.
* If positive, has to merge worker code from Session-2 with the session corresponding to that HIT.
* (I am not merging now, just checking)
* If negative, then turker did not reclaimed that ID
*
*
*/
public void findMissingHITSessions(){
if(missinHITSessionMap!=null)
for(String turkerID: this.missinHITSessionMap.keySet()){
HashMap<String,WorkerSession> missingLogSessionsMap = this.missinHITSessionMap.get(turkerID);
for(String logSessionID: missingLogSessionsMap.keySet()){
WorkerSession logSession = missingLogSessionsMap.get(logSessionID);
if(!this.allTurkSessionsMap.containsKey(logSessionID)){
System.out.println("Not reclaimed, turkerID: "+ turkerID+":" +logSessionID+":"+logSession.getFileName());
}
else{
HashMap<String, Turker> turkerMap = this.allTurkSessionsMap.get(logSessionID);
if(!turkerMap.containsKey(turkerID)){
System.out.println("Not reclaimed, turkerID: "+ turkerID+":" +logSessionID+":"+logSession.getFileName());
}
else{
Turker foundTurker = turkerMap.get(turkerID);
String batchFile = foundTurker.sessionBatchMap.get(logSessionID);
System.out.println("Found ELSEWHERE logSession, turkerID: "+ turkerID+":" +logSessionID+":"+batchFile);
}
}
}
}
}
/** Check whether a worker has any extra session that is not in the HIT list of a Turker
* @param hitsMap */
private boolean workerHasExtraSessions(String workerID, Turker turker){
HashMap<String,WorkerSession> workerSessionMap = this.workerSessionsMap.get(workerID);
for(WorkerSession composedSession: workerSessionMap.values()){
String workerSessionID = extract(composedSession.getId());
if(!turker.sessionMap.containsKey(workerSessionID)){
if((composedSession.getMicrotaskListSize()<3)) //Disconsider empty or incomplete sessions.
return false;
else
if (this.sessionID_Not_ClaimedByOtherTurkers(turker, workerSessionID))//Disconsider sessions that were not claimed by others (possibly worker did extra session),
return false; //However, it might be ok even if a worker in a different logSession had claimed the same sessionID, the test in place now to check whether the
//turker claimed the HIT in the wrong logSession.
else{
System.out.println("Invalid worker for turker:"+turker.turkerID+": worker:"+workerID+": session:"+workerSessionID+" HIT:"+composedSession.getFileName());
return true;
}
}
}
return false;
}
private boolean sessionID_Not_ClaimedByOtherTurkers(Turker turker, String sessionID){
HashMap<String, Turker> turkerMap = allTurkSessionsMap.get(sessionID);
if(turkerMap==null)//no turker claimed the session
return true;
else
if(turkerMap.size()<=1) //the only turker claiming it is the one being questioned
return true;
else
return false;
}
private String extract(String composedSessionID){
return composedSessionID.split(":")[0].trim();
}
//-----------------------------------------------------------------------------------------
// PRINTING METHODS
public void loadAllHITs(){
for(String[] batchFileList : checker.mturkAllLogs)
for(String batchFile: batchFileList)
this.hitsMapAll= importHITCodes(batchFile, this.hitsMapAll);
System.out.println("Total HITs imported: "+this.hitsMapAll.size());
}
public void printToFileAllTurkerHITs(){
HashMap<String, Turker> allHITMap = new HashMap<String,Turker>();
for(String batchFile: checker.mturkLogs_S2){
allHITMap= importHITCodes(batchFile, allHITMap);
}
System.out.println("TurkerID:HIT, number of workers: "+ allHITMap.size());
for(Turker turker: allHITMap.values()){
turker.printTurkerSessionHITs();
}
}
public void printTurkerWithDifferentWorkerID() {
for(Turker turker1: this.hitsMap1.values()){
Turker turker2 = this.hitsMap2.get(turker1.turkerID);
if(turker2!=null && turker1!=null && turker2.workerID!=null && turker1.workerID!=null){
if(turker2.workerID.compareTo(turker1.workerID)!=0){
System.out.println("*** Disambiguate workerID:"+turker1.workerID+" for: "+turker1.turkerID+" and workerkID:" +turker2.workerID+" for: "+turker2.turkerID);
}
else{//turker is in both RUNs, but has different workerIDs. We need to consolidate to one.
if(turker1.workerID.compareTo(turker2.workerID)!=0){
System.out.println("!!! Consolidate TurkerID:"+turker1.turkerID+": workerID1:"+turker1.workerID+": workerID2:"+turker2.workerID);
}
else{
System.out.println("OK in both RUNS - TurkerID:"+turker1.turkerID+": workerID1:"+turker1.workerID);
}
}
}
else{
//System.out.println("turkerID: "+turker1.turkerID+" NOT present in both RUNS");
}
}
}
public void printTurkersWithSameWorkerID() {
for(Turker turker1: this.hitsMap1.values()){
for(Turker turker2: this.hitsMap2.values()){
if(turker1.workerID!=null && turker2.workerID!=null)
if((turker1.turkerID.compareTo(turker2.turkerID)!=0) && (turker1.workerID.compareTo(turker2.workerID)==0)){
System.out.println("??? Disambiguate workerID:"+turker1.workerID+" for: "+turker1.turkerID+" and workerkID:" +turker2.workerID+" for: "+turker2.turkerID);
}
}
}
}
/**
* Build a map of TurkerIDs and the Turker entered in Mechanical Turk
* @param path
* @return
*/
public HashMap<String, Turker> importHITCodes(String batchFile, HashMap<String, Turker> hitsMap){
int turkerIDPos = 0;
int sessionIDPos = 1;
String path = checker.folder_MTurkLogs + batchFile;
HashMap<String, String> codeMap = new HashMap<String, String>();
BufferedReader log = null;
try {
//System.out.println("Batch: "+path);
log = new BufferedReader(new FileReader(path));
String line = log.readLine(); //discards first line
if(line==null){
log.close();
return null;
}
if(line.split(",").length >2){
turkerIDPos = 17;
sessionIDPos = 29;
}
else{
turkerIDPos = 0;
sessionIDPos = 1;
}
int repetition=1;
String repeated="repeated";
while ((line = log.readLine()) != null) {
if(line.equals(""))
continue;
String turkerID = line.split(",")[turkerIDPos].trim();
//System.out.println(turkerID);
String code = line.split(",")[sessionIDPos].trim(); //completion code entered by the worker
Turker turker;
//System.out.println(turkerID+":"+code);
if(hitsMap.containsKey(turkerID)){
turker = hitsMap.get(turkerID);
turker.addSession(code,batchFile);
}
else
turker = new Turker(turkerID, code, batchFile);
hitsMap.put(turkerID, turker);
//Update allTurkSessionMap
if(this.allTurkSessionsMap.containsKey(code)){
HashMap<String, Turker> turkerMap = this.allTurkSessionsMap.get(code);
turkerMap.put(turkerID, turker);
this.allTurkSessionsMap.put(code, turkerMap);
}
else{
HashMap<String, Turker> turkerMap = new HashMap<String, Turker>();
turkerMap.put(turkerID, turker);
this.allTurkSessionsMap.put(code, turkerMap);
}
//Check if same code was used by more than worker
if(codeMap.containsKey(code)){
System.out.println("repeated: "+turkerID+":"+code);
codeMap.put(code + "_"+ repeated+"_"+repetition, turkerID);
repetition++;
}
else
codeMap.put(code, turkerID);
}
log.close();
return hitsMap;
} catch (FileNotFoundException e) {
System.out.println("ERROR: Could not open log file: "+ path);
e.printStackTrace();
return null;
} catch (IOException e) {
System.out.println("ERROR: Could not read log file: "+ path);
e.printStackTrace();
return null;
}
}
//----------------------------------------------------------------------------------------------------------------------------------
public static boolean checkQuit(String workerID){
for(String id: quitWorkerID_S2){
if(id.compareTo(workerID)==0) return true;
}
return false;
}
public static boolean checkAllNotClaimed(){
TurkerWorkerMatcher matcher = new TurkerWorkerMatcher();
matcher.loadAllHITs();
boolean flag= true;
for(String sessionID:notClaimedIDs ){
if(matcher.allTurkSessionsMap.containsKey(sessionID)){
System.out.println("actually claimed: "+sessionID);
flag = false;
}
}
return flag;
}
public static String[] quitWorkerID_S1 = {
"66GI-3E0i-4-83",
"96GC-5a-2g0-58",
"193II5A4G917",
"265Gc5A-5I0-48",
"298Ic-9A0E8-80",
"335Ia3A9c161",
"373iG0E3C-18-8",
"406cI-5A0g-91-1",
"429EC-1I-1e-77-9",
"350gG8A3I-31-3",
"384EI-4i7I-5-2-6",
"551Cg7C1A-2-1-4",
"550ii2G3e-89-1",
"561ag2A0g9-3-8",
"598Ga7E5c-5-9-4",
"604Cc-7a0e3-5-9",
"594eA-4G9a-80-2",
"611Ee-3C-4G-903",
"628ce-1a8I-9-7-9",
"693ag0C9I-13-6",
"776eE-1G6a-274",
"779ia2G-6e4-2-1",
"766gc-6i2i-65-9",
"804ig5I6g6-4-9",
"855ce-6e-8A-7-3-2",
"886Ag6C-1a-2-54",
};
public static String[] quitWorkerID_S2 = {
"0ie7A3G-3-8-7",
"119CC0g1g7-24",
"124aA0a-6I5-2-9",
"41eI0e3i-806",
"145GG9e7E9-7-5",
"138iA3e-9A-85-8",
"86GA-3G-4C8-5-2",
"183Ei0I-4c-5-67",
"212GA0e-7A-925",
"92ea8E5i07-8",
"241aC5A9C120",
"225ca6i-4G404",
"264aa2G-6g-4-12",
"92ea8E5i07-8",
"293GC-8A2g-1-51",
"290Ea0C1E82-6",
"344aG4i-5e-6-93",
"378Ie4a4c0-3-7",
"388eg-9A4C1-3-2",
"207GI-1i3I004",
"397Ea0E1e-761",
"432ag-4C6c0-42",
"333aA2c-1a4-28",
"465ie-9I5c11-4",
"599GE-7I6c0-4-6",
"584cC0A4G-821",
"623ei-3i-6G-1-11",
"604Ic-1I5i105",
"678eg6E-1i620",
"704gE-1E5a-815",
"711CI1g-7G-6-6-5",
"715Ca-6I-2i71-8",
"785Ge4A-9I8-90",
"825GA-3i-2c-4-3-1",
"883ae6c-1C1-3-3",
"917AE6G-1e-186",
"909Ee-1C5I-65-5",
"537Cg0e-7E-5-68",
"976aG2C3g419",
"92ea8E5i07-8",
"1016IA6C1E13-1",
"1036GI8I-8e6-30",
"86GA-3G-4C8-5-2",
"1070Cc3A-8C-6-32",
"1057Ce-9i-9E-105",
"1115GC-8i-4i282",
"1129GE7I6i339",
"1139Ei9a-7g-98-4",
"1150cG-4E-2c808",
"1144aG9I5E-609",
"1164Ac-1A6E-19-8",
"1192ei5a-8c530",
"1199gG-2a-9I-60-7",
"1246Gc7A-7G130",
"1370ea0E-6C-67-9",
"1404Cc-4a6a8-2-6",
"1444gi0C-6a-69-2",
"1509Ia1a0g-367",
"1550cA6g7G-4-55",
"1503ge-6g-9C95-7",
"1564ia5g-9e0-94",
"1623GC7c8c9-37",
"1636Ga0a-3e701",
"1629ce-1A-9C-9-4-4",
"1651AC0i-8g0-13",
"509ag3C6G-120",
};
private static String[] notClaimedIDs = {
"97gI6G0a19-4",
"944ec0G-8g-911",
"943ac-8i-3I5-42",
"942IE9e7E7-95",
"93aa2G4g627",
"930gg-1E7i0-5-8",
"92Aa8E8C18-3",
"929ia-7A-6c-87-5",
"927Eg7G2c-6-26",
"926eg1i3A-134",
"920CC-3g6C1-6-8",
"91Cc4i3a000",
"90Ca-3i-3E04-4",
"902gI-4G9e5-76",
"89GE6I-7G22-6",
"896Ic-5a0a1-8-7",
"88AC7i0C-8-1-8",
"86cg-4A-9E-118",
"862EG-5a2c9-12",
"860ce-8i0i6-26",
"85EG-7C-1c253",
"857iE1A-3E90-8",
"84EE7E2G71-1",
"78Eg9C0a-1-9-3",
"776cc-5E-8c-7-9-5",
"770cE9I-8g-1-4-4",
"766ie4g2a8-5-8",
"765ce-7a-9E-4-62",
"764EE7e3c-1-7-1",
"762gA-4A-2I-95-3",
"761Ea2g9A-6-70",
"759AG-3A-5a6-46",
"758CE-9g-9g1-8-2",
"756Ig-5G2I-7-2-3",
"752Gc-2E9A20-8",
"74IE5g1C5-97",
"749Ci-2C7G64-1",
"740II-8c3G-4-37",
"73iC-9C-6E061",
"735EA-5I-7C-2-7-3",
"733ii-2G2a-526",
"724CC7A7c9-6-7",
"720cE7a1C4-4-5",
"711gE8i-5c9-20",
"708Ai-6c-3A-45-7",
"705Ec-6E-4I108",
"703ca-4g-4G710",
"701Ge0E-1a-5-6-5",
"699Ia8i4A-4-87",
"698EE5A3C-6-79",
"697aE8i2I418",
"695CC4g-7g3-62",
"694cA0i9a-8-50",
"691IA-5C6I-71-3",
"689ca-9I-2G-455",
"686eC-2a8C-370",
"685cE-9a8A-412",
"684Ei7i9E84-6",
"683GC-9A-2g-702",
"682Ee-7E-2i-4-1-9",
"680ia-6e6a-9-7-9",
"679aI-1E-5I-84-8",
"676AI5I-9a27-5",
"671ai-9g-2a801",
"66cg6a9G7-9-8",
"669ee3i7g27-5",
"668AG3I-8E4-73",
"665ce-2E4E41-6",
"665ce-2E4E41-6",
"660gI4G9C3-29",
"657eG-1I5i346",
"656Eg-4I-5C-985",
"649cg-3e8A0-50",
"649cg-3e8A0-50",
"649cg-3e8A0-50",
"648iE-6C-4I01-2",
"646gC-5E-7G-5-8-3",
"643gE4i-1I75-9",
"642ca1i-2C4-72",
"639AI-1g6G808",
"638ea1c-9g-5-3-5",
"638ea1c-9g-5-3-5",
"637IC0I7g0-3-1",
"635iI1a-2A2-53",
"633Ce7G-8e-9-7-3",
"632cg-6G2g-5-1-7",
"631CG1A-6g4-7-7",
"629II-4G5A1-59",
"629II-4G5A1-59",
"627EE6g0A-193",
"621EI3G-5G-2-10",
"620eC8I3e7-23",
"618ge-5c4c3-52",
"616GI-2c7i6-58",
"615gg-1A-3E-7-4-9",
"614AG-1C7A35-6",
"613gE-9c7a007",
"611CC6e-7i903",
"609ic3A-5G03-8",
"608IC1c-3c-300",
"557ce0c2e-495",
"554Ig-4a3A-307",
"552eE7E4a-2-84",
"551IG-8a-9C8-57",
"550cc-6A-6I-1-8-2",
"54eg7E-6a0-35",
"53Ea3G0g-6-40",
"49Ge2A-3A97-4",
"48eA8I-5G8-1-5",
"437iG-6a-4G-7-79",
"435Gc-2g7e38-1",
"433AI-9c3e-2-5-6",
"425cg-3C-4I8-7-1",
"409ea6a7c-5-10",
"386aE0E-5i83-4",
"384aE1C0e-10-2",
"383gI4I6c4-7-7",
"356Ec7i-9C7-60",
"355Ig-2e-9g-284",
"352eG6G8I245",
"345Ce-8I8I-700",
"342gi5C6e-25-2",
"342gi5C6e-25-2",
"341Ec-3G1i8-2-4",
"340eI0a-3c-987",
"340eI0a-3c-987",
"339cC2A0a-78-9",
"336cA1I9C-6-32",
"333Gc3A7E-8-48",
"328Ge1G4c-8-3-1",
"313eC3g-8G74-4",
"306Ic2a-7a-1-6-5",
"304GG0c0I-429",
"296AC-9G7C-7-40",
"295ia-3A-8i-430",
"286Ii8g-8G5-11",
"284ac-6c-7g6-7-8",
"27gA7g9c-3-69",
"276Ec-3A-6a7-44",
"269CA-3c-9i1-64",
"24CI-5C3G-583",
"240ca9i-7e-96-3",
"230EA-4E-3E0-21",
"230EA-4E-3E0-21",
"226ei6e2E461",
"221gI-9E7a1-3-9",
"21gg-8e3a-2-93",
"197GG2g-9e6-9-8",
"197GG2g-9e6-9-8",
"195ga9I2e-3-3-2",
"191gg2G-4a-8-8-2",
"189ac6A2c22-7",
"188ac-7g-3E766",
"187IA-4i-9g0-3-1",
"184IC-2c-1a140",
"184IC-2c-1a140",
"183eI-8A-8c-8-96",
"182iC9c-3I71-5",
"16gE1g-5E64-7",
"103AC-6A0G-68-7",
"100ae0i-5c08-8",
};
}
|
package com.tencent.mm.plugin.music.model.e;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import com.tencent.mm.sdk.platformtools.x;
class b$1 implements OnCompletionListener {
final /* synthetic */ b lzt;
b$1(b bVar) {
this.lzt = bVar;
}
public final void onCompletion(MediaPlayer mediaPlayer) {
x.e("MicroMsg.Music.MMMediaPlayer", "onCompletion, stop music");
this.lzt.gQ(true);
}
}
|
package com.emn.member.action;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import com.emn.common.EmnAction;
import com.emn.common.SqlMapConfig;
import com.emn.common.SqlMapUsableObj;
import com.emn.member.model.Member;
public class UserFinderAction extends EmnAction {
public static final Logger log = Logger.getLogger(UserFinderAction.class);
private List<Member> memberList;
private String memberId;
private String memberName;
private String message;
public List<Member> getMemberList() {
return memberList;
}
public void setMemberList(List<Member> memberList) {
this.memberList = memberList;
}
public String getMemberId() {
return memberId;
}
public void setMemberId(String memberId) {
this.memberId = memberId;
}
public String getMemberName() {
return memberName;
}
public void setMemberName(String memberName) {
this.memberName = memberName;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String execute() throws Exception {
Member member = new Member();
member.setMemberId(memberId);
member.setMemberName(memberId);
memberList = (List) SqlMapConfig.selectListEmn("findId", member);
if (memberList.size() == 0) {
this.message = "<font color='red'>일치하는 회원이 없습니다.</font>";
return INPUT;
} else {
this.message = "";
for (Member p : memberList) {
String memberId = p.getMemberId();
int cnt = 0;
cnt = memberId.length();
memberId = memberId.substring(0, 3);
for (int i = 0; i < cnt; i++) {
memberId += "*";
}
message += "ID : " + memberId + "<br/>";
}
return "success";
}
}
public String getUser() throws Exception {
Member member = new Member();
member.setMemberId(memberId);
member.setMemberName(memberId);
log.debug(member.getMemberId() + member.getMemberName());
memberList = (List) SqlMapConfig.selectListEmn("findIdPw", member);
log.debug("List = " + memberList.toString());
if (memberList.size() == 0) {
this.message = "<font color='red'>일치하는 회원이 없습니다.</font>";
return INPUT;
} /*
* else { this.message = ""; for (Member p : list) { message += "ID : "
* + memId + "<br/>"; } return "success"; }
*/
return "success";
}
}
|
package com.rx.rxmvvmlib.ui.binding.viewadapter.recyclerview;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import androidx.annotation.IntDef;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
/**
* Created by wuwei
* 2019/12/6
* 佛祖保佑 永无BUG
*/
public class LayoutManagers {
protected LayoutManagers() {
}
public interface LayoutManagerFactory {
RecyclerView.LayoutManager create(RecyclerView recyclerView);
}
/**
* A {@link LinearLayoutManager}.
*/
public static LayoutManagerFactory linear() {
return new LayoutManagerFactory() {
@Override
public RecyclerView.LayoutManager create(RecyclerView recyclerView) {
return new LinearLayoutManager(recyclerView.getContext()) {
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
};
}
public static LayoutManagerFactory linear(final boolean canScrollVertically) {
return new LayoutManagerFactory() {
@Override
public RecyclerView.LayoutManager create(RecyclerView recyclerView) {
return new LinearLayoutManager(recyclerView.getContext()) {
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean canScrollVertically() {
return canScrollVertically;
}
};
}
};
}
/**
* A {@link LinearLayoutManager} with the given orientation and reverseLayout.
*/
public static LayoutManagerFactory linear(@Orientation final int orientation, final boolean reverseLayout) {
return new LayoutManagerFactory() {
@Override
public RecyclerView.LayoutManager create(RecyclerView recyclerView) {
return new LinearLayoutManager(recyclerView.getContext(), orientation, reverseLayout) {
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
};
}
/**
* A {@link GridLayoutManager} with the given spanCount.
*/
public static LayoutManagerFactory grid(final int spanCount) {
return new LayoutManagerFactory() {
@Override
public RecyclerView.LayoutManager create(RecyclerView recyclerView) {
return new GridLayoutManager(recyclerView.getContext(), spanCount) {
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
};
}
/**
* A {@link GridLayoutManager} with the given spanCount, orientation and reverseLayout.
**/
public static LayoutManagerFactory grid(final int spanCount, @Orientation final int orientation, final boolean reverseLayout) {
return new LayoutManagerFactory() {
@Override
public RecyclerView.LayoutManager create(RecyclerView recyclerView) {
return new GridLayoutManager(recyclerView.getContext(), spanCount, orientation, reverseLayout) {
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
};
}
/**
* A {@link StaggeredGridLayoutManager} with the given spanCount and orientation.
*/
public static LayoutManagerFactory staggeredGrid(final int spanCount, @Orientation final int orientation) {
return new LayoutManagerFactory() {
@Override
public RecyclerView.LayoutManager create(RecyclerView recyclerView) {
return new StaggeredGridLayoutManager(spanCount, orientation) {
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
};
}
@IntDef({LinearLayoutManager.HORIZONTAL, LinearLayoutManager.VERTICAL})
@Retention(RetentionPolicy.SOURCE)
public @interface Orientation {
}
}
|
package com.example.funnybirds;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import java.util.ArrayList;
import java.util.List;
public class Sprite {
private List<Rect> frames;
private double x;
private double y;
private int currentFrame;
private Bitmap bitmap;
private double velocityX;
private double velocityY;
private int padding;
public void setX(double x) {
this.x = x;
}
public void setY(double y) {
this.y = y;
}
public int getFrameHeight() {
return frames.get(currentFrame).height();
}
public int getFrameWidth() {
return frames.get(currentFrame).width();
}
public void setVy(double velocityY) {
this.velocityY = velocityY;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double getVy() {
return velocityY;
}
public void update(int ms) {
currentFrame = (currentFrame + 1) % frames.size();
x = x + velocityX * ms / 1000.0;
y = y + velocityY * ms / 1000.0;
}
public Sprite(Bitmap bitmap, int countW, int countH, double velocityX, double velocityY, double x, double y) {
this.x = x;
this.y = y;
this.currentFrame = 0;
this.bitmap = bitmap;
this.frames = new ArrayList<Rect>();
int w = bitmap.getWidth() / countW;
int h = bitmap.getHeight() / countH;
this.velocityX = velocityX;
this.velocityY = velocityY;
this.padding = 20;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
if (i != 2 && j != 4)
frames.add(new Rect(j * w, i * h, j * w + w, i * h + h));
}
}
}
public void draw(Canvas canvas) {
Paint p = new Paint();
Rect destination = new Rect((int) x, (int) y, (int) (x + frames.get(currentFrame).width()), (int) (y + frames.get(currentFrame).height()));
canvas.drawBitmap(bitmap, frames.get(currentFrame), destination, p);
}
public Rect getBoundingBoxRect() {
return new Rect((int) x + padding, (int) y + padding, (int) (x + frames.get(currentFrame).width() - 2 * padding),
(int) (y + frames.get(currentFrame).width() - 2 * padding));
}
public boolean intersect(Sprite s) {
return getBoundingBoxRect().intersect(s.getBoundingBoxRect());
}
}
|
/*
* Copyright (C) 2015 P100 OG, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://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.shiftconnects.android.push.sample;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import com.shiftconnects.android.push.sample.manager.ExamplePushManager;
import com.shiftconnects.android.push.sample.service.ExamplePushRegistrationService;
import com.squareup.otto.Bus;
import com.squareup.otto.ThreadEnforcer;
import retrofit.RestAdapter;
/**
* Created by mattkranzler on 2/27/15.
*/
public class ExampleApplication extends Application {
private static final String TAG = ExampleApplication.class.getSimpleName();
private static final String GCM_SHARED_PREFS_NAME = "gcm-shared-prefs";
public static Bus EVENT_BUS;
public static ExamplePushRegistrationService PUSH_REGISTRATION_SERVICE;
public static ExamplePushManager PUSH_MANAGER;
private static final String GCM_SENDER_ID = "your_gcm_sender_id_here";
@Override public void onCreate() {
super.onCreate();
// create an event bus to allow our gcm intent service to notify when new messages are available
EVENT_BUS = new Bus(ThreadEnforcer.MAIN);
// create instances - typically these would be created as part of a dependency injection framework to allow for mocking, different environments, etc.
SharedPreferences gcmSharedPrefs = getSharedPreferences(GCM_SHARED_PREFS_NAME, Context.MODE_PRIVATE);
PUSH_REGISTRATION_SERVICE = new RestAdapter.Builder()
.setEndpoint(BuildConfig.PUSH_SERVER_ENDPOINT)
.setLogLevel(RestAdapter.LogLevel.FULL)
.build()
.create(ExamplePushRegistrationService.class);
PUSH_MANAGER = new ExamplePushManager(InstanceID.getInstance(this), GCM_SENDER_ID, gcmSharedPrefs, PUSH_REGISTRATION_SERVICE);
// this will register the device with GCM and retrieve a registration id for this device
PUSH_MANAGER.registerWithGCM();
}
}
|
package com.pangpang6.books.offer.chapter2;
import org.junit.Test;
public class P39_DuplicationInArrayTest {
int[] data = {2, 3, 1, 0, 2, 5, 3};
int[] data2 = {2, 3, 5, 4, 3, 2, 6, 6};
@Test
public void getDuplication5Test() {
int r = P39_DuplicationInArray.getDuplication5(data2);
System.out.println(r);
}
@Test
public void quickSortTest() {
P39_DuplicationInArray.quickSort(data, 0, data.length - 1);
System.out.println(data);
}
@Test
public void getDuplication2Test() {
int result = P39_DuplicationInArray.getDuplication2(data);
System.out.println(result);
}
@Test
public void getDuplicationTest() {
int result = P39_DuplicationInArray.getDuplication(data);
System.out.println(result);
}
}
|
package br.uff.ic.provmonitor.dao.impl.javadb;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import br.uff.ic.provmonitor.connection.ConnectionManager;
import br.uff.ic.provmonitor.dao.ExecutionStatusDAO;
import br.uff.ic.provmonitor.exceptions.ConnectionException;
import br.uff.ic.provmonitor.exceptions.DatabaseException;
import br.uff.ic.provmonitor.exceptions.ProvMonitorException;
import br.uff.ic.provmonitor.model.ExecutionStatus;
import br.uff.ic.provmonitor.utils.DateUtils;
public class ExecutionStatusDAO_JavaDBImpl implements ExecutionStatusDAO{
@Override
public ExecutionStatus getById(String elementId, String elementPath) throws ProvMonitorException{
Connection conn = ConnectionManager.getInstance().getConnection();
try {
PreparedStatement psGetById = conn.prepareStatement("SELECT * FROM EXECUTION_STATUS WHERE ID_ELEMENT LIKE ? AND PATH LIKE ? ");
psGetById.setString(1, elementId);
//psGetById.setString(2, elementPath);
String elementPath2 = elementPath.replaceAll("\\\\", "\\\\\\\\");
psGetById.setString(2, elementPath2);
ResultSet rs = psGetById.executeQuery();
if (rs == null || !rs.next()){
return null;
}else{
ExecutionStatus executionStatus = new ExecutionStatus();
executionStatus.setCommitId(rs.getString("ID_COMMIT"));
executionStatus.setElementId(rs.getString("ID_ELEMENT"));
executionStatus.setElementPath(rs.getString("PATH"));
executionStatus.setElementType(rs.getString("TYPE_ELEMENT"));
executionStatus.setEndTime(rs.getDate("END_TIME"));
executionStatus.setPerformers(rs.getString("PERFORMERS"));
executionStatus.setStartTime(rs.getDate("START_TIME"));
executionStatus.setStatus(rs.getString("STATUS"));
return executionStatus;
}
} catch (SQLException | RuntimeException e) {
throw new DatabaseException(e.getMessage(), e.getCause());
}
}
@Override
public void persist(ExecutionStatus executionStatus) throws ProvMonitorException{
Connection conn = ConnectionManager.getInstance().getConnection();
try{
try{
//Transaction control
conn.setAutoCommit(false);
}catch(SQLException e){
throw new ConnectionException(e.getMessage(), e.getCause(), e.getSQLState());
}
//Verifying schema
PreparedStatement psInsert = conn.prepareStatement("INSERT INTO EXECUTION_STATUS (ID_ELEMENT" +
",TYPE_ELEMENT" +
",STATUS" +
",START_TIME" +
",END_TIME" +
",PATH" +
",PERFORMERS" +
",ID_COMMIT" +
") values (?,?,?,?,?,?,?,?)");
psInsert.setString(1, executionStatus.getElementId());
psInsert.setString(2, executionStatus.getElementType());
psInsert.setString(3, executionStatus.getStatus());
psInsert.setDate(4, DateUtils.utilsDate2SqlDate(executionStatus.getStartTime()));
psInsert.setDate(5, DateUtils.utilsDate2SqlDate(executionStatus.getEndTime()));
psInsert.setString(6, executionStatus.getElementPath());
psInsert.setString(7, executionStatus.getPerformers());
psInsert.setString(8, executionStatus.getCommitId());
psInsert.executeUpdate();
conn.commit();
}catch(SQLException e){
//Schema object does not exist
try{
conn.rollback();
}catch(SQLException ex){
}
throw new DatabaseException(e.getMessage(), e.getCause());
}
}
@Override
public void update(ExecutionStatus executionStatus) throws ProvMonitorException {
Connection conn = ConnectionManager.getInstance().getConnection();
try{
try{
//Transaction control
conn.setAutoCommit(false);
}catch(SQLException e){
throw new ConnectionException(e.getMessage(), e.getCause(), e.getSQLState());
}
//Verifying schema
PreparedStatement psInsert = conn.prepareStatement("UPDATE EXECUTION_STATUS SET ID_ELEMENT = ? " +
",TYPE_ELEMENT = ? " +
",STATUS = ? " +
",START_TIME = ? " +
",END_TIME = ? " +
",PATH = ? " +
",PERFORMERS = ? " +
",ID_COMMIT = ? " +
" WHERE ID_ELEMENT = ? AND PATH = ? AND END_TIME IS NULL " );
psInsert.setString(1, executionStatus.getElementId());
psInsert.setString(2, executionStatus.getElementType());
psInsert.setString(3, executionStatus.getStatus());
psInsert.setDate(4, DateUtils.utilsDate2SqlDate(executionStatus.getStartTime()));
psInsert.setDate(5, DateUtils.utilsDate2SqlDate(executionStatus.getEndTime()));
psInsert.setString(6, executionStatus.getElementPath());
psInsert.setString(7, executionStatus.getPerformers());
psInsert.setString(8, executionStatus.getCommitId());
psInsert.setString(9, executionStatus.getElementId());
psInsert.setString(10, executionStatus.getElementPath());
psInsert.executeUpdate();
conn.commit();
}catch(SQLException e){
//Schema object does not exist
try{
conn.rollback();
}catch(SQLException ex){
}
throw new DatabaseException(e.getMessage(), e.getCause());
}
}
/**
* Verify table existence in database. <br />
* @return <code><b>true</b></code> - If table exists. <br />
* <code><b>false</b></code> - If table does not exist.
* @throws ProvMonitorException If table could not be created. <br />
*
*/
@Override
public boolean isTableCreated() throws ProvMonitorException{
Connection conn = ConnectionManager.getInstance().getConnection();
try{
try{
//Transaction control
conn.setAutoCommit(false);
}catch(SQLException e){
throw new ConnectionException(e.getMessage(), e.getCause(), e.getSQLState());
}
//Verifying schema
PreparedStatement psInsert = conn.prepareStatement("INSERT INTO EXECUTION_STATUS (ID_ELEMENT, TYPE_ELEMENT, STATUS) values (?,?,?)");
psInsert.setString(1,"TesteParam1");
psInsert.setString(2,"TesteParam2");
psInsert.setString(3,"TesteParam3");
psInsert.executeUpdate();
// //Testando RollBack e Controle manual de transação
// String selectOne = "SELECT * FROM EXECUTION_STATUS";
// Statement s = conn.createStatement();
// ResultSet rs1 = s.executeQuery(selectOne);
// while (rs1.next())
// {
// System.out.println("SelectOne: " + rs1.getString(1));
// }
conn.rollback();
// String selectTwo = "SELECT * FROM EXECUTION_STATUS";
// s = conn.createStatement();
// ResultSet rs2 = s.executeQuery(selectTwo);
// while (rs2 != null && rs2.next())
// {
// System.out.println("SelectTwo: " + rs2.getString(1));
// }
return true;
}catch(SQLException e){
//Schema object does not exist
try{
conn.rollback();
}catch(SQLException ex){
}
return false;
}
}
/**
* Create table in database. <br />
* @throws ProvMonitorException If table could not be created. <br />
* @throws DatabaseException <code>Database related problems.</code><br />
* <ul>
* <li>ConnectionException - Connection problems related.</li>
* <li>DatabaseException - Problems with the table creation itself.</li>
* </ul>
* */
@Override
public void createTable() throws ProvMonitorException{
Connection conn = ConnectionManager.getInstance().getConnection();
Statement s = null;
try{
try{
//Preparing statement
s = conn.createStatement();
//Transaction control
conn.setAutoCommit(false);
}catch(SQLException e){
throw new ConnectionException(e.getMessage(), e.getCause(), e.getSQLState());
}
if (s != null){
String createTableSQL="CREATE TABLE EXECUTION_STATUS ( ID_ELEMENT VARCHAR(255) NOT NULL" +
", TYPE_ELEMENT VARCHAR(255) NOT NULL" +
", STATUS VARCHAR(255) NOT NULL" +
", START_TIME DATETIME" +
", END_TIME DATETIME" +
", PATH VARCHAR(255)" +
", PERFORMERS VARCHAR(255)" +
", ID_COMMIT VARCHAR(255)" +
")";
s.executeUpdate(createTableSQL);
conn.commit();
}
}catch(SQLException e){
try{
conn.rollback();
}catch(SQLException ex){
}
throw new DatabaseException(e.getMessage(), e.getCause());
}
}
}
|
package io.github.tamashii.mineRPG.listeners;
import io.github.tamashii.mineRPG.Configs;
import io.github.tamashii.mineRPG.StringTable;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.*;
import org.bukkit.scoreboard.*;
/**
* PlayerListener.java
*
* @version 14.2.5.133
* @author Tamashii
*
*/
public class PlayerListener implements Listener {
@EventHandler
public void onJoin(PlayerJoinEvent e) {
final Player player = e.getPlayer();
// TODO Load user data here.
final World world = player.getWorld();
Scoreboard scoreboard = Bukkit.getScoreboardManager().getNewScoreboard();
final Objective objective = scoreboard.registerNewObjective("mineRPGStats", "dummy");
objective.setDisplayName(StringTable.get("status"));
objective.setDisplaySlot(DisplaySlot.SIDEBAR);
}
@EventHandler(ignoreCancelled = true)
public void onWorldChanged(PlayerChangedWorldEvent e) {
final Player player = e.getPlayer();
final World world = player.getWorld();
if (world.getName().equalsIgnoreCase(Configs.getGameWorld())) {
Scoreboard scoreboard = Bukkit.getScoreboardManager().getNewScoreboard();
final Objective objective = scoreboard.registerNewObjective("mineRPGStats", "dummy");
objective.setDisplayName(StringTable.get("status"));
objective.setDisplaySlot(DisplaySlot.SIDEBAR);
player.sendMessage(StringTable.get("welcome", Configs.getGameTitle()));
}
}
}
|
package ch.ubx.startlist.shared;
import java.io.Serializable;
import java.util.Calendar;
import javax.persistence.Id;
import com.googlecode.objectify.annotation.Cached;
import com.googlecode.objectify.annotation.Entity;
@Cached
@Entity
public abstract class Job implements Serializable {
private static final long serialVersionUID = 1L;
@Id
protected String name;
public abstract void execute(String string, Calendar now);
}
|
/*
* 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 gob.igm.ec;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author TOAPANTA_JUAN
*/
@Entity
@Table(name = "TTIPODIRECCION")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Ttipodireccion.findAll", query = "SELECT t FROM Ttipodireccion t")
, @NamedQuery(name = "Ttipodireccion.findByIdTipoDireccion", query = "SELECT t FROM Ttipodireccion t WHERE t.idTipoDireccion = :idTipoDireccion")
, @NamedQuery(name = "Ttipodireccion.findByDescTipoDireccion", query = "SELECT t FROM Ttipodireccion t WHERE t.descTipoDireccion = :descTipoDireccion")})
public class Ttipodireccion implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = "ID_TIPO_DIRECCION")
private Short idTipoDireccion;
@Size(max = 50)
@Column(name = "DESC_TIPO_DIRECCION")
private String descTipoDireccion;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "idTipoDireccion")
private Collection<Tdireccionesusr> tdireccionesusrCollection;
public Ttipodireccion() {
}
public Ttipodireccion(Short idTipoDireccion) {
this.idTipoDireccion = idTipoDireccion;
}
public Short getIdTipoDireccion() {
return idTipoDireccion;
}
public void setIdTipoDireccion(Short idTipoDireccion) {
this.idTipoDireccion = idTipoDireccion;
}
public String getDescTipoDireccion() {
return descTipoDireccion;
}
public void setDescTipoDireccion(String descTipoDireccion) {
this.descTipoDireccion = descTipoDireccion;
}
@XmlTransient
public Collection<Tdireccionesusr> getTdireccionesusrCollection() {
return tdireccionesusrCollection;
}
public void setTdireccionesusrCollection(Collection<Tdireccionesusr> tdireccionesusrCollection) {
this.tdireccionesusrCollection = tdireccionesusrCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idTipoDireccion != null ? idTipoDireccion.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Ttipodireccion)) {
return false;
}
Ttipodireccion other = (Ttipodireccion) object;
if ((this.idTipoDireccion == null && other.idTipoDireccion != null) || (this.idTipoDireccion != null && !this.idTipoDireccion.equals(other.idTipoDireccion))) {
return false;
}
return true;
}
@Override
public String toString() {
return this.descTipoDireccion;
}
}
|
package com.tyss.cg.filehandling;
import java.io.FileReader;
public class FileReaderExample {
public static void main(String[] args) {
try(FileReader fileReader=new FileReader("newFile.txt");){
int charUnicode;
while ((charUnicode = fileReader.read())!= -1) {
System.out.println((char)charUnicode);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.imwj.tmall.interceptor;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* @author langao_q
* @create 2019-12-18 15:20
* 登录拦截器:校验是否登录
* preHandle:在业务处理器处理请求之前被调用(常用)
* postHandle:在业务处理器处理请求执行完成后,生成视图之前执行(少)
* afterCompletion:在DispatcherServlet完全处理完请求后被调用,可用于清理资源等(少)
*/
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
HttpSession session = httpServletRequest.getSession();
String contextPath = httpServletRequest.getServletContext().getContextPath();
//需要登录的页面url
String[] requireAuthPages = new String[]{
"buy",
"alipay",
"payed",
"cart",
"bought",
"confirmPay",
"orderConfirmed",
"forebuyone",
"forebuy",
"foreaddCart",
"forecart",
"forechangeOrderItem",
"foredeleteOrderItem",
"forecreateOrder",
"forepayed",
"forebought",
"foreconfirmPay",
"foreorderConfirmed",
"foredeleteOrder",
"forereview",
"foredoreview"
};
//当前请求的url
String uri = httpServletRequest.getRequestURI();
//去掉指定字符串
uri = StringUtils.remove(uri, contextPath + "/");
String page = uri;
//判断是否是属于需要登录的url
if(beginWith(page, requireAuthPages)){
//校验用户是否登录
Subject subject = SecurityUtils.getSubject();
if(!subject.isAuthenticated()) {
httpServletResponse.sendRedirect("login");
return false;
}
}
return true;
}
/**
* 比较page是否存在于requiredAuthPages中
* startsWith() 方法用于检测字符串是否以指定的前缀开始。
* @param page
* @param requiredAuthPages
* @return
*/
private boolean beginWith(String page, String[] requiredAuthPages){
boolean result = false;
for(String requiredAuthPage : requiredAuthPages){
if(StringUtils.startsWith(page, requiredAuthPage)){
result = true;
break;
}
}
return result;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
|
package project.timesheetWebapp.dto;
import java.util.Date;
public class TimesheetTaskDTO {
private String name ;
private String details ;
private float hours ;
private Date date ;
private String task ;
private String employeeId ;
public String getEmployeeId() {
return employeeId;
}
public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}
public String getTask() {
return task;
}
public void setTask(String task) {
this.task = task;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public float getHours() {
return hours;
}
public void setHours(float hours) {
this.hours = hours;
}
@Override
public String toString() {
return "TimesheetTaskDTO [name=" + name + ", details=" + details + ", hours=" + hours + ", date=" + date + "]";
}
}
|
public static IntStream createFilteringStream(IntStream evenStream, IntStream oddStream) {
return // write your stream here
IntStream.concat(evenStream, oddStream).filter(x -> x % 3 == 0 && x % 5 == 0).sorted().skip(2);
}
|
package fiuba.algo3.modelo;
public class PublicacionCochera extends Publicacion {
public PublicacionCochera(String barrio, int precio, String moneda,
String inmobiliaria, Fecha fecha,
IdentificadorPublicacion nroPublicacion) {
Moneda monedaNueva = new Moneda(moneda);
this.agregarDatos(barrio, precio, monedaNueva, inmobiliaria, fecha, nroPublicacion);
}
}
|
package com.lti.controller;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.lti.entity.Student;
import com.lti.service.StudentService;
import com.mail.Sendmail;
@Controller
public class StudentController {
@Resource
private StudentService studentService;
@RequestMapping(path = "/registration.lti")
//public String register(HttpServletRequest request) {
//public String register(@RequestParam("name") String name, @RequestParam("email") String email, ...) {
public String registration(Student student) {
// System.out.println(student.getName());
studentService.registration(student);
return "confirmation.jsp";
}
@RequestMapping(path = "/searching.lti")
//public String register(HttpServletRequest request) {
//public String register(@RequestParam("name") String name, @RequestParam("email") String email, ...) {
public String registration(@RequestParam("email") String email, @RequestParam("password") String password, Map model) {
Student student = studentService.get(email, password);
model.put("student", student);
//System.out.println(student);
return "profile.jsp";
}
@RequestMapping(path = "/sendmail.lti")
public String mail(@RequestParam("email") String email)
{
Sendmail sendmail = new Sendmail();
sendmail.sendmail(email);
//System.out.println(student);
return "reset.jsp";
}
@RequestMapping(path = "/changepwd.lti")
public String change(@RequestParam("password") String password)
{
/*CHANGE PASSWORD KA LOGIC*/
return "reset.jsp";
}
}
|
package com.rest.jwtdemo.Service;
import com.rest.jwtdemo.Model.Document;
import com.rest.jwtdemo.Model.Folder;
import com.rest.jwtdemo.Repository.AuthorityRepository;
import com.rest.jwtdemo.Repository.DocumentAuthorityRepository;
import com.rest.jwtdemo.Repository.DocumentRepository;
import com.rest.jwtdemo.Repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class DocumentServiceImpl implements DocumentService{
Logger log = LoggerFactory.getLogger(DocumentServiceImpl.class);
private final UserRepository userRepository;
private final AuthorityRepository authorityRepository;
private final BCryptPasswordEncoder passwordEncoder;
private final DocumentRepository documentRepository;
private final FolderService folderService;
private final DocumentAuthorityRepository documentAuthorityRepository;
@Autowired
public DocumentServiceImpl(UserRepository userRepository, AuthorityRepository authorityRepository, BCryptPasswordEncoder passwordEncoder, DocumentRepository documentRepository, FolderService folderService, DocumentAuthorityRepository documentAuthorityRepository) {
this.userRepository = userRepository;
this.authorityRepository = authorityRepository;
this.passwordEncoder = passwordEncoder;
this.documentRepository = documentRepository;
this.folderService = folderService;
this.documentAuthorityRepository = documentAuthorityRepository;
}
public List<Document> getAllDocuments() {
List<Document> result = documentRepository.findAll();
log.info("IN getAllDocuments - {} documents found", result.size());
return result;
}
public List<Document> getDocumentsByName(String username){
List<Document> result = documentRepository.findByUserName(username);
log.info("IN getDocumentsByName - document: {} found by username: {}", result, username);
return result;
}
public Document findByFileName(String name){
Document result = documentRepository.findByFileName(name);
log.info("IN findByFileName - document: {} found by name: {}", result, name);
return result;
}
@Transactional
@Override
public void deleteByFileName(String name) {
documentAuthorityRepository.deleteByFileName(name);
documentRepository.deleteByFileName(name);
log.info("IN delete - document with name: {} successfully deleted", name);
}
}
|
/****************************************************
* $Project: DinoAge $
* $Date:: Jan 27, 2008 2:14:06 AM $
* $Revision: $
* $Author:: khoanguyen $
* $Comment:: $
**************************************************/
package org.ddth.blogging.api;
public abstract class BasicBlogAPI implements BlogAPI {
private String author;
private String password;
private String blogURL;
public String getAuthor() {
return author;
}
public String getPassword() {
return password;
}
public String getBlogURL() {
return blogURL;
}
public void setup(String blogURL, String author, String password) {
this.blogURL = blogURL;
this.author = author;
this.password = password;
}
}
|
package com.plapp.entities.messaging;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.plapp.entities.greenhouse.Plant;
import java.io.Serializable;
import java.util.Date;
public class ScheduleActionMQDTO implements Serializable {
@JsonUnwrapped
private Plant plant;
private String action;
private Date date;
private int periodicity;
private String additionalInfo;
public ScheduleActionMQDTO(){}
public ScheduleActionMQDTO(Plant plant, String action, Date date, int periodicity, String additionalInfo){
this.plant = plant;
this.action = action;
this.date = date;
this.periodicity = periodicity;
this.additionalInfo = additionalInfo;
}
public Plant getPlant() {
return plant;
}
public void setPlant(Plant plant) {
this.plant = plant;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getPeriodicity() {
return periodicity;
}
public void setPeriodicity(int periodicity) {
this.periodicity = periodicity;
}
public String getAdditionalInfo() {
return additionalInfo;
}
public void setAdditionalInfo(String additionalInfo) {
this.additionalInfo = additionalInfo;
}
@Override
public String toString() {
return "ScheduleActionMQDTO{" +
"plant=" + plant +
", action='" + action + '\'' +
", date=" + date +
", periodicity=" + periodicity +
", additionalInfo='" + additionalInfo + '\'' +
'}';
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred;
import java.io.IOException;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.fs.FileSystem;
/**
* <code>InputFormat</code> describes the input-specification for a
* Map-Reduce job.
*
* <p>The Map-Reduce framework relies on the <code>InputFormat</code> of the
* job to:<p>
* <ol>
* <li>
* Validate the input-specification of the job.
* <li>
* Split-up the input file(s) into logical {@link InputSplit}s, each of
* which is then assigned to an individual {@link Mapper}.
* </li>
* <li>
* Provide the {@link RecordReader} implementation to be used to glean
* input records from the logical <code>InputSplit</code> for processing by
* the {@link Mapper}.
* </li>
* </ol>
*
* <p>The default behavior of file-based {@link InputFormat}s, typically
* sub-classes of {@link FileInputFormat}, is to split the
* input into <i>logical</i> {@link InputSplit}s based on the total size, in
* bytes, of the input files. However, the {@link FileSystem} blocksize of
* the input files is treated as an upper bound for input splits. A lower bound
* on the split size can be set via
* <a href="{@docRoot}/../mapred-default.html#mapreduce.input.fileinputformat.split.minsize">
* mapreduce.input.fileinputformat.split.minsize</a>.</p>
*
* <p>Clearly, logical splits based on input-size is insufficient for many
* applications since record boundaries are to respected. In such cases, the
* application has to also implement a {@link RecordReader} on whom lies the
* responsibilty to respect record-boundaries and present a record-oriented
* view of the logical <code>InputSplit</code> to the individual task.
*
* @see InputSplit
* @see RecordReader
* @see JobClient
* @see FileInputFormat
* @deprecated Use {@link org.apache.hadoop.mapreduce.InputFormat} instead.
*/
@Deprecated
@InterfaceAudience.Public
@InterfaceStability.Stable
public interface InputFormat<K, V> {
/**
* Logically split the set of input files for the job.
*
* <p>Each {@link InputSplit} is then assigned to an individual {@link Mapper}
* for processing.</p>
*
* <p><i>Note</i>: The split is a <i>logical</i> split of the inputs and the
* input files are not physically split into chunks. For e.g. a split could
* be <i><input-file-path, start, offset></i> tuple.
*
* @param job job configuration.
* @param numSplits the desired number of splits, a hint.
* @return an array of {@link InputSplit}s for the job.
*/
InputSplit[] getSplits(JobConf job, int numSplits) throws IOException;
/**
* Get the {@link RecordReader} for the given {@link InputSplit}.
*
* <p>It is the responsibility of the <code>RecordReader</code> to respect
* record boundaries while processing the logical split to present a
* record-oriented view to the individual task.</p>
*
* @param split the {@link InputSplit}
* @param job the job that this split belongs to
* @return a {@link RecordReader}
*/
RecordReader<K, V> getRecordReader(InputSplit split,
JobConf job,
Reporter reporter) throws IOException;
}
|
package com.peng.pp_app_sdk.common;
import android.os.Environment;
/**
* Created on 2015/12/10 0010.
* Author wangpengpeng
* Email 1678173987@qq.com
* Description 专门用来定义常量
*/
public class Constants {
public static final int handler_base = 0x100;
public static final String ACTION_PUSH_DATA = "fm.data.push.action";
public static final String ACTION_NEW_VERSION = "apk.update.action";
public static final String ACTION_MY = "android.intent.action.MYBROADCAST";
public static final String FILE_PATH_ROOT = Environment.getExternalStorageDirectory().getPath();//根目录路径
public static String APP_NAME = "";//APP 名称
public static final String IS_FIRST_LIST = "IS_FIRST_LIST";
public static final String IS_FIRST = "IS_FIRST";//第一次
public static final String DEVICE_ID = "DEVICE_ID";//设备id
public static final String EMULATOR_DEVICE_ID = "EMULATOR_DEVICE_ID";//设备id
public static final String VERSION_NUMBER = "VERSION_NUMBER";//版本号
public static final int DEFAULT_MAX_CONNECTIONS = 10;//默认最大连接
public static final String BIGPICS = "BIGPICS";//大图片
public static final String BIGPICS_POSITON = "BIGPICS_POSITON";//大图片位置
public static final boolean IS_DEBUG = true;//是否debug
}
|
package com.lcz.register.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.lcz.register.entity.User;
import com.lcz.register.utils.DbUtils;
public class UserDaoImpl implements UserDao{
public void register(User user) {
//注册用户的操作,将用户信息存入数据库中
Connection conn = null;
try {
conn=DbUtils.getConnection();
String sql ="insert into user(username,email,password,state,code) values(?,?,?,?,?)";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1, user.getUserName());
ps.setString(2, user.getEmail());
ps.setString(3, user.getPassword());
ps.setInt(4, user.getState());
ps.setString(5, user.getCode());
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
DbUtils.close(conn);
}
}
//根据激活码查询用户的方法
public User findByCode(String code) {
Connection conn = null;
User user=null;
try {
conn=DbUtils.getConnection();
String sql="select *from user where code=?";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1, code);
ResultSet rs = ps.executeQuery();;
user=new User();
while(rs.next()) {
user.setId(rs.getInt("id"));
user.setUserName(rs.getString("username"));
user.setEmail(rs.getString("email"));
user.setPassword(rs.getString("password"));
user.setState(rs.getInt("state"));
user.setCode(rs.getString("code"));
return user;
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("查询失败");
}finally {
DbUtils.close(conn);
}
return user;
}
//查找到激活码后,更新数据库中的表
public void update(User user) {
Connection conn = null;
try {
conn=DbUtils.getConnection();
String sql="update user set state=1 where id=?";
PreparedStatement ps=conn.prepareStatement(sql);
// ps.setString(1, user.getUserName());
// ps.setString(2, user.getPassword());
// ps.setString(3, user.getEmail());
// ps.setInt(4, user.getState());
// ps.setString(5, user.getCode());
ps.setInt(1, user.getId());
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
System.out.println("更新失败");
}finally {
DbUtils.close(conn);
}
}
//登录
public User login(User user){
User loginUser = null;
Connection conn = null;
PreparedStatement ps = null;
try{
conn = DbUtils.getConnection();
String sql = "select * from user where email=? and password=?";
ps = conn.prepareStatement(sql);
ps.setString(1,user.getEmail());
ps.setString(2,user.getPassword());
ResultSet rs = ps.executeQuery();
if(rs.next()){
loginUser = new User();
loginUser.setEmail(rs.getString("email"));
loginUser.setPassword(rs.getString("password"));
}
} catch (SQLException e){
e.printStackTrace();
} finally {
DbUtils.close(conn);
}
return loginUser;
}
}
|
package com.company;
import java.io.*;
/**
* 创建文件的规则是在 BufferWriter.java的package的父目录 也就是 com 文件夹的父目录(src 下面)
*/
public class BufferWriter {
public static void main(String[] args) throws IOException {
// write your code here
File file = new File("test.txt");
//file.mkdirs();
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
bufferedWriter.write("I am test");
bufferedWriter.close();
System.out.println("File created successful!");
}
}
|
package sort.shell;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/*
* description:
* author: W W
* date:2019-07-02 14:30
* */
public class ShellSort {
public static void main(String[] args) {
int[] array={5, 4, 3, 1, 2, 6, 7, 8, 9};
sort(array);
System.out.println(Arrays.toString(array));
}
/**
* 希尔排序法(ShellSort)
* 主要思想:让相隔[增量]之间的元素有序,逐步缩小[增量],使得数组逐步有序(因为趋近有序,所以不会像插入排序那样频繁的移动数据)
* 时间复杂度: 最好情况为:已经有序,O(n)
* 最坏的情况为:希尔增量----O(n^2),Hibbard增量()----O(n^(3/2))
* 平均情况:O(n^1.5)
*
* @param array 待排序数组
* @return
* @author W W
* @date 2019-07-04 14:34:29
*/
public static void sort(int[] array){
final int length=array.length;
//初始分为三个局部
//目前主流的两个增量策略为: 希尔增量序列公式=n/2 ,最坏O(n^2)
// Hibbard增量序列公式=(len + 1)/ 2 - 1 ,最坏O(n^(3/2))
int increment=(length + 1)/ 2 - 1;
while (increment>0){
//内部其实就是一个插入排序。(多个组的数据做插入排序)
for(int i= increment;i<length;i++){
//临时存放待排序的值
int temp=array[i];
int j=i;
while (j>=increment && temp<array[j-increment]){
array[j]=array[j-increment];
j-=increment;
}
//插入
array[j]=temp;
}
increment= (increment + 1)/ 2 - 1;
}
}
}
|
package com.komaxx.komaxx_gl;
/**
* Important interface to process interaction.
*
* @author Matthias Schicker
*/
public interface ICameraInfoProvider {
/**
* Translates a point on the screen to world coordinates on the z==0 plane.
*
* @param result the result in world coordinates ([x,y,0]).
* <b>MUST NOT</b> be the inputvector pixelXY.
* @param pixelXY the point on the screen.
*/
void pixel2ZeroPlaneCoord(float[] result, float[] pixelXY);
}
|
package MiniNet;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DataBase {
/**
* @param args
*/
public DataBase(){
try {
//加载HSQLDB数据库JDBC驱动
Class.forName("org.hsqldb.jdbcDriver");
//在内存中建立临时数据库score,用户名为sa,密码为空
@SuppressWarnings("unused")
Connection connect = DriverManager.getConnection("jdbc:hsqldb:file:db/file;shutdown=true", "sa", "");
System.out.println("Link is OK!");
Statement state = connect.createStatement();
state.executeUpdate("drop table children if exists");
state.executeUpdate("create table children (Name VARCHAR(20), Image VARCHAR(20),Status VARCHAR(20),Age VARCHAR(20),Gender VARCHAR(20),states VARCHAR(20))");
System.out.println("Create is OK!");
state.executeUpdate("Insert into children (Name, Image,Status,Gender,Age,states) Values('Alex Smith', '', 'student at RMIT', 'M', 21, 'WA')");
state.executeUpdate("Insert into children (Name, Image,Status,Gender,Age,states) Values('Ben Turner', '“BenPhoto.jpg”', '“manager at Coles”', 'M', '35', 'VIC')");
state.executeUpdate("Insert into children (Name, Image,Status,Gender,Age,states) Values('Hannah White', '“Hannah.png”', '“student at PLC”', 'F', '14', 'VIC')");
state.executeUpdate("Insert into children (Name, Image,Status,Gender,Age,states) Values('Zoe Foster','“”', '“Founder of ZFX”', 'F', '28', 'VIC')");
state.executeUpdate("Insert into children (Name, Image,Status,Gender,Age,states) Values('Mark Turner', '“Mark.jpeg”', '“”', 'M', '2', 'VIC')");
System.out.println("Insert is OK!");
PreparedStatement pstmt2 = connect.prepareStatement("select * from children");
ResultSet rs = pstmt2.executeQuery();
while(rs.next()){
String x;
x = rs.getString(1) + " " + rs.getString(2)+ " " + rs.getString(3)+ " " + rs.getString(4)+ " " + rs.getString(5)+ " " + rs.getString(6);
System.out.println(x);
}
System.out.println("Select is OK!");
pstmt2.close();
rs.close();
state.close();
connect.close();
} catch (SQLException e){
e.printStackTrace();
} catch (ClassNotFoundException e){
e.printStackTrace();
}
}
}
|
package com.zzh.user.po;
import com.zzh.common.model.BaseModel;
/**
* @author ZengZhiHang
* @create 2019-04-22-16:41
*/
public class UserBean extends BaseModel {
private String mobile;
private String password;
public String getMoblie() {
return mobile;
}
public void setMoblie(String moblie) {
this.mobile = moblie;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
|
package dominio;
/**
* establece los personajes no manejables por el jugador (NPCs) y sus
* estadisticas y atributos
*
*/
public class NonPlayableCharacter extends Character implements Peleable {
private static final int DIFICULTADALEATORIA = -1;
private static final double EVITARATAQUE = 0.15;
private static final double DANIOATAQUE = 1.5;
private static final int EXPERIENCIAPORNIVEL = 30;
private static final int DIFERENTESDIFICULTADES = 3;
private static final int FUERZABASE1 = 10;
private static final int SALUDBASE1 = 30;
private static final int DEFENSABASE1 = 2;
private static final int AUMENTOFUERZA1 = 3;
private static final int AUMENTOSALUD1 = 15;
private static final int AUMENTODEFENSA1 = 1;
private static final int FUERZABASE2 = 20;
private static final int SALUDBASE2 = 40;
private static final int DEFENSABASE2 = 5;
private static final int AUMENTOFUERZA2 = 6;
private static final int AUMENTOSALUD2 = 20;
private static final int AUMENTODEFENSA2 = 2;
private static final int FUERZABASE3 = 30;
private static final int SALUDBASE3 = 50;
private static final int DEFENSABASE3 = 4;
private static final int AUMENTOFUERZA3 = 10;
private static final int AUMENTOSALUD3 = 25;
private static final int AUMENTODEFENSA3 = 4;
/**
* Establece un personaje no jugable con determinados atributos basados en
* la dificultad elegida
* @param nombre Nombre del personaje
* @param nivel Nivel del personaje
* @param dificultadNPC Dificultad del NPC
* @param random Numero random para esquivar el ataque
*/
public NonPlayableCharacter(final String nombre, final int nivel,
final int dificultadNPC, final RandomGenerator random) {
super(0, 0, 0, nombre, nivel);
int dificultad;
if (dificultadNPC == DIFICULTADALEATORIA) {
dificultad = random.nextInt(DIFERENTESDIFICULTADES);
} else {
dificultad = dificultadNPC;
}
if (dificultad == 0) {
this.setFuerza(FUERZABASE1 + (nivel - 1) * AUMENTOFUERZA1);
this.setSalud(SALUDBASE1 + (nivel - 1) * AUMENTOSALUD1);
this.setDefensa(DEFENSABASE1 + (nivel - 1) * AUMENTODEFENSA1);
} else {
if (dificultad == 1) {
this.setFuerza(FUERZABASE2 + (nivel - 1) * AUMENTOFUERZA2);
this.setSalud(SALUDBASE2 + (nivel - 1) * AUMENTOSALUD2);
this.setDefensa(DEFENSABASE2 + (nivel - 1) * AUMENTODEFENSA2);
} else {
this.setFuerza(FUERZABASE3 + (nivel - 1) * AUMENTOFUERZA3);
this.setSalud(SALUDBASE3 + (nivel - 1) * AUMENTOSALUD3);
this.setDefensa(DEFENSABASE3 + (nivel - 1) * AUMENTODEFENSA3);
}
}
}
/**
* Devuelve la experiencia que necesita por nivel * 30
* @return int Expeciencia por nivel
*/
public int otorgarExp() {
return this.getNivel() * EXPERIENCIAPORNIVEL;
}
/**
* permite un ataque del personaje no jugable contra otro personaje
* @param atacado Peleable que realiza el ataque
* @param random Numero random para esquivar el ataque
* @return int Del valor del danio realizado
*/
public int atacar(final Peleable atacado, final RandomGenerator random) {
if (random.nextDouble() <= EVITARATAQUE) {
return atacado.serAtacado((int) (this.getAtaque() * DANIOATAQUE), random);
} else {
return atacado.serAtacado(this.getAtaque(), random);
}
}
/**
* reduce la salud del personaje no jugable cuando es atacado y
* devuelve el dano recibido, o devuelve cero si esquivo el golpe o su
* defensa es mayor que el dano del atacante
* @param danio El danio que hacer el atacante
* @param random Numero random para evitar el ataque
* @return danio devuelve el danio realizado
*/
public int serAtacado(final int danio, final RandomGenerator random) {
if (random.nextDouble() >= EVITARATAQUE) {
int auxdanio = danio;
auxdanio -= this.getDefensa() / 2;
if (auxdanio > 0) {
this.setSalud(this.getSalud() - auxdanio);
return auxdanio;
}
return 0;
}
return 0;
}
/**
* Aumento de experiencia recibido por parametro
* @param exp Aumenta la Experiencia
*/
public void ganarExperiencia(final int exp) {
}
/**
* devuelve el valor del atributo "fuerza"
* @return fuerza Devuelve la fuerza como int
*/
@Override
public int getAtaque() {
return this.getFuerza();
}
/**
* establece un valor para el atributo "ataque"
* @param ataque Es el atributo de ataque
*/
@Override
public void setAtaque(final int ataque) {
this.setFuerza(ataque);
}
@Override
public void serCurado(final int puntosDeMagia) {
}
@Override
public int serDesernegizado(final int danio) {
return 0;
}
@Override
public int serRobadoSalud(final int danio) {
return 0;
}
/**
* Determina si es un NonPlayableCharacter
* @return boolean Devuelve True siempre
*/
public boolean isNPC() {
return true;
}
}
|
class hello.java
{
}
|
package com.app.firefighter;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseUser;
/**
* A simple {@link Fragment} subclass.
*/
public class StartupLoginFragment extends Fragment {
//locate variable
protected EditText email,password;
Button LoginIn;
public StartupLoginFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.fragment_startup_login, container, false);
email = (EditText)v.findViewById(R.id.startupEmail);
password = (EditText)v.findViewById(R.id.startupPassword);
LoginIn = (Button)v.findViewById(R.id.startupLogin);
//LoginIn button click listener
LoginIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String Email = email.getText().toString().trim();
String Password = password.getText().toString().trim();
if (Email.isEmpty() || Password.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Oops!!!")
.setMessage("Email Id and Password is not match")
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
} else {
ParseUser.logInInBackground(Email, Password, new LogInCallback() {
@Override
public void done(ParseUser parseUser, ParseException e) {
if (e == null) {
Intent intent = new Intent(getActivity(), StartupHomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
getActivity().finish();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Oops!").setMessage(e.getMessage())
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
return v;
}
}
|
package com.yoeki.kalpnay.hrporatal.Survey;
public class QuestionModel{
String question;
String question1;
String questionunread;
String questioncount;
String answeredquestin;
String question2;
public String getQuestioncount() {
return questioncount;
}
public void setQuestioncount(String questioncount) {
this.questioncount = questioncount;
}
public String getAnsweredquestin() {
return answeredquestin;
}
public void setAnsweredquestin(String answeredquestin) {
this.answeredquestin = answeredquestin;
}
public String getQuestion2() {
return question2;
}
public void setQuestion2(String question2) {
this.question2 = question2;
}
public String getQuestion1() {
return question1;
}
public void setQuestion1(String question1) {
this.question1 = question1;
}
public String getQuestionunread() {
return questionunread;
}
public void setQuestionunread(String questionunread) {
this.questionunread = questionunread;
}
public String getQuestion(){
return question;
}
public void setQuestion(String question){
this.question = question;
}
}
|
package com.cloudogu.smeagol;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.apereo.cas.client.authentication.AttributePrincipal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.util.Base64;
import java.util.Map;
import java.util.Objects;
import static com.cloudogu.smeagol.ScmHttpClient.createRestTemplate;
/**
* Util methods to get the authenticated {@link Account} from current request.
*
* @author Sebastian Sdorra
*/
@Service
public class AccountService {
private static final Logger LOG = LoggerFactory.getLogger(AccountService.class);
private final ObjectFactory<HttpServletRequest> requestFactory;
private final String scmUrl;
private final RestTemplate scmRestTemplate;
// For local development purposes only
private final String accessKey;
private static final String ACCESS_TOKEN_ENDPOINT = "/api/v2/cas/auth/";
@Autowired
public AccountService(ObjectFactory<HttpServletRequest> requestFactory, RestTemplateBuilder restTemplateBuilder,
@Value("${scm.accessKey:#{null}}") String accessKey,
@Value("${scm.url}") String scmUrl, Stage stage) {
this.scmRestTemplate = createRestTemplate(restTemplateBuilder, stage, scmUrl);
this.requestFactory = requestFactory;
this.scmUrl = scmUrl;
// For local development purposes only
this.accessKey = accessKey;
}
/**
* Retrieves the current account from the request. The method uses the stored cas account to build an
* {@link Account} object, uses cas proxy ticket to fetch an access token from the scm server and caches the result in the
* current user session.
*
* @return current authenticated account
*/
public Account get() {
HttpServletRequest request = requestFactory.getObject();
HttpSession session = request.getSession(true);
Account account = (Account) session.getAttribute(Account.class.getName());
if (account != null) {
boolean shouldRefetch = true;
try {
shouldRefetch = shouldRefetchToken(account.getAccessToken());
} catch (Exception e) {
LOG.warn("could not determine whether access token should be refreshed: ", e);
}
if (!shouldRefetch) {
return account;
}
}
account = getNewAccount(request);
session.setAttribute(Account.class.getName(), account);
return account;
}
private Account getNewAccount(HttpServletRequest request) {
Account account;
AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal();
if (principal == null) {
throw new AuthenticationException("could not find principal in request");
}
String accessToken = getAccessToken(principal);
Map<String, Object> attributes = principal.getAttributes();
account = new Account(
Objects.toString(attributes.get("username")),
accessToken,
Objects.toString(attributes.get("displayName")),
Objects.toString(attributes.get("mail"))
);
return account;
}
private String getAccessToken(AttributePrincipal principal) {
// Should be used in local development only
if (this.accessKey != null){
return this.accessKey;
}
String accessTokenEndpointURL = getAccessTokenEndpoint();
String pt = principal.getProxyTicketFor(accessTokenEndpointURL);
if (Strings.isNullOrEmpty(pt)) {
throw new AuthenticationException("could not get proxy ticket for scm access token endpoint");
}
return fetchSCMAccessToken(ACCESS_TOKEN_ENDPOINT, pt);
}
private String getAccessTokenEndpoint() {
String accessEndpointURL = scmUrl;
if (accessEndpointURL.endsWith("/")) {
accessEndpointURL = accessEndpointURL.substring(0, accessEndpointURL.length() - 1);
}
return accessEndpointURL.concat(ACCESS_TOKEN_ENDPOINT);
}
private String fetchSCMAccessToken(String url, String proxyTicket) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<String> request = new HttpEntity<>("ticket=" + proxyTicket, headers);
String accessToken = this.scmRestTemplate.postForObject(url, request, String.class);
if (Strings.isNullOrEmpty(accessToken)) {
throw new AuthenticationException("could not get accessToken from scm endpoint");
}
return accessToken;
}
protected static boolean shouldRefetchToken(String jwt) throws IOException {
String[] chunks = jwt.split("\\.");
Base64.Decoder decoder = Base64.getDecoder();
String payload = new String(decoder.decode(chunks[1]));
ObjectMapper mapper = new ObjectMapper();
SCMJwt scmJwt = mapper.readValue(payload, SCMJwt.class);
long currentUnixTime = System.currentTimeMillis() / 1000L;
return scmJwt.exp - currentUnixTime < 60;
}
@JsonIgnoreProperties(ignoreUnknown = true)
static class SCMJwt {
private long exp;
public void setExp(long exp) {
this.exp = exp;
}
}
}
|
package com.zpjr.cunguan.presenter.impl.investment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zpjr.cunguan.action.action.investment.IPMDInfoAction;
import com.zpjr.cunguan.action.impl.investment.PMDInfoActionImpl;
import com.zpjr.cunguan.adapter.PMDInfoImgAdapter;
import com.zpjr.cunguan.common.retrofit.PresenterCallBack;
import com.zpjr.cunguan.common.utils.SnackbarUtil;
import com.zpjr.cunguan.entity.module.LoanImagesModule;
import com.zpjr.cunguan.entity.module.LoanModule;
import com.zpjr.cunguan.presenter.presenter.investment.IPMDInfoPresenter;
import com.zpjr.cunguan.ui.activity.investment.PMDInfoFragment;
import com.zpjr.cunguan.ui.activity.investment.PreviewImgActivity;
import com.zpjr.cunguan.view.investment.IPMDInfoView;
import java.util.List;
/**
* Description: 更多详情--项目信息接presenter
* Autour: LF
* Date: 2017/7/19 11:14
*/
public class PMDInfoPresenterImpl implements IPMDInfoPresenter, PresenterCallBack {
private IPMDInfoView mView;
private IPMDInfoAction mAction;
private LoanImagesModule mModule;
public PMDInfoPresenterImpl(IPMDInfoView view) {
this.mView = view;
this.mAction = new PMDInfoActionImpl();
}
@Override
public void getCompanyImg(String loanId) {
mAction.getCompanyImg(loanId, this);
}
@Override
public void webViewInitialByContent(WebView webView, String content) {
webView.loadDataWithBaseURL(null, content, "text/html", "utf-8", null);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
webView.getSettings().setDefaultFontSize(14);
webView.setWebChromeClient(new WebChromeClient());
}
@Override
public void clearWebView(WebView... webViews) {
for (WebView view : webViews) {
if (view != null) {
view.removeAllViews();
view.destroy();
}
}
}
@Override
public void onSuccess(Object result) {
mModule = JSON.parseObject(result.toString(), LoanImagesModule.class);
if (mModule.isSuccess()) {
List<LoanImagesModule.DataBean.IMAGEBean> list = mModule.getData().getIMAGE();
//设置布局管理器
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mView.getContext());
linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
mView.getRecyclerView().setLayoutManager(linearLayoutManager);
//设置适配器
PMDInfoImgAdapter adapter = new PMDInfoImgAdapter(mView.getContext(), list, mView.getRecyclerView());
mView.getRecyclerView().setAdapter(adapter);
} else {
SnackbarUtil.ShortSnackbar(mView.getActivityView(), mModule.getErrorMessage(), SnackbarUtil.INFO).show();
}
}
@Override
public void onFail(String errMsg) {
SnackbarUtil.ShortSnackbar(mView.getActivityView(), errMsg, SnackbarUtil.INFO).show();
}
}
|
package model;
public class Donor {
private String User_email;
private String Name;
private String Address;
private String Mobile_Number;
public Donor(String user_email, String name, String address, String mobile_Number) {
super();
User_email = user_email;
Name = name;
Address = address;
Mobile_Number = mobile_Number;
}
public String getUser_email() {
return User_email;
}
public void setUser_email(String user_email) {
User_email = user_email;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getMobile_Number() {
return Mobile_Number;
}
public void setMobile_Number(String mobile_Number) {
Mobile_Number = mobile_Number;
}
}
|
package com.bluemingo.bluemingo.persistence;
import org.springframework.stereotype.Repository;
import com.bluemingo.bluemingo.domain.AdvVO;
import com.bluemingo.bluemingo.domain.Ref_listVO;
import com.bluemingo.bluemingo.generic.GenericDAOImpl;
/** Last Edit 2017-02-12
* RefListVO - RefListDAO - RefListService - RefListController
* product-item
* item-option
* reservation-deliver
*/
@Repository("ref_listDao")
public class Ref_listDAOImpl extends GenericDAOImpl<Ref_listVO, Integer> implements Ref_listDAO{
public Ref_listDAOImpl() {
super(Ref_listVO.class);
}
}
|
package bank;
class Friend{
public static void main(String[] args){
Account acc=new Account();
//System.out.println("친구의 조작 전 잔고는 "+acc.balance);
//acc.balance=acc.balance+8000;
//변수에 대한, 직접 접근을 하지말고, 메서드 호출로 데이터를 변경해보자!
acc.setBalance(150000);
System.out.println("친구의 조작 후 잔고는 "+acc.getBalance());
//현재 Friend클래스는 Account와 같은 패키지에 있으므로, Account가 보유한
//default 접근제한이 걸려있는 모든 변수에 맘대로 접근이 가능하다!
System.out.println("은행명 : "+acc.bankName);
System.out.println("계좌주 : "+acc.master);
System.out.println("계좌번호 : "+acc.num);
}
}
|
package com.tencent.mm.ui.base.preference;
import android.view.View;
import android.view.View.OnClickListener;
class InputPreference$1 implements OnClickListener {
final /* synthetic */ InputPreference tCy;
InputPreference$1(InputPreference inputPreference) {
this.tCy = inputPreference;
}
public final void onClick(View view) {
if (InputPreference.a(this.tCy) != null && InputPreference.b(this.tCy) != null && InputPreference.b(this.tCy).getText() != null) {
InputPreference.b(this.tCy).getText().toString();
}
}
}
|
package helloworld.lifeline.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import helloworld.lifeline.misc.Logger;
import helloworld.lifeline.model.UserModel;
import helloworld.lifeline.service.IUserService;
import inti.ws.spring.exception.client.BadRequestException;
@RestController
@RequestMapping(value = "/user")
@ComponentScan("helloworld.lifeline.service")
public class UserController {
private static final Logger logger = Logger.getInstance(DonationCampController.class);
@Autowired
private IUserService userService;
/***
* Returns the user associated with userId @param id
*
* @param id
* @return
* @throws BadRequestException
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public UserModel getByID(@PathVariable("id") int id) throws BadRequestException {
logger.info("Request for geting a user with given id started");
UserModel model = userService.getByID(id);
logger.info("Request for geting a user with given id ended successfully");
return model;
}
/****
* Creates a User @param user in the records.
*
* @param user
*/
@RequestMapping(value = "/save", method = RequestMethod.POST)
@ResponseBody
@ResponseStatus(HttpStatus.CREATED)
public void create(@RequestBody UserModel user) {
logger.info("Request for saving a user started");
userService.create(user);
logger.info("Request for saving a user started ended successfully");
}
}
|
package iks;
import java.util.ArrayList;
import java.util.List;
/**
* Created by kiiv0317 on 19.12.2017.
*/
public class Application {
public static void main(String[] args) {
List lst = new ArrayList<>();
lst.add("sdfdf");
lst.add("sqwedf");
}
}
|
package com.tencent.d.a.c;
import junit.framework.Assert;
public final class c {
private static b vlw = new a((byte) 0);
public static void a(b bVar) {
Assert.assertTrue(bVar != null);
vlw = bVar;
}
public static void v(String str, String str2, Object... objArr) {
vlw.v(str, str2, objArr);
}
public static void d(String str, String str2, Object... objArr) {
vlw.d(str, str2, objArr);
}
public static void i(String str, String str2, Object... objArr) {
vlw.i(str, str2, objArr);
}
public static void w(String str, String str2, Object... objArr) {
vlw.w(str, str2, objArr);
}
public static void e(String str, String str2, Object... objArr) {
vlw.e(str, str2, objArr);
}
public static void a(String str, Throwable th, String str2) {
vlw.a(str, th, str2);
}
}
|
package com.kunsoftware.service;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.kunsoftware.bean.ProductPriceTplRequestBean;
import com.kunsoftware.entity.FlightChedule;
import com.kunsoftware.entity.FlightChedulePrice;
import com.kunsoftware.entity.ProductPriceTpl;
import com.kunsoftware.exception.KunSoftwareException;
import com.kunsoftware.mapper.FlightCheduleMapper;
import com.kunsoftware.mapper.FlightChedulePriceMapper;
import com.kunsoftware.mapper.ProductPriceTplMapper;
@Service
public class ProductPriceTplService {
private static Logger logger = LoggerFactory.getLogger(ProductPriceTplService.class);
@Autowired
private ProductPriceTplMapper mapper;
@Autowired
private FlightCheduleMapper flightCheduleMapper;
@Autowired
private FlightChedulePriceMapper flightChedulePriceMapper;
public List<ProductPriceTpl> getProductPriceTplListAll(Integer flightId) {
logger.info("query");
return mapper.getProductPriceTplListAll(flightId);
}
@Transactional
public ProductPriceTpl insert(ProductPriceTplRequestBean requestBean) throws KunSoftwareException {
ProductPriceTpl record = new ProductPriceTpl();
BeanUtils.copyProperties(requestBean, record);
mapper.insert(record);
return record;
}
public ProductPriceTpl selectByPrimaryKey(Integer id) throws KunSoftwareException {
return mapper.selectByPrimaryKey(id);
}
@Transactional
public int updateByPrimaryKey(ProductPriceTplRequestBean requestBean,Integer id) throws KunSoftwareException {
ProductPriceTpl record = mapper.selectByPrimaryKey(id);
BeanUtils.copyProperties(requestBean, record);
return mapper.updateByPrimaryKeySelective(record);
}
@Transactional
public int deleteByPrimaryKey(Integer id) throws KunSoftwareException {
return mapper.deleteByPrimaryKey(id);
}
@Transactional
public void deleteByPrimaryKey(Integer[] id) throws KunSoftwareException {
for(int i = 0;i < id.length;i++) {
mapper.deleteByPrimaryKey(id[i]);
}
}
@Transactional
public void createFlightChedulePrice(Integer id) throws KunSoftwareException {
ProductPriceTpl productPriceTpl = mapper.selectByPrimaryKey(id);
createFlightChedulePrice(productPriceTpl);
}
@Transactional
public void createFlightChedulePrice(ProductPriceTpl productPriceTpl) throws KunSoftwareException {
Integer productResourceId = productPriceTpl.getProductResourceId();
Integer productPriceTplId = productPriceTpl.getId();
Integer flightCheduleId;
FlightChedulePrice flightCheduleprice = null;
List<FlightChedule> list = flightCheduleMapper.selectAuditFlightChedule(productResourceId);
Integer id = null;
for(FlightChedule flightChedule:list) {
flightCheduleId = flightChedule.getId();
flightCheduleprice = flightChedulePriceMapper.selectByFlightCheduleId(flightCheduleId, productPriceTplId);
if(flightCheduleprice == null) {
flightCheduleprice = new FlightChedulePrice();
id = null;
} else {
id = flightCheduleprice.getId();
}
BeanUtils.copyProperties(productPriceTpl, flightCheduleprice);
flightCheduleprice.setId(id);
flightCheduleprice.setFlightCheduleId(flightCheduleId);
flightCheduleprice.setProductPriceTplId(productPriceTplId);
if(flightCheduleprice.getId() == null) {
flightChedulePriceMapper.insert(flightCheduleprice);
} else {
flightChedulePriceMapper.updateByPrimaryKeySelective(flightCheduleprice);
}
}
}
}
|
package com.cisco.jwt_spring_boot.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public class CredentialsException extends RuntimeException {
public CredentialsException(String msg) {
super(msg);
}
}
|
package cbde.labs.hbase_mapreduce.reader;
public class MyHBaseReader_VerticalPartitioning extends MyHBaseReader {
protected String[] scanFamilies() {
String[] families = {"fam_1","fam_2"};
return families;
}
}
|
package co.th.aten.network.web;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import org.jboss.seam.international.status.Messages;
import org.jboss.solder.logging.Logger;
import co.th.aten.network.control.CustomerControl;
import co.th.aten.network.entity.MemberCustomer;
import co.th.aten.network.entity.TransactionMoney;
import co.th.aten.network.i18n.AppBundleKey;
import co.th.aten.network.producer.DBDefault;
import co.th.aten.network.security.CurrentUserManager;
import co.th.aten.network.util.StringUtil;
@ViewScoped
@Named
public class MoneyAddAndDeductController implements Serializable {
private static final long serialVersionUID = 1L;
@Inject
private Logger log;
@Inject
@DBDefault
private EntityManager em;
@Inject
private CurrentUserManager currentUser;
@Inject
private FacesContext facesContext;
@Inject
private CustomerControl customerControl;
@Inject
private Messages messages;
private MemberCustomer memberSearch;
private Date newDate;
private String memberCode;
private String memberName;
private Double deductMoney;
private Double addMoney;
private String remark;
@PostConstruct
public void init(){
log.info("init method MoneyAddAndDeductController");
newDate = new Date();
memberSearch = null;
memberCode = "";
memberName = "";
deductMoney = null;
addMoney = null;
remark = "";
}
public void search(){
try{
memberSearch = null;
if(memberCode!=null && memberCode.length()>0){
memberSearch = (MemberCustomer)em.createQuery("From MemberCustomer Where customerMember =:customerMember ")
.setParameter("customerMember", memberCode).getSingleResult();
memberName = StringUtil.n2b(memberSearch.getTitleName())+StringUtil.n2b(memberSearch.getFirstName())+" "+StringUtil.n2b(memberSearch.getLastName());
}else{
memberName = "";
messages.error(new AppBundleKey("error.label.money.inputMemberCode",FacesContext.getCurrentInstance().getViewRoot().getLocale().getLanguage()));
}
}catch(Exception e){
memberName = "";
log.info("Error : "+e.getMessage());
messages.error(new AppBundleKey("error.label.money.notFoundMemberCode",FacesContext.getCurrentInstance().getViewRoot().getLocale().getLanguage()));
}
}
public void confirmMoney(){
try{
TransactionMoney trxMoney = new TransactionMoney();
trxMoney.setTrxMoneyDatetime(new Date());
trxMoney.setCustomerId(memberSearch.getCustomerId());
if(deductMoney!=null && deductMoney > 0){
trxMoney.setAmount(new BigDecimal(StringUtil.n2b(deductMoney)));
trxMoney.setTrxMoneyStatus(new Integer(1));
}else{
trxMoney.setAmount(new BigDecimal(StringUtil.n2b(addMoney)));
trxMoney.setTrxMoneyStatus(new Integer(2));
}
trxMoney.setTrxMoneyFlag(new Integer(0));
trxMoney.setRemark(remark);
trxMoney.setCreateBy(currentUser.getCurrentAccount().getUserId());
trxMoney.setCreateDate(new Date());
trxMoney.setUpdateBy(currentUser.getCurrentAccount().getUserId());
trxMoney.setUpdateDate(new Date());
double moneyOld = StringUtil.n2b(memberSearch.geteMoney()).doubleValue();
if(deductMoney!=null && deductMoney > 0){
memberSearch.seteMoney(new BigDecimal(moneyOld-StringUtil.n2b(deductMoney)));
}else{
memberSearch.seteMoney(new BigDecimal(moneyOld+StringUtil.n2b(addMoney)));
}
trxMoney.setBalance(memberSearch.geteMoney());
em.persist(trxMoney);
em.merge(memberSearch);
memberSearch = null;
messages.info(new AppBundleKey("info.label.money.success",FacesContext.getCurrentInstance().getViewRoot().getLocale().getLanguage()));
}catch(Exception e){
e.printStackTrace();
messages.error(new AppBundleKey("error.label.money.fail",FacesContext.getCurrentInstance().getViewRoot().getLocale().getLanguage()));
}
}
public Date getNewDate() {
return newDate;
}
public void setNewDate(Date newDate) {
this.newDate = newDate;
}
public String getMemberCode() {
return memberCode;
}
public void setMemberCode(String memberCode) {
this.memberCode = memberCode;
}
public String getMemberName() {
return memberName;
}
public void setMemberName(String memberName) {
this.memberName = memberName;
}
public Double getDeductMoney() {
return deductMoney;
}
public void setDeductMoney(Double deductMoney) {
this.deductMoney = deductMoney;
}
public Double getAddMoney() {
return addMoney;
}
public void setAddMoney(Double addMoney) {
this.addMoney = addMoney;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public MemberCustomer getMemberSearch() {
return memberSearch;
}
public void setMemberSearch(MemberCustomer memberSearch) {
this.memberSearch = memberSearch;
}
}
|
package me.zakeer.justchat.database;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class SqliteHandle extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "maindatabase";
private static String FRIEND_TABLE = "tb_friends" ;
// MAINCAT Table Columns names
private static final String KEY_FRIEND_ID = "f_id";
private static final String KEY_FRIEND_NAME = "f_name";
private static final String KEY_FRIEND_PHONE = "f_phone";
private static final String KEY_FRIEND_IMG = "f_img";
private static final String KEY_FRIEND_CHECKED = "f_checked";
public SqliteHandle(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " + FRIEND_TABLE + "("
+ KEY_FRIEND_ID + " INTEGER PRIMARY KEY,"
+ KEY_FRIEND_NAME + " TEXT,"
+ KEY_FRIEND_PHONE + " TEXT,"
+ KEY_FRIEND_IMG + " TEXT,"
+ KEY_FRIEND_CHECKED + " TEXT" + " )";
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + FRIEND_TABLE);
// Create tables again
onCreate(db);
}
public void insertInFriend(FriendData details) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_FRIEND_ID, details.getFriend_id());
values.put(KEY_FRIEND_NAME, details.getFname());
values.put(KEY_FRIEND_PHONE, details.getPhone());
values.put(KEY_FRIEND_IMG, details.getPic());
values.put(KEY_FRIEND_CHECKED, "0");
// Inserting Row
db.insert(FRIEND_TABLE, null, values);
db.close(); // Closing database connection
}
// Getting All Details
public List<FriendData> getAllFriendDetails() {
List<FriendData> list = new ArrayList<FriendData>();
// Select All Query
String selectQuery = "SELECT * FROM " + FRIEND_TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
FriendData details = new FriendData();
details.setFriend_id(cursor.getString(0));
details.setFname(cursor.getString(1));
details.setPhone(cursor.getString(2));
details.setPic(cursor.getString(3));
String ch=cursor.getString(4);
details.setStatus(ch);
Log.e("", ch);
/* if(ch.equals("0"))
details.setIschecked(false);
else
details.setIschecked(true);
*/ // Adding to list
list.add(details);
} while (cursor.moveToNext());
}
cursor.close();
return list;
}
// Getting All Checked
public List<FriendData> getCheckedFriendDetails() {
List<FriendData> list = new ArrayList<FriendData>();
// Select All Query
String selectQuery = "SELECT * FROM " + FRIEND_TABLE+" WHERE "+KEY_FRIEND_CHECKED+" = '1'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
FriendData details = new FriendData();
details.setFriend_id(cursor.getString(0));
details.setFname(cursor.getString(1));
details.setPhone(cursor.getString(2));
details.setPic(cursor.getString(3));
String ch=cursor.getString(4);
/* if(ch.equals("0"))
details.setIschecked(false);
else
details.setIschecked(true);
*/ // Adding to list
list.add(details);
} while (cursor.moveToNext());
}
cursor.close();
return list;
}
// Getting Count Of All Checked
public int getCheckedCount() {
String count="0";
String selectQuery = "SELECT count(*) FROM " + FRIEND_TABLE+" WHERE "+KEY_FRIEND_CHECKED+" = '1'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
count = cursor.getString(0);
} while (cursor.moveToNext());
}
cursor.close();
int total = Integer.parseInt(count);
return total;
}
// Getting All Details
public void changeCheck(String Stat,String f_id)
{
String selectQuery;
selectQuery = "UPDATE "+FRIEND_TABLE+" SET "+KEY_FRIEND_CHECKED+" = "+"'"+Stat+"'"
+" WHERE "+KEY_FRIEND_ID+" = '"+f_id+"'";
Log.e("QUERY", selectQuery);
SQLiteDatabase db = this.getWritableDatabase();
Cursor cu = db.rawQuery(selectQuery, null);
cu.moveToFirst();
cu.close();
}
public void SelectAll(String Stat)
{
String selectQuery;
selectQuery = "UPDATE "+FRIEND_TABLE+" SET "+KEY_FRIEND_CHECKED+" = "+"'"+Stat+"'";
Log.e("QUERY", selectQuery);
SQLiteDatabase db = this.getWritableDatabase();
Cursor cu = db.rawQuery(selectQuery, null);
cu.moveToFirst();
cu.close();
}
// delete All scan Details
public void deleteAllFriendDetails() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(FRIEND_TABLE, null, null);
}
}
|
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.servlet.admin;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.apache.commons.io.IOUtils;
import org.junit.internal.TextListener;
import org.junit.runner.JUnitCore;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;
import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.openkm.util.WebUtils;
/**
* Unit Testing servlet
*/
public class UnitTestingServlet extends BaseServlet {
private static final long serialVersionUID = 1L;
private static Logger log = LoggerFactory.getLogger(UnitTestingServlet.class);
private static final String[][] breadcrumb = new String[][] { new String[] { "experimental.jsp", "Experimental" }, };
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
log.debug("doGet({}, {})", request, response);
String test = WebUtils.getString(request, "test");
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
OutputStream os = response.getOutputStream();
PrintStream ps = new PrintStream(os);
header(ps, "Unit testing", breadcrumb);
ps.flush();
RunListener listener = new CustomListener(ps);
JUnitCore junit = new JUnitCore();
junit.addListener(listener);
if (test != null && !test.isEmpty()) {
try {
Class<?> clazz = Class.forName(test);
ps.println("<b>" + clazz.getCanonicalName() + "</b><br/>");
ps.flush();
ps.println("<pre>");
ps.flush();
junit.run(clazz);
ps.println("</pre>");
ps.flush();
} catch (ClassNotFoundException e) {
warn(ps, e.getMessage());
}
} else {
for (Class<?> clazz : new Reflections("com.openkm.test.api").getSubTypesOf(TestCase.class)) {
ps.println("<a style=\"color: black; font-weight:bold;\" href=\"UnitTesting?test=" + clazz.getCanonicalName() + "\">"
+ clazz.getCanonicalName() + "</a><br/>");
ps.flush();
ps.println("<pre>");
ps.flush();
junit.run(clazz);
ps.println("</pre>");
ps.flush();
}
}
ps.println("<span style=\"color: blue; font-weight:bold;\">>>> End Of Unit Testing <<<</span>");
footer(ps);
ps.flush();
IOUtils.closeQuietly(ps);
IOUtils.closeQuietly(os);
}
/**
* Print HTML page header
*/
private void header(PrintStream out, String title, String[][] breadcrumb) {
out.println("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
out.println("<head>");
out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />");
out.println("<link rel=\"Shortcut icon\" href=\"favicon.ico\" />");
out.println("<link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" />");
out.println("<title>" + title + "</title>");
out.println("</head>");
out.println("<body>");
out.println("<ul id=\"breadcrumb\">");
for (String[] elto : breadcrumb) {
out.println("<li class=\"path\">");
out.print("<a href=\"" + elto[0] + "\">" + elto[1] + "</a>");
out.print("</li>");
}
out.println("<li class=\"path\">" + title + "</li>");
out.println("</ul>");
out.println("<br/>");
}
/**
* Print HTML page footer
*/
private void footer(PrintStream out) {
out.println("</body>");
out.println("</html>");
}
/**
* Print warn messages
*/
public void warn(PrintStream out, String msg) {
out.print("<div class=\"warn\">" + msg + "</div>");
}
/**
* Custom listener
*/
class CustomListener extends TextListener {
private PrintStream fWriter;
public CustomListener(PrintStream writer) {
super(writer);
fWriter = writer;
}
@Override
protected void printFailure(Failure each, String prefix) {
fWriter.println("<span style=\"color: red\">");
fWriter.println(prefix + ") " + each.getTestHeader() + " => " + each.getMessage());
fWriter.println(each.getException());
for (String line : each.getTrace().split("\\r?\\n")) {
if (line.trim().startsWith("at com.openkm")) {
fWriter.println(line);
}
}
fWriter.println("</span>");
}
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred;
import junit.framework.Assert;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.server.jobtracker.JTConfig;
import org.apache.hadoop.util.ToolRunner;
import org.apache.hadoop.util.Shell.ShellCommandExecutor;
import org.junit.Test;
public class TestSimulatorDeterministicReplay {
public static final Log LOG = LogFactory.getLog(
TestSimulatorDeterministicReplay.class);
protected SimulatorJobSubmissionPolicy policy = SimulatorJobSubmissionPolicy.REPLAY;
@Test
public void testMain() throws Exception {
Path hadoopLogDir = new Path(
System.getProperty("test.build.data"), "mumak-replay");
Path hadoopLogDir1 = new Path(hadoopLogDir, "run1");
Path hadoopLogDir2 = new Path(hadoopLogDir, "run2");
runMumak(hadoopLogDir1, 50031);
LOG.info("Run1 done");
runMumak(hadoopLogDir2, 50032);
compareLogDirs(hadoopLogDir1.toString(), hadoopLogDir2.toString());
}
void compareLogDirs(String dir1, String dir2) {
try {
try {
// If there is no diff available, we skip the test and end up in
// the catch block
// Make sure diff understands the -r option
ShellCommandExecutor executor = new ShellCommandExecutor(new String[] {
"diff", "-r", "-q", "/dev/null", "/dev/null" });
executor.execute();
if (executor.getExitCode() != 0) {
LOG.warn("diff -r -q is not working, skipping the test");
return;
}
} catch (Exception e) {
LOG.warn("diff -r -q is not working, skipping the test", e);
return;
}
// Run the real comparison
ShellCommandExecutor executor =
new ShellCommandExecutor(new String[] {"diff", "-r", "-q", dir1, dir2});
executor.execute();
Assert.assertEquals("Job history logs differ, diff returned",
0, executor.getExitCode());
} catch (Exception e) {
LOG.warn("Exception while diffing: " + e);
Assert.fail(String.format(
"Exception while diffing %s and %s. Exception - %s",
dir1, dir2, e));
}
}
// We need a different http port parameter for each run as the socket
// is not closed properly in hadoop
void runMumak(Path hadoopLogDir, int jobTrackerHttpPort)
throws Exception {
final Configuration conf = new Configuration();
conf.set(SimulatorJobSubmissionPolicy.JOB_SUBMISSION_POLICY, policy.name());
final FileSystem lfs = FileSystem.getLocal(conf);
final Path rootInputDir = new Path(
System.getProperty("src.test.data", "data")).makeQualified(lfs);
final Path traceFile = new Path(rootInputDir, "19-jobs.trace.json.gz");
final Path topologyFile = new Path(rootInputDir, "19-jobs.topology.json.gz");
LOG.info("traceFile = " + traceFile + " topology = " + topologyFile);
conf.setLong("mumak.start.time", 10);
// Run 20 minutes of the simulation
conf.setLong("mumak.terminate.time", 10 + 20*60*1000);
conf.setLong("mumak.random.seed", 42);
// SimulatorEngine reads conf and the system property too (!)
System.setProperty("hadoop.log.dir", hadoopLogDir.toString());
conf.set("hadoop.log.dir", hadoopLogDir.toString());
conf.set("mapred.job.tracker.http.address",
"0.0.0.0:" + jobTrackerHttpPort);
conf.setBoolean(JTConfig.JT_PERSIST_JOBSTATUS, false);
String[] args = { traceFile.toString(), topologyFile.toString() };
int res = ToolRunner.run(conf, new SimulatorEngine(), args);
Assert.assertEquals(0, res);
}
}
|
/**
* Control de paquetes general
*/
package com.jbsistemas;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Esta clase captura los mensajes del proceso de envío de correos y los
* escribe en un log externo. El propósito de éste log es poder
* visualizar los mensajes output si no se ejecuta por línea de comandos.
*
* @author David Cruz Jiménez
* @author Daniel Torres Silva
* @version 2.0
* @since 1.0
*/
public class Singleton {
private static final Singleton inst = new Singleton();
/**
* Llamado a propiedades del constructor general.
*/
private Singleton() {
super();
}
/**
* Permite generar un registro de datos en el log externo SendEmail. El
* archivo se escribe en la misma carpeta donde se ejecuta el componente
* SendEmail.
*
* @param str Cadena de carateres {@code String} que se escribirá en
* el log
* @param apnd Si se especifica <code>true</code>, la siguiente cadena
* será escrita debajo del resto de datos existentes sin crear un
* flujo nuevo
* @see java.io.FileOutputStream
* @see java.io.File
* @see java.io.PrintWriter
*/
protected synchronized void writeToFile(String str, boolean apnd) {
try (PrintWriter out = new PrintWriter(new FileOutputStream(new File("SendEmail.log"), apnd))) {
out.println(str);
out.flush();
out.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Singleton.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Obtiene una instancia de tipo <code>Singleton</code>. Se requiere para
* obtener el acceso a escribir el archivo log.
*
* @return Una instancia de tipo {@code Singleton}
*/
protected static Singleton getInstance() {
return inst;
}
}
|
package day61_exceptions_collections.checked_exceptions;
public class CheckedExceptionDemo {
public static void main(String[] args) throws InterruptedException {
System.out.println("About to sleep for 5 seconds");
//Thread.sleep(1000); causes/ throwa an InterruptedException , which is a checked exception
//1.Handling using TRY/CATCH
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//2.Using throws InterruptedException
Thread.sleep(5000);
System.out.println("Woke up after 5 seconds");
}
}
|
package com.example.mna.mishnapals;
import android.content.Intent;
import androidx.annotation.NonNull;
//import android.support.v7.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class EmailPasswordSignin extends AppCompatActivity {
private FirebaseAuth mAuth;
Button createAccount;
EditText emailEntry, passEntry;
String email, password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_email_password_signin);
mAuth = FirebaseAuth.getInstance();
FirebaseUser currUser = mAuth.getCurrentUser();
createAccount = (Button)findViewById(R.id.createAccountEmailPass);
emailEntry = (EditText)findViewById(R.id.emailPassEmail);
passEntry = (EditText)findViewById(R.id.emailPassPas);
email = emailEntry.getText().toString();
password = passEntry.getText().toString();
createAccount.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
newAccount(email, password);
}
});
}
public void newAccount(String email, String password){
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
FirebaseUser user = mAuth.getCurrentUser();
startActivity(new Intent(getBaseContext(), HomeScreen.class));
EmailPasswordSignin.this.finish();
}
else{
}
}
});
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.joget.valuprosys.products;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.joget.apps.app.service.AppUtil;
/**
*
* @author realakuma
*/
public class AppContext {
private static AppContext instance;
private AbstractApplicationContext appContext;
public synchronized static AppContext getInstance() {
if (instance == null) {
instance = new AppContext();
}
return instance;
}
private AppContext() {
System.out.print(this.getClass().getResource("/"));
//this.appContext = new ClassPathXmlApplicationContext("productsApplicationContext.xml");
Thread currentThread = Thread.currentThread();
ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
try {
currentThread.setContextClassLoader(this.getClass().getClassLoader());
this.appContext = new ClassPathXmlApplicationContext(new String[]{"/productsApplicationContext.xml"}, this.getClass(), AppUtil.getApplicationContext());
} finally {
currentThread.setContextClassLoader(threadContextClassLoader);
}
}
public AbstractApplicationContext getAppContext() {
return appContext;
}
}
|
package com.tencent.mm.plugin.freewifi.model;
import com.tencent.mm.g.a.gf;
import com.tencent.mm.sdk.b.b;
import com.tencent.mm.sdk.b.c;
class j$2 extends c<gf> {
final /* synthetic */ j jkt;
j$2(j jVar) {
this.jkt = jVar;
this.sFo = gf.class.getName().hashCode();
}
public final /* synthetic */ boolean a(b bVar) {
gf gfVar = (gf) bVar;
com.tencent.mm.plugin.freewifi.e.b.aPg();
com.tencent.mm.plugin.freewifi.e.b.J(gfVar.bPr.intent);
return false;
}
}
|
package com.example.appfootball;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.widget.ImageView;
public class ImageViewPager extends ActionBarActivity {
int position;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setTitle("GALLERY");
setContentView(R.layout.view_pager);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Intent intent = getIntent();
position = getIntent().getExtras().getInt("id");
GalleryImageAdapter imageAdapter = new GalleryImageAdapter(this);
List<ImageView> images = new ArrayList<ImageView>();
for (int i = 0; i < imageAdapter.getCount(); i++) {
ImageView imageView = new ImageView(this);
imageView.setImageResource(imageAdapter.imageIDs[i]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
images.add(imageView);
}
//Set the images into ViewPager
ImagePagerAdapter pagerAdapter= new ImagePagerAdapter(images);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(pagerAdapter);
//Show Images following the position
viewPager.setCurrentItem(position);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
}
|
package com.runningphotos.ui;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* Created by Tensa on 06.02.2016.
*/
@Controller
public class BuyPhotosController {
@RequestMapping(value = "/buyPhotos")
public ModelAndView getBuyPhotos(){
ModelAndView model = new ModelAndView("buyPhotos");
return model;
}
}
|
package entities;
import java.sql.Date;
public class RoomRequest {
private int id;
private boolean isOpened;
private Room room;
private Client client;
private Admin admin;
private Date checkInDate;
private Date checkOutDate;
private Invoice invoice;
private int peopleNum;
private String category;
public RoomRequest() {
}
public RoomRequest(Client client, int peopleNum, String category, Date checkInDate, Date checkOutDate) {
this.isOpened = true;
this.client = client;
this.peopleNum = peopleNum;
this.category = category;
this.checkInDate = checkInDate;
this.checkOutDate = checkOutDate;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isOpened() {
return isOpened;
}
public void setOpened(boolean opened) {
isOpened = opened;
}
public Room getRoom() {
return room;
}
public void setRoom(Room room) {
this.room = room;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public Admin getAdmin() {
return admin;
}
public void setAdmin(Admin admin) {
this.admin = admin;
}
public Date getCheckInDate() {
return checkInDate;
}
public void setCheckInDate(Date checkInDate) {
this.checkInDate = checkInDate;
}
public Date getCheckOutDate() {
return checkOutDate;
}
public void setCheckOutDate(Date checkOutDate) {
this.checkOutDate = checkOutDate;
}
public Invoice getInvoice() {
return invoice;
}
public void setInvoice(Invoice invoice) {
this.invoice = invoice;
}
public int getPeopleNum() {
return peopleNum;
}
public void setPeopleNum(int peopleNum) {
this.peopleNum = peopleNum;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
@Override
public String toString() {
return "RoomRequest{" +
"id=" + id +
", isOpened=" + isOpened +
", room=" + room +
", client=" + client +
", admin=" + admin +
", checkInDate=" + checkInDate +
", checkOutDate=" + checkOutDate +
", invoice=" + invoice +
", peopleNum=" + peopleNum +
", category='" + category + '\'' +
'}';
}
}
|
package com.wire.bots.sdk.exceptions;
import java.io.IOException;
import java.util.UUID;
public class MissingStateException extends IOException {
public MissingStateException(UUID botId) {
super("Unknown botId: " + botId);
}
}
|
// represents a list of Person's buddies
class ConsLoBuddy implements ILoBuddy {
Person first;
ILoBuddy rest;
ConsLoBuddy(Person first, ILoBuddy rest) {
this.first = first;
this.rest = rest;
}
/*TEMPLATE
* FIELDS
* ...this.first... -- Person
* ...this.rest... -- ILoBuddy
*
* METHODS:
* ...this.in(Person)... -- Boolean
* ...this.partyCount(ILoBoddy)... -- int
* ...this.countCommonBuddies(buddies).. -- int
* ...this.hasDistantBuddy(person, IloBuddy).. -- Boolean
* ...this.accumulate(ILoBuddy)... -- ILoBuddy
*
* METHODS FOR FIELDS:
* ...this.rest.in(Person)... -- Boolean
* ...this.rest.partyCount(ILoBoddy)... -- int
* ...this.rest.countCommonBuddies(buddies).. -- int
* ...this.rest.hasDistantBuddy(person, IloBuddy).. -- Boolean
* ...this.rest.accumulate(ILoBuddy)... -- ILoBuddy
*/
// returns the number of people that are direct buddies
// of both this and that person
public int countCommonBuddies(ILoBuddy that) {
if (that.in(this.first))
return 1 + this.rest.countCommonBuddies(that);
else return this.rest.countCommonBuddies(that);
}
// is the given person in this list
public boolean in(Person given) {
return given.equals(this.first) || this.rest.in(given);
}
// will the given person be invited to a party
// organized by this person?
public boolean hasDistantBuddy(Person that, ILoBuddy remove) {
if (remove.in(this.first))
return this.rest.hasDistantBuddy(that, remove);
else return this.first.buddies.hasDistantBuddy
(that, new ConsLoBuddy(this.first, remove))
|| this.rest.hasDistantBuddy
(that, new ConsLoBuddy(this.first, remove))
|| this.first.equals(that);
}
// returns the number of people who will show up at the party
// given by this person
public int partyCount(ILoBuddy remove) {
if (remove.in(this.first))
return this.rest.partyCount(remove);
else return 1 + this.first.buddies.partyCount
(new ConsLoBuddy(this.first, remove))
+ this.rest.partyCount(this.first.buddies.accumulate
(new ConsLoBuddy(this.first, remove)));
}
// give the accumulator of the preceding function
public ILoBuddy accumulate(ILoBuddy remove) {
return this.rest.accumulate(new ConsLoBuddy(this.first, remove));
}
}
|
package com.puti.pachong.util;
import lombok.SneakyThrows;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.function.Function;
/**
* @author yaotianchi
* @date 2019/10/14
*/
public class FileUtil {
@SneakyThrows
public static void updateFileToAnother(String originFilePath, String targetFilePath, Function<String, String> lineProcess) {
List<String> allLines = Files.readAllLines(Paths.get(originFilePath));
for (String line : allLines) {
String updatedStr = lineProcess.apply(line);
Files.write(Paths.get(targetFilePath), updatedStr.getBytes(),
StandardOpenOption.WRITE, StandardOpenOption.APPEND, StandardOpenOption.CREATE);
}
}
/**
* @param dirPath
*/
public static void createDirsIfNotExists(String dirPath) {
File file = new File(dirPath);
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}
}
|
package com.tao.dao;
import java.sql.ResultSet;
import com.tao.model.Auction;
import com.tao.model.Collection;
import com.tao.model.Commodity;
import com.tao.model.Order;
import com.tao.utils.DataProcess;
public class AuctionDao extends Dao {
public AuctionDao(DataProcess dataProcess){
super(dataProcess);
}
public boolean add(Auction auction) {
final int cSize = 6;
String sql = "insert into auction"
+ "(commodityID,deadLine,activePrice,currentPrice,currentMail,mailOfparticipants)"
+ " values(?";
for (int i = 1; i != cSize; i++) {
sql += ",?";
}
sql += ")";
return dataProcess.execute(sql,
auction.getCommodity().getId(),
auction.getDeadline(),
auction.getActivePrice(),
auction.getCurrentPrice(),
auction.getCurrentMail(),
""
);
}
public ResultSet queryAuction(int commodityID){
String sql = "select * from auction where commodityID = ?";
return dataProcess.executeQuery(sql, commodityID);
}
public void removeAuction(int id){
String sql = "delete from auction_table where commodityID = ?";
dataProcess.execute(sql,id);
}
public ResultSet queryParticipants(int commodityID){
String sql = "select mailOfbuyer from auction_table where commodityID = ?";
return dataProcess.executeQuery(sql, commodityID);
}
public void updateAuction(Auction auction){
String sql = "update auction set currentPrice = ?,currentMail = ? where ID = ?";
dataProcess.execute(sql,auction.getCurrentPrice(),auction.getCurrentMail(),auction.getAuctionID());
}
public void updateAskOrder(Commodity commodity,double price,String email){
String sql = "update auction_table set deposit = ? where commodityID = ? AND mailOfbuyer = ?";
dataProcess.execute(sql, price,commodity.getId(),email);
}
public void deleteAskOrder(int commodityID){
String sql = "delete from auction_table where commodityID = ?";
dataProcess.execute(sql, commodityID);
}
public void deleteAuction(int commodityID){
String sql = "delete from auction where commodityID = ?";
dataProcess.execute(sql,commodityID);
}
public void addOrder(Commodity commodity,double price,String email){
String sql = "insert into auction_table(" +
"commodityID,itemNum,mailOfbuyer,mailOfseller,deposit,dealType) values(?";
int oSize = 6;
Order order = new Order(
0,
commodity.getId(),
1,
email,
commodity.getMailOfseller(),
commodity.getPrice(),
commodity.getType());
for (int i = 1; i != oSize; i++) {
sql += ",?";
}
sql += ")";
System.out.println(price);
dataProcess.execute(
sql,
order.getCommodityID(),
order.getItemNum(),
order.getMailOfbuyer(),
order.getMailOfseller(),
price,
order.getDealType()
);
}
}
|
package com.tencent.mm.g.a;
import com.tencent.mm.sdk.b.b;
public final class hp extends b {
public a bQV;
public b bQW;
public hp() {
this((byte) 0);
}
private hp(byte b) {
this.bQV = new a();
this.bQW = new b();
this.sFm = false;
this.bJX = null;
}
}
|
package by.tc.task01.enumeration;
public enum OperatingSystem {
WINDOWS, LINUX, OSX
}
|
package com.ehootu.park.service;
import com.ehootu.park.model.EnterprisePlatformWorkEntity;
import com.ehootu.park.model.PublicInformationEntity;
import java.util.List;
import java.util.Map;
/**
*
*
* @author yinyujun
* @email
* @date 2017-09-21 10:21:37
*/
public interface EnterprisePlatformWorkService {
EnterprisePlatformWorkEntity queryObject(String id);
List<EnterprisePlatformWorkEntity> queryList(Map<String, Object> map);
int queryTotal(Map<String, Object> map);
void save(EnterprisePlatformWorkEntity EnterprisePlatformWork);
void update(EnterprisePlatformWorkEntity EnterprisePlatformWork);
void delete(String id);
void deleteBatch(Integer[] ids);
List<EnterprisePlatformWorkEntity> select(String id);
List<EnterprisePlatformWorkEntity> selectOne(String dizhibianma);
List<EnterprisePlatformWorkEntity> selectAddress(String enterprise_address);
void save(EnterprisePlatformWorkEntity enterprisePlatformWork, PublicInformationEntity publicInformation, String pageName);
}
|
/*
Document : SME_Lending
Created on : August 21, 2015, 11:56:42 AM
Author : Anuj Verma
*/
package com.spring.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="sme_principal_sales_manager_for_p1sc")
public class SMEPrincipalSalesManagerEmailForP1SC implements java.io.Serializable {
private static final long serialVersionUID = 674349086388708431L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;
private String payment_consultant_email;
private String principals_spoc_email;
private String principals_regional_managers_email;
private String principals_store_managers_email;
private String others_email;
private String store_code;
private Integer main_principal_id;
private Integer sub_principal_id;
private String principal_name;
private String city;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPayment_consultant_email() {
return payment_consultant_email;
}
public void setPayment_consultant_email(String payment_consultant_email) {
this.payment_consultant_email = payment_consultant_email;
}
public String getPrincipals_spoc_email() {
return principals_spoc_email;
}
public void setPrincipals_spoc_email(String principals_spoc_email) {
this.principals_spoc_email = principals_spoc_email;
}
public String getPrincipals_regional_managers_email() {
return principals_regional_managers_email;
}
public void setPrincipals_regional_managers_email(
String principals_regional_managers_email) {
this.principals_regional_managers_email = principals_regional_managers_email;
}
public String getPrincipals_store_managers_email() {
return principals_store_managers_email;
}
public void setPrincipals_store_managers_email(
String principals_store_managers_email) {
this.principals_store_managers_email = principals_store_managers_email;
}
public String getOthers_email() {
return others_email;
}
public void setOthers_email(String others_email) {
this.others_email = others_email;
}
public String getStore_code() {
return store_code;
}
public void setStore_code(String store_code) {
this.store_code = store_code;
}
public Integer getMain_principal_id() {
return main_principal_id;
}
public void setMain_principal_id(Integer main_principal_id) {
this.main_principal_id = main_principal_id;
}
public Integer getSub_principal_id() {
return sub_principal_id;
}
public void setSub_principal_id(Integer sub_principal_id) {
this.sub_principal_id = sub_principal_id;
}
public String getPrincipal_name() {
return principal_name;
}
public void setPrincipal_name(String principal_name) {
this.principal_name = principal_name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
|
package net.dragberry.taglibrary.tags;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;
public class Paragraph extends BodyTagSupport{
private static final long serialVersionUID = 1080913554298404564L;
private String color;
public void setColor(String color) {
this.color = color;
}
@Override
public int doAfterBody() throws JspException {
BodyContent content = getBodyContent();
String str = content.getString();
JspWriter out = content.getEnclosingWriter();
try {
out.append("<p style='color:"+ color + "'>");
out.append(str);
out.append("</p>");
} catch (IOException e) {
e.printStackTrace();
}
return super.doAfterBody();
}
}
|
package com.ss.android.ugc.aweme.miniapp.g;
public final class ab {
private static volatile aa a;
public static aa a() {
// Byte code:
// 0: ldc com/ss/android/ugc/aweme/miniapp/g/ab
// 2: monitorenter
// 3: getstatic com/ss/android/ugc/aweme/miniapp/g/ab.a : Lcom/ss/android/ugc/aweme/miniapp/g/aa;
// 6: ifnonnull -> 40
// 9: ldc com/ss/android/ugc/aweme/miniapp/g/aa
// 11: monitorenter
// 12: getstatic com/ss/android/ugc/aweme/miniapp/g/ab.a : Lcom/ss/android/ugc/aweme/miniapp/g/aa;
// 15: ifnonnull -> 28
// 18: new com/ss/android/ugc/aweme/miniapp/g/aa
// 21: dup
// 22: invokespecial <init> : ()V
// 25: putstatic com/ss/android/ugc/aweme/miniapp/g/ab.a : Lcom/ss/android/ugc/aweme/miniapp/g/aa;
// 28: ldc com/ss/android/ugc/aweme/miniapp/g/aa
// 30: monitorexit
// 31: goto -> 40
// 34: astore_0
// 35: ldc com/ss/android/ugc/aweme/miniapp/g/aa
// 37: monitorexit
// 38: aload_0
// 39: athrow
// 40: getstatic com/ss/android/ugc/aweme/miniapp/g/ab.a : Lcom/ss/android/ugc/aweme/miniapp/g/aa;
// 43: astore_0
// 44: ldc com/ss/android/ugc/aweme/miniapp/g/ab
// 46: monitorexit
// 47: aload_0
// 48: areturn
// 49: astore_0
// 50: ldc com/ss/android/ugc/aweme/miniapp/g/ab
// 52: monitorexit
// 53: aload_0
// 54: athrow
// Exception table:
// from to target type
// 3 12 49 finally
// 12 28 34 finally
// 28 31 49 finally
// 35 40 49 finally
// 40 44 49 finally
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\ss\androi\\ugc\aweme\miniapp\g\ab.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package com.chuxin.family.accounting;
import java.util.Calendar;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.Toast;
import com.chuxin.family.app.CxRootActivity;
import com.chuxin.family.global.CxGlobalParams;
import com.chuxin.family.main.CxMain;
import com.chuxin.family.neighbour.CxNbNeighboursHome;
import com.chuxin.family.neighbour.CxNeighbourList;
import com.chuxin.family.net.CxAccountingApi;
import com.chuxin.family.net.ConnectionManager.JSONCaller;
import com.chuxin.family.parse.CxAccountingParser;
import com.chuxin.family.parse.been.CxParseBasic;
import com.chuxin.family.parse.been.data.AccountHomeItem;
import com.chuxin.family.parse.been.data.DateData;
import com.chuxin.family.resource.CxResourceString;
import com.chuxin.family.utils.DateUtil;
import com.chuxin.family.utils.DialogUtil;
import com.chuxin.family.utils.CxLog;
import com.chuxin.family.utils.TextUtil;
import com.chuxin.family.utils.ToastUtil;
import com.chuxin.family.utils.DialogUtil.OnSureClickListener;
import com.chuxin.family.R;
/**
* 记账的添加和修改删除类
* @author wentong.men
*
*/
public class CxChangeAccountActivity extends CxRootActivity {
public enum AccountMode{
ADD_MODE,UPDATE_MODE
}
private int type; //支出还是收入 1 支出,2收入
private AccountMode mode;//是增加还是修改删除
private String accountId; //账目id
private String tempCategoryOut; //支出类别缓存
private String tempCategoryIn; //收入类别缓存
private String tempAuthor; //记账人
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.cx_fa_activity_account_change_account);
initTitle();
init();
}
private void init() {
final InputMethodManager input = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
tempAuthor=CxGlobalParams.getInstance().getUserId();//默认自己
type=1; //默认1
date = DateUtil.getNumberTime(-1);//当前日期时间类
AccountHomeItem item=null;
Intent intent = getIntent();
String extra = intent.getStringExtra(CxAccountingParam.ACCOUNT_CONTENT);
if(TextUtils.isEmpty(extra)){//记账不传参数
mode=AccountMode.ADD_MODE;
}else{
mode=AccountMode.UPDATE_MODE;
CxAccountingParser parser=new CxAccountingParser();
item = parser.getAccountItem(extra);
}
tvOut = (TextView) findViewById(R.id.cx_fa_accounting_account_tv_out);
tvIn = (TextView) findViewById(R.id.cx_fa_accounting_account_tv_in);
tvMoney = (EditText) findViewById(R.id.cx_fa_accounting_account_money_tv);
tvCategory = (TextView) findViewById(R.id.cx_fa_accounting_account_category_tv);
tvFrom = (TextView) findViewById(R.id.cx_fa_accounting_account_from_tv);
tvDate = (TextView) findViewById(R.id.cx_fa_accounting_account_date_tv);
tvRemark = (TextView) findViewById(R.id.cx_fa_accounting_account_remark_tv);
LinearLayout layoutMoney = (LinearLayout) findViewById(R.id.cx_fa_accounting_account_money_layout);
LinearLayout layoutCategory = (LinearLayout) findViewById(R.id.cx_fa_accounting_account_category_layout);
LinearLayout layoutFrom = (LinearLayout) findViewById(R.id.cx_fa_accounting_account_from_layout);
LinearLayout layoutDate = (LinearLayout) findViewById(R.id.cx_fa_accounting_account_date_layout);
layoutOut = (LinearLayout) findViewById(R.id.cx_fa_accounting_account_out_layout);
layoutIn = (LinearLayout) findViewById(R.id.cx_fa_accounting_account_in_layout);
Button delBtn= (Button) findViewById(R.id.cx_fa_accounting_change_account_delete);
if(mode==AccountMode.UPDATE_MODE){//删改模式
accountId=item.getId();
if(1==item.getType()){
type=1;
layoutOut.setBackgroundResource(R.drawable.cx_fa_accounting_homepage_detail_bg_white);
tvOut.setText(TextUtil.getNewSpanStr(getString(R.string.cx_fa_accounting_out), 18, Color.rgb(235, 161, 121)));
layoutIn.setBackgroundResource(R.drawable.cx_fa_accounting_homepage_detail_bg_gray);
tvIn.setText(TextUtil.getNewSpanStr(getString(R.string.cx_fa_accounting_in), 16, Color.rgb(55, 50, 47)));
}else{
type=2;
layoutIn.setBackgroundResource(R.drawable.cx_fa_accounting_homepage_detail_bg_white);
tvIn.setText(TextUtil.getNewSpanStr(getString(R.string.cx_fa_accounting_in), 18, Color.rgb(235, 161, 121)));
layoutOut.setBackgroundResource(R.drawable.cx_fa_accounting_homepage_detail_bg_gray);
tvOut.setText(TextUtil.getNewSpanStr(getString(R.string.cx_fa_accounting_out), 16, Color.rgb(55, 50, 47)));
}
int from = item.getFrom();
tempAuthor=item.getAuthor();
if(item.getAuthor().equals(CxGlobalParams.getInstance().getPartnerId())){//如果记账人是对方,则修改 来自
if(from==1){
from=2;
}else if(from==2){
from=1;
}
titleText.setText(CxResourceString.getInstance().str_accounting_account_title_opposite_account);
delBtn.setVisibility(View.GONE);
}else{
titleText.setText(getString(R.string.cx_fa_accounting_account_title_edit_account));
delBtn.setVisibility(View.VISIBLE);
}
tvFrom.setText(TextUtil.numberToFrom(this, from));
tvMoney.setText(TextUtil.getNewSpanStr(TextUtil.transforToMoney(item.getMoney()), 20, Color.RED));
tvCategory.setText(TextUtil.numberToCategory(this, item.getCategory()));
String tempdate=item.getDate();
tvDate.setText(tempdate.substring(0,4)+"-"+tempdate.substring(4,6)+"-"+tempdate.substring(6,8));
tvRemark.setText(item.getDesc());
// tvDate.setText(item.getDate());
tvMoney.setFocusable(false);
// input.hideSoftInputFromWindow(tvMoney.getWindowToken(), 0);
}else if(mode==AccountMode.ADD_MODE){//增加模式
titleText.setText(getString(R.string.cx_fa_accounting_homepage_add_account));
delBtn.setVisibility(View.GONE);
type=1;
layoutOut.setBackgroundResource(R.drawable.cx_fa_accounting_homepage_detail_bg_white);
tvOut.setText(TextUtil.getNewSpanStr(getString(R.string.cx_fa_accounting_out), 18, Color.rgb(235, 161, 121)));
layoutIn.setBackgroundResource(R.drawable.cx_fa_accounting_homepage_detail_bg_gray);
tvIn.setText(TextUtil.getNewSpanStr(getString(R.string.cx_fa_accounting_in), 16, Color.rgb(55, 50, 47)));
// tvMoney.setText(TextUtil.getNewSpanStr("0", 16, Color.RED));
tvCategory.setText(getString(R.string.cx_fa_accounting_category_out_athome_short));
tvFrom.setText(getString(R.string.cx_fa_accounting_account_me));
tvDate.setText(date.getDateStr());
input.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);//弹出键盘
tvMoney.setFocusable(true);
tvMoney.requestFocus();
tvMoney.requestFocusFromTouch();
}
// tvMoney.setInputType(InputType.TYPE_CLASS_PHONE );
tvMoney.setSelection(tvMoney.getText().toString().length());
tvMoney.setCursorVisible(false);
tvMoney.setHint(TextUtil.getNewSpanStr("0", 20, Color.RED).toString());
// tvMoney.addTextChangedListener(textListener);
tvMoney.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus){
input.hideSoftInputFromWindow(tvMoney.getWindowToken(), 0);
}
}
});
// tvMoney.setOnClickListener(new OnClickListener() {
//
// @Override
// public void onClick(View v) {
// tvMoney.setFocusable(true);
// tvMoney.requestFocus();
// tvMoney.requestFocusFromTouch();
// tvMoney.setSelection(tvMoney.getText().toString().length());
// tvMoney.setCursorVisible(false);
// input.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
// }
// });
layoutMoney.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
tvMoney.setFocusable(true);
tvMoney.requestFocus();
tvMoney.requestFocusFromTouch();
tvMoney.setSelection(tvMoney.getText().toString().length());
tvMoney.setCursorVisible(false);
input.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
});
delBtn.setOnClickListener(contentListener);
layoutCategory.setOnClickListener(contentListener);
layoutFrom.setOnClickListener(contentListener);
layoutDate.setOnClickListener(contentListener);
layoutOut.setOnClickListener(contentListener);
layoutIn.setOnClickListener(contentListener);
}
//初始化标题栏
private void initTitle() {
Button backBtn = (Button) findViewById(R.id.cx_fa_activity_title_back);
Button saveBtn = (Button) findViewById(R.id.cx_fa_activity_title_more);
titleText = (TextView) findViewById(R.id.cx_fa_activity_title_info);
// titleText.setText(getString(R.string.cx_fa_accounting_homepage_add_account));
backBtn.setText(getString(R.string.cx_fa_navi_back));
saveBtn.setText(getString(R.string.cx_fa_save_text));
saveBtn.setVisibility(View.VISIBLE);
backBtn.setOnClickListener(titleListener);
saveBtn.setOnClickListener(titleListener);
}
OnClickListener contentListener =new OnClickListener() {
@Override
public void onClick(View v) {
tvMoney.setFocusable(false);
switch(v.getId()){
case R.id.cx_fa_accounting_change_account_delete:
DialogUtil du = DialogUtil.getInstance();
du.getSimpleDialog(CxChangeAccountActivity.this, null,getString(R.string.cx_fa_accounting_account_sure_delete), null, null).show();
du.setOnSureClickListener(new OnSureClickListener() {
@Override
public void surePress() {
try {
DialogUtil.getInstance().getLoadingDialogShow(CxChangeAccountActivity.this, -1);
CxAccountingApi.getInstance().requestAccountDelete(accountId, delCaller);
} catch (Exception e) {
DialogUtil.getInstance().setLoadingDialogDismiss(null, -1, 1000);
e.printStackTrace();
}
}
});
break;
case R.id.cx_fa_accounting_account_out_layout:
outOnClick();
break;
case R.id.cx_fa_accounting_account_in_layout:
inOnClick();
break;
case R.id.cx_fa_accounting_account_money_layout:
// tvMoney.setFocusable(true);
// tvMoney.requestFocus();
// showMoneyDialog();
break;
case R.id.cx_fa_accounting_account_category_layout:
showCategoryOrFromDialog(1);
break;
case R.id.cx_fa_accounting_account_from_layout:
showCategoryOrFromDialog(2);
break;
case R.id.cx_fa_accounting_account_date_layout:
showDateDialog();
break;
default:
break;
}
}
};
OnClickListener titleListener =new OnClickListener() {
@Override
public void onClick(View v) {
tvMoney.setFocusable(false);
switch(v.getId()){
case R.id.cx_fa_activity_title_back:
back();
break;
case R.id.cx_fa_activity_title_more:
save();
break;
default:
break;
}
}
};
protected void save() {
if(mode==AccountMode.UPDATE_MODE && tempAuthor.equals(CxGlobalParams.getInstance().getPartnerId())){
ToastUtil.getSimpleToast(this, -1, getString(R.string.cx_fa_accounting_account_save_opposite_fail), 1).show();
return;
}
String money = tvMoney.getText().toString().trim().replace(",", "");
if(money.equals("") || money.equals("0")){
ToastUtil.getSimpleToast(this, -1, getString(R.string.cx_fa_accounting_account_save_nomoney), 1).show();
return;
}
if(money.startsWith("-")){
ToastUtil.getSimpleToast(CxChangeAccountActivity.this, -1, getString(R.string.cx_fa_accounting_account_save_fuzhi), 1).show();
return ;
}
// if(money.contains(" ")){
// ToastUtil.getSimpleToast(RkChangeAccountActivity.this, -1, "请不要输入负值", 1).show();
// return ;
// }
if(!money.startsWith("+") && (money.contains("-") || money.contains("+"))){
ToastUtil.getSimpleToast(CxChangeAccountActivity.this, -1, getString(R.string.cx_fa_accounting_account_save_zhengfuhao), 1).show();
return;
}
if(money.contains(".")){
ToastUtil.getSimpleToast(CxChangeAccountActivity.this, -1, getString(R.string.cx_fa_accounting_account_save_point), 1).show();
return ;
}
if((!money.startsWith("+") && money.length()>9) || money.length()>10){
ToastUtil.getSimpleToast(CxChangeAccountActivity.this, -1, getString(R.string.cx_fa_accounting_account_save_big), 1).show();
tvMoney.setText(TextUtil.getNewSpanStr("0", 20, Color.RED).toString());
return;
}
String sendMoney = money.replace("+", "").replace(" ", "")+"00";
int category = TextUtil.categoryToNumber(this, tvCategory.getText().toString().trim());
int from = TextUtil.fromToNumber(this, tvFrom.getText().toString().trim());
String date = tvDate.getText().toString().trim().replaceAll("-", "");
String desc=tvRemark.getText().toString().trim();
try {
DialogUtil.getInstance().getLoadingDialogShow(CxChangeAccountActivity.this, -1);
CxAccountingApi.getInstance().requestAccountAddOrUpdate(accountId, type, sendMoney, category, from, date, desc, updateCaller);
} catch (Exception e) {
DialogUtil.getInstance().setLoadingDialogDismiss(null, -1, 1000);
e.printStackTrace();
}
}
protected void back() {
if(mode==AccountMode.ADD_MODE){
if(!tvMoney.getText().toString().trim().equals("0") && !tvMoney.getText().toString().trim().equals("")){
DialogUtil du = DialogUtil.getInstance();
du.setOnSureClickListener(new OnSureClickListener() {
@Override
public void surePress() {
finish();
overridePendingTransition(R.anim.tran_pre_in, R.anim.tran_pre_out);
}
});
du.getSimpleDialog(this, null, getString(R.string.cx_fa_accounting_account_sure_leave), null, null).show();
return;
}
}
finish();
overridePendingTransition(R.anim.tran_pre_in, R.anim.tran_pre_out);
}
private TextView tvOut;
private TextView tvIn;
private EditText tvMoney;
private TextView tvCategory;
private TextView tvFrom;
private TextView tvDate;
private TextView tvRemark;
private DateData date;
//已废弃不用
// protected void showMoneyDialog() {
// View view = View.inflate(this, R.layout.cx_fa_widget_accounting_money_dialog,null);
// final EditText moneyEt = (EditText) view.findViewById(R.id.cx_fa_accounting_change_account_money_dialog_et);
// Button cancelBtn = (Button) view.findViewById(R.id.cx_fa_accounting_change_account_money_dialog_cancel);
// Button okBtn = (Button) view.findViewById(R.id.cx_fa_accounting_change_account_money_dialog_ok);
//
// final Dialog dialog=new Dialog(this, R.style.simple_dialog);
// dialog.setContentView(view);
// cancelBtn.setOnClickListener(new OnClickListener() {
//
// @Override
// public void onClick(View v) {
// dialog.dismiss();
// }
// });
// okBtn.setOnClickListener(new OnClickListener() {
//
// @Override
// public void onClick(View v) {
// if(TextUtils.isEmpty(moneyEt.getText().toString().trim())){
// ToastUtil.getSimpleToast(RkChangeAccountActivity.this, -1, "你还没有输入金额!", 1).show();
//// moneyEt.setHint("你还没有输入金额!");
// }else {
//
// String money= moneyEt.getText().toString().trim();
// money=TextUtil.transforToMoney(money);
// if(TextUtils.isEmpty(money)){
// ToastUtil.getSimpleToast(RkChangeAccountActivity.this, -1, "输入金额过大,最大单位为亿。", 1).show();
// tvMoney.setText(TextUtil.getNewSpanStr("0", 14, Color.RED).toString());
// }else{
// if(money.contains(".")){
// ToastUtil.getSimpleToast(RkChangeAccountActivity.this, -1, "最小单位为元,请不要输入小数点。", 1).show();
// return ;
// }
// dialog.dismiss();
// tvMoney.setText(TextUtil.getNewSpanStr(money, 14, Color.RED).toString());
// }
// }
// }
// });
// dialog.show();
// }
//日期dialog
protected void showDateDialog() {
View view = View.inflate(this, R.layout.cx_fa_widget_accounting_date_dialog,null);
final DatePicker dateDp = (DatePicker) view.findViewById(R.id.cx_fa_accounting_change_account_date_dialog_dp);
Button cancelBtn = (Button) view.findViewById(R.id.cx_fa_accounting_change_account_date_dialog_cancel);
Button okBtn = (Button) view.findViewById(R.id.cx_fa_accounting_change_account_date_dialog_ok);
final Calendar c1 = Calendar.getInstance();
String dateStr = tvDate.getText().toString().trim();
String[] split = dateStr.split("-");
dateDp.init(Integer.parseInt(split[0]),
Integer.parseInt(split[1])-1,
Integer.parseInt(split[2]), new OnDateChangedListener(){
public void onDateChanged(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
c1.set(Calendar.YEAR, year);
c1.set(Calendar.MONTH, monthOfYear);
c1.set(Calendar.DAY_OF_MONTH, dayOfMonth);
}
});
EditText monthE = (EditText)((ViewGroup)((ViewGroup) ((ViewGroup) dateDp.getChildAt(0)).getChildAt(0)).getChildAt(1)).getChildAt(1);
EditText yearE = (EditText)((ViewGroup)((ViewGroup) ((ViewGroup) dateDp.getChildAt(0)).getChildAt(0)).getChildAt(0)).getChildAt(1);
EditText dayE = (EditText)((ViewGroup)((ViewGroup) ((ViewGroup) dateDp.getChildAt(0)).getChildAt(0)).getChildAt(2)).getChildAt(1);
if(yearE != null) {
yearE.setTextSize(16);
}
if(monthE != null) {
monthE.setTextSize(16);
}
if(dayE != null) {
dayE.setTextSize(16);
}
final Dialog dialog=new Dialog(this, R.style.simple_dialog);
dialog.setContentView(view);
cancelBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
okBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final DateData newDate=DateUtil.getNumberTime(c1.getTimeInMillis());
// if(newDate.getYear()>date.getYear() || (newDate.getYear()==date.getYear() && newDate.getMonth()>date.getMonth())
// || (newDate.getYear()==date.getYear() && newDate.getMonth()==date.getMonth() && newDate.getDay()>date.getDay())){
//
// ToastUtil.getSimpleToast(RkChangeAccountActivity.this, -1, "今天"+date.getDay()+"号,日期不能超过今天", 1).show();
// return ;
// }
dialog.dismiss();
tvDate.setText(newDate.getDateStr());
}
});
dialog.show();
}
private Dialog dialog;
protected void showCategoryOrFromDialog(int cateOrFrom) {
View view = View.inflate(this, R.layout.cx_fa_widget_accounting_categary_and_from_dialog,null);
LinearLayout out = (LinearLayout) view.findViewById(R.id.cx_fa_accounting_change_account_categary_out);
LinearLayout in = (LinearLayout) view.findViewById(R.id.cx_fa_accounting_change_account_categary_in);
LinearLayout from = (LinearLayout) view.findViewById(R.id.cx_fa_accounting_change_account_from);
Button cancelBtn = (Button) view.findViewById(R.id.cx_fa_accounting_change_account_category_dialog_cancel);
if(cateOrFrom==1){//1则弹出类别
from.setVisibility(View.GONE);
if(type==1){
in.setVisibility(View.GONE);
out.setVisibility(View.VISIBLE);
}else if(type==2){
out.setVisibility(View.GONE);
in.setVisibility(View.VISIBLE);
}
}else if(cateOrFrom==2){//2则弹出from
out.setVisibility(View.GONE);
in.setVisibility(View.GONE);
from.setVisibility(View.VISIBLE);
}
TextView out1= (TextView) view.findViewById(R.id.cx_fa_accounting_change_account_categary_dialog_out1);
TextView out2= (TextView) view.findViewById(R.id.cx_fa_accounting_change_account_categary_dialog_out2);
TextView out3= (TextView) view.findViewById(R.id.cx_fa_accounting_change_account_categary_dialog_out3);
TextView out4= (TextView) view.findViewById(R.id.cx_fa_accounting_change_account_categary_dialog_out4);
TextView out5= (TextView) view.findViewById(R.id.cx_fa_accounting_change_account_categary_dialog_out5);
TextView out6= (TextView) view.findViewById(R.id.cx_fa_accounting_change_account_categary_dialog_out6);
TextView out7= (TextView) view.findViewById(R.id.cx_fa_accounting_change_account_categary_dialog_out7);
TextView out8= (TextView) view.findViewById(R.id.cx_fa_accounting_change_account_categary_dialog_out8);
TextView in1= (TextView) view.findViewById(R.id.cx_fa_accounting_change_account_categary_dialog_in1);
TextView in2= (TextView) view.findViewById(R.id.cx_fa_accounting_change_account_categary_dialog_in2);
TextView in3= (TextView) view.findViewById(R.id.cx_fa_accounting_change_account_categary_dialog_in3);
TextView in4= (TextView) view.findViewById(R.id.cx_fa_accounting_change_account_categary_dialog_in4);
TextView me= (TextView) view.findViewById(R.id.cx_fa_accounting_change_account_from_me);
TextView opposite= (TextView) view.findViewById(R.id.cx_fa_accounting_change_account_from_opposite);
TextView both= (TextView) view.findViewById(R.id.cx_fa_accounting_change_account_from_both);
out1.setOnClickListener(categoryListener);
out2.setOnClickListener(categoryListener);
out3.setOnClickListener(categoryListener);
out4.setOnClickListener(categoryListener);
out5.setOnClickListener(categoryListener);
out6.setOnClickListener(categoryListener);
out7.setOnClickListener(categoryListener);
out8.setOnClickListener(categoryListener);
in1.setOnClickListener(categoryListener);
in2.setOnClickListener(categoryListener);
in3.setOnClickListener(categoryListener);
in4.setOnClickListener(categoryListener);
me.setOnClickListener(fromListener);
opposite.setOnClickListener(fromListener);
both.setOnClickListener(fromListener);
cancelBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog=new Dialog(this, R.style.simple_dialog);
dialog.setContentView(view);
dialog.show();
}
//来自点击
OnClickListener fromListener=new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
String from="";
switch (v.getId()) {
case R.id.cx_fa_accounting_change_account_from_me:
from=getString(R.string.cx_fa_accounting_account_me);
break;
case R.id.cx_fa_accounting_change_account_from_opposite:
from=getString(CxResourceString.getInstance().str_pair);
break;
case R.id.cx_fa_accounting_change_account_from_both:
from=getString(R.string.cx_fa_accounting_account_both);
break;
default:
break;
}
tvFrom.setText(from);
}
};
//类别点击
OnClickListener categoryListener =new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
String category="";
switch(v.getId()){
case R.id.cx_fa_accounting_change_account_categary_dialog_out1:
category=getString(R.string.cx_fa_accounting_category_out_athome_short);
break;
case R.id.cx_fa_accounting_change_account_categary_dialog_out2:
category=getString(R.string.cx_fa_accounting_category_out_traffic_short);
break;
case R.id.cx_fa_accounting_change_account_categary_dialog_out3:
category=getString(R.string.cx_fa_accounting_category_out_catering_short);
break;
case R.id.cx_fa_accounting_change_account_categary_dialog_out4:
category=getString(R.string.cx_fa_accounting_category_out_entertainment_short);
break;
case R.id.cx_fa_accounting_change_account_categary_dialog_out5:
category=getString(R.string.cx_fa_accounting_category_out_shopping_short);
break;
case R.id.cx_fa_accounting_change_account_categary_dialog_out6:
category=getString(R.string.cx_fa_accounting_category_out_education_short);
break;
case R.id.cx_fa_accounting_change_account_categary_dialog_out7:
category=getString(R.string.cx_fa_accounting_category_out_financial_short);
break;
case R.id.cx_fa_accounting_change_account_categary_dialog_out8:
category=getString(R.string.cx_fa_accounting_category_out_gratitude_short);
break;
case R.id.cx_fa_accounting_change_account_categary_dialog_in1:
category=getString(R.string.cx_fa_accounting_category_in_wages_short);
break;
case R.id.cx_fa_accounting_change_account_categary_dialog_in2:
category=getString(R.string.cx_fa_accounting_category_in_award_short);
break;
case R.id.cx_fa_accounting_change_account_categary_dialog_in3:
category=getString(R.string.cx_fa_accounting_category_in_investment_short);
break;
case R.id.cx_fa_accounting_change_account_categary_dialog_in4:
category=getString(R.string.cx_fa_accounting_category_in_other_short);
break;
}
tvCategory.setText(category);
}
};
//点击支出
protected void outOnClick() {
type=1;
layoutOut.setBackgroundResource(R.drawable.cx_fa_accounting_homepage_detail_bg_white);
tvOut.setText(TextUtil.getNewSpanStr(getString(R.string.cx_fa_accounting_out), 18, Color.rgb(235, 161, 121)));
layoutIn.setBackgroundResource(R.drawable.cx_fa_accounting_homepage_detail_bg_gray);
tvIn.setText(TextUtil.getNewSpanStr(getString(R.string.cx_fa_accounting_in), 16, Color.rgb(55, 50, 47)));
tempCategoryIn=tvCategory.getText().toString().trim();
if(!TextUtils.isEmpty(tempCategoryOut)){
tvCategory.setText(tempCategoryOut);
}else{
tvCategory.setText(getString(R.string.cx_fa_accounting_category_out_athome_short));
}
}
//点击收入
protected void inOnClick() {
type=2;
layoutIn.setBackgroundResource(R.drawable.cx_fa_accounting_homepage_detail_bg_white);
tvIn.setText(TextUtil.getNewSpanStr(getString(R.string.cx_fa_accounting_in), 18, Color.rgb(235, 161, 121)));
layoutOut.setBackgroundResource(R.drawable.cx_fa_accounting_homepage_detail_bg_gray);
tvOut.setText(TextUtil.getNewSpanStr(getString(R.string.cx_fa_accounting_out), 16, Color.rgb(55, 50, 47)));
tempCategoryOut=tvCategory.getText().toString().trim();
if(!TextUtils.isEmpty(tempCategoryIn)){
tvCategory.setText(tempCategoryIn);
}else{
tvCategory.setText(getString(R.string.cx_fa_accounting_category_in_wages_short));
}
}
JSONCaller delCaller = new JSONCaller() {
@Override
public int call(Object result) {
DialogUtil.getInstance().setLoadingDialogDismiss(null, -1, 1000);
if(result==null){
showResponseToast(getString(R.string.cx_fa_net_response_code_null),0);
return -1;
}
CxParseBasic del=null;
try {
del=(CxParseBasic) result;
} catch (Exception e) {
e.printStackTrace();
}
if(del==null || del.getRc()==408){
showResponseToast(getString(R.string.cx_fa_net_response_code_null),0);
return -2;
}
int rc=del.getRc();
if(0!=rc){
if(TextUtils.isEmpty(del.getMsg())){
showResponseToast(getString(R.string.cx_fa_net_response_code_fail),0);
}else{
showResponseToast(del.getMsg(),0);
}
return rc;
}
CxLog.i("men", ">>>>>>>>>>>>>>>>>>>2");
CxAccountingParam.getInstance().setDelAccount(accountId);
finish();
overridePendingTransition(R.anim.tran_pre_in, R.anim.tran_pre_out);
return 0;
}
};
JSONCaller updateCaller = new JSONCaller() {
@Override
public int call(Object result) {
DialogUtil.getInstance().setLoadingDialogDismiss(null, -1, 1000);
if(result==null){
showResponseToast(getString(R.string.cx_fa_net_response_code_null),0);
return -1;
}
CxParseBasic del=null;
try {
del=(CxParseBasic) result;
} catch (Exception e) {
e.printStackTrace();
}
if(del==null || del.getRc()==408){
showResponseToast(getString(R.string.cx_fa_net_response_code_null),0);
return -2;
}
int rc=del.getRc();
if(0!=rc){
if(TextUtils.isEmpty(del.getMsg())){
showResponseToast(getString(R.string.cx_fa_net_response_code_fail),0);
}else{
showResponseToast(del.getMsg(),0);
}
return rc;
}
CxAccountingParam.getInstance().setUpdateAccount("");
finish();
overridePendingTransition(R.anim.tran_pre_in, R.anim.tran_pre_out);
return 0;
}
};
private LinearLayout layoutOut;
private LinearLayout layoutIn;
private Dialog fromDialog;
private TextView titleText;
/**
*
* @param info
* @param number 0 失败;1 成功;2 不要图。
*/
private void showResponseToast(String info,int number) {
Message msg = new Message();
msg.obj = info;
msg.arg1=number;
new Handler(CxChangeAccountActivity.this.getMainLooper()) {
public void handleMessage(Message msg) {
if ((null == msg) || (null == msg.obj)) {
return;
}
int id=-1;
if(msg.arg1==0){
id= R.drawable.chatbg_update_error;
}else if(msg.arg1==1){
id=R.drawable.chatbg_update_success;
}
ToastUtil.getSimpleToast(CxChangeAccountActivity.this, id,
msg.obj.toString(), 1).show();
};
}.sendMessage(msg);
}
@Override
protected void onDestroy() {
super.onDestroy();
date=null;
}
public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {
if (keyCode == android.view.KeyEvent.KEYCODE_BACK) {
back();
return false;
}
return super.onKeyDown(keyCode, event);
};
TextWatcher textListener = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.length()>0){
tvMoney.setHint("");
}else{
tvMoney.setHint(TextUtil.getNewSpanStr("0", 20, Color.RED).toString());
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
};
}
|
package com.farm.report;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.farm.monitor.R;
import com.farm.monitor.R.color;
import com.farm.monitor.R.dimen;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Typeface;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.TableRow;
import android.widget.TextView;
import com.farm.db.DatabaseHandler;
import com.farm.db.DatabaseManager;
import com.farm.tables.MonitorPoint;
/*
* This class is used for generating monitor points report
*/
public class MonitorPointsReport {
public List<MonitorPoint> monitorpoints = null;
public List<String> columnHeaders = null;
public List<TextView> headersTextViewsList;
public Map columnPairs;
int columnCount = 0;
DatabaseHandler db = null;
Activity activity;
int cellHeight = 50, cellWidth = 120, headerCellHeight = 40;
int textSizeHeader = 16, textSizeRow = 15;
public MonitorPointsReport(Activity activity) {
try {
db = new DatabaseHandler();
this.activity = activity;
} catch (Exception e) {
}
}
/*
* Returns all monitor points
*/
List<MonitorPoint> getAllMonitorPoints() {
return monitorpoints;
}
/*
* gets all monitor points data from database
*/
public List<MonitorPoint> getAllDataList() {
monitorpoints = null;
String selectQuery;
Cursor cursor = null;
try {
monitorpoints = new ArrayList<MonitorPoint>();
selectQuery = "SELECT * FROM monitorpoint";
cursor = DatabaseManager.getInstance().openDatabase().rawQuery(selectQuery, null);
columnCount = cursor.getColumnCount();
if (cursor.moveToFirst()) {
do {
monitorpoints.add(new MonitorPoint(cursor.getInt(cursor.getColumnIndex("monitorpointid")),
cursor.getString(cursor.getColumnIndex("monitorpointname")),
cursor.getInt(cursor.getColumnIndex("pointid")),
cursor.getString(cursor.getColumnIndex("referenceimagepath")),
cursor.getString(cursor.getColumnIndex("imagespath")),
cursor.getString(cursor.getColumnIndex("monitorpointlocation"))));
} while (cursor.moveToNext());
}
} catch (Exception e) {
} finally {
cursor.close();
}
return monitorpoints;
}
/*
* Creates header names for monitor point report
*/
public List<String> getAllDataHeaders() {
columnHeaders = null;
Cursor cursor = null;
try {
columnHeaders = new ArrayList<String>();
String selectQuery = "SELECT monitorpointid as Id, monitorpointname as Name, monitorpointlocation as Location, pointid as pointid, referenceimagepath as Refimagepath ,imagespath as Imagespath FROM monitorpoint";
cursor = DatabaseManager.getInstance().openDatabase().rawQuery(selectQuery, null);
columnCount = cursor.getColumnCount();
columnHeaders.add("Name");
columnHeaders.add("Location");
columnHeaders.add("RefImagepath");
columnHeaders.add("ImagePath");
columnPairs = new HashMap<String, String>();
columnPairs.put("Name", "monitorpointname");
columnPairs.put("Location", "monitorpointlocation");
columnPairs.put("Refimagepath", "referenceimagepath");
columnPairs.put("imagespath", "Imagespath");
} catch (Exception e) {
} finally {
cursor.close();
}
return columnHeaders;
}
/*
* creates header row for monitor point report
*/
public TableRow getHeaderRow() {
try {
TableRow dataRow = (TableRow) activity.findViewById(R.id.tableRowMPHeader);
headersTextViewsList = new ArrayList<TextView>();
TableRow.LayoutParams params = new TableRow.LayoutParams();
TableRow.LayoutParams params1 = new TableRow.LayoutParams();
TextView t;
for (int i = 0; i < columnHeaders.size(); i++) {
if (columnHeaders.get(i).contains("Id"))
t = getHeaderTextView(columnHeaders.get(i), cellWidth - 30);
else if (columnHeaders.get(i).contains("Date") || columnHeaders.get(i).contains("Name"))
t = getHeaderTextView(columnHeaders.get(i), cellWidth + 40);
else
t = getHeaderTextView(columnHeaders.get(i), cellWidth);
dataRow.addView(t, params);
headersTextViewsList.add(t);
}
return dataRow;
} catch (Exception e) {
return null;
}
}
/*
* creates text view for monitor point report header
*/
public TextView getHeaderTextView(String text, int cellWidth) {
TextView t = new TextView(activity);
try {
t.setText(text);
t.setTextColor(activity.getResources().getColor(color.reportheadertextcolor));
t.setBackgroundColor(activity.getResources().getColor(color.reportheaderbackcolor));
t.setTextSize(activity.getResources().getDimension(dimen.reportheadertextsize));
int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, cellWidth,
activity.getResources().getDisplayMetrics());
t.setMaxWidth(px);
t.setMinimumWidth(px);
int he = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, headerCellHeight,
activity.getResources().getDisplayMetrics());
t.setMinimumHeight(he);
t.setMaxHeight(he);
int textSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, textSizeHeader,
activity.getResources().getDisplayMetrics());
t.setTextSize(textSize);
t.setGravity(Gravity.CENTER);
t.setSingleLine();
t.setTypeface(null, Typeface.BOLD);
} catch (Exception e) {
}
return t;
}
/*
* creates a table row for a monitorpoint record
*/
public TableRow getDataRow(int i) {
TableRow dataRow = new TableRow(activity);
try {
dataRow.setBackgroundColor(activity.getResources().getColor(color.reportrowbackcolor));
MonitorPoint monitorpoint = monitorpoints.get(i);
TableRow.LayoutParams params = new TableRow.LayoutParams();
dataRow.addView(getTextView("" + monitorpoint.monitorpointName, i, cellWidth + 40), params);
dataRow.addView(getTextView("" + monitorpoint.monitorpointLocation, i, cellWidth), params);
dataRow.addView(getTextView("" + monitorpoint.referenceImagePath, i, cellWidth), params);
dataRow.addView(getTextView("" + monitorpoint.imagesPath, i, cellWidth), params);
} catch (Exception e) {
}
return dataRow;
}
/*
* creates textview for monitorpoint row data
*/
public TextView getTextView(String text, int i, int cellWidth) {
TextView t = new TextView(activity);
try {
t.setText(text);
t.setTextColor(activity.getResources().getColor(color.reportdatatextcolor));
if (i % 2 == 0)
t.setBackgroundColor(activity.getResources().getColor(color.reportdatabackcolor1));
else
t.setBackgroundColor(activity.getResources().getColor(color.reportdatabackcolor2));
t.setTextSize(activity.getResources().getDimension(dimen.reportdatatextsize));
int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, cellWidth,
activity.getResources().getDisplayMetrics());
t.setMaxWidth(px);
t.setMinimumWidth(px);
int he = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, cellHeight,
activity.getResources().getDisplayMetrics());
t.setMinimumHeight(he);
t.setMaxHeight(he);
int textSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, textSizeRow,
activity.getResources().getDisplayMetrics());
t.setTextSize(textSize);
t.setGravity(Gravity.CENTER);
t.setSingleLine();
} catch (Exception e) {
}
return t;
}
}
|
package com.demo.modules.sys.entity;
import org.springframework.data.annotation.Id;
import java.io.Serializable;
import java.sql.Timestamp;
/**
* 系统日志
*
* @author Centling Techonlogies
* @email xxx@demo.com
* @url www.demo.com
* @date 2017年8月14日 下午8:05:17
*/
public class SysLogEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private Long id;
private Long userId;
private String username;
private String module;
private String operation;
private String method;
private String params;
private Long executeTime;
private String ip;
private Timestamp createTime;
public SysLogEntity() {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getParams() {
return params;
}
public void setParams(String params) {
this.params = params;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public Timestamp getCreateTime() {
return createTime;
}
public void setCreateTime(Timestamp createTime) {
this.createTime = createTime;
}
public String getModule() {
return module;
}
public void setModule(String module) {
this.module = module;
}
public Long getExecuteTime() {
return executeTime;
}
public void setExecuteTime(Long executeTime) {
this.executeTime = executeTime;
}
}
|
package com.mycompany.tripler_merge;
/**
* Created by Vidya Prabhu on 21-07-2017.
*/
import android.app.Application;
import android.content.Intent;
/**
* Created by Vidya Prabhu on 17-07-2017.
*/
import android.app.Application;
import android.content.Intent;
public class App extends Application {
@Override
public void onCreate(){
super.onCreate();
startService(new Intent(this,MyService.class));
}
}
|
package com.tencent.mm.plugin.account.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import com.tencent.mm.ab.l;
import com.tencent.mm.kernel.g;
import com.tencent.mm.modelfriend.a;
class o$13 implements OnClickListener {
final /* synthetic */ l bFp;
final /* synthetic */ o eTO;
o$13(o oVar, l lVar) {
this.eTO = oVar;
this.bFp = lVar;
}
public final void onClick(DialogInterface dialogInterface, int i) {
g.DF().a(701, this.eTO);
this.eTO.eSA = new g(new 1(this), ((a) this.bFp).getUsername(), ((a) this.bFp).Oi(), this.eTO.eTG.bTi);
this.eTO.eSA.a(this.eTO.eTG);
}
}
|
package com.weigs.BridgePattern;
/**
* @author weigs
* @date 2017/7/3 0003
*/
public class RedCircle implements DrawAPI{
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color:red, radius:"
+radius+",x:"+x+",y:"+y+"]");
}
}
|
package modul3.bruchrechnung;
public class Fraction {
private int numerator;
private int denominator;
private int wholeNumber;
public Fraction(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
public Fraction(int wholeNumber, int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
this.wholeNumber = wholeNumber;
}
public int getZaehler() {
return numerator;
}
public void setZaehler(int numerator) {
this.numerator = numerator;
}
public int getNenner() {
return denominator;
}
public void setNenner(int denominator) {
this.denominator = denominator;
}
public int getGanzZahl() {
return wholeNumber;
}
public void setGanzZahl(int wholeNumber) {
this.wholeNumber = wholeNumber;
}
private void correctionBruch(Fraction bruch) {
if (this.getZaehler() < 0 && this.denominator < 0) {
this.setZaehler(Math.abs(this.getZaehler()));
this.setNenner(Math.abs(this.getNenner()));
}
if (bruch.getZaehler() < 0 && bruch.getNenner() < 0) {
bruch.setZaehler(Math.abs(bruch.getZaehler()));
bruch.setNenner(Math.abs(bruch.getNenner()));
}
}
public Fraction multiplyBy(Fraction bruch) {
correctionBruch(bruch);
return new Fraction(this.numerator * bruch.getZaehler(), this.denominator * bruch.getNenner());
}
public Fraction divideBy(Fraction bruch) {
correctionBruch(bruch);
return new Fraction(numerator * bruch.getNenner(), denominator * bruch.getZaehler());
}
public Fraction add(Fraction bruch) {
int mainDenominator = denominator * bruch.getNenner();
return new Fraction((mainDenominator / denominator * numerator) + (mainDenominator / bruch.getNenner() * bruch.getZaehler()), mainDenominator);
}
public Fraction sub(Fraction bruch) {
int mainDenominator = denominator * bruch.getNenner();
return new Fraction((mainDenominator / denominator * numerator) - (mainDenominator / bruch.getNenner() * bruch.getZaehler()), mainDenominator);
}
public static Fraction reduceFraction(Fraction bruch) {
int denominator = bruch.getNenner();
int numerator = bruch.getZaehler();
int i = Math.abs(denominator);
while (i != 1) {
if ((denominator % i == 0) && (numerator % i == 0)) {
denominator = denominator / i;
numerator = numerator / i;
} else {
i--;
}
}
if (numerator > denominator) {
return new Fraction(numerator / denominator, numerator % denominator, denominator);
}
return new Fraction(numerator, denominator);
}
@Override
public String toString() {
if (wholeNumber >= 1) {
return wholeNumber + " " + numerator + "/" + denominator;
}
return numerator + "/" + denominator;
}
}
|
package com.mes.cep.meta.ProcessSegmentModel;
/**
* @author Stephen·Wen
* @email 872003894@qq.com
* @date 2017年4月18日
* @Chinesename 材料段规格
*/
public class MaterialSegmentSpecification {
}
|
package com.sdk4.boot.bo;
import com.alibaba.fastjson.JSON;
import com.sdk4.boot.enums.UserTypeEnum;
import com.sdk4.common.util.JWTUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;
/**
* 授权认证 Token 结构
*
* @author sh
*/
@Slf4j
@Data
public class Token {
private UserTypeEnum type;
private String login_id;
private Date expireTime;
private Map<String, Object> extra;
public boolean expire() {
boolean result = false;
if (expireTime != null && expireTime.getTime() < System.currentTimeMillis()) {
result = true;
}
return result;
}
public String tokenString() throws UnsupportedEncodingException {
String jsonString = JSON.toJSONString(this);
return JWTUtils.createJsonToken(jsonString);
}
public static Token create(LoginUser loginUser) {
Token token = new Token();
token.setType(loginUser.getUserType());
token.setLogin_id(loginUser.getLoginId());
token.setExpireTime(loginUser.getExpireTime());
return token;
}
public static Token parseToken(String tokenString) {
Token token = null;
try {
String jsonString = JWTUtils.verifyJsonToken(tokenString);
if (StringUtils.isNotEmpty(jsonString)) {
token = JSON.parseObject(jsonString, Token.class);
}
} catch (Exception e) {
log.error("解析token失败:{}", tokenString, e);
}
return token;
}
}
|
package com.travix.medusa.busyflights.domain.busyflights;
import java.time.LocalDate;
public class BusyFlightsRequest {
private String origin;
private String destination;
private LocalDate departureDate;
private LocalDate returnDate;
private int numberOfPassengers;
public BusyFlightsRequest(String origin, String destination, LocalDate departureDate, LocalDate returnDate,
int numberOfPassengers) {
super();
this.origin = origin;
this.destination = destination;
this.departureDate = departureDate;
this.returnDate = returnDate;
this.numberOfPassengers = numberOfPassengers;
}
public String getOrigin() {
return origin;
}
public void setOrigin(final String origin) {
this.origin = origin;
}
public String getDestination() {
return destination;
}
public void setDestination(final String destination) {
this.destination = destination;
}
public LocalDate getDepartureDate() {
return departureDate;
}
public void setDepartureDate(final LocalDate departureDate) {
this.departureDate = departureDate;
}
public LocalDate getReturnDate() {
return returnDate;
}
public void setReturnDate(final LocalDate returnDate) {
this.returnDate = returnDate;
}
public int getNumberOfPassengers() {
return numberOfPassengers;
}
public void setNumberOfPassengers(final int numberOfPassengers) {
this.numberOfPassengers = numberOfPassengers;
}
}
|
/*
* 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 project;
/**
*
* @author ASUS
*/
public class SinhVien {
private String maSV;
private String tenSV;
private String namSinh;
private Lop lop;
private Khoa khoa;
private String diaChi;
public SinhVien() {
}
public SinhVien(String maSV, String tenSV, String namSinh, Lop lop, Khoa khoa, String diaChi) {
this.maSV = maSV;
this.tenSV = tenSV;
this.namSinh = namSinh;
this.lop = lop;
this.khoa = khoa;
this.diaChi = diaChi;
}
public String getMaSV() {
return maSV;
}
public void setMaSV(String maSV) {
this.maSV = maSV;
}
public String getTenSV() {
return tenSV;
}
public void setTenSV(String tenSV) {
this.tenSV = tenSV;
}
public String getNamSinh() {
return namSinh;
}
public void setNamSinh(String namSinh) {
this.namSinh = namSinh;
}
public Lop getLop() {
return lop;
}
public void setLop(Lop lop) {
this.lop = lop;
}
public Khoa getKhoa() {
return khoa;
}
public void setKhoa(Khoa khoa) {
this.khoa = khoa;
}
public String getDiaChi() {
return diaChi;
}
public void setDiaChi(String diaChi) {
this.diaChi = diaChi;
}
public String stringGhiFile(){
return this.maSV + ":" + this.tenSV + ":" + this.namSinh + ":" +
khoa.getTenKhoa() + ":" + lop.getTenLop() + ":" + this.diaChi;
}
}
|
package lists;
import java.util.Comparator;
import entities.Invoice;
public class TotalComparator<E> implements Comparator<E>{
//Returns a value greater than 0 if the first argument has a larger grand total than the second argument
//Returns a value less than 0 if the second argument has a larger grand total than the first argument
@Override
public int compare(E arg0, E arg1) {
// TODO Auto-generated method stub
return (int) (Math.round(((Invoice) arg0).getInvoiceGrandTotal()) - Math.round(((Invoice) arg1).getInvoiceGrandTotal()));
}
}
|
package com.tencent.mm.pluginsdk.model;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import com.tencent.mm.pluginsdk.model.h.a;
import java.util.ArrayList;
class h$1 extends AsyncTask<Void, Void, Cursor> {
final /* synthetic */ String[] qyN;
final /* synthetic */ a qyO;
final /* synthetic */ Context val$context;
h$1(Context context, String[] strArr, a aVar) {
this.val$context = context;
this.qyN = strArr;
this.qyO = aVar;
}
protected final /* synthetic */ Object doInBackground(Object[] objArr) {
return this.val$context.getContentResolver().query(Uri.parse("content://com.tencent.mm.plugin.gwallet.queryprovider"), null, null, this.qyN, null);
}
protected final /* synthetic */ void onPostExecute(Object obj) {
Cursor cursor = (Cursor) obj;
if (cursor == null || cursor.getCount() <= 0) {
ArrayList arrayList = new ArrayList();
for (String nVar : this.qyN) {
arrayList.add(new n(-1, nVar, "", "", "", 10237));
}
this.qyO.u(arrayList);
} else {
cursor.moveToFirst();
ArrayList m = h.m(cursor);
cursor.close();
this.qyO.u(m);
}
super.onPostExecute(cursor);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.beweb.lunel.programmation.exosEnVrac.algo;
/**
*
* @author lowas
*/
public class Exercice7 {
public static void launch(){
String bonjour = "bonjour";
String bonsoir = "bonsoir";
// Init morning pour pas avoir de fail
boolean morning = true;
if (morning) {
System.out.println(bonjour + " vous");
}else{
System.out.println(bonsoir + " vous");
}
System.out.println("Exo 7 : #chuck-norris { color: #BADA55; } " +
"} ");
}
}
|
package ex1;
/*
@luizASSilveira
*/
import java.util.ArrayList;
public class Monitor {
private ArrayList<String> buffer = new ArrayList<>();
private int sizeBuffer;
private int contConsumidor = 0;
private int contPublicador = 0;
private boolean empty = true;
public Monitor(int sizeBuffer) {
this.sizeBuffer = sizeBuffer;
}
public synchronized String take(){
while ( empty || (this.contPublicador <= this.contConsumidor)) { //or para nao pegar buffer vazio
try {
wait();
} catch (InterruptedException e){
System.out.println(e);
}
}
empty = true;
notifyAll();
String message = this.buffer.get( this.contConsumidor % this.sizeBuffer );
this.contConsumidor++;
return message;
}
public synchronized void put(String menssage){
while ( !empty ){
try {
wait();
}catch (InterruptedException e) {
System.out.println(e);
}
}
empty = false;
this.buffer.add( this.contPublicador % this.sizeBuffer, menssage);
this.contPublicador++;
notifyAll();
}
public int getPosition() {
return this.contConsumidor % this.sizeBuffer;
}
}
|
package com.facebook.react.common;
import java.util.HashMap;
import java.util.Map;
public class MapBuilder {
public static <K, V> Builder<K, V> builder() {
return new Builder<K, V>();
}
public static <K, V> HashMap<K, V> newHashMap() {
return new HashMap<K, V>();
}
public static <K, V> Map<K, V> of() {
return newHashMap();
}
public static <K, V> Map<K, V> of(K paramK, V paramV) {
Map<?, ?> map = of();
map.put(paramK, paramV);
return (Map)map;
}
public static <K, V> Map<K, V> of(K paramK1, V paramV1, K paramK2, V paramV2) {
Map<?, ?> map = of();
map.put(paramK1, paramV1);
map.put(paramK2, paramV2);
return (Map)map;
}
public static <K, V> Map<K, V> of(K paramK1, V paramV1, K paramK2, V paramV2, K paramK3, V paramV3) {
Map<?, ?> map = of();
map.put(paramK1, paramV1);
map.put(paramK2, paramV2);
map.put(paramK3, paramV3);
return (Map)map;
}
public static <K, V> Map<K, V> of(K paramK1, V paramV1, K paramK2, V paramV2, K paramK3, V paramV3, K paramK4, V paramV4) {
Map<?, ?> map = of();
map.put(paramK1, paramV1);
map.put(paramK2, paramV2);
map.put(paramK3, paramV3);
map.put(paramK4, paramV4);
return (Map)map;
}
public static <K, V> Map<K, V> of(K paramK1, V paramV1, K paramK2, V paramV2, K paramK3, V paramV3, K paramK4, V paramV4, K paramK5, V paramV5) {
Map<?, ?> map = of();
map.put(paramK1, paramV1);
map.put(paramK2, paramV2);
map.put(paramK3, paramV3);
map.put(paramK4, paramV4);
map.put(paramK5, paramV5);
return (Map)map;
}
public static <K, V> Map<K, V> of(K paramK1, V paramV1, K paramK2, V paramV2, K paramK3, V paramV3, K paramK4, V paramV4, K paramK5, V paramV5, K paramK6, V paramV6) {
Map<?, ?> map = of();
map.put(paramK1, paramV1);
map.put(paramK2, paramV2);
map.put(paramK3, paramV3);
map.put(paramK4, paramV4);
map.put(paramK5, paramV5);
map.put(paramK6, paramV6);
return (Map)map;
}
public static <K, V> Map<K, V> of(K paramK1, V paramV1, K paramK2, V paramV2, K paramK3, V paramV3, K paramK4, V paramV4, K paramK5, V paramV5, K paramK6, V paramV6, K paramK7, V paramV7) {
Map<?, ?> map = of();
map.put(paramK1, paramV1);
map.put(paramK2, paramV2);
map.put(paramK3, paramV3);
map.put(paramK4, paramV4);
map.put(paramK5, paramV5);
map.put(paramK6, paramV6);
map.put(paramK7, paramV7);
return (Map)map;
}
public static final class Builder<K, V> {
private Map mMap = MapBuilder.newHashMap();
private boolean mUnderConstruction = true;
private Builder() {}
public final Map<K, V> build() {
if (this.mUnderConstruction) {
this.mUnderConstruction = false;
return this.mMap;
}
throw new IllegalStateException("Underlying map has already been built");
}
public final Builder<K, V> put(K param1K, V param1V) {
if (this.mUnderConstruction) {
this.mMap.put(param1K, param1V);
return this;
}
throw new IllegalStateException("Underlying map has already been built");
}
}
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\common\MapBuilder.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package com.example.nkalchos19.aim1;
/**
* Created by Nkalchos19 on 2/4/2019.
*/
public class Contact {
public int contactID;
public String firstName;
public String lastName;
public String phone;
public String email;
public String contactType;
public Contact (int contactID, String firstName, String lastName, String phone, String email, String contactType)
{
this.contactID = contactID;
this.firstName = firstName;
this.lastName = lastName;
this.phone = phone;
this.email = email;
this.contactType = contactType;
}
public int getContactID() {
return contactID;
}
public void setContactID(int contactID) {
this.contactID = contactID;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getContactType() {
return contactType;
}
public void setContactType(String contactType) {
this.contactType = contactType;
}
}
|
package com.tencent.mm.aa;
import android.annotation.SuppressLint;
import com.tencent.mm.a.o;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.modelsfs.FileOp;
import com.tencent.mm.network.u;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.ao;
import com.tencent.mm.sdk.platformtools.at;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.ab;
import java.io.InputStream;
import java.io.OutputStream;
import junit.framework.Assert;
import org.xwalk.core.XWalkUpdater;
public final class g implements e {
private at dHA = null;
j dHh = null;
b dHx = null;
m dHy = null;
boolean dHz = false;
public interface b {
int bd(int i, int i2);
}
@SuppressLint({"DefaultLocale"})
class a implements com.tencent.mm.sdk.platformtools.at.a {
public String dHB = null;
public boolean dHC = true;
private com.tencent.mm.compatible.util.g.a dHD;
public j dHd = null;
public a(j jVar) {
this.dHd = jVar;
this.dHB = q.Kp().c(jVar.getUsername(), true, false);
this.dHD = new com.tencent.mm.compatible.util.g.a();
}
public final boolean Kr() {
Throwable e;
OutputStream outputStream;
if (this.dHd == null) {
return false;
}
String Kx = this.dHd.Kx();
String str = "";
if (com.tencent.mm.kernel.g.Eg().Dx()) {
r3 = new Object[4];
com.tencent.mm.kernel.g.Eg();
r3[1] = o.getString(com.tencent.mm.kernel.a.Df());
r3[2] = Integer.valueOf(ao.getNetTypeForStat(ad.getContext()));
r3[3] = Integer.valueOf(ao.getStrength(ad.getContext()));
str = String.format("http://weixin.qq.com/?version=%d&uin=%s&nettype=%d&signal=%d", r3);
}
x.d("MicroMsg.GetHDHeadImgHelper", "dkreferer dkavatar user: %s referer: %s url:%s", this.dHd.getUsername(), str, Kx);
this.dHC = true;
u a;
InputStream inputStream;
try {
a = com.tencent.mm.network.b.a(Kx, null);
try {
a.setRequestMethod("GET");
a.setRequestProperty("referer", str);
a.setConnectTimeout(5000);
a.setReadTimeout(5000);
if (com.tencent.mm.network.b.a(a) != 0) {
x.e("MicroMsg.GetHDHeadImgHelper", "checkHttpConnection failed! url:%s", Kx);
return true;
}
inputStream = a.getInputStream();
if (inputStream == null) {
try {
x.d("MicroMsg.GetHDHeadImgHelper", "getInputStream failed. url:%s", Kx);
return true;
} catch (Exception e2) {
e = e2;
outputStream = null;
x.e("MicroMsg.GetHDHeadImgHelper", "exception:%s", bi.i(e));
this.dHC = true;
if (a != null) {
try {
a.aBv.disconnect();
} catch (Throwable e3) {
x.e("MicroMsg.GetHDHeadImgHelper", "exception:%s", bi.i(e3));
x.e("MicroMsg.GetHDHeadImgHelper", "close conn failed : %s", e3.getMessage());
}
}
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
return true;
}
}
byte[] bArr = new byte[1024];
outputStream = FileOp.jx(this.dHB + ".tmp");
while (true) {
try {
int read = inputStream.read(bArr);
if (read == -1) {
break;
}
outputStream.write(bArr, 0, read);
} catch (Exception e4) {
e3 = e4;
x.e("MicroMsg.GetHDHeadImgHelper", "exception:%s", bi.i(e3));
this.dHC = true;
if (a != null) {
try {
a.aBv.disconnect();
} catch (Throwable e32) {
x.e("MicroMsg.GetHDHeadImgHelper", "exception:%s", bi.i(e32));
x.e("MicroMsg.GetHDHeadImgHelper", "close conn failed : %s", e32.getMessage());
}
}
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
return true;
}
}
this.dHC = false;
outputStream.close();
a.aBv.disconnect();
try {
inputStream.close();
inputStream = null;
outputStream = null;
a = null;
} catch (Exception e5) {
e32 = e5;
outputStream = null;
a = null;
x.e("MicroMsg.GetHDHeadImgHelper", "exception:%s", bi.i(e32));
this.dHC = true;
if (a != null) {
try {
a.aBv.disconnect();
} catch (Throwable e322) {
x.e("MicroMsg.GetHDHeadImgHelper", "exception:%s", bi.i(e322));
x.e("MicroMsg.GetHDHeadImgHelper", "close conn failed : %s", e322.getMessage());
}
}
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
return true;
}
if (a != null) {
try {
a.aBv.disconnect();
} catch (Throwable e3222) {
x.e("MicroMsg.GetHDHeadImgHelper", "exception:%s", bi.i(e3222));
x.e("MicroMsg.GetHDHeadImgHelper", "close conn failed : %s", e3222.getMessage());
}
}
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
return true;
} catch (Exception e6) {
e3222 = e6;
inputStream = null;
outputStream = null;
x.e("MicroMsg.GetHDHeadImgHelper", "exception:%s", bi.i(e3222));
this.dHC = true;
if (a != null) {
try {
a.aBv.disconnect();
} catch (Throwable e32222) {
x.e("MicroMsg.GetHDHeadImgHelper", "exception:%s", bi.i(e32222));
x.e("MicroMsg.GetHDHeadImgHelper", "close conn failed : %s", e32222.getMessage());
}
}
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
return true;
}
} catch (Exception e7) {
e32222 = e7;
inputStream = null;
outputStream = null;
a = null;
}
}
public final boolean Ks() {
if (g.this.dHz) {
return false;
}
if (this.dHC || bi.oW(this.dHB)) {
g.this.dHx.bd(4, -1);
return false;
}
x.d("MicroMsg.GetHDHeadImgHelper", "dkavatar user:" + this.dHd.getUsername() + " urltime:" + this.dHD.Ad());
if (com.tencent.mm.model.am.a.dBs != null) {
com.tencent.mm.model.am.a.dBs.aY((int) FileOp.mI(this.dHB + ".tmp"), 0);
}
FileOp.deleteFile(this.dHB);
FileOp.av(this.dHB + ".tmp", this.dHB);
m.ae(this.dHB, g.this.dHh.getUsername());
g.this.dHx.bd(0, 0);
return true;
}
}
public g() {
com.tencent.mm.kernel.g.DF().a(158, (e) this);
}
public final void Ku() {
com.tencent.mm.kernel.g.DF().b(158, (e) this);
}
public final int a(String str, b bVar) {
Assert.assertTrue("GetHDHeadImg must set callback", true);
if (bi.oW(str)) {
bVar.bd(3, XWalkUpdater.ERROR_SET_VERNUM);
return XWalkUpdater.ERROR_SET_VERNUM;
}
String XV;
this.dHx = bVar;
if (ab.gY(str)) {
XV = ab.XV(str);
} else {
XV = str;
}
this.dHh = q.KH().kc(XV);
x.d("MicroMsg.GetHDHeadImgHelper", "GetHDHeadImg: %s", XV);
if (this.dHh == null || !this.dHh.getUsername().equals(XV)) {
this.dHh = new j();
this.dHh.username = XV;
}
if (bi.oW(this.dHh.Kx())) {
x.w("MicroMsg.GetHDHeadImgHelper", "dkhurl [%s] has NO URL flag:%d !", str, Integer.valueOf(this.dHh.csA));
this.dHy = new m(XV);
if (com.tencent.mm.kernel.g.DF().a(this.dHy, 0)) {
return 0;
}
bVar.bd(3, -102);
return -102;
}
j jVar = this.dHh;
if (this.dHA == null || this.dHA.ciz()) {
this.dHA = new at(1, "get-hd-headimg", 1);
}
if (this.dHA.c(new a(jVar)) == 0) {
return 0;
}
bVar.bd(3, -103);
return -103;
}
public final void a(int i, int i2, String str, l lVar) {
this.dHx.bd(i, i2);
}
}
|
package repls04;
import java.util.*;
public class UniqueNum {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int size = scan.nextInt();
int[] nums = new int[size];
for (int i = 0; i < size; i++) {
nums[i] = scan.nextInt();
}
int count =0;
for(int n =0;n < nums.length; n++){
for(int k =0; k < nums.length;k++){
if( n !=k && nums[n] == nums[k]){
count++;
}
}
if(count ==0){
System.out.println(nums[n]);
}
}
}
}
|
/*
* created 12.12.2005
*
* $Id:ForeignKeyEditPart.java 2 2005-11-02 03:04:20Z csell $
*/
package com.byterefinery.rmbench.util;
import org.eclipse.draw2d.Cursors;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.gef.ConnectionEditPart;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.Request;
import org.eclipse.gef.requests.ReconnectRequest;
import org.eclipse.gef.tools.ConnectionEndpointTracker;
import org.eclipse.swt.graphics.Cursor;
import com.byterefinery.rmbench.editparts.ForeignKeyEditPart;
import com.byterefinery.rmbench.figures.MoveableAnchor;
import com.byterefinery.rmbench.operations.MoveAnchorOperation;
/**
* Tracker for anchor movement.
*
* @author Hannes Niederhausen
*
*/
public class RMBConnectionEndpointTracker extends ConnectionEndpointTracker {
private String commandName;
/*
* a reconnect request that maintains the target reference. We dont want reconnect
* operations, therefore this avoids routing anomalies during dragging of connection
* endpoints
*/
private static class ReconnectRequest2 extends ReconnectRequest {
public void setTargetEditPart(EditPart part) {
//part might be null => ignore
}
public EditPart getTarget() {
return getConnectionEditPart().getTarget();
}
}
public RMBConnectionEndpointTracker(ConnectionEditPart cep, String commandName) {
super(cep);
setCommandName(commandName);
}
protected Cursor getDefaultCursor() {
return Cursors.SIZEALL;
}
protected Request createTargetRequest() {
ReconnectRequest request = new ReconnectRequest2();
Point location = new Point();
location.x = getStartLocation().x + getDragMoveDelta().width;
location.y = getStartLocation().y + getDragMoveDelta().height;
request.setLocation(location);
request.setConnectionEditPart(getConnectionEditPart());
request.setType(getCommandName());
return request;
}
public void setCommandName(String newCommandName) {
commandName = newCommandName;
}
protected String getCommandName() {
return commandName;
}
protected boolean handleMove() {
return true;
}
protected boolean handleButtonDown(int button) {
MoveableAnchor anchor = null;
if (commandName.equals(REQ_RECONNECT_SOURCE)) {
anchor = (MoveableAnchor) ((ForeignKeyEditPart) getConnectionEditPart()).getSourceConnectionAnchor();
} else {
anchor = (MoveableAnchor) ((ForeignKeyEditPart) getConnectionEditPart()).getTargetConnectionAnchor();
}
anchor.setPreview(true);
return super.handleButtonDown(button);
}
protected boolean handleButtonUp(int button) {
MoveableAnchor anchor = null;
if (commandName.equals(REQ_RECONNECT_SOURCE)) {
anchor = (MoveableAnchor) ((ForeignKeyEditPart) getConnectionEditPart())
.getSourceConnectionAnchor();
}
else {
anchor = (MoveableAnchor) ((ForeignKeyEditPart) getConnectionEditPart())
.getTargetConnectionAnchor();
}
anchor.setPreview(false);
MoveAnchorOperation op = new MoveAnchorOperation(anchor, anchor.getEdge(), anchor
.getSlotNumber());
op.execute(this);
return super.handleButtonUp(button);
}
protected Cursor calculateCursor() {
return Cursors.SIZEALL;
}
}
|
package util.media;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import com.coremedia.iso.boxes.Container;
import com.googlecode.mp4parser.authoring.Movie;
import com.googlecode.mp4parser.authoring.Track;
import com.googlecode.mp4parser.authoring.builder.DefaultMp4Builder;
import com.googlecode.mp4parser.authoring.container.mp4.MovieCreator;
public class ComMediaUtil {
public static boolean mux(String videoFile, String audioFile, String outputFile) {
Movie video;
try {
video = new MovieCreator().build(videoFile);
} catch (RuntimeException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
Movie audio;
try {
audio = new MovieCreator().build(audioFile);
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (NullPointerException e) {
e.printStackTrace();
return false;
}
Track audioTrack = audio.getTracks().get(0);
video.addTrack(audioTrack);
Container out = new DefaultMp4Builder().build(video);
FileOutputStream fos;
try {
fos = new FileOutputStream(outputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
BufferedWritableFileByteChannel byteBufferByteChannel = new BufferedWritableFileByteChannel(fos);
try {
out.writeContainer(byteBufferByteChannel);
byteBufferByteChannel.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
private static class BufferedWritableFileByteChannel implements WritableByteChannel {
private static final int BUFFER_CAPACITY = 1000000;
private boolean isOpen = true;
private final OutputStream outputStream;
private final ByteBuffer byteBuffer;
private final byte[] rawBuffer = new byte[BUFFER_CAPACITY];
private BufferedWritableFileByteChannel(OutputStream outputStream) {
this.outputStream = outputStream;
this.byteBuffer = ByteBuffer.wrap(rawBuffer);
}
@Override
public int write(ByteBuffer inputBuffer) throws IOException {
int inputBytes = inputBuffer.remaining();
if (inputBytes > byteBuffer.remaining()) {
dumpToFile();
byteBuffer.clear();
if (inputBytes > byteBuffer.remaining()) {
throw new BufferOverflowException();
}
}
byteBuffer.put(inputBuffer);
return inputBytes;
}
@Override
public boolean isOpen() {
return isOpen;
}
@Override
public void close() throws IOException {
dumpToFile();
isOpen = false;
}
private void dumpToFile() {
try {
outputStream.write(rawBuffer, 0, byteBuffer.position());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] args) {
mux("F:\\download\\youtube\\Chinajoy SG.mp4", "F:\\download\\youtube\\Chinajoy SG.webm", "F:\\download\\youtube\\Chinajoy SG_.mp4");
}
}
|
package view;
import java.util.Scanner;
import entity.Account;
public class AccountView {
private Account account;
private int accId;
private double money;
private String password;
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAccId() {
return accId;
}
public void setAccId(int accId) {
this.accId = accId;
}
public void addAccount(){
System.out.println("输入账户编号");
accId=Integer.parseInt(getString());
System.out.println("输入账户密码");
password=getString();
System.out.println("请输入充值金额");
money=Double.parseDouble(getString());
account = new Account(accId,money,password);
}
public void lookAcc(){
System.out.println("输入账户编号");
accId=Integer.parseInt(getString());
}
public void addMoney(){
System.out.println("请输入充值金额");
money=Double.parseDouble(getString());
}
public void subMoney(){
System.out.println("请输入转出金额");
money=Double.parseDouble(getString());
}
public void modifyPassword(){
System.out.println("输入新账户密码");
password= getString();
}
public void checkPassword(){
System.out.println("输入支付密码");
password=getString();
}
public void look(Account a){
System.out.println("账户编号:"+a.getAccId()+"\t 余额:"+a.getMoney()+"\t");
}
private String getString() {
Scanner sc= new Scanner(System.in);
return sc.next();
}
}
|
package com.example.spring04.modelVO;
public class Criteria {
private int atPage;
private int perPagePost;
private int startPost;
private int endPost;
public Criteria() {
this.atPage = 1;
this.perPagePost = 10;
}
public void setAtPage(int atPage) {
if(atPage <= 0) {
this.atPage = 1;
return;
}
this.atPage = atPage;
}
public void setPerPagePost(int perPagePost) {
if(perPagePost <= 0 || perPagePost > 100) {
this.perPagePost = 10;
return;
}
this.perPagePost = perPagePost;
}
public int getAtPage() {
return atPage;
}
// public int getStartPost () {
// return (this.atPage - 1) * perPagePost;
// }
public int getPerPagePost() {
return this.perPagePost;
}
public int getStartPost() {
startPost = ((atPage - 1) * perPagePost) + 1;
return startPost;
}
public int getEndPost() {
endPost = startPost + perPagePost -1;
return endPost;
}
@Override
public String toString() {
return "Criteria [atPage=" + atPage + ", perPagePost=" + perPagePost + ", startPost=" + startPost + ", endPost="
+ endPost + "]";
}
}
|
package org.alienideology.jcord.event.handler;
import org.alienideology.jcord.event.guild.member.GuildMemberLeaveEvent;
import org.alienideology.jcord.internal.object.IdentityImpl;
import org.alienideology.jcord.internal.object.guild.Guild;
import org.alienideology.jcord.internal.object.guild.Member;
import org.json.JSONObject;
/**
* @author AlienIdeology
*/
public class GuildMemberRemoveEventHandler extends EventHandler {
public GuildMemberRemoveEventHandler(IdentityImpl identity) {
super(identity);
}
@Override
public void dispatchEvent(JSONObject json, int sequence) {
Guild guild = (Guild) identity.getGuild(json.getString("guild_id"));
Member member = guild.removeMember(json.getJSONObject("user").getString("id"));
dispatchEvent(new GuildMemberLeaveEvent(identity, guild, sequence, member));
}
}
|
package ru.learn2code.yrank.service;
import ru.learn2code.yrank.model.User;
public interface UserService {
User save(User user);
User findByUsername(String username);
User getCurrentUser();
User findByEmail(String email);
void saveDefaultSettings();
}
|
/**
*
*/
package com.dev.jdbc;
/**
* @author Tejas Chaudhary
*
*/
public class Comments {
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.