text
stringlengths
10
2.72M
package com.bluecode.mhmd.prototypes; import android.app.Activity; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.TextView; import com.bluecode.mhmd.prototypes.Component.CircleProgressBar; public class FitnessApp1 extends Activity implements SensorEventListener { private CircleProgressBar myCircleProgress; private SensorManager mSensorManager; private Sensor mStep; private TextView stepTxt; private int stepDetector = 0; private int counterSteps = 0; private int stepCounter = 0; int progress = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(com.bluecode.mhmd.prototypes.R.layout.activity_main); myCircleProgress = findViewById(R.id.progressBar); stepTxt = findViewById(R.id.txt_progress_steps); mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mStep = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER); } @Override public void onSensorChanged(SensorEvent sensorEvent) { switch (sensorEvent.sensor.getType()) { case Sensor.TYPE_STEP_COUNTER: if (counterSteps < 1) { counterSteps = (int)sensorEvent.values[0]; } progress = (int)sensorEvent.values[0] - counterSteps; myCircleProgress.setProgress(progress); stepTxt.setText(progress + ""); break; case Sensor.TYPE_STEP_DETECTOR: stepDetector++; break; } } @Override public void onAccuracyChanged(Sensor sensor, int i) { } @Override protected void onResume() { super.onResume(); mSensorManager.registerListener(this, mStep, SensorManager.SENSOR_DELAY_FASTEST); } @Override protected void onPause() { super.onPause(); mSensorManager.unregisterListener(this); } }
package com.wangzhu.other; /** * Created by wang.zhu on 2021-03-09 17:27. **/ public class OuterClassBean { private int a = 1; private static int b = 20; private static final int c = 30; static void outerStaticMethod() { } void outerMethod() { } /** * 静态内部类 * 可以有自己的成员变量、静态变量 * 可以有静态方法、成员方法 * 静态方法:自己的静态变量、外部类的静态变量 * 成员方法:自己的静态变量、外部类的静态变量、自己的成员变量 */ public static class A { private int aA = 2; private static int bA = 21; private static final int cA = 31; public void innerMethod() { System.out.println(aA); System.out.println(A.bA); System.out.println(A.cA); // System.out.println(OuterClassBean.this.a); System.out.println(OuterClassBean.b); System.out.println(OuterClassBean.c); // OuterClassBean.this.outerMethod(); OuterClassBean.outerStaticMethod(); } public static void innerStaticMethod() { System.out.println(A.bA); System.out.println(A.cA); System.out.println(OuterClassBean.b); System.out.println(OuterClassBean.c); OuterClassBean.outerStaticMethod(); } } /** * 成员内部类 * 可以有自己的成员变量 * 可以有成员方法 * 成员方法:外部类的静态变量、自己的成员变量、外部类的成员变量 */ public class B { private int aB = 3; // private static int bB = 22; private static final int cB = 32; public void innerMethod() { System.out.println(aB); System.out.println(cB); System.out.println(OuterClassBean.this.a); System.out.println(OuterClassBean.b); System.out.println(OuterClassBean.c); OuterClassBean.outerStaticMethod(); OuterClassBean.this.outerMethod(); } // private static void innerStaticMethod() { // // } } public class C extends B { } public class D extends A { private void cal() { System.out.println(OuterClassBean.b); System.out.println(OuterClassBean.this.a); } } public static class E extends A { private void cal() { System.out.println(OuterClassBean.b); // System.out.println(InnerClassBean.this.a); } } //创建静态内部类对象的一般形式为: 外部类类名.内部类类名 xxx = new 外部类类名.内部类类名() //创建成员内部类对象的一般形式为: 外部类类名.内部类类名 xxx = 外部类对象名.new 内部类类名() private void builderV1() { OuterClassBean.A aa = new OuterClassBean.A(); aa.innerMethod(); OuterClassBean.A.innerStaticMethod(); OuterClassBean outerClassBean = new OuterClassBean(); OuterClassBean.B b = outerClassBean.new B(); b.innerMethod(); new B(); } private static void builderV2() { OuterClassBean.A aa = new OuterClassBean.A(); aa.innerMethod(); OuterClassBean.A.innerStaticMethod(); OuterClassBean outerClassBean = new OuterClassBean(); OuterClassBean.B b = outerClassBean.new B(); b.innerMethod(); // new B(); } }
package com.java9whatsnew.language_improvements; import java.util.Optional; public class OptionalOr { public static void main(String[] args) { // antes, no java 8 Optional<Book> localFallback = Optional.of(Book.getBook()); Book bestBookBefore = getBestOffer() .orElse(getExternalOffer().orElse(localFallback.get())); // .get eh RUIM // .get eh ruim pois nao sabemos se um livro vai ser realmente retornado // tambem precisamos ficar concatenando chamadas orElse System.out.println(bestBookBefore); System.out.println("===================================="); // java 9 metodo or Optional<Book> bestBookAfter = getBestOffer() .or(() -> getExternalOffer()) // como essa chamada retorna um optional com valor, o proximo elo (or) nao sera chamado .or(() -> localFallback); System.out.println(bestBookAfter); } private static Optional<Book> getExternalOffer() { return Optional.of(Book.getBook("External Book", "Bruxao", 10.50)); } private static Optional<Book> getBestOffer() { return Optional.empty(); } }
package com.ethan.df.singleton_pattern; import java.io.ObjectStreamException; /** * 饿汉单例模式 */ public class HungrySingleton { private static final HungrySingleton mInstance = new HungrySingleton(); private HungrySingleton() { } public static HungrySingleton getInstance() { return mInstance; } /** * 反序列化钩子函数 * 防止反序列化时重新创建实例的现象 */ private Object readResolve() throws ObjectStreamException { return mInstance; } }
package com.penglai.haima.adapter; import androidx.annotation.Nullable; import android.widget.TextView; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.penglai.haima.R; import com.penglai.haima.bean.ProductSelectBean; import java.util.List; /** * Created by ${flyjiang} on 2019/10/17. * 文件说明: */ public class ProductSelectAdapter extends BaseQuickAdapter<ProductSelectBean, BaseViewHolder> { public ProductSelectAdapter(@Nullable List<ProductSelectBean> data) { super(R.layout.item_select_product, data); } @Override protected void convert(BaseViewHolder helper, final ProductSelectBean item) { TextView tv_price = helper.getView(R.id.tv_price); TextView tv_count = helper.getView(R.id.tv_count); TextView tv_name = helper.getView(R.id.tv_name); tv_price.setText("¥" + item.getPrice()); tv_count.setText("×" + item.getChoose_number()); tv_name.setText(item.getTitle()); } }
package jadx.core.statistics; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import jadx.core.codegen.ArgTypes; import jadx.core.codegen.CodeWriter; import jadx.core.codegen.ConditionGen; import jadx.core.codegen.InsnGen; import jadx.core.codegen.MethodGen; import jadx.core.codegen.RegionGen; import jadx.core.dex.attributes.AFlag; import jadx.core.dex.instructions.SwitchNode; import jadx.core.dex.instructions.args.InsnArg; import jadx.core.dex.nodes.IBlock; import jadx.core.dex.nodes.IContainer; import jadx.core.dex.nodes.IRegion; import jadx.core.dex.nodes.InsnNode; import jadx.core.dex.regions.Region; import jadx.core.dex.regions.SwitchRegion; import jadx.core.dex.regions.conditions.Compare; import jadx.core.dex.regions.conditions.IfCondition; import jadx.core.dex.regions.conditions.IfRegion; import jadx.core.dex.regions.loops.ForEachLoop; import jadx.core.dex.regions.loops.ForLoop; import jadx.core.dex.regions.loops.LoopRegion; import jadx.core.dex.regions.loops.LoopType; import jadx.core.utils.exceptions.CodegenException; /** * Encapsulates the statistics of an if, else if, else (held each as */ public class IfStatistic { MethodGen mth; RegionGen rGen; IfRegion ifRegion; IContainer els; List<Statistic> statistics; InsnGen iGen; ConditionGen cGen; public IfStatistic(IfRegion ifRegion, MethodGen mth, RegionGen rGen) { this.mth = mth; this.rGen = rGen; this.ifRegion = ifRegion; this.statistics = new ArrayList<Statistic>(); this.iGen = new InsnGen(mth, false); cGen = new ConditionGen(iGen); createStatistics(); } public List<Statistic> getStatistics() { return statistics; } private void createStatistics() { // Populate else block and statistics try { CodeWriter writer = new CodeWriter(); // Then cGen.add(writer, ifRegion.getCondition()); System.out.println("Found If: " + writer.toString()); // IfRegion, abstractly an IRegion int ifNestingLevel = getNestingLevel((IRegion) ifRegion) - 1; int numIfContainers = rGen.getIfRegionInfo(ifRegion).size() + 1; addStatistic(ifRegion.getThenRegion(), ifRegion.getElseRegion(), ifRegion.getCondition(), false, ifNestingLevel, numIfContainers); // Handle the conditions else if and else cases for (IfRegionInfo info : rGen.getIfRegionInfo(ifRegion)) { // If/Else If Case if (!info.isElse()) { writer = new CodeWriter(); cGen.add(writer, info.getCondition()); System.out.println("Found Else If: " + info.getCondition()); IfRegion ir = (IfRegion) info.getRegion(); addStatistic(ir.getThenRegion(), ir.getElseRegion(), info.getCondition(), info.isElse(), ifNestingLevel, numIfContainers); } // Else Case else { //System.out.println("Found Else"); //addStatistic(info.getRegion(), info.getCondition(), info.isElse(), ifNestingLevel); } } } catch (CodegenException e) { e.printStackTrace(); } } private void addStatistic(IContainer thenRegion, IContainer elseRegion, IfCondition condition, boolean isElse, int nestingLevel, int numIfContainers) throws CodegenException { CodeWriter writer = new CodeWriter(); ConditionGen cGen = new ConditionGen(iGen); cGen.add(writer, condition); Statistic stat = new Statistic(thenRegion, elseRegion, condition, writer.toString(), mth); stat.setNumNestedIfStatements(rGen.getNumNestedIfConditions(thenRegion)); stat.setInLoop(inLoop((IRegion) thenRegion)); stat.setNestingLevel(nestingLevel); stat.setNumIfContainers(numIfContainers); List<Compare> comparisons = iGen.getCompareList(condition); stat.setComparisonList(comparisons); InsnVariableContainer vc = new InsnVariableContainer(); for (Compare compare : comparisons) { iGen.handleCompare(vc, compare); } vc.separateLiteralsAndVariables(); updateVariablesForStat(stat, condition, vc); updateLiteralsForStat(stat, condition, vc); updateMethodCallsForStat(stat, condition, vc); //System.out.println(vc.toString()); getThenVariableStatistics(stat, vc, thenRegion); getElseVariableStatistics(stat, vc, elseRegion); stat.setNumStatements(stat.getNumStatementsInThen() + stat.getNumStatementsInElse()); System.out.println("On Method: " + mth.getMethodNode().getMethodInfo().getFullName()); System.out.println("=================="); statistics.add(stat); } private void getThenVariableStatistics(Statistic stat, InsnVariableContainer vc, IContainer thenRegion) throws CodegenException { System.out.println("Get Then Variable Usage"); int totalMethodCalls = 0; int totalReadThenRead = 0; int totalWriteThenWrite = 0; int totalReadThenWrite = 0; int totalWriteThenRead = 0; int totalWrites = 0; int totalUniqueReads = 0; int totalReads = 0; int totalUniqueMethodCalls = 0; int numStatementsInThen = 0; numStatementsInThen = getNumStatements(thenRegion); Set<String> methodCalls = new HashSet<String>(); // Handle Simple Statements for (IBlock block : rGen.getBlocksForRegion(thenRegion)) { int i = 1; for (InsnNode insn : block.getInstructions()) { if (!insn.contains(AFlag.SKIP)) { InsnVariableContainer insnVC = new InsnVariableContainer(); iGen.getInsnVariables(insnVC, insn); System.out.println((i++) + ": " + insn); insnVC.separateLiteralsAndVariables(); if (insnVC.getMethodCalls().size() > 0) { for (MethodCall call : insnVC.getMethodCalls()) { methodCalls.add(call.toString()); } totalMethodCalls++; } for (VariableUsage usage : insnVC.getReadVariables()) { if (stat.getUniqueReadVarInCond().contains(usage.toString())) { totalReadThenRead++; } if (stat.getUniqueWriteVarInCond().contains(usage.toString())) { totalReadThenWrite++; } } for (VariableUsage usage : insnVC.getWriteVariables()) { if (stat.getUniqueReadVarInCond().contains(usage.toString())) { totalWriteThenRead++; } if (stat.getUniqueReadVarInCond().contains(usage.toString())) { totalWriteThenWrite++; } } if (insnVC.getWriteVariables().size() > 0) { totalWrites++; } if (countVariables(insnVC.getReadVariables()) > 0) { totalUniqueReads++; totalReads += (countVariables(insnVC.getReadVariables())); } } } } // Handle Switch enum/int/boolean read for (SwitchRegion region : rGen.getSwitchRegion(thenRegion)) { numStatementsInThen++; SwitchNode switchInsn = (SwitchNode) region.getHeader().getInstructions().get(0); InsnArg arg = switchInsn.getArg(0); InsnVariableContainer switchVC = new InsnVariableContainer(); iGen.getVariableUsageFromArg(false, switchVC, arg, false); switchVC.separateLiteralsAndVariables(); if (switchVC.getMethodCalls().size() > 0) { for (MethodCall call : switchVC.getMethodCalls()) { methodCalls.add(call.toString()); } totalMethodCalls++; } for (VariableUsage usage : switchVC.getReadVariables()) { if (stat.getUniqueReadVarInCond().contains(usage.toString())) { totalReadThenRead++; } if (stat.getUniqueWriteVarInCond().contains(usage.toString())) { totalReadThenWrite++; } } for (VariableUsage usage : switchVC.getWriteVariables()) { if (stat.getUniqueReadVarInCond().contains(usage.toString())) { totalWriteThenRead++; } if (stat.getUniqueReadVarInCond().contains(usage.toString())) { totalWriteThenWrite++; } } if (switchVC.getWriteVariables().size() > 0) { totalWrites++; } if (countVariables(switchVC.getReadVariables()) > 0) { totalUniqueReads++; totalReads += (countVariables(switchVC.getReadVariables())); } } // Handle If Conditions for (IfCondition condition : rGen.getConditionsForRegion(thenRegion)) { numStatementsInThen++; InsnVariableContainer conditionVC = new InsnVariableContainer(); List<Compare> conditionComparisons = iGen.getCompareList(condition); for (Compare compare : conditionComparisons) { iGen.handleCompare(conditionVC, compare); } conditionVC.separateLiteralsAndVariables(); if (conditionVC.getMethodCalls().size() > 0) { for (MethodCall call : conditionVC.getMethodCalls()) { methodCalls.add(call.toString()); } totalMethodCalls++; } for (VariableUsage usage : conditionVC.getReadVariables()) { if (stat.getUniqueReadVarInCond().contains(usage.toString())) { totalReadThenRead++; } if (stat.getUniqueWriteVarInCond().contains(usage.toString())) { totalReadThenWrite++; } } for (VariableUsage usage : conditionVC.getWriteVariables()) { if (stat.getUniqueReadVarInCond().contains(usage.toString())) { totalWriteThenRead++; } if (stat.getUniqueReadVarInCond().contains(usage.toString())) { totalWriteThenWrite++; } } if (conditionVC.getWriteVariables().size() > 0) { totalWrites++; } if (countVariables(conditionVC.getReadVariables()) > 0) { totalUniqueReads++; totalReads += (countVariables(conditionVC.getReadVariables())); } } // Handle Loop Condition for (LoopRegion loop : rGen.getLoopsForRegion(thenRegion)) { numStatementsInThen++; if (loop.getCondition() != null) { LoopType type = loop.getType(); InsnVariableContainer loopVC = new InsnVariableContainer(); if (type != null) { // Exclude ForLoop, no condition is used for this case. if (!(type instanceof ForEachLoop)) { List<Compare> loopComparisons = iGen.getCompareList(loop.getCondition()); for (Compare compare : loopComparisons) { iGen.handleCompare(loopVC, compare); } } if (type instanceof ForLoop) { ForLoop forLoop = (ForLoop) type; iGen.getInsnVariables(loopVC, forLoop.getInitInsn()); iGen.getInsnVariables(loopVC, forLoop.getIncrInsn()); } if (type instanceof ForEachLoop) { System.out.println("Hello"); ForEachLoop forEachLoop = (ForEachLoop) type; System.out.println(forEachLoop.getVarArg()); iGen.getVariableUsageFromArg(true, loopVC, forEachLoop.getVarArg(), false); iGen.getVariableUsageFromArg(false, loopVC, forEachLoop.getIterableArg(), false); } } loopVC.separateLiteralsAndVariables(); if (loopVC.getMethodCalls().size() > 0) { for (MethodCall call : loopVC.getMethodCalls()) { methodCalls.add(call.toString()); } totalMethodCalls++; } for (VariableUsage usage : loopVC.getReadVariables()) { if (stat.getUniqueReadVarInCond().contains(usage.toString())) { totalReadThenRead++; } if (stat.getUniqueWriteVarInCond().contains(usage.toString())) { totalReadThenWrite++; } } for (VariableUsage usage : loopVC.getWriteVariables()) { if (stat.getUniqueReadVarInCond().contains(usage.toString())) { totalWriteThenRead++; } if (stat.getUniqueReadVarInCond().contains(usage.toString())) { totalWriteThenWrite++; } } if (loopVC.getWriteVariables().size() > 0) { totalWrites++; } if (countVariables(loopVC.getReadVariables()) > 0) { totalUniqueReads++; totalReads += (countVariables(loopVC.getReadVariables())); } } } totalUniqueMethodCalls = methodCalls.size(); /* System.out.println("Total Variable Read Then Read: " + totalReadThenRead); System.out.println("Total Variable Write Then Write: " + totalWriteThenWrite); System.out.println("Total Variable Read Then Write: " + totalReadThenWrite); System.out.println("Total Variable Write Then Read: " + totalWriteThenRead); System.out.println("Total Variable Reads (Multiple variables per statement): " + totalReads); System.out.println("Total Variable Unique Reads (One per statement): " + totalUniqueReads); System.out.println("Total Variable Writes: " + totalWrites); System.out.println("Total Method Calls: " + totalMethodCalls); System.out.println("Total Unique Method Calls: " + totalUniqueMethodCalls); */ stat.setNumStatementsInThen(numStatementsInThen); stat.setTotalReadsInThen(totalReads); stat.setTotalUniqueReadsInThen(totalUniqueReads); stat.setTotalWritesInThen(totalWrites); stat.setTotalReadReadInThen(totalReadThenRead); stat.setTotalReadWriteInThen(totalReadThenWrite); stat.setTotalWriteReadInThen(totalWriteThenRead); stat.setTotalWriteWriteInThen(totalWriteThenWrite); stat.setTotalMethodCallsInThen(totalMethodCalls); stat.setTotalUniqueMethodCallsInThen(totalUniqueMethodCalls); } private void getElseVariableStatistics(Statistic stat, InsnVariableContainer vc, IContainer elseRegion) throws CodegenException { System.out.println("Get Else Variable Usage"); System.out.println(""); int totalMethodCalls = 0; int totalReadThenRead = 0; int totalWriteThenWrite = 0; int totalReadThenWrite = 0; int totalWriteThenRead = 0; int totalWrites = 0; int totalUniqueReads = 0; int totalReads = 0; int totalUniqueMethodCalls = 0; int numStatementsInElse = 0; if (elseRegion != null) { numStatementsInElse = getNumStatements(elseRegion); Set<String> methodCalls = new HashSet<String>(); // Handle Simple Statements for (IBlock block : rGen.getBlocksForRegion(elseRegion)) { int i = 0; for (InsnNode insn : block.getInstructions()) { if (!insn.contains(AFlag.SKIP)) { InsnVariableContainer insnVC = new InsnVariableContainer(); iGen.getInsnVariables(insnVC, insn); insnVC.separateLiteralsAndVariables(); System.out.println((i++) + ": " + insn); if (insnVC.getMethodCalls().size() > 0) { for (MethodCall call : insnVC.getMethodCalls()) { methodCalls.add(call.toString()); } totalMethodCalls++; } for (VariableUsage usage : insnVC.getReadVariables()) { if (stat.getUniqueReadVarInCond().contains(usage.toString())) { totalReadThenRead++; } if (stat.getUniqueWriteVarInCond().contains(usage.toString())) { totalReadThenWrite++; } } for (VariableUsage usage : insnVC.getWriteVariables()) { if (stat.getUniqueReadVarInCond().contains(usage.toString())) { totalWriteThenRead++; } if (stat.getUniqueReadVarInCond().contains(usage.toString())) { totalWriteThenWrite++; } } if (insnVC.getWriteVariables().size() > 0) { totalWrites++; } if (countVariables(insnVC.getReadVariables()) > 0) { totalUniqueReads++; totalReads += (countVariables(insnVC.getReadVariables())); } } } } // Handle Switch enum/int/boolean read for (SwitchRegion region : rGen.getSwitchRegion(elseRegion)) { numStatementsInElse++; SwitchNode switchInsn = (SwitchNode) region.getHeader().getInstructions().get(0); InsnArg arg = switchInsn.getArg(0); InsnVariableContainer switchVC = new InsnVariableContainer(); iGen.getVariableUsageFromArg(false, switchVC, arg, false); switchVC.separateLiteralsAndVariables(); if (switchVC.getMethodCalls().size() > 0) { for (MethodCall call : switchVC.getMethodCalls()) { methodCalls.add(call.toString()); } totalMethodCalls++; } for (VariableUsage usage : switchVC.getReadVariables()) { if (stat.getUniqueReadVarInCond().contains(usage.toString())) { totalReadThenRead++; } if (stat.getUniqueWriteVarInCond().contains(usage.toString())) { totalReadThenWrite++; } } for (VariableUsage usage : switchVC.getWriteVariables()) { if (stat.getUniqueReadVarInCond().contains(usage.toString())) { totalWriteThenRead++; } if (stat.getUniqueReadVarInCond().contains(usage.toString())) { totalWriteThenWrite++; } } if (switchVC.getWriteVariables().size() > 0) { totalWrites++; } if (countVariables(switchVC.getReadVariables()) > 0) { totalUniqueReads++; totalReads += (countVariables(switchVC.getReadVariables())); } } // Handle If Conditions for (IfCondition condition : rGen.getConditionsForRegion(elseRegion)) { numStatementsInElse++; InsnVariableContainer conditionVC = new InsnVariableContainer(); List<Compare> conditionComparisons = iGen.getCompareList(condition); for (Compare compare : conditionComparisons) { iGen.handleCompare(conditionVC, compare); } conditionVC.separateLiteralsAndVariables(); if (conditionVC.getMethodCalls().size() > 0) { for (MethodCall call : conditionVC.getMethodCalls()) { methodCalls.add(call.toString()); } totalMethodCalls++; } for (VariableUsage usage : conditionVC.getReadVariables()) { if (stat.getUniqueReadVarInCond().contains(usage.toString())) { totalReadThenRead++; } if (stat.getUniqueWriteVarInCond().contains(usage.toString())) { totalReadThenWrite++; } } for (VariableUsage usage : conditionVC.getWriteVariables()) { if (stat.getUniqueReadVarInCond().contains(usage.toString())) { totalWriteThenRead++; } if (stat.getUniqueReadVarInCond().contains(usage.toString())) { totalWriteThenWrite++; } } if (conditionVC.getWriteVariables().size() > 0) { totalWrites++; } if (countVariables(conditionVC.getReadVariables()) > 0) { totalUniqueReads++; totalReads += (countVariables(conditionVC.getReadVariables())); } } // Handle Loop Condition for (LoopRegion loop : rGen.getLoopsForRegion(elseRegion)) { numStatementsInElse++; if (loop.getCondition() != null) { LoopType type = loop.getType(); InsnVariableContainer loopVC = new InsnVariableContainer(); if (type != null) { // Exclude ForLoop, no condition is used for this case. if (!(type instanceof ForEachLoop)) { List<Compare> loopComparisons = iGen.getCompareList(loop.getCondition()); for (Compare compare : loopComparisons) { iGen.handleCompare(loopVC, compare); } } if (type instanceof ForLoop) { ForLoop forLoop = (ForLoop) type; iGen.getInsnVariables(loopVC, forLoop.getInitInsn()); iGen.getInsnVariables(loopVC, forLoop.getIncrInsn()); } if (type instanceof ForEachLoop) { System.out.println("Hello"); ForEachLoop forEachLoop = (ForEachLoop) type; System.out.println(forEachLoop.getVarArg()); iGen.getVariableUsageFromArg(true, loopVC, forEachLoop.getVarArg(), false); iGen.getVariableUsageFromArg(false, loopVC, forEachLoop.getIterableArg(), false); } } loopVC.separateLiteralsAndVariables(); if (loopVC.getMethodCalls().size() > 0) { for (MethodCall call : loopVC.getMethodCalls()) { methodCalls.add(call.toString()); } totalMethodCalls++; } for (VariableUsage usage : loopVC.getReadVariables()) { if (stat.getUniqueReadVarInCond().contains(usage.toString())) { totalReadThenRead++; } if (stat.getUniqueWriteVarInCond().contains(usage.toString())) { totalReadThenWrite++; } } for (VariableUsage usage : loopVC.getWriteVariables()) { if (stat.getUniqueReadVarInCond().contains(usage.toString())) { totalWriteThenRead++; } if (stat.getUniqueReadVarInCond().contains(usage.toString())) { totalWriteThenWrite++; } } if (loopVC.getWriteVariables().size() > 0) { totalWrites++; } if (countVariables(loopVC.getReadVariables()) > 0) { totalUniqueReads++; totalReads += (countVariables(loopVC.getReadVariables())); } } } totalUniqueMethodCalls = methodCalls.size(); /* System.out.println("Total Variable Read Then Read: " + totalReadThenRead); System.out.println("Total Variable Write Then Write: " + totalWriteThenWrite); System.out.println("Total Variable Read Then Write: " + totalReadThenWrite); System.out.println("Total Variable Write Then Read: " + totalWriteThenRead); System.out.println("Total Variable Reads (Multiple variables per statement): " + totalReads); System.out.println("Total Variable Unique Reads (One per statement): " + totalUniqueReads); System.out.println("Total Variable Writes: " + totalWrites); System.out.println("Total Method Calls: " + totalMethodCalls); System.out.println("Total Unique Method Calls: " + totalUniqueMethodCalls); */ } stat.setNumStatementsInElse(numStatementsInElse); stat.setTotalReadsInElse(totalReads); stat.setTotalUniqueReadsInElse(totalUniqueReads); stat.setTotalWritesInElse(totalWrites); stat.setTotalReadReadInElse(totalReadThenRead); stat.setTotalReadWriteInElse(totalReadThenWrite); stat.setTotalWriteReadInElse(totalWriteThenRead); stat.setTotalWriteWriteInElse(totalWriteThenWrite); stat.setTotalMethodCallsInElse(totalMethodCalls); stat.setTotalUniqueMethodCallsInElse(totalUniqueMethodCalls); } private int countVariables(List<VariableUsage> usages) { int variableReads = 0; for (VariableUsage usage : usages) { if (usage.isVariable()) variableReads++; } return variableReads; } private void updateVariablesForStat(Statistic stat, IfCondition condition, InsnVariableContainer vc) throws CodegenException { // Read, Write, and Method Calls from If Condition Set<String> readVariables = new HashSet<String>(); Set<String> writeVariables = new HashSet<String>(); for (VariableUsage usage : vc.getReadVariables()) { readVariables.add(usage.toString()); } for (VariableUsage usage : vc.getWriteVariables()) { writeVariables.add(usage.toString()); } stat.setReadVarInCond(vc.getReadVariables()); stat.setWriteVarInCond(vc.getWriteVariables()); stat.setUniqueReadVarInCond(readVariables); stat.setUniqueWriteVarInCond(writeVariables); } private void updateLiteralsForStat(Statistic stat, IfCondition condition, InsnVariableContainer vc) { Set<String> readLiterals = new HashSet<String>(); Set<String> writeLiterals = new HashSet<String>(); for (VariableUsage usage : vc.getReadLiterals()) { readLiterals.add(usage.toString()); } for (VariableUsage usage : vc.getWriteLiterals()) { writeLiterals.add(usage.toString()); } stat.setReadLitInCond(vc.getReadLiterals()); stat.setWriteLitInCond(vc.getWriteLiterals()); stat.setUniqueReadLitInCond(readLiterals); stat.setUniqueWriteLitInCond(writeLiterals); } private void updateMethodCallsForStat(Statistic stat, IfCondition condition, InsnVariableContainer vc) { Set<String> methodCalls = new HashSet<String>(); for (MethodCall call : vc.getMethodCalls()) { methodCalls.add(call.toString());} stat.setMethodCallsInCond(vc.getMethodCalls()); stat.setUniqueMethodCallsInCond(methodCalls); } private int getNumStatements(IContainer container) throws CodegenException { int numStatements = 0; for (IBlock block : rGen.getBlocksForRegion(container)) { for (InsnNode node : block.getInstructions()) { if (!node.contains(AFlag.SKIP_ARG)) { numStatements++; } } } for (IfCondition condition : rGen.getConditionsForRegion(container)) { numStatements++; } for (SwitchRegion switches : rGen.getSwitchRegion(container)) { numStatements++; } for (LoopRegion loop : rGen.getLoopsForRegion(container)) { numStatements++; } return numStatements; } private boolean inLoop(IRegion region) { if (region.getParent() == null) { return false; } else if (region instanceof LoopRegion) { return true; } else { return inLoop(region.getParent()); } } private int getNestingLevel(IRegion region) { if (region.getParent() == null) { return 0; } else { if (region instanceof Region) { return getNestingLevel(region.getParent()) + 0; } else { return getNestingLevel(region.getParent()) + 1; } } } }
package mod6AI.ai; import java.util.*; import java.util.stream.Collectors; /** * Created by Student on 24-11-2014. */ public abstract class Tokenizer { /** * Splits the input String in separate words, cast them to lower and strips all non alphanumerical characters. * @param in a String. * @return a collection with separate words. */ public static Collection<String> tokenize(String in) { Collection<String> out; out = Arrays.asList(in.split("[\\s\\.,;:\"()?!@#$%^&*()-]")).stream() .map(String::toLowerCase) .map(Tokenizer::removeAllNoneAlphanumeric) .filter(s -> !s.isEmpty()) .collect(Collectors.toList()); return out; } /** * Removes all non alphanumeric characters. * @param in a String. * @return the input String from which all none alphanumeric characters are removed. */ public static String removeAllNoneAlphanumeric(String in) { // TODO: maybe keep some special chars under special conditions. For example: ' in don't return in.replaceAll("[^a-zA-Z0-9]", ""); } }
package org.toptaxi.taximeter.adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.toptaxi.taximeter.MainApplication; import org.toptaxi.taximeter.R; import org.toptaxi.taximeter.data.Order; import java.util.ArrayList; public class HisOrdersAdapters extends BaseAdapter { protected static String TAG = "#########" + HisOrdersAdapters.class.getName(); private LayoutInflater lInflater; private ArrayList<Order> orders; private Integer LastID = 0; public HisOrdersAdapters(Context mContext) { lInflater = (LayoutInflater) mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); orders = new ArrayList<>(); } public void AppendNewData(ArrayList<Order> data){ orders.addAll(data); } public ArrayList<Order> LoadMore() { ArrayList<Order> results = new ArrayList<>(); try { JSONObject data = new JSONObject(MainApplication.getInstance().getDot().getDataType("his_orders", String.valueOf(LastID))); //Log.d(TAG, "loadMore data = " + data.toString()); if (data.has("his_orders")){ JSONArray paymentsJSON = data.getJSONArray("his_orders"); for (int itemID = 0; itemID < paymentsJSON.length(); itemID ++){ Order order = new Order(); order.setFromJSON(paymentsJSON.getJSONObject(itemID)); results.add(order); LastID = order.getID(); } } } catch (JSONException e) { //Log.d(TAG, "JSONException"); e.printStackTrace(); } //Log.d(TAG, "LoadMore resultCount = " + resultCount); return results; } @Override public int getCount() { return orders.size(); } @Override public Order getItem(int position) { return orders.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { view = lInflater.inflate(R.layout.item_his_orders, parent, false); } Order order = orders.get(position); if (order != null){ ((TextView)view.findViewById(R.id.tvHisOrderDate)).setText(order.getDate()); ((TextView)view.findViewById(R.id.tvHisOrderStatus)).setText(order.getStateName()); view.findViewById(R.id.llHisOrderCaption).setBackgroundResource(order.getCaptionColor()); if (order.getFirstPointInfo() != null){ view.findViewById(R.id.tvHisOrderFirstRoutePoint).setVisibility(View.VISIBLE); ((TextView)view.findViewById(R.id.tvHisOrderFirstRoutePoint)).setText(order.getFirstPointInfo()); } else {view.findViewById(R.id.tvHisOrderFirstRoutePoint).setVisibility(View.GONE);} if (order.getLastPointInfo() != null){ view.findViewById(R.id.tvHisOrderLastRoutePoint).setVisibility(View.VISIBLE); ((TextView)view.findViewById(R.id.tvHisOrderLastRoutePoint)).setText(order.getLastPointInfo()); } else {view.findViewById(R.id.tvHisOrderLastRoutePoint).setVisibility(View.GONE);} } return view; } }
package com.megathrone.tmall.controller; import com.megathrone.tmall.pojo.Product; import com.megathrone.tmall.pojo.ProductImage; import com.megathrone.tmall.service.ProductImageService; import com.megathrone.tmall.service.ProductService; import com.megathrone.tmall.util.ImageUtil; import com.megathrone.tmall.util.UploadedImageFile; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.imageio.ImageIO; import javax.servlet.http.HttpSession; import java.awt.image.BufferedImage; import java.io.File; import java.util.List; @Controller @RequestMapping("") public class ProductImageController { @Autowired ProductService productService; @Autowired ProductImageService productImageService; @RequestMapping("admin_productImage_add") public String add(ProductImage pi, HttpSession session, UploadedImageFile uploadedImageFile) { productImageService.add(pi); String fileName = pi.getId() + ".jpg"; String imageFolder; String imageFolder_small = null; String imageFolder_middle = null; if (ProductImageService.type_single.equals(pi.getType())) { imageFolder = session.getServletContext().getRealPath("img/productSingle"); imageFolder_small = session.getServletContext().getRealPath("img/productSingle_small"); imageFolder_middle = session.getServletContext().getRealPath("img/productSingle_middle"); } else { imageFolder = session.getServletContext().getRealPath("img/productDetail"); } File f = new File(imageFolder, fileName); f.getParentFile().mkdirs(); try { uploadedImageFile.getImage().transferTo(f); BufferedImage img = ImageUtil.change2jpg(f); ImageIO.write(img, "jpg", f); if (ProductImageService.type_single.equals(pi.getType())) { File f_small = new File(imageFolder_small, fileName); File f_middle = new File(imageFolder_middle, fileName); ImageUtil.resizeImage(f, 56, 56, f_small); ImageUtil.resizeImage(f, 217, 190, f_middle); } } catch (Exception e) { e.printStackTrace(); } return "redirect:admin_productImage_list?pid=" + pi.getPid(); } @RequestMapping("admin_productImage_delete") public String delete(int id, HttpSession session) { ProductImage pi = productImageService.get(id); String fileName = pi.getId() + ".jpg"; String imageFolder; String imageFolder_small = null; String imageFolder_middle = null; if (ProductImageService.type_single.equals(pi.getType())) { imageFolder = session.getServletContext().getRealPath("img/productSingle"); imageFolder_small = session.getServletContext().getRealPath("img/productSingle_small"); imageFolder_middle = session.getServletContext().getRealPath("img/productSingle_middle"); File imageFile = new File(imageFolder, fileName); File f_small = new File(imageFolder_small, fileName); File f_middle = new File(imageFolder_middle, fileName); imageFile.delete(); f_small.delete(); f_middle.delete(); } else { imageFolder = session.getServletContext().getRealPath("img/productDetail"); File imageFile = new File(imageFolder, fileName); imageFile.delete(); } productImageService.delete(id); return "redirect:admin_productImage_list?pid=" + pi.getPid(); } @RequestMapping("admin_productImage_list") public String list(int pid, Model model) { Product p = productService.get(pid); List<ProductImage> pisSingle = productImageService.list(pid, ProductImageService.type_single); List<ProductImage> pisDetail = productImageService.list(pid, ProductImageService.type_detail); model.addAttribute("p", p); model.addAttribute("pisSingle", pisSingle); model.addAttribute("pisDetail", pisDetail); return "admin/listProductImage"; } }
package com.example.myapplication.edit; import androidx.work.OneTimeWorkRequest; import androidx.work.PeriodicWorkRequest; import androidx.work.WorkManager; import com.example.myapplication.data.db.dao.PersonDao; import com.example.myapplication.data.db.entity.Patients; import com.example.myapplication.utils.Constants; import com.example.myapplication.utils.MyWorker; import com.example.myapplication.utils.Util; import java.util.concurrent.TimeUnit; public class EditPresenter implements EditContract.Presenter { private final EditContract.View mView; private final PersonDao personDao; public EditPresenter(EditContract.View mMainView, PersonDao personDao) { this.mView = mMainView; this.mView.setPresenter(this); this.personDao = personDao; } @Override public void start() { } @Override public void save(Patients person) { long ids = this.personDao.insertPerson(person); mView.close(); } @Override public boolean validate(Patients person) { if (person.name.isEmpty() || !Util.isValidName(person.name)) { mView.showErrorMessage(Constants.FIELD_NAME); return false; } if (person.address.isEmpty()) { mView.showErrorMessage(Constants.FIELD_ADDRESS); return false; } if (person.phone.isEmpty() || !Util.isValidPhone(person.phone)) { mView.showErrorMessage(Constants.FIELD_PHONE); return false; } if (person.email.isEmpty() || !Util.isValidEmail(person.email)) { mView.showErrorMessage(Constants.FIELD_EMAIL); return false; } if (person.bloodGroup.isEmpty() ) { mView.showErrorMessage(Constants.FIELD_BLOODGROUP); return false; }if (person.weight.isEmpty() ) { mView.showErrorMessage(Constants.FIELD_WEIGHT); return false; }if (person.height.isEmpty() ) { mView.showErrorMessage(Constants.FIELD_HEIGHT); return false; } if (person.birthday == null) { mView.showErrorMessage(Constants.FIELD_BIRTHDAY); return false; } return true; } @Override public void showDateDialog() { mView.openDateDialog(); } @Override public void getPatientsAndPopulate(long id) { Patients person = personDao.findPerson(id); if (person != null) { mView.populate(person); } } @Override public void update(Patients person) { int ids = this.personDao.updatePerson(person); mView.close(); } @Override public void startWorkManager() { // This wil uplaod data to the server periodically PeriodicWorkRequest compressionWork = new PeriodicWorkRequest.Builder(MyWorker.class, 20, TimeUnit.MINUTES) .build(); WorkManager.getInstance().enqueue(compressionWork); } }
/* * * This software is the confidential and proprietary information of * shall not disclose such Confidential Information and shall use * it only in accordance with the terms of the license agreement */ package com.sshfortress.common.filter; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Service; import com.sshfortress.common.contants.ViewContants; import com.sshfortress.common.enums.HttpChannelType; /** <p class="detail"> * 功能:这里写类描述 * </p> * @ClassName: TicketHelper * @version V1.0 */ @Service("ticketHelper") public class TicketHelper { /** * jar包不要引错 org.apache.commons.logging.* */ private static final Log logger = LogFactory.getLog("TSOU-SESSION"); /** <p class="detail"> * 功能:更新cookie时间 * </p> * @param response * @param ticket */ public void setCookie(HttpServletRequest request, HttpServletResponse response, String ticket) { // 信任保存 Cookie cookie = new Cookie(ViewContants.LOGIN_TICKET_KEY, ticket); // 要使此处有效 则访问地址必须与此处的域名一致 cookie.setDomain(request.getServerName()); // 设置父path cookie.setPath("/"); // 设置有效期存放至客户端硬盘否则为浏览器内存 cookie.setMaxAge(ViewContants.TRUST_COOKIE_TIME); //存活期为秒 response.addCookie(cookie); } /** <p class="detail"> * 功能:三种方式归纳取原文ticket * </p> * @param request * @param httpChannelType * @return */ public String getTicket(HttpServletRequest request, HttpChannelType httpChannelType) { Cookie cookies[] = request.getCookies(); String ticket = null; if (null != cookies) { for (Cookie cookie : cookies) { if (StringUtils.equals(ViewContants.LOGIN_TICKET_KEY, cookie.getName())) { ticket = StringUtils.trim(cookie.getValue()); StringBuilder builder = new StringBuilder(httpChannelType.name()); builder.append(":获取到cookie的ticket=").append(ticket); builder.append(":客户端请求地址=").append(request.getServerName()).append("===="); builder.append(cookie.getDomain()); logger.info(builder.toString()); break; } } } // java后台设置的cookie存在则header部分肯定也存在即可获取, // 测试非后台塞入cookie的取值 如:跨域情况下、安卓情况 if (StringUtils.isBlank(ticket)) { ticket = customHeadTicket(request, httpChannelType); } if (StringUtils.isBlank(ticket)) { ticket = StringUtils.trim(request.getParameter(ViewContants.LOGIN_TICKET_KEY)); } return ticket; } /** <p class="detail"> * 功能:清楚取到的cookie * </p> * @param response * @param cookie */ public void deleteCookie(HttpServletResponse response, Cookie cookie) { if (cookie != null) { cookie.setMaxAge(0); response.addCookie(cookie); } } /** <p class="detail"> * 功能:自定义的header ticket * </p> * @param request * @param httpChannelType * @return */ private String customHeadTicket(HttpServletRequest request, HttpChannelType httpChannelType) { String ticket = request.getHeader(ViewContants.LOGIN_TICKET_KEY); if (StringUtils.isNotBlank(ticket)) { logger.info(httpChannelType.name() + ": header部分获取到ticket=" + ticket); } /* Enumeration<?> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String key = (String) headerNames.nextElement(); logger.info(httpChannelType.name() + ": header部分: key=" + key + "; value=" + request.getHeader(key)); }*/ return StringUtils.trim(ticket); } /** <p class="detail"> * 功能:从Header部分取 * </p> * @param request * @return */ /* private String getHeadTicket(HttpServletRequest request, HttpChannelType httpChannelType) { String headerCookie = StringUtils.trim(request.getHeader(ViewContants.LOGIN_HEADER_COOKIE)); if (StringUtils.isNotBlank(headerCookie)) { String[] cookies = StringUtils.split(headerCookie, ";"); for (String cookie : cookies) { if (cookie.contains(ViewContants.LOGIN_TICKET_KEY)) { String tickets[] = StringUtils.split(cookie, "="); if (tickets.length == 2) { logger.info(httpChannelType.name() + ": header部分获取到的cookie-ticket=" + tickets[1]); return StringUtils.trim(tickets[1]); } } } } return null; }*/ /** <p class="detail"> * 功能:app取 request cookies * </p> * @param request * @return */ /* public Cookie getTicketCookie(HttpServletRequest request, HttpChannelType httpChannelType) { Cookie cookies[] = request.getCookies(); Cookie cookie = null; if (null != cookies) { for (Cookie c : cookies) { if (!StringUtils.equals(ViewContants.LOGIN_TICKET_KEY, c.getName())) { continue; } logger.info(httpChannelType.name() + ": cookie获取到ticket:" + request.getServerName() + "====" + c.getDomain()); cookie = c; break; } } return cookie; }*/ }
package com.stylefeng.guns.rest.film.bean.rebuild; import java.io.Serializable; /** * @Author: xf * @Date: 2019/6/7 9:39 */ public class Actor implements Serializable { //private int uuid; private String actorName; private String actorImg; private String roleName; /*public int getUuid() { return uuid; } public void setUuid(int uuid) { this.uuid = uuid; }*/ public String getActorName() { return actorName; } public void setActorName(String actorName) { this.actorName = actorName; } public String getActorImg() { return actorImg; } public void setActorImg(String actorImg) { this.actorImg = actorImg; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } }
/** * Copyright 2014 Bill McDowell * * This file is part of theMess (https://github.com/forkunited/theMess) * * 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 ark.model.evaluation.metric; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import ark.data.annotation.Datum; import ark.data.annotation.Datum.Tools.LabelMapping; import ark.data.feature.FeaturizedDataSet; import ark.model.SupervisedModel; import ark.util.Pair; import ark.util.SerializationUtil; /** * SupervisedModelEvaluation represents evaluation measure * for a supervised classification model. * * Implementations of particular evaluation measures derive * from SupervisedModelEvaluation, and SupervisedModelEvaluation * is primarily responsible for providing the methods necessary * for deserializing these evaluation measures from configuration * files. * * @author Bill McDowell * * @param <D> datum type * @param <L> datum label type */ public abstract class SupervisedModelEvaluation<D extends Datum<L>, L> { protected LabelMapping<L> labelMapping; /** * @return a generic name by which to refer to the evaluation */ public abstract String getGenericName(); /** * * @param model * @param data * @param predictions * @return the value of the evaluation measure for the model with predictions on the * given data set. This method should generally start by calling * 'getMappedActualAndPredictedLabels' to get the labels according to the 'labelMapping' * function, and then compute the measure using those returned labels. * */ protected abstract double compute(SupervisedModel<D, L> model, FeaturizedDataSet<D, L> data, Map<D, L> predictions); /** * @return parameters of the evaluation measure that can be set through the experiment * configuration file */ protected abstract String[] getParameterNames(); /** * @param parameter * @return the value of the given parameter */ protected abstract String getParameterValue(String parameter); /** * * @param parameter * @param parameterValue * @param datumTools * @return true if the parameter has been set to parameterValue. Some parameters are set to * objects retrieved through datumTools that are named by parameterValue. */ protected abstract boolean setParameterValue(String parameter, String parameterValue, Datum.Tools<D, L> datumTools); /** * @return a generic instance of the evaluation measure. This is used when deserializing * the parameters for the measure from a configuration file */ protected abstract SupervisedModelEvaluation<D, L> makeInstance(); /** * @param predictions * @return a list of pairs of actual predicted labels that are mapped by * the label mapping (labelMapping) from the given predictions map */ protected List<Pair<L, L>> getMappedActualAndPredictedLabels(Map<D, L> predictions) { List<Pair<L, L>> mappedLabels = new ArrayList<Pair<L, L>>(predictions.size()); for (Entry<D, L> prediction : predictions.entrySet()) { L actual = prediction.getKey().getLabel(); L predicted = prediction.getValue(); if (this.labelMapping != null) { actual = this.labelMapping.map(actual); predicted = this.labelMapping.map(predicted); } Pair<L, L> mappedPair = new Pair<L, L>(actual, predicted); mappedLabels.add(mappedPair); } return mappedLabels; } /** * * @param model * @param data * @param predictions * @return the value of the evaluation measure for the model with predictions on the * given data set. If the model has a label mapping, then it is used when * computing the evaluation measure. */ public double evaluate(SupervisedModel<D, L> model, FeaturizedDataSet<D, L> data, Map<D, L> predictions) { LabelMapping<L> modelLabelMapping = model.getLabelMapping(); if (this.labelMapping != null) model.setLabelMapping(this.labelMapping); double evaluation = compute(model, data, predictions); model.setLabelMapping(modelLabelMapping); return evaluation; } public SupervisedModelEvaluation<D, L> clone(Datum.Tools<D, L> datumTools) { return clone(datumTools, null); } public SupervisedModelEvaluation<D, L> clone(Datum.Tools<D, L> datumTools, Map<String, String> environment) { SupervisedModelEvaluation<D, L> clone = makeInstance(); String[] parameterNames = getParameterNames(); for (int i = 0; i < parameterNames.length; i++) { String parameterValue = getParameterValue(parameterNames[i]); if (environment != null && parameterValue != null) { for (Entry<String, String> entry : environment.entrySet()) parameterValue = parameterValue.replace("${" + entry.getKey() + "}", entry.getValue()); } clone.setParameterValue(parameterNames[i], parameterValue, datumTools); } return clone; } public boolean deserialize(BufferedReader reader, boolean readGenericName, Datum.Tools<D, L> datumTools) throws IOException { if (readGenericName && SerializationUtil.deserializeGenericName(reader) == null) return false; Map<String, String> parameters = SerializationUtil.deserializeArguments(reader); if (parameters != null) for (Entry<String, String> entry : parameters.entrySet()) { if (entry.getKey().equals("labelMapping")) this.labelMapping = datumTools.getLabelMapping(entry.getValue()); else setParameterValue(entry.getKey(), entry.getValue(), datumTools); } return true; } public boolean serialize(Writer writer) throws IOException { writer.write(toString(false)); return true; } public String toString(boolean withVocabulary) { if (withVocabulary) { StringWriter stringWriter = new StringWriter(); try { if (serialize(stringWriter)) return stringWriter.toString(); else return null; } catch (IOException e) { return null; } } else { String genericName = getGenericName(); Map<String, String> parameters = new HashMap<String, String>(); String[] parameterNames = getParameterNames(); for (int i = 0; i < parameterNames.length; i++) parameters.put(parameterNames[i], getParameterValue(parameterNames[i])); if (this.labelMapping != null) parameters.put("labelMapping", this.labelMapping.toString()); StringWriter parametersWriter = new StringWriter(); try { SerializationUtil.serializeArguments(parameters, parametersWriter); } catch (IOException e) { return null; } String parametersStr = parametersWriter.toString(); return genericName + "(" + parametersStr + ")"; } } public String toString() { return toString(false); } public boolean fromString(String str, Datum.Tools<D, L> datumTools) { try { return deserialize(new BufferedReader(new StringReader(str)), true, datumTools); } catch (IOException e) { } return true; } }
package com.arthur.leetcode; /** * @title: No124 * @Author ArthurJi * @Date: 2021/4/9 12:49 * @Version 1.0 */ public class No124 { public static void main(String[] args) { } public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() { } TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } } int max = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { if (root == null) { return 0; } dfs(root); return max; } private int dfs(TreeNode root) { if (root == null) { return 0; } int left = Math.max(0, dfs(root.left)); int right = Math.max(0, dfs(root.right)); max = Math.max(left + right + root.val, max); return root.val + Math.max(left, right); } } /*124. 二叉树中的最大路径和 路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。 路径和 是路径中各节点值的总和。 给你一个二叉树的根节点 root ,返回其 最大路径和 。 示例 1: 输入:root = [1,2,3] 输出:6 解释:最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6 示例 2: 输入:root = [-10,9,20,null,null,15,7] 输出:42 解释:最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42*/ /* 【二叉树中的最大路径和】递归,条理清晰 Ikaruga 发布于 2019-08-02 48.4k 解题思路: 二叉树 abc,a 是根结点(递归中的 root),bc 是左右子结点(代表其递归后的最优解)。 最大的路径,可能的路径情况: a / \ b c b + a + c。 b + a + a 的父结点。 a + c + a 的父结点。 其中情况 1,表示如果不联络父结点的情况,或本身是根结点的情况。 这种情况是没法递归的,但是结果有可能是全局最大路径和。 情况 2 和 3,递归时计算 a+b 和 a+c,选择一个更优的方案返回,也就是上面说的递归后的最优解啦。 另外结点有可能是负值,最大和肯定就要想办法舍弃负值(max(0, x))(max(0,x))。 但是上面 3 种情况,无论哪种,a 作为联络点,都不能够舍弃。 代码中使用 val 来记录全局最大路径和。 ret 是情况 2 和 3。 lmr 是情况 1。 所要做的就是递归,递归时记录好全局最大和,返回联络最大和。 代码: int maxPathSum(TreeNode* root, int &val) { if (root == nullptr) return 0; int left = maxPathSum(root->left, val); int right = maxPathSum(root->right, val); int lmr = root->val + max(0, left) + max(0, right); int ret = root->val + max(0, max(left, right)); val = max(val, max(lmr, ret)); return ret; } int maxPathSum(TreeNode* root) { int val = INT_MIN; maxPathSum(root, val); return val; } 下一篇:「手画图解」别纠结递归的细节 | 124.二叉树中的最大路径和 © 著作权归作者所有 74 条评论 精选评论(3) cheney-2 cheney (编辑过)2020-03-28 思路一致,但是感觉我的注释更好理解~ int max = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { if (root == null) { return 0; } dfs(root); return max; } */ /** * 返回经过root的单边分支最大和, 即Math.max(root, root+left, root+right) * * @param root * @return *//* public int dfs(TreeNode root) { if (root == null) { return 0; } //计算左边分支最大值,左边分支如果为负数还不如不选择 int leftMax = Math.max(0, dfs(root.left)); //计算右边分支最大值,右边分支如果为负数还不如不选择 int rightMax = Math.max(0, dfs(root.right)); //left->root->right 作为路径与已经计算过历史最大值做比较 max = Math.max(max, root.val + leftMax + rightMax); // 返回经过root的单边最大分支给当前root的父节点计算使用 return root.val + Math.max(leftMax, rightMax); }*/
public class UseFinally { public static void main(String[] args) { try // Unchecked Exception { int a=100, b=0, c; c=a/b; System.out.println(c); } catch(AssertionError e) { System.out.println(e); System.out.println("Display"); } finally // Finally block will always execute. { System.out.println("YOU HAVE TO PRINT THIS"); } } }
package ehwaz.problem_solving.ds.arrays.SparseArrays; import java.util.*; /** * Created by Sangwook on 2016-04-05. */ public class SparseArrays { public static int[] solveProb(String[] inputLines, int numOfStr, String[] queryLines, int numOfQuery) { int[] results = new int[numOfQuery]; Map<String, Integer> mapStrCnt = new HashMap<String, Integer>(); for (int i = 0; i < numOfStr; i++) { String inputStr = inputLines[i]; int curCnt = (mapStrCnt.containsKey(inputStr)) ? mapStrCnt.get(inputStr) : 0; mapStrCnt.put(inputStr, curCnt + 1); } for (int j = 0; j < numOfQuery; j++) { String query = queryLines[j]; if (mapStrCnt.containsKey(query)) { results[j] = mapStrCnt.get(query); } else { results[j] = 0; } } return results; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int numOfStr = sc.nextInt(); sc.nextLine(); String[] inputLines = new String[numOfStr]; for (int i = 0; i < numOfStr; i++) { inputLines[i] = sc.nextLine(); } int numOfQuery = sc.nextInt(); sc.nextLine(); String[] queryLines = new String[numOfQuery]; for (int i = 0; i < numOfQuery; i++) { queryLines[i] = sc.nextLine(); } int[] results = solveProb(inputLines, numOfStr, queryLines, numOfQuery); for (int result : results) { System.out.println(result); } } }
package work; @FunctionalInterface // contains a single method only public interface Myinter { public abstract void sayHello(); } // create a seperate class and implement the interface // anonymous call for implementing interface
package com.socialportal.domain.blog.infrastructure.seach; import com.socialportal.domain.blog.model.BlogEntry; import org.springframework.stereotype.Component; @Component public class BlogEntrySearchDtoFactory { public BlogEntrySearchDto createBlogEntrySearchDto(BlogEntry blogEntry) { BlogEntrySearchDto dto = new BlogEntrySearchDto(); dto.setEntryId(blogEntry.getEntryId()); dto.setTitle(blogEntry.getTitle()); dto.setText(blogEntry.getText()); return dto; } }
/* * @(#) IMessageLogService.java * Copyright (c) 2006 eSumTech Co., Ltd. All Rights Reserved. */ package com.esum.wp.ims.procstatus.service; import java.io.IOException; import com.esum.appframework.service.IBaseService; /** * * @author bhyoo@esumtech.com * @version $Revision: 1.1 $ $Date: 2008/07/31 01:50:03 $ */ public interface IProcStatusService extends IBaseService { Object selectProcStatusList(Object object); }
/****************************************************************************** * __ * * <-----/@@\-----> * * <-< < \\// > >-> * * <-<-\ __ /->-> * * Data / \ Crow * * ^ ^ * * info@datacrow.net * * * * This file is part of Data Crow. * * Data Crow is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public * * License as published by the Free Software Foundation; either * * version 3 of the License, or any later version. * * * * Data Crow is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public * * License along with this program. If not, see http://www.gnu.org/licenses * * * ******************************************************************************/ package net.datacrow.console.wizards.moduleimport; import java.awt.GridBagConstraints; import java.awt.Insets; import net.datacrow.console.Layout; import net.datacrow.console.components.panels.TaskPanel; import net.datacrow.console.wizards.WizardException; import net.datacrow.console.wizards.itemimport.ItemImporterTaskPanel; import net.datacrow.core.migration.IModuleWizardClient; import net.datacrow.core.migration.moduleimport.ModuleImporter; import net.datacrow.core.resources.DcResources; import org.apache.log4j.Logger; public class PanelImportTask extends ModuleImportWizardPanel implements IModuleWizardClient { private static Logger logger = Logger.getLogger(ItemImporterTaskPanel.class.getName()); private TaskPanel tp = new TaskPanel(TaskPanel._DUPLICATE_PROGRESSBAR); private ModuleImporter importer; public PanelImportTask() { build(); } @Override public Object apply() throws WizardException { return getDefinition(); } @Override public void destroy() { if (importer != null) importer.cancel(); importer = null; if (tp != null) tp.destroy(); tp = null; } @Override public String getHelpText() { return DcResources.getText("msgModuleImportHelp"); } @Override public void onActivation() { if (getDefinition() != null && getDefinition().getFile() != null) start(); } @Override public void onDeactivation() { cancel(); } private void start() { ImportDefinition def = getDefinition(); if (importer != null) importer.cancel(); importer = new ModuleImporter(def.getFile()); try { importer.start(this); } catch (Exception e ) { notifyMessage(e.getMessage()); logger.error(e, e); } } private void build() { setLayout(Layout.getGBL()); add(tp, Layout.getGBC( 0, 1, 1, 1, 1.0, 1.0 ,GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets( 5, 5, 5, 5), 0, 0)); } private void cancel() { if (importer != null) importer.cancel(); notifyFinished(); } @Override public void notifyMessage(String msg) { tp.addMessage(msg); } @Override public void notifyNewTask() { tp.clear(); } @Override public void notifyStarted(int count) { tp.initializeTask(count); } @Override public void notifyStartedSubProcess(int count) { tp.initializeSubTask(count); } @Override public void notifyProcessed() { tp.updateProgressTask(); } @Override public void notifySubProcessed() { tp.updateProgressSubTask(); } @Override public void notifyError(Exception e) { logger.error(e, e); notifyMessage(DcResources.getText("msgModuleImportError", e.toString())); } @Override public void notifyFinished() { notifyMessage(DcResources.getText("msgModuleImportFinished")); } }
/* * Created on Mar 1, 2007 * */ package com.citibank.ods.entity.pl.valueobject; /** * @author fernando.salgado */ public class TplCustomerPrvtEntityVO extends BaseTplCustomerPrvtEntityVO { }
import java.util.ArrayList; import java.util.Comparator; /** * Given an array of integers, sort the array into a wave like array and return it, In other words, arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5..... */ public class WaveArray { public ArrayList<Integer> wave(ArrayList<Integer> a) { if (a.size() == 1 || a.isEmpty()) return a; ArrayList<Integer> res = (ArrayList<Integer>) a.clone(); res.sort(Comparator.naturalOrder()); for (int i = 0; i < a.size() - 1; i+=2) { int tmp = res.get(i); res.set(i, res.get(i+1)); res.set(i+1, tmp); } return res; } }
/* ***************************************************************************/ package com.abstracts.neo.pages; /* ***************************************************************************/ /* ***************************************************************************/ import com.abstracts.neo.modules.SettingsSideNavigationMenu; import com.abstracts.neo.modules.TopNavigationBar; import com.abstracts.neo.core.Page; import java.util.Optional; import java.util.function.Supplier; /* ***************************************************************************/ /** * @author Edinson E. Padrón Urdaneta */ public class SettingsPage extends Page { private final Supplier<Boolean> at = () -> getWebDriver().getTitle().equals("Settings"); private TopNavigationBar topNavigationBarModule; private SettingsSideNavigationMenu sideNavigationMenuModule; @Override public Optional<Supplier<Boolean>> getAt() { return Optional.of(at); } public SettingsSideNavigationMenu getSideNavigationMenuModule() { if (sideNavigationMenuModule == null) { sideNavigationMenuModule = new SettingsSideNavigationMenu(this); } return sideNavigationMenuModule; } public TopNavigationBar getTopNavigationBarModule() { if (topNavigationBarModule == null) { topNavigationBarModule = new TopNavigationBar(this); } return topNavigationBarModule; } }
/** * */ package com.parlourforu.rest; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; 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.RestController; import com.parlourforu.model.Customer; import com.parlourforu.service.ICustomerService; /** * @author Dixit * */ @RestController @RequestMapping("/api/customer") @Component public class CustomerRestService { @Autowired private ICustomerService customerService; @RequestMapping(value = "/create", method = RequestMethod.POST) Customer create(@RequestBody @Valid Customer customer) { return customerService.create(customer); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) Customer delete(@PathVariable("id") String id) { return customerService.delete(id); } @RequestMapping(value = "/getAll", method = RequestMethod.GET) List<Customer> findAll() { return customerService.findAll(); } @RequestMapping(value = "/getById/{id}", method = RequestMethod.GET) Customer findById(@PathVariable("id") String id) { return customerService.findById(id); } @RequestMapping(value = "/update/{id}", method = RequestMethod.PUT) Customer update(@RequestBody @Valid Customer todoEntry) { return customerService.update(todoEntry); } /* * @ExceptionHandler * * @ResponseStatus(HttpStatus.NOT_FOUND) public void * handleTodoNotFound(TodoNotFoundException ex) { } */ }
package com.goldenasia.lottery.data; import com.google.gson.annotations.SerializedName; /** * Created by ACE-PC on 2016/5/4. */ public class Options { /** * rebate : 0.120 * prize : 1940 */ @SerializedName("rebate") private double rebate;//·µµã @SerializedName("prize") private double prize;//½±½ð×é public void setRebate(double rebate) { this.rebate = rebate; } public void setPrize(double prize) { this.prize = prize; } public double getRebate() { return rebate; } public double getPrize() { return prize; } }
package fr.skytasul.quests.structure; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; import org.apache.commons.lang.Validate; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import fr.skytasul.quests.BeautyQuests; import fr.skytasul.quests.api.QuestsAPI; import fr.skytasul.quests.players.PlayerAccount; import fr.skytasul.quests.players.PlayerQuestDatas; public class BranchesManager{ private Map<Integer, QuestBranch> branches = new LinkedHashMap<>(); private final Quest quest; public BranchesManager(Quest quest){ this.quest = quest; } public Quest getQuest(){ return quest; } public int getBranchesAmount(){ return branches.size(); } public void addBranch(QuestBranch branch){ Validate.notNull(branch, "Branch cannot be null !"); branches.put(branches.size(), branch); } public int getID(QuestBranch branch){ for (Entry<Integer, QuestBranch> en : branches.entrySet()){ if (en.getValue() == branch) return en.getKey(); } BeautyQuests.logger.severe("Trying to get the ID of a branch not in manager of quest " + quest.getID()); return -1; } public List<QuestBranch> getBranches() { return branches.entrySet().stream().sorted(Comparator.comparingInt(Entry::getKey)).map(Entry::getValue).collect(Collectors.toList()); } public QuestBranch getBranch(int id){ return branches.get(id); } public QuestBranch getPlayerBranch(PlayerAccount acc) { if (!acc.hasQuestDatas(quest)) return null; return branches.get(acc.getQuestDatas(quest).getBranch()); } public boolean hasBranchStarted(PlayerAccount acc, QuestBranch branch){ if (!acc.hasQuestDatas(quest)) return false; return acc.getQuestDatas(quest).getBranch() == branch.getID(); } /** * Called internally when the quest is updated for the player * @param p Player */ public final void objectiveUpdated(Player p, PlayerAccount acc) { if (quest.hasStarted(acc)) { QuestsAPI.propagateQuestsHandlers(x -> x.questUpdated(acc, p, quest)); } } public void startPlayer(PlayerAccount acc){ PlayerQuestDatas datas = acc.getQuestDatas(getQuest()); datas.resetQuestFlow(); datas.setStartingTime(System.currentTimeMillis()); branches.get(0).start(acc); } public void remove(PlayerAccount acc) { if (!acc.hasQuestDatas(quest)) return; QuestBranch branch = getPlayerBranch(acc); if (branch != null) branch.remove(acc, true); } public void remove(){ for (QuestBranch branch : branches.values()){ branch.remove(); } branches.clear(); } public void save(ConfigurationSection section) { ConfigurationSection branchesSection = section.createSection("branches"); branches.forEach((id, branch) -> { try { branch.save(branchesSection.createSection(Integer.toString(id))); }catch (Exception ex) { BeautyQuests.logger.severe("Error when serializing the branch " + id + " for the quest " + quest.getID(), ex); BeautyQuests.savingFailure = true; } }); } @Override public String toString() { return "BranchesManager{branches=" + branches.size() + "}"; } public static BranchesManager deserialize(ConfigurationSection section, Quest qu) { BranchesManager bm = new BranchesManager(qu); ConfigurationSection branchesSection; if (section.isList("branches")) { // migration on 0.19.3: TODO remove List<Map<?, ?>> branches = section.getMapList("branches"); section.set("branches", null); branchesSection = section.createSection("branches"); branches.stream() .sorted((x, y) -> { int xid = (Integer) x.get("order"); int yid = (Integer) y.get("order"); if (xid < yid) return -1; if (xid > yid) return 1; throw new IllegalArgumentException("Two branches with same order " + xid); }).forEach(branch -> { int order = (Integer) branch.remove("order"); branchesSection.createSection(Integer.toString(order), branch); }); }else { branchesSection = section.getConfigurationSection("branches"); } // it is needed to first add all branches to branches manager // in order for branching stages to be able to access all branches // during QuestBranch#load, no matter in which order those branches are loaded Map<QuestBranch, ConfigurationSection> tmpBranches = new HashMap<>(); for (String key : branchesSection.getKeys(false)) { try { int id = Integer.parseInt(key); QuestBranch branch = new QuestBranch(bm); bm.branches.put(id, branch); tmpBranches.put(branch, branchesSection.getConfigurationSection(key)); }catch (NumberFormatException ex) { BeautyQuests.logger.severe("Cannot parse branch ID " + key + " for quest " + qu.getID()); BeautyQuests.loadingFailure = true; return null; } } for (QuestBranch branch : tmpBranches.keySet()) { try { if (!branch.load(tmpBranches.get(branch))) { BeautyQuests.getInstance().getLogger().severe("Error when deserializing the branch " + branch.getID() + " for the quest " + qu.getID() + " (false return)"); BeautyQuests.loadingFailure = true; return null; } }catch (Exception ex) { BeautyQuests.logger.severe("Error when deserializing the branch " + branch.getID() + " for the quest " + qu.getID(), ex); BeautyQuests.loadingFailure = true; return null; } } return bm; } }
/* * 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 asignacion5; /** * * @author hendryf * 24.09.21 * @param <AnyType> Tipo de dato que almacena el nodo */ public class Nodo<AnyType> { private AnyType dato; private Nodo<AnyType> enlace; //proximo nodo de la estructura /** * Metodo constructor para ultimo nodo * Nodo sin enlace * @param dato */ public Nodo(AnyType dato){ this.dato = dato; enlace = null; } /** * Metodo constructor a partir de las especificaciones * @param dato * @param enlace */ public Nodo(AnyType dato, Nodo<AnyType> enlace ){ this.dato = dato; this.enlace = enlace; } public AnyType getDato() { return dato; } public void setDato(AnyType dato) { this.dato = dato; } public Nodo<AnyType> getEnlace() { return enlace; } public void setEnlace(Nodo<AnyType> enlace) { this.enlace = enlace; } @Override public String toString(){ return String.valueOf(dato) ; } }
package mx.infornet.smartgym; import android.app.Dialog; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Build; import androidx.core.app.NotificationCompat; public class BroadcastAvancePerderPeso extends BroadcastReceiver { private int idNotify = 2; private String channelId = "my_channel_02"; private NotificationCompat.Builder mBuilder; @Override public void onReceive(Context context, Intent intent) { NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); mBuilder = new NotificationCompat.Builder(context, null); Intent notificationIntent = new Intent(context, AvancePerderPesoActivity.class); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent intent1 = PendingIntent.getActivity(context, 1, notificationIntent, 0); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ //nombre visible del canal CharSequence name = "Avance"; //descripcion visible del canal String descripcion = "Abre esta notificacion para que registres tu avance"; int importance = NotificationManager.IMPORTANCE_HIGH; NotificationChannel mChannel = new NotificationChannel(channelId, name, importance); //se configura el canal de la notificacion mChannel.setDescription(descripcion); mChannel.enableLights(true); //se determina luces, vibracion, etc mChannel.setLightColor(Color.BLACK); mChannel.enableVibration(true); mChannel.setVibrationPattern(new long[] {100,200,300,400,500,400,300,200,400}); manager.createNotificationChannel(mChannel); mBuilder = new NotificationCompat.Builder(context, channelId); } mBuilder .setSmallIcon(R.mipmap.icon) .setContentTitle("Avance") .setContentText("Cuéntanos como te está llendo") .setStyle(new NotificationCompat.BigTextStyle().bigText("Abre esta notificacion para que registres tu avance")) .setAutoCancel(true) .setContentIntent(intent1); manager.notify(idNotify, mBuilder.build()); } }
package spring.cache.model; import java.lang.reflect.Method; import org.springframework.cache.interceptor.KeyGenerator; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; @NoArgsConstructor @Slf4j public class CustomKeyGenerator implements KeyGenerator { private static final String KEY_DELIMITER = "."; private static final String PREFIX_DELIMITER = ":"; @Override public Object generate(Object target, Method method, Object... params) { StringBuilder keyBuilder = new StringBuilder(); if (target != null) { keyBuilder.append(target.getClass().getSimpleName()); } if (method != null) { keyBuilder.append(KEY_DELIMITER); keyBuilder.append(method.getName()); } for (Object param : params) { if (param != null) { keyBuilder.append(PREFIX_DELIMITER); keyBuilder.append(param); } } String result = keyBuilder.toString(); log.trace("CustomKeyGenerator : {}", result); return result; } }
import java.util.*; public class Knapsack { static int optimalWeight(int W, int[] w) { //write you code here int result = 0; for (int i = 0; i < w.length; i++) { if (result + w[i] <= W) { result += w[i]; } } return result; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int W, n; W = scanner.nextInt(); n = scanner.nextInt(); int[] w = new int[n]; for (int i = 0; i < n; i++) { w[i] = scanner.nextInt(); } System.out.println(optimalWeight(W, w)); } }
package com.lenovohit.hcp.appointment.manager; import com.lenovohit.hcp.appointment.model.RegInfo; import com.lenovohit.hcp.base.model.HcpUser; import com.lenovohit.hcp.base.model.HisOrder; import com.lenovohit.hcp.payment.model.HcpOrder; /** * * @description 挂号接口操作类,挂号的业务操作接口 * @author jatesun * @version 1.0.0 * @date 2017年4月13日 */ public interface RegisterManager { /** * 挂号操作 * 1生成流水号、发票号(fm_invoice_manage)21状态,记录reg_info表 * 2记录收费明细表(oc_chargedetail) * 3发票信息表(oc_invoiceinfo) * 4发票分类表(oc_invoiceinfo_detail) * 5门诊支付方式表(oc_payway)插入以便后续调用收银台 * @param info */ @Deprecated RegInfo register(RegInfo info); /** * 新的挂号流程,先调用收银台 * 1生成流水号、21状态,记录reg_info表 * 2记录收费明细表(oc_chargedetail) * 问题:返回hcporder,供收银台使用,后续独立应该没有任何返回或者返回true false。涉及收银台相关全都不应该在his出现 * @param info * @return */ HisOrder registerToPay(RegInfo info); /** * 退号操作 TODO 退号主体逻辑如果后台退费,也应该写在回调里,不应该写在这里 * 前置:已挂号并且未就诊 * 1生成一条负的invoiceinfo信息。 * 2更新reg_info(原)reg_state为12,记录canceloper caceltime * 3更新oc_chargedetail为apply-state4、cancel1 canceloper canceltime * 4oc——invoiceinfo cancle cancel信息 * 5oc-invoice-detail cancel相关 * 6oc-payway cancel相关 * @param regId */ void cancel(RegInfo info,HcpUser user); }
package com.example.covid_19.Activites; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ProgressBar; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import com.example.covid_19.Adapter.CountryAdapter; import com.example.covid_19.Model.Country; import com.example.covid_19.R; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class ShowAllCountriesActivity extends AppCompatActivity { RecyclerView recyclerView ; CountryAdapter adapter; List<Country> countryList; EditText textSaerch; RequestQueue requestQueue; ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show_all_countries); recyclerView = (RecyclerView)findViewById(R.id.Rv); countryList = new ArrayList<>(); progressBar = findViewById(R.id.pro_id); progressBar.setVisibility(View.INVISIBLE); textSaerch = findViewById(R.id.txtSreach); FetchCountry(); textSaerch.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { adapter.getFilter().filter(textSaerch.getText()); } @Override public void afterTextChanged(Editable s) { } }); } private void FetchCountry() { progressBar.setVisibility(View.VISIBLE); String url = "https://api.covid19api.com/summary"; JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { JSONArray array=response.getJSONArray("Countries"); for (int i=0;i<array.length();i++) { Country country=new Country(); JSONObject object = array.getJSONObject(i); country.setCountry(object.getString("Country")); country.setCountryCode(object.getString("CountryCode")); country.setNewConfirmed(object.getInt("NewConfirmed")); country.setTotalConfirmed(object.getInt("TotalConfirmed")); country.setNewDeaths(object.getInt("NewDeaths")); country.setTotalDeaths(object.getInt("TotalDeaths")); country.setNewRecovered(object.getInt("NewRecovered")); country.setTotalRecovered(object.getInt("TotalRecovered")); countryList.add(country); } } catch (JSONException e) { e.printStackTrace(); } adapter = new CountryAdapter(ShowAllCountriesActivity.this,countryList); recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext())); recyclerView.setAdapter(adapter); progressBar.setVisibility(View.INVISIBLE); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); requestQueue= Volley.newRequestQueue(ShowAllCountriesActivity.this); requestQueue.add(request); } }
import java.awt.Color; /** * Snake * * This class holds information needed to create/get/manipulate instances of a Snake object. */ import java.awt.Graphics; public class Snake extends GameObj { public static final int SIZE = 20; // LEFT = 1; // RIGHT = 2; // UP = 3; // DOWN = 4; private int direction; private Color color; public Snake(int px, int py, int courtWidth, int courtHeight, Color color, int direction) { super(px, py, SIZE, SIZE, courtWidth, courtHeight); this.color = color; this.direction = direction; } @Override public void draw(Graphics g) { g.setColor(this.color); g.fillRect(this.getPx(), this.getPy(), this.getWidth(), this.getHeight()); } public int getDir() { return this.direction; } public void setDir(int direction) { this.direction = direction; } }
package com.metoo.foundation.domain; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import com.metoo.core.constant.Globals; import com.metoo.core.domain.IdEntity; /** * * <p> * Title: GoodsCase.java * </p> * * <p> * Description: 橱窗展示管理类,用来管理首页等页面中推荐商品、广告、图片等橱窗信息,更加方便用户灵活控制页面信息 * </p> * * <p> * Copyright: Copyright (c) 2015 * </p> * * <p> * Company: 沈阳网之商科技有限公司 www.koala.com * </p> * * @author erikzhang * * @date 2014-9-16 * * @version koala_b2b2c 2.0 */ @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @Entity @Table(name = Globals.DEFAULT_TABLE_SUFFIX + "goods_case") public class GoodsCase extends IdEntity { private String case_name;// 橱窗名称 @Column(columnDefinition = "int default 0") private int sequence;// 排序 @Column(columnDefinition = "int default 0") private int display; private String case_id;// 橱窗标识,如index_top为首页顶部橱窗,页面显示橱窗时作为参数传递 @Column(columnDefinition = "LongText") private String case_content;// 橱窗信息,使用json管理 public GoodsCase() { super(); // TODO Auto-generated constructor stub } public GoodsCase(Long id, Date addTime) { super(id, addTime); // TODO Auto-generated constructor stub } public String getCase_id() { return case_id; } public void setCase_id(String case_id) { this.case_id = case_id; } public int getDisplay() { return display; } public void setDisplay(int display) { this.display = display; } public int getSequence() { return sequence; } public void setSequence(int sequence) { this.sequence = sequence; } public String getCase_name() { return case_name; } public void setCase_name(String case_name) { this.case_name = case_name; } public String getCase_content() { return case_content; } public void setCase_content(String case_content) { this.case_content = case_content; } }
/* * 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 armexperiment; /** * * @author Athena */ public class FacePair{ private final Face presFace; private final Face compFace; public FacePair(Face presFace, Face compFace) { this.presFace = presFace; this.compFace = compFace; } public Face getPresFace() { return presFace; } public Face getCompFace() { return compFace; } public boolean isPresHappy(){ if(presFace.getHappyURL() == null || presFace.getHappyURL().equals("")) return false; return true; } // public getPresFace //private final String presFaceID; //private final String compFaceID; // private final boolean male; // private final String emotionURL; // private final boolean presEmption = 0; // 0=sad and 1=happy // private final String sadURL; // private final String neutralURL; // private boolean happyEmotionSelected; // private int presentationOrder; public FacePair() { this.presFace = null; this.compFace = null; } }
import java.util.Scanner; class BirthdayExceptDemo { public static void main(String[] args) { boolean isAgain=false; Scanner scanner=new Scanner(System.in); do { System.out.println("Input the year month and day the person birth in:"); int year = Integer.parseInt( scanner.next()); int month = Integer.parseInt( scanner.next()); int day = Integer.parseInt( scanner.next()); try { new Person().SetBirthday(year,month,day); } catch(YearInvalidException ey) { System.out.println("catch YearInvalidException"); ey.printStackTrace(); } catch(MonthInvalidException em) { System.out.println("catch MonthInvalidException"); em.printStackTrace(); } catch(DayInvalidException ed) { System.out.println("catch DayInvalidException"); ed.printStackTrace(); } catch(BirthdayInvalidException eb) { System.out.println("catch BirthdayInvalidException"); eb.printStackTrace(); } finally { while(true) { System.out.println("Once again? y/n"); char c = scanner.next().charAt(0); if(c=='y'||c=='Y') { isAgain=true; break; } else if(c=='n'||c=='N') { isAgain=false; System.out.println("Goodbye"); break; } else System.out.println("y/n please!"); } } } while (isAgain); } } class Person { private int year,month,day; static final int YEAR_MIN=1970; // static final int YEAR_MAX= Calendar.getInstance().get(Calendar.YEAR); static final int YEAR_MAX= 2017; static final int MONTH_MIN=1; static final int MONTH_MAX=12; static final int DAY_MIN=1; static final int DAY_MAX=31; public void SetBirthday(int year, int month, int day) throws BirthdayInvalidException,YearInvalidException,MonthInvalidException,DayInvalidException { if(year<=YEAR_MIN) throw new YearInvalidException("Birth year too early"); else if(year>YEAR_MAX) throw new YearInvalidException("Birth year is not come yeat"); else this.year = year; if(month<MONTH_MIN) throw new MonthInvalidException("Birth month too little"); else if(month>MONTH_MAX) throw new MonthInvalidException("Birth month too big"); else this.month = month; if(day<DAY_MIN) throw new MonthInvalidException("Birth day too little"); else if(day>DAY_MAX) throw new MonthInvalidException("Birth day too big"); else { switch(month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: break; case 4: case 6: case 9: case 11: if(day>DAY_MAX-1) throw new MonthInvalidException("Birth day too big"); else this.day=day; break; case 2: if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0)//Leap year { if(day>DAY_MAX-2) throw new MonthInvalidException("Birth day too big"); else this.day=day; } else { if(day>DAY_MAX-3) throw new MonthInvalidException("Birth day too big"); else this.day=day; } break; default: throw new BirthdayInvalidException("BirthdayInvalid"); } } System.out.println("your birthday: "+year+"-"+month+"-"+day); } } class BirthdayInvalidException extends Exception { BirthdayInvalidException() { } BirthdayInvalidException(String msg) { super(msg); } } class YearInvalidException extends BirthdayInvalidException { YearInvalidException(){} YearInvalidException(String msg) { super(msg); } } class MonthInvalidException extends BirthdayInvalidException { MonthInvalidException(){} MonthInvalidException(String msg) { super(msg); } } class DayInvalidException extends BirthdayInvalidException { DayInvalidException(){} DayInvalidException(String msg) { super(msg); } }
package a3.logic; import a3.behaviour.Explore; import a3.memory.CollectiveMemory; import static a3.utility.Action.getRandomAction; import static a3.utility.Debug.println; import aiantwars.EAction; import aiantwars.IAntInfo; import aiantwars.ILocationInfo; import java.util.List; /** * @author Tobias Jacobsen */ public class ScoutLogic { private final IAntInfo thisAnt; private final ILocationInfo thisLocation; private final List<EAction> possibleActions; private final CollectiveMemory cm; public ScoutLogic(IAntInfo thisAnt, ILocationInfo thisLocation, List<EAction> possibleActions, CollectiveMemory cm) { this.thisAnt = thisAnt; this.thisLocation = thisLocation; this.possibleActions = possibleActions; this.cm = cm; } public EAction getAction() { println("Scout: Current loc: " + thisLocation.getX() + "," + thisLocation.getY() + ", direction: " + thisAnt.getDirection() + ", AP: " + thisAnt.getActionPoints() + "| Available actions: " + possibleActions.toString()); // a. when location has food and ant's food load is below 5, then pickup food if (possibleActions.contains(EAction.PickUpFood) && thisAnt.getFoodLoad() < 5) { return EAction.PickUpFood; } else { // b. else explore Explore explore = new Explore(thisAnt, thisLocation, cm); EAction action = explore.getAction(); if (possibleActions.contains(action) && !action.equals(EAction.Pass)) { return action; } } // c. If no action was returned, then get random action return getRandomAction(possibleActions); } }
package com.pos.porschetower.datamodel; /** * Created by coala on 10/19/2020. */ public class ShowroomItem { public String img_url; public String car_name; public String status_description; public String car_status; public int btn_color; public int btn_txt_color; }
package generating; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Random; public class DeliveryDateColumnGenerator implements ColumnGenerator{ private SimpleDateFormat sdf = new SimpleDateFormat(); public String generateColumnValue(Calendar[] benchTime, String[] tradeDate, boolean[] tradeDateGenerateflag,boolean[] tradeIdExistence,int rowsNumber){ //Calendar now = Calendar.getInstance(); String fd = new String(); if(tradeDateGenerateflag[0]==true){ String pattern = "dd/MM/yyyy"; Random r = new Random(); //now.set(2014, 1, 1); // trade date 之后 2到5年的每个月的第3个周四 Calendar now = benchTime[0]; now.add(Calendar.DATE, (int) (Math.floor(2*365 + Math.abs(365*3*r.nextFloat())))); now = get3thursday(now); fd = getDateFormat(now, pattern); } else{ new TradeDateColumnGenerator().generateColumnValue(benchTime, tradeDate, tradeDateGenerateflag,tradeIdExistence,rowsNumber); tradeDateGenerateflag[0]=true; String pattern = "dd/MM/yyyy"; Random r = new Random(); //now.set(2014, 1, 1); // trade date 之后 2到5年的每个月的第3个周四 Calendar now = benchTime[0]; now.add(Calendar.DATE, (int) (Math.floor(2*365 + Math.abs(365*3*r.nextFloat())))); now = get3thursday(now); fd = getDateFormat(now, pattern); } return fd; } // 第3个周四 private synchronized Calendar get3thursday(java.util.Calendar gc) { /** * 详细设计: 纠正为本月第3周 的周四 */ //gc.get(Calendar.DAY_OF_WEEK_IN_MONTH) switch (gc.get(Calendar.DAY_OF_WEEK_IN_MONTH)) { case (1): gc.add(Calendar.DATE, 14); break; case (2): gc.add(Calendar.DATE, 7); break; case (3): gc.add(Calendar.DATE, 0); break; case (4): gc.add(Calendar.DATE, -7); break; case (5): gc.add(Calendar.DATE, -14); break; } switch (gc.get(Calendar.DAY_OF_WEEK)) { case (Calendar.SUNDAY): gc.add(Calendar.DATE, -3); break; case (Calendar.SATURDAY): gc.add(Calendar.DATE, -2); break; case (Calendar.MONDAY): gc.add(Calendar.DATE, 3); break; case (Calendar.TUESDAY): gc.add(Calendar.DATE, 2); break; case (Calendar.WEDNESDAY): gc.add(Calendar.DATE, 1); break; case (Calendar.FRIDAY): gc.add(Calendar.DATE, -1); break; } // return gc.getTime(); return gc; } // 返回日期的相应格式 private synchronized String getDateFormat(java.util.Calendar cal, String pattern) { return getDateFormat(cal.getTime(), pattern); } // 返回日期的相应格式 private synchronized String getDateFormat(java.util.Date date, String pattern) { synchronized (sdf) { String str = null; sdf.applyPattern(pattern); str = sdf.format(date); return str; } } }
package xtrus.user.comp.ua.table; import com.esum.framework.common.sql.Record; import com.esum.framework.core.component.ComponentException; import com.esum.framework.core.component.table.InfoRecord; public class UaSvrInfoRecord extends InfoRecord { private static final long serialVersionUID = 1L; private String svrInfoId; private String hostIp; private int hostPort; private boolean useServer; private int connectionTimeout = 180; public UaSvrInfoRecord(Record record) throws ComponentException { super(record); } public UaSvrInfoRecord(String[] ids, Record record) throws ComponentException { super(ids, record); } @Override protected void init(Record record) throws ComponentException { this.svrInfoId = record.getString("SVR_INFO_ID").trim(); this.hostIp = record.getString("UA_HOST_IP", "127.0.0.1").trim(); this.hostPort = Integer.parseInt(record.getString("UA_HOST_PORT", "5029")); this.useServer = record.getString("USE_SERVER", "N").trim().equals("Y"); this.connectionTimeout = Integer.parseInt(record.getString("CONNECTION_TIMEOUT", "180")); } public String getSvrInfoId() { return svrInfoId; } public void setSvrInfoId(String svrInfoId) { this.svrInfoId = svrInfoId; } public String getHostIp() { return hostIp; } public void setHostIp(String hostIp) { this.hostIp = hostIp; } public int getHostPort() { return hostPort; } public void setHostPort(int hostPort) { this.hostPort = hostPort; } public boolean isUseServer() { return useServer; } public void setUseServer(boolean useServer) { this.useServer = useServer; } public int getConnectionTimeout() { return connectionTimeout; } public void setConnectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; } }
package com.zhouqi.schedule.trigger.impl; import com.zhouqi.entity.CfgTask; import org.apache.commons.lang3.StringUtils; import org.quartz.SimpleScheduleBuilder; import org.quartz.TriggerBuilder; /** * ${DESCRIPTION} * * @author zhouqi * @date 2018/4/13 9:19 */ public class SimpleTriggerExpression extends AbstractTriggerExpression{ @Override public void triggerBuilder(TriggerBuilder builder, CfgTask task) { String expression = task.getTriggerExpr(); SimpleScheduleBuilder simpleBuilder = SimpleScheduleBuilder.simpleSchedule(); if (!StringUtils.isEmpty(expression)) { String[] parts = expression.trim().split(" "); if (parts.length > 0) { simpleBuilder.withIntervalInMilliseconds(Integer.parseInt(parts[0]) * 60 * 1000); } if (parts.length > 1) { simpleBuilder.withRepeatCount(Integer.parseInt(parts[1])); } } else { simpleBuilder.withRepeatCount(1); } builder.withSchedule(simpleBuilder); builder.withPriority((int) task.getPripority()); } @Override public String comment() { return "The format is [IntervalInSeconds RepeatCount] default just shot one"; } @Override public String type() { return "S"; } }
package com.sap.als.persistence; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; @Entity @NamedQueries({ @NamedQuery(name = "WritingTestDrawingById", query = "select d from WritingTestDrawing d where d.id = :id") }) public class WritingTestDrawing implements Serializable { private static final long serialVersionUID = 1L; public WritingTestDrawing() { } @Id @GeneratedValue private long id; private String drawingName; @Column(columnDefinition = "BLOB") private byte[] drawingImage; private String drawTime; private String drawingTitle; //for compatibility purpose add this field and not using the drawingName public String getDrawTime() { return drawTime; } public void setDrawTime(String drawTime) { this.drawTime = drawTime; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDrawingName() { return drawingName; } public void setDrawingName(String drawingName) { this.drawingName = drawingName; } public byte[] getDrawingImage() { return drawingImage; } public void setDrawingImage(byte[] value) { this.drawingImage = value; } public String getDrawingTitle() { return drawingTitle; } public void setDrawingTitle(String drawingTitle) { this.drawingTitle = drawingTitle; } }
package com.test.base; import com.test.SolutionA; import junit.framework.TestCase; public class Example extends TestCase { private SolutionA solution; @Override protected void setUp() throws Exception { super.setUp(); } public void testSolutionA() { solution = new SolutionA(); assertSolution(); } private void assertSolution() { int[][] numsA = {{1,2,3,4,5,6},{1,2,3,4,5,6},{1,2,3,4,5,6},{1,2,3,4,5,6}}; int[][] resultA = solution.matrixReshape(numsA, 6, 4); ArrayUtils.print(resultA); } @Override protected void tearDown() throws Exception { super.tearDown(); } }
/** * Support for <a href='http://xmpp.org/extensions/xep-0077.html'>XEP-0077: In-Band Registration</a>. */ package tigase.jaxmpp.core.client.xmpp.modules.registration;
import javax.swing.JOptionPane; public class grade_enter_app { public static void main(String[] args) { final int MAX_AMOUNT = 10; String[] names = new String[MAX_AMOUNT]; double[] grades = new double[MAX_AMOUNT]; enterGrades(names, grades); } public static void enterGrades(String[] name, double[] grade) { boolean condition = false; for (int x = 0; x < name.length; x++) { do { name[x] = JOptionPane.showInputDialog("Enter Name " + (x+1) + ":"); if (name[x].equals("")) { JOptionPane.showMessageDialog(null, "Name cannot be blank!"); } else { condition = true; } } while (!condition); condition = false; do { try { grade[x] = Double.parseDouble(JOptionPane.showInputDialog("Enter Grade " + (x+1) + ":")); if (grade[x] < 0 || grade[x] > 100) { JOptionPane.showMessageDialog(null, "Grade cannot be LESS than 0 OR GREATER than 100"); } else { condition = true; } } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "Grade MUST be a positive integar"); } } while (!condition); condition = false; } } }
/** * Copyright (C) 2008 Atlassian * * 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.atlassian.theplugin.commons.jira; import com.atlassian.connector.commons.FieldValueGeneratorFactory; import com.atlassian.connector.commons.jira.FieldValueGenerator; import com.atlassian.connector.commons.jira.JIRAActionField; import com.atlassian.connector.commons.jira.JIRAActionFieldBean; import com.atlassian.connector.commons.jira.JIRAIssue; import com.atlassian.theplugin.commons.jira.api.fields.*; import com.google.common.collect.Maps; import org.codehaus.jettison.json.JSONObject; import org.jetbrains.annotations.NotNull; import java.util.*; /** * User: jgorycki * Date: Apr 2, 2009 * Time: 3:11:21 PM */ public final class JiraActionFieldType { public enum WidgetType { UNSUPPORTED, ASSIGNEE, REPORTER, ISSUE_TYPE, SUMMARY, DESCRIPTION, ENVIRONMENT, DUE_DATE, TIMETRACKING, VERSIONS, FIX_VERSIONS, RESOLUTION, PRIORITY, COMPONENTS, SECURITY, CUSTOM_FIELD } private static final class WidgetTypeAndFieldFiller { private final int sortOrder; private FieldFiller filler; private WidgetType widgetType; private WidgetTypeAndFieldFiller(WidgetType widgetType, int sortOrder, FieldFiller filler) { this.sortOrder = sortOrder; this.filler = filler; this.widgetType = widgetType; } public FieldFiller getFiller() { return filler; } public WidgetType getWidgetType() { return widgetType; } public int getSortOrder() { return sortOrder; } } private static class FieldValueGeneratorFactoryImpl implements FieldValueGeneratorFactory { @Override public FieldValueGenerator get(JIRAActionField field, JSONObject fieldDef) { String key = field.getFieldId().startsWith("customfield_") ? "customfield" : field.getFieldId(); WidgetTypeAndFieldFiller widgetAndFiller = typeMap.get(key); return widgetAndFiller.getFiller(); } } private static FieldValueGeneratorFactoryImpl fvgFactory = new FieldValueGeneratorFactoryImpl(); public static void init() { JIRAActionFieldBean.setGeneratorFactory(fvgFactory); } private static Map<String, WidgetTypeAndFieldFiller> typeMap = Maps.newHashMap(); private static CustomFieldFiller customFieldFiller = new CustomFieldFiller(); static { int i = 0; typeMap.put("summary", new WidgetTypeAndFieldFiller(WidgetType.SUMMARY, ++i, new SummaryFiller())); typeMap.put("resolution", new WidgetTypeAndFieldFiller(WidgetType.RESOLUTION, ++i, new ResolutionFiller())); typeMap.put("issuetype", new WidgetTypeAndFieldFiller(WidgetType.ISSUE_TYPE, ++i, new IssueTypeFiller())); typeMap.put("priority", new WidgetTypeAndFieldFiller(WidgetType.PRIORITY, ++i, new PriorityFiller())); typeMap.put("duedate", new WidgetTypeAndFieldFiller(WidgetType.DUE_DATE, ++i, new DueDateFiller())); typeMap.put("components", new WidgetTypeAndFieldFiller(WidgetType.COMPONENTS, ++i, new ComponentsFiller())); typeMap.put("versions", new WidgetTypeAndFieldFiller(WidgetType.VERSIONS, ++i, new AffectsVersionsFiller())); typeMap.put("fixVersions", new WidgetTypeAndFieldFiller(WidgetType.FIX_VERSIONS, ++i, new FixVersionsFiller())); typeMap.put("assignee", new WidgetTypeAndFieldFiller(WidgetType.ASSIGNEE, ++i, new AssigneeFiller())); typeMap.put("reporter", new WidgetTypeAndFieldFiller(WidgetType.REPORTER, ++i, new ReporterFiller())); typeMap.put("environment", new WidgetTypeAndFieldFiller(WidgetType.ENVIRONMENT, ++i, new EnvironmentFiller())); typeMap.put("description", new WidgetTypeAndFieldFiller(WidgetType.DESCRIPTION, ++i, new DescriptionFiller())); typeMap.put("timetracking", new WidgetTypeAndFieldFiller(WidgetType.TIMETRACKING, ++i, new TimeTrackingFiller())); typeMap.put("security", new WidgetTypeAndFieldFiller(WidgetType.SECURITY, ++i, new SecurityFiller())); typeMap.put("customfield", new WidgetTypeAndFieldFiller(WidgetType.CUSTOM_FIELD, ++i, new CustomFieldFiller())); } private JiraActionFieldType() { } public static WidgetType getFieldTypeForFieldId(@NotNull JIRAActionField field) { return getFieldTypeForFieldId(field.getFieldId()); } public static WidgetType getFieldTypeForFieldId(String fieldId) { if (typeMap.containsKey(fieldId)) { return typeMap.get(fieldId).getWidgetType(); } if (fieldId.startsWith("customfield")) { return typeMap.get("customfield").getWidgetType(); } return WidgetType.UNSUPPORTED; } /** * @param issue must be detailed issue * @param fields fields to pre-fill * @return list of fields with original values from the server */ public static List<JIRAActionField> fillFieldValues(JIRAIssue issue, List<JIRAActionField> fields) { List<JIRAActionField> result = new ArrayList<JIRAActionField>(); for (JIRAActionField field : fields) { JIRAActionField filledField = fillField(issue, field); if (filledField != null) { result.add(filledField); } } // pstefaniak: why were we adding time fields? // addTimeFields(issue, result); return result; } /* private static void addTimeFields(JIRAIssue issue, List<JIRAActionField> result) { String originalEstimate = issue.getOriginalEstimateInSeconds(); String remainingEstimate = issue.getRemainingEstimateInSeconds(); String timeSpent = issue.getTimeSpentInSeconds(); if (originalEstimate != null) { JIRAActionField originalEstimateField = new JIRAActionFieldBean("timeoriginalestimate", "Original Estimate"); originalEstimateField.addValue(originalEstimate); result.add(originalEstimateField); } if (remainingEstimate != null) { JIRAActionField remainingEstimateField = new JIRAActionFieldBean("timeestimate", "Remaining Estimate"); remainingEstimateField.addValue(remainingEstimate); result.add(remainingEstimateField); } if (timeSpent != null) { JIRAActionField timeSpentField = new JIRAActionFieldBean("timespent", "Time Spent"); timeSpentField.addValue(timeSpent); result.add(timeSpentField); } }*/ private static JIRAActionField fillField(JIRAIssue issue, final JIRAActionField field) { WidgetTypeAndFieldFiller widgetTypeAndFieldFiller = typeMap.get(field.getFieldId()); JIRAActionFieldBean result = new JIRAActionFieldBean(field); if (widgetTypeAndFieldFiller != null) { result.setValues(widgetTypeAndFieldFiller.getFiller().getFieldValues(field.getFieldId(), issue)); } else { result.setValues(customFieldFiller.getFieldValues(field.getFieldId(), issue)); } return result; } public static Collection<JIRAActionField> sortFieldList(List<JIRAActionField> fieldList) { int customFieldOffset = typeMap.size(); Map<Integer, JIRAActionField> sorted = new TreeMap<Integer, JIRAActionField>(); for (JIRAActionField field : fieldList) { if (typeMap.containsKey(field.getFieldId())) { sorted.put(typeMap.get(field.getFieldId()).getSortOrder(), field); } else { sorted.put(customFieldOffset++, field); } } return sorted.values(); } }
package com.BasicJava; public class DowhileExample { public static void main(String[] args) { int k=10; do { System.out.println("web driver"); k--; } while(k>10); } }
package com.fei.repo; import com.fei.model.User; import java.sql.*; /** * Created by freddy on 4/2/2017. */ public class Mysql { private Connection getDbConnection() throws Exception{ try { // Grab login info for MySQL from the credentials node String hostname = System.getenv("dbhost"); String user = System.getenv("user"); // String password = System.getenv("password"); // String port = System.getenv("port"); // String hostname = "172.16.51.58"; // String user = "root"; // String password = "111111"; // String port = "3306"; Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://" + hostname + ":" + "3306" + "/"; Connection conn = DriverManager.getConnection(url, user, null); conn.createStatement().execute("create database if not exists " + "user"); System.out.println("Checked db."); conn.createStatement().execute("CREATE TABLE if not exists user.user" + " (name varchar(255), email varchar(255), country varchar(100))"); System.out.println("Checked table."); conn.close(); String dbUrl = url + "user"; System.out.println("Connecting to mysql:" + dbUrl); return DriverManager.getConnection(dbUrl, user, null); } catch (Exception e) { System.out.println("Caught error: "); e.printStackTrace(); throw e; } } public User getUser(String name) { Connection conn = null; Statement stmt = null; User result = null; try{ conn = getDbConnection(); System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; sql = "SELECT name, email, country FROM user where name=\"" + name + "\""; ResultSet rs = stmt.executeQuery(sql); while(rs.next()){ result = new User(); result.setName(rs.getString("name")); result.setEmail(rs.getString("email")); result.setCountry(rs.getString("country")); System.out.println("Find user:" + result.getName() + " from mysql db."); } rs.close(); stmt.close(); conn.close(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try return result; } public void addUser(User user) { Connection conn = null; Statement stmt = null; try{ conn = getDbConnection(); stmt = conn.createStatement(); String sql; sql = "INSERT INTO user(name,email,country) " + "VALUES (\"" + user.getName() + "\",\"" + user.getEmail() + "\",\"" + user.getCountry() + "\")"; System.out.println("Will execute sql:" + sql); stmt.executeUpdate(sql); stmt.close(); conn.close(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try } }
package web.inject; import java.util.EnumSet; import javax.inject.Named; import javax.inject.Singleton; import javax.servlet.DispatcherType; import javax.servlet.ServletContextListener; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Provides; import com.google.inject.Stage; import com.google.inject.servlet.GuiceFilter; import com.google.inject.servlet.GuiceServletContextListener; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; /** Inject Server */ public class ServerModule extends AbstractModule { @Provides @Singleton public Server providesServer( @Named("appContextListener") ServletContextListener appContextListener, @Named("server.port") Integer port) { Server server = new Server(port); ServletContextHandler contextHandler = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS); contextHandler.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class)); contextHandler.addEventListener(appContextListener); return server; } @Provides @Singleton @Named("appContextListener") public ServletContextListener providesAppContextListener(@Named("env.stage") String stage) { return new GuiceServletContextListener() { @Override protected Injector getInjector() { return Guice.createInjector(Stage.valueOf(stage), new AppServletModule()); } }; } }
package gui; import java.awt.EventQueue; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import da.WarehouseDA; public class AddWarehouse extends JFrame { private JTextField txtName; private JTextField txtAddress; private JTextField txtDescription; private WarehouseDA warehouseDA; public AddWarehouse() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle("Add Warehouse"); setBounds(300, 200, 376, 391); getContentPane().setLayout(null); JLabel lblAddWarehouse = new JLabel("Add Warehouse"); lblAddWarehouse.setFont(new Font("Tahoma", Font.BOLD, 20)); lblAddWarehouse.setBounds(90, 11, 171, 38); getContentPane().add(lblAddWarehouse); JLabel lblNewLabel = new JLabel("Name"); lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 14)); lblNewLabel.setBounds(23, 67, 74, 14); getContentPane().add(lblNewLabel); JLabel lblAddress = new JLabel("Address"); lblAddress.setFont(new Font("Tahoma", Font.PLAIN, 14)); lblAddress.setBounds(23, 107, 74, 14); getContentPane().add(lblAddress); JLabel lblDesciption = new JLabel("Desciption"); lblDesciption.setFont(new Font("Tahoma", Font.PLAIN, 14)); lblDesciption.setBounds(23, 193, 74, 14); getContentPane().add(lblDesciption); txtName = new JTextField(); txtName.setFont(new Font("Tahoma", Font.PLAIN, 13)); txtName.setBounds(128, 60, 210, 30); getContentPane().add(txtName); txtName.setColumns(10); txtAddress = new JTextField(); txtAddress.setFont(new Font("Tahoma", Font.PLAIN, 13)); txtAddress.setColumns(10); txtAddress.setBounds(128, 101, 210, 81); getContentPane().add(txtAddress); txtDescription = new JTextField(); txtDescription.setFont(new Font("Tahoma", Font.PLAIN, 13)); txtDescription.setColumns(10); txtDescription.setBounds(128, 193, 210, 89); getContentPane().add(txtDescription); JButton btnSave = new JButton("Save"); btnSave.setFont(new Font("Tahoma", Font.PLAIN, 14)); btnSave.setBounds(60, 306, 89, 23); getContentPane().add(btnSave); JButton btnCancle = new JButton("Cancle"); btnCancle.setFont(new Font("Tahoma", Font.PLAIN, 14)); btnCancle.setBounds(204, 306, 89, 23); getContentPane().add(btnCancle); btnSave.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub addWarehouse(); WarehouseList.getWHList(); } }); btnCancle.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub AddWarehouse.this.dispose(); } }); } private void addWarehouse() { String name = txtName.getText(); String address = txtAddress.getText(); String description = txtDescription.getText(); warehouseDA.insert(name, address, description); } public static void main(String[] args) { // TODO Auto-generated method stub EventQueue.invokeLater(new Runnable() { public void run() { try { AddWarehouse form = new AddWarehouse(); form.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } }
package info.finny.msvc.service; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; public interface WordFeignClient { @RequestMapping (method= RequestMethod.GET, value = "/") public String getWord(); }
package chen.shu.hex_empire_v1; public enum State { MENU(), MAP(), PLAY(); }
package com.example.simpledashcam; import android.view.View; import android.widget.AdapterView; public class CameraListAdaptorItemSelected implements AdapterView.OnItemSelectedListener { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { } public void onNothingSelected(AdapterView<?> parent) { } }
package com.maco.juegosEnGrupo.server.dominio; import java.io.IOException; import java.util.Random; import org.json.JSONException; import org.json.JSONObject; import com.maco.blackjack.jsonMessage.BlackJackBoardMessage; import com.maco.tresenraya.jsonMessages.TresEnRayaBoardMessage; import com.maco.tresenraya.jsonMessages.TresEnRayaMatchReadyMessage; import com.maco.tresenraya.jsonMessages.TresEnRayaMovement; import com.maco.tresenraya.jsonMessages.TresEnRayaWaitingMessage; import edu.uclm.esi.common.jsonMessages.ErrorMessage; import edu.uclm.esi.common.jsonMessages.JSONMessage; import edu.uclm.esi.common.jsonMessages.OKMessage; import edu.uclm.esi.common.server.domain.User; import edu.uclm.esi.common.server.sockets.Notifier; public class TresEnRaya extends Match { public static int TRES_EN_RAYA = 1; public static char X='X', O='O', WHITE = ' '; private User userWithTurn; private char[][] squares; public TresEnRaya(Game game) { super(game); squares=new char[3][3]; for (int row=0; row<3; row++) for (int col=0; col<3; col++) squares[row][col]=WHITE; } @Override public String toString() { String r=""; for (int row=0; row<3; row++) for (int col=0; col<3; col++) r+=this.squares[row][col]; r+="#" + this.players.get(0).getEmail() + "#"; if (this.players.size()==2) { r+=this.players.get(1).getEmail() + "#"; r+=this.userWithTurn.getEmail(); } return r; } @Override public void postMove(User user, JSONObject jsoMovement) throws Exception { if (!jsoMovement.get("type").equals(TresEnRayaMovement.class.getSimpleName())) { throw new Exception("Unexpected type of movement"); } int row=jsoMovement.getInt("row"); int col=jsoMovement.getInt("col"); JSONMessage result=null; if (this.squares[row][col]!=WHITE) { result=new ErrorMessage("Square busy"); Notifier.get().post(user, result); } else if (!this.isTheTurnOf(user)) { result=new ErrorMessage("It's not your turn"); Notifier.get().post(user, result); } updateBoard(row, col, result); } @Override protected void updateBoard(int row, int col, JSONMessage result) throws JSONException, IOException { if (result==null) { if (this.userWithTurn.equals(this.players.get(0))) { this.squares[row][col]=X; this.userWithTurn=this.players.get(1); } else { this.squares[row][col]=O; this.userWithTurn=this.players.get(0); } result=new TresEnRayaBoardMessage(this.toString()); Notifier.get().post(this.players, result); } } @Override protected boolean isTheTurnOf(User user) { return this.userWithTurn.equals(user); } @Override protected void postAddUser(User user) { if (this.players.size()==2) { Random dado=new Random(); JSONMessage jsTurn=new TresEnRayaWaitingMessage("Match ready. You have the turn."); JSONMessage jsNoTurn=new TresEnRayaWaitingMessage("Match ready. Wait for the opponent to move."); if (dado.nextBoolean()) { this.userWithTurn=this.players.get(0); try { Notifier.get().post(this.players.get(0), jsTurn); Notifier.get().post(this.players.get(1), jsNoTurn); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { this.userWithTurn=this.players.get(1); try { Notifier.get().post(this.players.get(1), jsTurn); Notifier.get().post(this.players.get(0), jsNoTurn); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { JSONMessage jsBoard=new TresEnRayaBoardMessage(this.toString()); Notifier.get().post(this.players.get(0), jsBoard); Notifier.get().post(this.players.get(1), jsBoard); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { JSONMessage jsm=new TresEnRayaWaitingMessage("Waiting for one more player"); try { Notifier.get().post(this.players.get(0), jsm); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @Override protected void updateBoard(JSONMessage result, int idmatch) throws JSONException, IOException { // TODO Auto-generated method stub } @Override protected void postBet(User user, JSONObject jsoBet,int idmatch) throws Exception { // TODO Auto-generated method stub } @Override protected void postRequestCard(User user, JSONObject jsoRec, int idMatch) throws Exception { // TODO Auto-generated method stub } @Override protected void postPlanted(User user, JSONObject jsoRec,int idmatch) throws Exception { // TODO Auto-generated method stub } }
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.PrintWriter; import org.semanticweb.owlapi.apibinding.OWLManager; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyCreationException; import org.semanticweb.owlapi.model.OWLOntologyManager; import org.semanticweb.owlapi.reasoner.InferenceType; import eu.trowl.owlapi3.rel.reasoner.el.RELReasonerFactory; import eu.trowl.owlapi3.rel.reasoner.el.RELReasoner;; public class TROWLEL { public static void main(String[] args) throws OWLOntologyCreationException { // File c=new File("/home/ajkamal/Desktop/Import/pizza.owl"); // IRI physicalIRI = IRI.create(c); // OWLOntologyManager manager = OWLManager.createOWLOntologyManager(); // OWLOntology ontology = manager.loadOntologyFromOntologyDocument(physicalIRI); // RELReasonerFactory relfactory = new RELReasonerFactory(); // RELReasoner reasoner = relfactory.createReasoner(ontology); // System.out.println("Check consistency: " + reasoner.isConsistent()); // System.out.println("Check consistency: " + reasoner.countersubsumers()); // System.out.println("Check consistency: " + reasoner.countersubsumers()); // OWLDataFactory df = manager.getOWLDataFactory(); // try{ // reasoner.precomputeInferences(InferenceType.CLASS_ASSERTIONS); // //following Lines are to see super classes of Container // OWLClass clsA = df.getOWLClass(IRI.create("http://www.co-ode.org/ontologies/pizza/pizza.owl#Rosa")); // Set<OWLClassExpression> superClasses = clsA.getSuperClasses(ontology); // //System.out.println("Hello World\n"+superClasses.iterator().toString()); // for (OWLClassExpression g : superClasses) { // System.out.println("The superclasses are:"+g); // } // } // catch (Exception e) { // e.printStackTrace(); // } File c=new File(args[0]); IRI physicalIRI = IRI.create(c); OWLOntologyManager manager = OWLManager.createOWLOntologyManager(); OWLOntology ontology = manager.loadOntologyFromOntologyDocument(physicalIRI); RELReasonerFactory relfactory = new RELReasonerFactory(); RELReasoner reasoner = relfactory.createReasoner(ontology); long startTime = System.nanoTime(); reasoner.precomputeInferences(InferenceType.CLASS_HIERARCHY); long endTime = System.nanoTime(); long duration = ((endTime - startTime)); Runtime runtime = Runtime.getRuntime(); // Run the garbage collector runtime.gc(); long memory = (runtime.totalMemory() - runtime.freeMemory()); long tmemory=runtime.totalMemory(); System.out.print(duration+" "); System.out.print(tmemory/(1024L * 1024L)+" "); System.out.print((memory/(1024L * 1024L))+" "); if (reasoner.isConsistent()) { // Now we create an output stream that HermiT can use to write the axioms. The output stream is // a wrapper around the file into which the axioms are written. File prettyPrintHierarchyFile=new File("/home/ajkamal/Desktop/fma.owl"); if (!prettyPrintHierarchyFile.exists()) // prettyPrintHierarchyFile.createNewFile(); // turn to an absolute file, so that we can write to it prettyPrintHierarchyFile=prettyPrintHierarchyFile.getAbsoluteFile(); // BufferedOutputStream prettyPrintHierarchyStreamOut=new BufferedOutputStream(new FileOutputStream(prettyPrintHierarchyFile)); // The output stream is wrapped into a print write with autoflush. // PrintWriter output=new PrintWriter(prettyPrintHierarchyStreamOut,true); // Now we let HermiT pretty print the hierarchies. Since all parameters are set to true, // HermiT will print the class and the object property and the data property hierarchy. long t=System.currentTimeMillis(); t=System.currentTimeMillis()-t; // reasoner.printHierarchies(output, true, true, true); // Now save a copy in OWL/XML format //File f = new File("example.xml"); //IRI documentIRI2 = IRI.create(f); //manager.saveOntology(school, new OWLXMLOntologyFormat(), documentIRI2); //System.out.println("Ontology saved in XML format."); } else { System.out.println("Ontology malformed."); } // // OWLDataFactory df = manager.getOWLDataFactory(); // try{ // reasoner.precomputeInferences(InferenceType.CLASS_ASSERTIONS); // //following Lines are to see super classes of Container // // // OWLClass clsA = df.getOWLClass(IRI.create("http://www.ihtsdo.org/#SCTID_10019001_1")); // System.out.println(clsA); // Set<OWLClassExpression> superClasses = clsA.getSuperClasses(ontology); // //System.out.println("Hello World\n"+superClasses.iterator().toString()); // for (OWLClassExpression g : superClasses) { // System.out.println("The superclasses are:"+g); // } // // } // catch (Exception e) { // e.printStackTrace(); // } } } //reasoner.precomputeInferences(InferenceType.CLASS_HIERARCHY); //reasoner.precomputeInferences(InferenceType.CLASS_HIERARCHY); //reasoner.getSubClasses(df.getOWLClass("http://www.co−ode.org/ontologies/pizza/pizza.owl#RealItalianPizza",true), false).forEach(System.out::println);;
package psoft.backend.exception.comentario; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.BAD_REQUEST) public class ComentarioInvalidoException extends RuntimeException { public ComentarioInvalidoException(String s) { } }
package id.bts.PiWebRestIoT.util; public enum SwitchStatus { OFF, ON }
package dk.jrpe.monitor.ejb.remote; import javax.ejb.Remote; /** * * @author Jörgen Persson */ @Remote public interface MonitorSessionBeanRemote { String test(); }
package pro2e.teamX.userinterface; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Box; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class FilterPanel extends JPanel implements ActionListener { public JCheckBox keinfilter = new JCheckBox("Kein Filter"); public JCheckBox smoothingfilter = new JCheckBox("Smoothing"); public JCheckBox Tiefpassfilter = new JCheckBox("Tiefpassfilter"); public JLabel lbgrenzfrequenz = new JLabel("Grenzfrequenz:"); public JTextField tfGrenzfrequenz = new JTextField(30); public JLabel lbAnzahlwerte = new JLabel("Anzahl Werte:"); public JTextField tfAnzahlwerte = new JTextField(30); public JCheckBox cbRechteck = new JCheckBox("Rechteck"); public JCheckBox cbGauss = new JCheckBox("Gauss"); public Box.Filler bfiller; public FilterPanel() { this.setLayout(new GridBagLayout()); this.setPreferredSize(new Dimension(400, 200)); add(keinfilter, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 0, 0)); add(smoothingfilter, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 0, 0)); add(Tiefpassfilter, new GridBagConstraints(2, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 0, 0)); add(lbgrenzfrequenz, new GridBagConstraints(0, 2, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(10, 10, 10, 10), 0, 0)); add(tfGrenzfrequenz, new GridBagConstraints(0, 3, 3, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 0, 0)); add(cbRechteck, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 0, 0)); add(cbGauss, new GridBagConstraints(1, 1, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 0, 0)); add(lbAnzahlwerte, new GridBagConstraints(0, 2, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 0, 0)); add(tfAnzahlwerte, new GridBagConstraints(0, 3, 3, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 0, 0)); add(Box.createVerticalGlue(), new GridBagConstraints(0, 4, 3, 0, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.VERTICAL, new Insets(10, 10, 10, 10), 0, 0)); keinfilter.addActionListener(this); smoothingfilter.addActionListener(this); Tiefpassfilter.addActionListener(this); lbgrenzfrequenz.setVisible(false); tfGrenzfrequenz.setVisible(false); lbAnzahlwerte.setVisible(false); tfAnzahlwerte.setVisible(false); cbGauss.addActionListener(this); cbRechteck.addActionListener(this); cbGauss.setVisible(false); cbRechteck.setVisible(false); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if (e.getSource() == smoothingfilter) { keinfilter.setSelected(false); Tiefpassfilter.setSelected(false); cbRechteck.setVisible(true); cbGauss.setVisible(true); tfAnzahlwerte.setVisible(true); lbAnzahlwerte.setVisible(true); lbgrenzfrequenz.setVisible(false); tfGrenzfrequenz.setVisible(false); Box.createHorizontalGlue().setVisible(false); } if (e.getSource() == keinfilter) { keinfilter.setSelected(true); Tiefpassfilter.setSelected(false); cbRechteck.setVisible(false); cbGauss.setVisible(false); tfAnzahlwerte.setVisible(false); lbAnzahlwerte.setVisible(false); lbgrenzfrequenz.setVisible(false); tfGrenzfrequenz.setVisible(false); smoothingfilter.setSelected(false); } if (e.getSource() == Tiefpassfilter) { keinfilter.setSelected(false); smoothingfilter.setSelected(false); Tiefpassfilter.setSelected(true); tfGrenzfrequenz.setVisible(true); lbgrenzfrequenz.setVisible(true); cbGauss.setVisible(false); cbRechteck.setVisible(false); tfAnzahlwerte.setVisible(false); lbAnzahlwerte.setVisible(false); } } }
package com.krixon.ecosystem.profiling.domain; import lombok.Getter; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.validation.constraints.NotNull; @Entity @Getter @DiscriminatorValue("textual") public class TextualAnswer extends Answer { @NotNull private String value; private TextualAnswer() { super(); } private TextualAnswer(AnswerId id, @NotNull String value) { super(id); this.value = value; } public static TextualAnswer submit(AnswerId id, AnswerSubmission submission) { TextualAnswer instance = new TextualAnswer(id, extractSubmittedValue(submission)); // TODO: Fire an event. return instance; } @Override public void resubmit(AnswerSubmission submission) { value = extractSubmittedValue(submission); } private static String extractSubmittedValue(AnswerSubmission submission) { return (String) submission.getValue(); } }
package com.cbsystematics.edu.eshop.service; import com.cbsystematics.edu.eshop.dao.IUserDAOImpl; import com.cbsystematics.edu.eshop.entities.User; import java.util.List; public class IUserServiceImpl implements IUserService { private IUserDAOImpl userDAO; public IUserServiceImpl() { this.userDAO = new IUserDAOImpl(); } @Override public User createUser(User user) { return userDAO.create(user); } @Override public User updateUser(User user) { return userDAO.update(user); } @Override public User getUser(Integer id) { return userDAO.get(id); } @Override public void deleteUser(Integer id) { userDAO.delete(id); } @Override public List<User> getAllUsers() { return userDAO.getAll(); } }
package com.dh.comunicacao.comunicacaofragmentfragment; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import com.dh.comunicacao.R; public class MainActivity extends AppCompatActivity implements FirstFragmentListener { private FirstFragment firstFragment = new FirstFragment(); private SecondFragment secondFragment = new SecondFragment(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_fragment_fragment); if(savedInstanceState == null){ addFragment(firstFragment, R.id.frameLayout1); addFragment(secondFragment, R.id.frameLayout2); }else{ firstFragment = (FirstFragment)getFragmentById(R.id.frameLayout1); secondFragment = (SecondFragment)getFragmentById(R.id.frameLayout2); } } private void addFragment(Fragment fragment, int layoutId){ getSupportFragmentManager().beginTransaction().add(layoutId, fragment).commit(); } private Fragment getFragmentById(int layoutId){ return getSupportFragmentManager().findFragmentById(layoutId); } @Override public void getMessage(String message) { secondFragment.getTextView().setText(message); } }
/* * Copyright 2013-2014 JetBrains s.r.o. * * 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 jetbrains.buildServer.sbtlogger; import junit.framework.Assert; import org.junit.Test; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class SbtLoggerOutputTest { @Test public void testPluginStatus() throws IOException, InterruptedException { SbtProcess.runAndTest("sbt-teamcity-logger", new File("test/testdata/compileerror").getAbsolutePath(),"plugin_status_output.txt"); } @Test public void testCompileErrorOutput() throws IOException, InterruptedException { SbtProcess.runAndTest("compile", new File("test/testdata/compileerror").getAbsolutePath()); } @Test public void testCompileSuccessfulOutput() throws IOException, InterruptedException { SbtProcess.runAndTest("compile", new File("test/testdata/compilesuccessful").getAbsolutePath()); } @Test public void testMultiProjectsOutput() throws IOException, InterruptedException { SbtProcess.runAndTest("compile", new File("test/testdata/multiproject").getAbsolutePath()); } @Test public void testTmp() throws IOException, InterruptedException { SbtProcess.runAndTestWithAdditionalParams("--debug","compile", new File("test/testdata/multiproject").getAbsolutePath()); } @Test public void testScalaTest() throws IOException, InterruptedException { int exitCode = SbtProcess.runAndTest("test", new File("test/testdata/testsupport/scalatest").getAbsolutePath(), "output.txt", "output1.txt"); //if need exit code equals 0, otherwise in TeamCity additional non-informative build problem message will appear Assert.assertEquals(0,exitCode); } @Test public void testNoSbtFileInProject() throws IOException, InterruptedException { SbtProcess.runAndTest("compile", new File("test/testdata/nosbtfile").getAbsolutePath()); } @Test public void testWarningInTestOutput() throws IOException, InterruptedException { SbtProcess.runAndTest("test", new File("test/testdata/TW35693").getAbsolutePath()); } @Test public void testTW35404_error() throws IOException, InterruptedException { SbtProcess.runAndTest("compile", new File("test/testdata/TW35404_error").getAbsolutePath()); } @Test public void testTW35404_debug() throws IOException, InterruptedException { SbtProcess.runAndTest("compile", new File("test/testdata/TW35404_debug").getAbsolutePath()); } @Test public void testSubProject_compile() throws IOException, InterruptedException { SbtProcess.runAndTest("backend/compile", new File("test/testdata/subproject").getAbsolutePath()); } @Test public void testRunTestWithSbt() throws IOException, InterruptedException { int exitCode = SbtProcess.runAndTest("test", new File("test/testdata/testsupport/scalatest").getAbsolutePath(), "output.txt", "output1.txt"); //if need exit code equals 0, otherwise in TeamCity additional non-informative build problem message will appear Assert.assertEquals(0,exitCode); } @Test public void testRunWithPluginFromBintray() throws IOException, InterruptedException { SbtProcess.runWithoutApplyAndTest("test", new File("test/testdata/bintray").getAbsolutePath()); } @Test public void testRunWithPluginFromBintrayWithReApply() throws IOException, InterruptedException { SbtProcess.runAndTest("test", new File("test/testdata/bintray").getAbsolutePath()); } @Test public void testOtherSbtVersions() throws IOException, InterruptedException { SbtProcess.runAndTestWithAdditionalParams("sbtVersion", "--info", new File("test/testdata/otherVersions").getAbsolutePath()); } @Test public void testProjectWithJavaSources() throws IOException, InterruptedException { SbtProcess.runAndTestWithAdditionalParams("clean compile run", "--debug", new File("test/testdata/withJavaSources").getAbsolutePath(),"output.txt"); } @Test public void testIgnoredTest() throws IOException, InterruptedException { SbtProcess.runAndTestWithAdditionalParams("--info", "test", new File("test/testdata/ignoredTest").getAbsolutePath()); } @Test public void testNestedSuites() throws IOException, InterruptedException { SbtProcess.runAndTestWithAdditionalParams("--info", "test", new File("test/testdata/testsupport/nested").getAbsolutePath()); } @Test public void testSpecTW46964() throws IOException, InterruptedException { SbtProcess.runAndTest("testOnly", new File("test/testdata/testsupport/scalatest_TW46964").getAbsolutePath(),"output.txt"); } @Test public void testSpec2() throws IOException, InterruptedException { SbtProcess.runAndTest("testOnly", new File("test/testdata/testsupport/spec2").getAbsolutePath(),"output.txt"); } @Test public void testTW50753_initErrorInTests() throws IOException, InterruptedException { SbtProcess.runAndTest("clean compile test", new File("test/testdata/TW-50753_initErrorInTests").getAbsolutePath(),"output.txt"); } @Test public void testParallelTestExecutionTW43578() throws IOException, InterruptedException { SbtProcess.runAndTestWithAdditionalParams("--info", "test", new File("test/testdata/testsupport/parallelTestExecutionTW43578/src/").getAbsolutePath(), "output.txt","output1.txt", "output2.txt","output3.txt","output4.txt","output5.txt", "output7.txt", "output6.txt", "output8.txt", "output9.txt", "output10.txt", "output11.txt"); } /** * Service method. Allows quickly investigate test cases failed directly on TeamCity agent. * Agent output should be placed in test data directory and could be checked against required output * * @throws IOException */ public void testServerLogs() throws IOException { String workingDir = new File("test/testdata/multiproject").getAbsolutePath(); File requiredFile = new File(workingDir + File.separator + "output.txt"); File serverLogs = new File(workingDir + File.separator + "server_logs.log"); SbtProcess.checkOutputTest(new BufferedReader(new FileReader(serverLogs)), new BufferedReader(new FileReader(requiredFile)), null); } }
package com.legaoyi.persistence.jpa.service.impl; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.legaoyi.persistence.jpa.dao.GeneralDao; import com.legaoyi.persistence.jpa.model.Pagination; import com.legaoyi.persistence.jpa.service.GeneralService; /** * @author gaoshengbo */ @Service("generalService") @Transactional public class GeneralServiceImpl implements GeneralService { @Autowired @Qualifier("generalDao") private GeneralDao generalDao; @Override public Object get(String entityName, Object id) throws Exception { return this.generalDao.get(entityName, id); } @Override public long count(String entityName, Map<String, Object> andCondition) throws Exception { return this.generalDao.count(entityName, andCondition); } @Override public long countByHql(String hql, Object... params) throws Exception { return this.generalDao.countByHql(hql, params); } @Override public long countBySql(String sql, Object... params) throws Exception { return this.generalDao.countBySql(sql, params); } @Override public List<?> findBySql(String sql) throws Exception { return this.generalDao.findBySql(sql); } @Override public List<?> findBySql(String sql, Object... params) throws Exception { return this.generalDao.findBySql(sql, params); } @Override public List<?> findBySqlWithPage(String sql, int pageSize, int pageNo, Object... params) throws Exception { return this.generalDao.findBySqlWithPage(sql, pageSize, pageNo, params); } @Override public Pagination pageFindBySql(String sql, int pageSize, int pageNo, Object... params) throws Exception { return this.generalDao.pageFindBySql(sql, pageSize, pageNo, params); } @Override public List<?> findByHql(String hql) throws Exception { return this.generalDao.findByHql(hql); } @Override public List<?> findByHql(String hql, Object... params) throws Exception { return this.generalDao.findByHql(hql, params); } @Override public Pagination pageFindByHql(String hql, int pageSize, int pageNo, Object... params) throws Exception { return this.generalDao.pageFindByHql(hql, pageSize, pageNo, params); } @Override public List<?> findAll(String entityName) throws Exception { return this.generalDao.findAll(entityName); } @Override public List<?> findAll(String entityName, String[] selectFields) throws Exception { return this.generalDao.findAll(entityName, selectFields); } @Override public List<?> find(String entityName, String orderBy, boolean desc, Map<String, Object> andCondition) throws Exception { return this.generalDao.find(entityName, orderBy, desc, andCondition); } @Override public List<?> find(String entityName, String orderBy, boolean desc, int pageSize, int pageNo, Map<String, Object> andCondition) throws Exception { return this.generalDao.find(entityName, orderBy, desc, pageSize, pageNo, andCondition); } @Override public List<?> find(String entityName, String[] selectFields, String orderBy, boolean desc, Map<String, Object> andCondition) throws Exception { return this.generalDao.find(entityName, selectFields, orderBy, desc, andCondition); } @Override public List<?> find(String entityName, String[] selectFields, String orderBy, boolean desc, int pageSize, int pageNo, Map<String, Object> andCondition) throws Exception { return this.generalDao.find(entityName, selectFields, orderBy, desc, pageSize, pageNo, andCondition); } @Override public Pagination pageFind(String entityName, String orderBy, boolean desc, int pageSize, int pageNo, Map<String, Object> andCondition) throws Exception { return this.generalDao.pageFind(entityName, orderBy, desc, pageSize, pageNo, andCondition); } @Override public Pagination pageFind(String entityName, String[] selectFields, String orderBy, boolean desc, int pageSize, int pageNo, Map<String, Object> andCondition) throws Exception { return this.generalDao.pageFind(entityName, selectFields, orderBy, desc, pageSize, pageNo, andCondition); } @Override public Object persist(String entityName, Map<String, Object> entity) throws Exception { return this.generalDao.persist(entityName, entity); } @Override public Object persist(Object entity) throws Exception { return this.generalDao.persist(entity); } @Override public Object merge(String entityName, Object id, Map<String, Object> entity) throws Exception { return this.generalDao.merge(entityName, id, entity); } @Override public Object merge(Object entity) throws Exception { return this.generalDao.merge(entity); } @Override public void delete(String entityName, Object id) throws Exception { this.generalDao.delete(entityName, id); } @Override public void delete(String entityName, Map<String, Object> andCondition) throws Exception { this.generalDao.delete(entityName, andCondition); } @Override public void delete(Object entity) throws Exception { this.generalDao.delete(entity); } @Override public void delete(String entityName, Object[] ids) throws Exception { if (ids != null) { for (Object id : ids) { this.delete(entityName, id); } } } @Override public void deleteBySql(String sql, Object... params) throws Exception { this.generalDao.deleteBySql(sql, params); } @Override public boolean isExistField(String entityName, String fieldName) { return this.generalDao.isExistField(entityName, fieldName); } }
/* * Copyright 2014 Victor Melnik <annimon119@gmail.com>, and * individual contributors as indicated by the @authors tag. * * 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.annimon.jecp; /** * The Graphics class is the abstract base class for all graphics contexts that allow an application to draw onto components that are * realized on various devices, as well as onto off-screen images. * * @author aNNiMON */ public abstract class Graphics { /** * Draws Image with its top-left corner at (x, y). * * @param image image to be drawn * @param x x-coordinate * @param y y-coordinate */ public abstract void drawImage(Image image, int x, int y); /** * Draws a line using current color. * * @param startingX x where line starts. * @param startingY y where line starts. * @param endingX x where line ends. * @param endingY y where line ends. */ public abstract void drawLine(int startingX, int startingY, int endingX, int endingY); /** * Draws an empty rectangle using current color. * * @param x x where rectangle starts. * @param y y where rectangle starts. * @param width width of rectangle. * @param height height of rectangle. */ public abstract void drawRect(int x, int y, int width, int height); /** * Draws a string using current color and font. * * @param text string to be drawn. * @param x x where string starts. * @param y y where string starts. */ public abstract void drawString(String text, int x, int y); /** * Draws a filled rectangle using current color. * * @param x x where rectangle starts. * @param y y where rectangle starts. * @param width width of rectangle. * @param height height of rectangle. */ public abstract void fillRect(int x, int y, int width, int height); /** * Draws a filled triangle using current color. * @param x1 x position of first point * @param y1 y position of first point * @param x2 x position of second point * @param y2 y position of second point * @param x3 x position of third point * @param y3 y position of third point */ public abstract void fillTriangle(int x1, int y1, int x2, int y2, int x3, int y3); /** * Returns width of a text using current font. * * @param text text to be measured. * @return string width in pixels. */ public abstract int getTextWidth(String text); /** * Returns height of a text line using current font. * * @return line height in pixels. */ public abstract int getTextHeight(); /** * Sets current color to specified. Color is an integer formed in 0xRRGGBB way. * * @param color color to be set. */ public abstract void setColor(int color); /** * Sets current color to specified. Each integer is 0-255 component of color in its RGB-presentation. * * @param red red component of color. * @param green green component of color. * @param blue blue component of color. */ public abstract void setColor(int red, int green, int blue); /** * Draws a polygon using specified options. Its center is located at (centerX, centerY). <br/><br/> * Number of points are used to form polygon, assuming that if number of points will be close to positive infinity then polygon will * form circle. * * @param centerX * @param centerY * @param numPoints points to make polygon. * @param radius radius of polygon. * @param startAngle angle in radians to start drawing polygon. * @throws IllegalArgumentException if numPoints is less than 3. */ public final void drawPolygon(int centerX, int centerY, int numPoints, int radius, double startAngle) throws IllegalArgumentException { if (numPoints < 2) { throw new IllegalArgumentException("Number of points for polygon cant be less than 3."); } final double deltaAngle = Math.toRadians(360f / numPoints); int startX = (int) (centerX + Math.sin(startAngle) * radius); int startY = (int) (centerY + Math.cos(startAngle) * radius); for (int i = 0; i <= numPoints; i++) { final double angle = startAngle + i * deltaAngle; final int endX = (int) (centerX + Math.sin(angle) * radius); final int endY = (int) (centerY + Math.cos(angle) * radius); drawLine(startX, startY, endX, endY); startX = endX; startY = endY; } } }
package com.ccspace.facade.domain.common.enums.singleton; import com.ccspace.facade.domain.common.threadlocals.BaseLockSign; import com.ccspace.facade.domain.common.threadlocals.DemoRedisLockSign; /** * @AUTHOR CF 获取对应threadLocal的单例对象 * @DATE Created on 2018/4/4 11:30. */ public enum SingletonLocal { INSTANCE; private DemoRedisLockSign demoLocal; SingletonLocal() { demoLocal = new DemoRedisLockSign(); } /** * @description * @author CF create on 2018/11/16 11:00 */ public BaseLockSign getDemoLocal() { return demoLocal; } }
package com.socialteinc.socialate; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.*; import com.squareup.picasso.Callback; import com.squareup.picasso.Picasso; public class ViewOtherUserProfile extends AppCompatActivity{ private String TAG = ViewEntertainmentActivity.class.getSimpleName(); private ProgressDialog mProgressDialog; private Toolbar mToolbar; private ImageView getProfilePicture; private TextView getDisplayName; private TextView getFullName; private EditText getDescrip; private String ownerUID; private String commentorUID; private boolean check; private String mUsersKey; // Firebase instance variables private FirebaseAuth mFirebaseAuth; private FirebaseDatabase mFireBaseDatabase; private DatabaseReference mProfileDatabaseReference; private DatabaseReference mProfileDatabaseReference1; private boolean checker; //intentService variables private connect_receiver connect_receiver; private IntentFilter intentFilter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.view_edit_profile_activity); // get identifier key Intent intent = getIntent(); Intent intent1 = getIntent(); ownerUID = intent.getStringExtra("entertainmentUploader"); commentorUID = intent1.getStringExtra("commentUploader"); checker = intent1.getBooleanExtra("check", false); setChecker(checker); // Initialize references to views mToolbar = findViewById(R.id.ProfileToolbar2); getProfilePicture = findViewById(R.id.imageView2); getDisplayName = findViewById(R.id.displayNameTextView); getFullName = findViewById(R.id.fullNameTextView); getDescrip = findViewById(R.id.describeEditText); // Initialize Firebase components mFireBaseDatabase = FirebaseDatabase.getInstance(); mFirebaseAuth = FirebaseAuth.getInstance(); mProfileDatabaseReference = mFireBaseDatabase.getReference().child("users"); mProfileDatabaseReference1 = mFireBaseDatabase.getReference().child("users"); //mUsersKey = mFirebaseAuth. //Initialise toolbar setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle("View Profile"); // progress bar mProgressDialog = new ProgressDialog(this); if(getChecker()){ // for testing purposes if(commentorUID == null){ commentorUID = "rv32DonlxHVQz7IHcCSUyx4xRx42"; (findViewById(R.id.ViewProfileProgressBar3)).setVisibility(View.GONE); } // Display comment uploader profile details mProfileDatabaseReference1.child(commentorUID).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String user_display = (String) dataSnapshot.child("displayName").getValue(); String user_name = (String) dataSnapshot.child("name").getValue(); String user_image = (String) dataSnapshot.child("profileImage").getValue(); String user_descrip = (String) dataSnapshot.child("description").getValue(); getDisplayName.setText(user_display); getFullName.setText(user_name); getDescrip.setText(user_descrip); Picasso.with(getApplicationContext()) .load(user_image) .into(getProfilePicture, new Callback() { @Override public void onSuccess() { (findViewById(R.id.ViewProfileProgressBar3)).setVisibility(View.GONE); } @Override public void onError() { } }); } @Override public void onCancelled(DatabaseError databaseError) { } }); }else { //for testing purposes if(ownerUID == null){ ownerUID = "B7TbLOcLXggRL1TyQxrgrGlwMiO2"; (findViewById(R.id.ViewProfileProgressBar3)).setVisibility(View.GONE); } // Display entertainment uploader profile details mProfileDatabaseReference.child(ownerUID).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String user_display = (String) dataSnapshot.child("displayName").getValue(); String user_name = (String) dataSnapshot.child("name").getValue(); String user_image = (String) dataSnapshot.child("profileImage").getValue(); String user_descrip = (String) dataSnapshot.child("description").getValue(); getDisplayName.setText(user_display); getFullName.setText(user_name); getDescrip.setText(user_descrip); Picasso.with(getApplicationContext()) .load(user_image) .into(getProfilePicture, new Callback() { @Override public void onSuccess() { (findViewById(R.id.ViewProfileProgressBar3)).setVisibility(View.GONE); } @Override public void onError() { } }); } @Override public void onCancelled(DatabaseError databaseError) { } }); } //starting the intent service startIntentService(); } public void setChecker(boolean check){ this.check = check; } public boolean getChecker(){ return check; } public void startIntentService(){ //intentService intentFilter = new IntentFilter(connect_receiver.PROCESS_RESPONSE); intentFilter.addCategory(Intent.CATEGORY_DEFAULT); connect_receiver = new connect_receiver(); registerReceiver(connect_receiver,intentFilter); Intent service = new Intent(getApplicationContext(), connection_service.class); startService(service); } public class connect_receiver extends BroadcastReceiver { public static final String PROCESS_RESPONSE = "com.socialteinc.socialate.intent.action.PROCESS_RESPONSE"; boolean response = true; @Override public void onReceive(Context context, Intent intent) { boolean response1 = intent.getBooleanExtra("response",true); if((!response1) && (response1 != response)){ Snackbar sb = Snackbar.make(findViewById(R.id.other_profile_view), "Oops, No data connection?", Snackbar.LENGTH_LONG); View v = sb.getView(); v.setBackgroundColor(ContextCompat.getColor(getApplication(), R.color.colorPrimary)); sb.show(); } response = response1; } } }
package com.fz.dao; import com.fz.pojo.OrderDetail; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; /** * @author: FZ * @date: 2021/4/16 21:46 * @description: */ public interface OrderDetailDao extends JpaRepository<OrderDetail,String > { List<OrderDetail> findByOrderId(String orderId); }
package ru.r2cloud.ssdv; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.junit.Test; public class Base40Test { @Test public void test() { assertEquals("SORA", Base40.decode(0x000e7240)); } @Test public void testInvalid() { assertNull(Base40.decode(0L)); } @Test public void testInvalid2() { assertNull(Base40.decode(0xF4240000L)); } }
package cn.xeblog.xechat.domain.vo; import cn.xeblog.xechat.enums.CodeEnum; import cn.xeblog.xechat.enums.inter.Code; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Getter; import lombok.Setter; import lombok.ToString; import java.io.Serializable; /** * 响应数据结构 * * @author yanpanyi * @date 2019/3/20 */ @Getter @Setter @ToString @JsonInclude(JsonInclude.Include.NON_NULL) public class ResponseVO implements Serializable { private static final long serialVersionUID = -5327212050370584991L; private static final CodeEnum success = CodeEnum.SUCCESS; /** * 响应码 */ private int code; /** * 响应数据 */ private Object data; /** * 响应描述 */ private String desc; /** * 成功响应且带响应数据 * * @param data */ public ResponseVO(Object data) { this.code = success.getCode(); this.desc = success.getDesc(); this.data = data; } /** * 只带响应code和desc * * @param code */ public ResponseVO(Code code) { this.code = code.getCode(); this.desc = code.getDesc(); } }
/** * All rights Reserved, Designed By www.tydic.com * @Title: ItemParamServiceImpl.java * @Package com.taotao.service.impl * @Description: TODO(用一句话描述该文件做什么) * @author: axin * @date: 2018年12月11日 下午11:09:38 * @version V1.0 * @Copyright: 2018 www.hao456.top Inc. All rights reserved. */ package com.taotao.service.impl; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.taotao.common.pojo.DataGridResult; import com.taotao.common.pojo.TaotaoResult; import com.taotao.mapper.TbItemParamMapper; import com.taotao.pojo.TbItemParam; import com.taotao.pojo.TbItemParamExample; import com.taotao.service.ItemParamService; /** * @ClassName: ItemParamServiceImpl * @Description:TODO * @author: Axin * @date: 2018年12月11日 下午11:09:38 * @Copyright: 2018 www.hao456.top Inc. All rights reserved. */ @Service public class ItemParamServiceImpl implements ItemParamService{ @Autowired private TbItemParamMapper itemParamMapper; /* (non-Javadoc) * @see com.taotao.service.ItemParamService#getItemParamList(java.lang.Integer, java.lang.Integer) */ @Override public DataGridResult getItemParamList(Integer page, Integer rows) { TbItemParamExample example = new TbItemParamExample(); PageHelper.startPage(page, rows); List<TbItemParam> list = this.itemParamMapper.selectByExampleWithBLOBs(example); PageInfo<TbItemParam> pageInfo = new PageInfo<>(list); long total = pageInfo.getTotal(); DataGridResult result = new DataGridResult(); result.setTotal(total); result.setRows(list); return result; } @Override public TaotaoResult getItemParamByCid(long cid) { TbItemParamExample example = new TbItemParamExample(); example.createCriteria().andItemCatIdEqualTo(cid); List<TbItemParam> list = this.itemParamMapper.selectByExampleWithBLOBs(example); //判断是否查询到结果 if(list != null && list.size()>0){ return TaotaoResult.ok(list.get(0)); } return TaotaoResult.ok(); } /* (non-Javadoc) * @see com.taotao.service.ItemParamService#insertItemParam(com.taotao.pojo.TbItemParam) */ @Override public TaotaoResult insertItemParam(TbItemParam itemParam) { //补全pojo itemParam.setCreated(new Date()); itemParam.setUpdated(new Date()); this.itemParamMapper.insert(itemParam); return TaotaoResult.ok(); } }
/** * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.appcloud.core; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.appcloud.common.AppCloudException; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import java.util.Collection; import java.util.Hashtable; public class DomainMappingManager { private static final Log log = LogFactory.getLog(DomainMappingManager.class); // DNS records public static final String DNS_A_RECORD = "A"; public static final String DNS_CNAME_RECORD = "CNAME"; private static final String JNDI_KEY_NAMING_FACTORY_INITIAL = "java.naming.factory.initial"; private static final String JNDI_KEY_DNS_TIMEOUT = "com.sun.jndi.dns.timeout.initial"; private static final String JDNI_KEY_DNS_RETRIES = "com.sun.jndi.dns.timeout.retries"; /** * Check whether there is a CNAME entry from {@code customUrl} to {@code pointedUrl}. * * @param pointedUrl url that is pointed by the CNAME entry of {@code customUrl} * @param customUrl custom url. * @return success whether there is a CNAME entry from {@code customUrl} to {@code pointedUrl} * @throws AppCloudException */ public boolean verifyCustomUrlByCname(String pointedUrl, String customUrl) throws AppCloudException { Hashtable<String, String> env = new Hashtable<String, String>(); boolean success; // set environment configurations env.put(JNDI_KEY_NAMING_FACTORY_INITIAL, "com.sun.jndi.dns.DnsContextFactory"); env.put(JNDI_KEY_DNS_TIMEOUT, "5000"); env.put(JDNI_KEY_DNS_RETRIES, "1"); try { Multimap<String, String> resolvedHosts = resolveDNS(customUrl, env); Collection<String> resolvedCnames = resolvedHosts.get(DNS_CNAME_RECORD); if (!resolvedCnames.isEmpty() && resolvedCnames.contains(pointedUrl)) { if (log.isDebugEnabled()) { log.debug(pointedUrl + " can be reached from: " + customUrl + " via CNAME records"); } success = true; } else { if (log.isDebugEnabled()) { log.debug(pointedUrl + " cannot be reached from: " + customUrl + " via CNAME records"); } success = false; } } catch (AppCloudException e) { log.error("Error occurred while resolving dns for: " + customUrl, e); throw new AppCloudException("Error occurred while resolving dns for: " + customUrl, e); } catch (NamingException e) { // we are logging this as warn messages since this is caused, due to an user error. For example if the // user entered a rubbish custom url(Or a url which is, CNAME record is not propagated at the // time of adding the url), then url validation will fail but it is not an system error log.warn(pointedUrl + " cannot be reached from: " + customUrl + " via CNAME records. Provided custom" + " url: " + customUrl + " might not a valid url.", e); success = false; } return success; } /** * Resolve CNAME and A records for the given {@code hostname}. * * @param domain hostname to be resolved. * @param environmentConfigs environment configuration * @return {@link com.google.common.collect.Multimap} of resolved dns entries. This {@link com.google.common.collect.Multimap} will contain the resolved * "CNAME" and "A" records from the given {@code hostname} * @throws AppCloudException if error occurred while the operation */ public Multimap<String, String> resolveDNS(String domain, Hashtable<String, String> environmentConfigs) throws AppCloudException, NamingException { // result mutimap of dns records. Contains the cname and records resolved by the given hostname // ex: CNAME => foo.com,bar.com // A => 192.1.2.3 , 192.3.4.5 Multimap<String, String> dnsRecordsResult = ArrayListMultimap.create(); Attributes dnsRecords; boolean isARecordFound = false; boolean isCNAMEFound = false; try { if (log.isDebugEnabled()) { log.debug("DNS validation: resolving DNS for " + domain + " " + "(A/CNAME)"); } DirContext context = new InitialDirContext(environmentConfigs); String[] dnsRecordsToCheck = new String[] { DNS_A_RECORD, DNS_CNAME_RECORD }; dnsRecords = context.getAttributes(domain, dnsRecordsToCheck); } catch (NamingException e) { String msg = "DNS validation: DNS query failed for: " + domain + ". Error occurred while configuring " + "directory context."; log.error(msg, e); throw new AppCloudException(msg, e); } try { // looking for for A records Attribute aRecords = dnsRecords.get(DNS_A_RECORD); if (aRecords != null && aRecords.size() > 0) { // if an A record exists NamingEnumeration aRecordHosts = aRecords.getAll(); // get all resolved A entries String aHost; while (aRecordHosts.hasMore()) { isARecordFound = true; aHost = (String) aRecordHosts.next(); dnsRecordsResult.put(DNS_A_RECORD, aHost); if (log.isDebugEnabled()) { log.debug("DNS validation: A record found: " + aHost); } } } // looking for CNAME records Attribute cnameRecords = dnsRecords.get(DNS_CNAME_RECORD); if (cnameRecords != null && cnameRecords.size() > 0) { // if CNAME record exists NamingEnumeration cnameRecordHosts = cnameRecords .getAll(); // get all resolved CNAME entries for hostname String cnameHost; while (cnameRecordHosts.hasMore()) { isCNAMEFound = true; cnameHost = (String) cnameRecordHosts.next(); if (cnameHost.endsWith(".")) { // Since DNS records are end with "." we are removing it. // For example real dns entry for www.google.com is www.google.com. cnameHost = cnameHost.substring(0, cnameHost.lastIndexOf('.')); } dnsRecordsResult.put(DNS_CNAME_RECORD, cnameHost); if (log.isDebugEnabled()) { log.debug("DNS validation: recurring on CNAME record towards host " + cnameHost); } dnsRecordsResult.putAll(resolveDNS(cnameHost, environmentConfigs)); // recursively resolve cnameHost } } if (!isARecordFound && !isCNAMEFound && log.isDebugEnabled()) { log.debug("DNS validation: No CNAME or A record found for domain: '" + domain); } return dnsRecordsResult; } catch (NamingException ne) { String msg = "DNS validation: DNS query failed for: " + domain + ". Provided domain: " + domain + " might be a " + "non existing domain."; // we are logging this as warn messages since this is caused, due to an user error. For example if the // user entered a rubbish custom url(Or a url which is, CNAME record is not propagated at the // time of adding the url), then url validation will fail but it is not an system error log.warn(msg, ne); throw new NamingException(msg); } } }
package com.example.hp.iris; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.speech.tts.TextToSpeech; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.view.KeyEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.ImageView; import android.widget.Toast; import com.google.android.gms.vision.CameraSource; import com.google.android.gms.vision.face.FaceDetector; import java.io.IOException; import java.util.HashMap; /** * Created by HP on 9/6/2017. */ public class cloudcamera extends AppCompatActivity implements TextToSpeech.OnInitListener,TextToSpeech.OnUtteranceCompletedListener{ CameraSource cameraSource; SurfaceView cameraView; ImageView imageView; Bitmap bmp,bmp2; String path; public Uri imageuri; Intent intent; TextToSpeech tvvs; //BarcodeDetector barcodeDetector; SurfaceHolder surfaceHolder; byte[] bytes1; final int RequestCameraPermissionID = 1001; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.camera1); cameraView = (SurfaceView) findViewById(R.id.surface_view); imageView=(ImageView)findViewById(R.id.imageView); tvvs=new TextToSpeech(cloudcamera.this,cloudcamera.this); // surfaceHolder = cameraView.getHolder(); // surfaceHolder.addCallback(this); // surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); final FaceDetector detector = new FaceDetector.Builder(getApplicationContext()).build(); cameraSource = new CameraSource.Builder(getApplicationContext(), detector) .setFacing(CameraSource.CAMERA_FACING_BACK) .setRequestedFps(2.0f) .setAutoFocusEnabled(true) .build(); cameraView.getHolder().addCallback(new SurfaceHolder.Callback() { @Override public void surfaceCreated(SurfaceHolder surfaceHolder) { try { if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(cloudcamera.this, new String[]{Manifest.permission.CAMERA}, RequestCameraPermissionID); return; } cameraSource.start(cameraView.getHolder()); } catch (IOException e) { e.printStackTrace(); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { cameraSource.stop(); } }); cameraView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { cameraSource.takePicture(null, new CameraSource.PictureCallback() { @Override public void onPictureTaken(byte[] bytes) { detector.release(); cameraSource.release(); // bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); // //bmp.compress(Bitmap.CompressFormat.PNG,bytes); // File dir= // Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); // System.out.println("bit is "+bytes); // System.out.println("LOL 1"+dir); // File output = new File(dir, "CameraContentDemo.jpeg"); // System.out.println("LOL 1"+output); // imageUri=Uri.fromFile(output); // System.out.println("LOL 1"+imageUri); // // Toast.makeText(MainActivity.this, "Picture Captured"+imageUri, Toast.LENGTH_SHORT).show(); // // Log.d("BITMAP", bmp.getWidth() + "x" + bmp.getHeight()); // bytes1=bytes; if(!tvvs.isSpeaking()){ HashMap<String,String> params=new HashMap<String, String>(); params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"sampleText"); tvvs.speak("picture capture long press to enable vision ",TextToSpeech.QUEUE_ADD,params); } else{ tvvs.stop(); } Bitmap picture = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); // int rotation = camera1.this.getWindowManager().getDefaultDisplay().getRotation(); // if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) { // Matrix matrix = new Matrix(); // matrix.postRotate(90); // // create a rotated version and replace the original bitmap // picture = Bitmap.createBitmap(picture, 0, 0, picture.getWidth(), picture.getHeight(), matrix, true); // } MediaStore.Images.Media.insertImage(getContentResolver(), picture, "NiceCameraExample", "NiceCameraExample test"); path=MediaStore.Images.Media.insertImage(getContentResolver(), picture, "NiceCameraExample", "NiceCameraExample test"); } }); // ByteArrayOutputStream stream = new ByteArrayOutputStream(); // bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream); // bytes= stream.toByteArray(); // //cameraSource.takePicture(CameraSource.ShutterCallback, CameraSource.PictureCallback,null); } }); cameraView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { // intent=new Intent(MainActivity.this,Main2Activity.class); // Toast.makeText(MainActivity.this, "Uri"+imageUri, Toast.LENGTH_SHORT).show(); // intent.putExtra("img",bytes1); // startActivity(intent); // finish(); runOnUiThread(new Runnable() { @Override public void run() { if(!tvvs.isSpeaking()){ HashMap<String,String> params=new HashMap<String, String>(); params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"sampleText"); tvvs.speak("Vision enabled , press on screen to process",TextToSpeech.QUEUE_ADD,params); if(path!=null) { imageuri = Uri.parse(path); Intent intt = new Intent(cloudcamera.this,cloudvision.class); intt.putExtra("callerclass","cloudcamera"); intt.putExtra("uri", imageuri.toString()); Toast.makeText(cloudcamera.this, "" + imageuri, Toast.LENGTH_SHORT).show(); startActivity(intt); finish(); } } else{ tvvs.stop(); } } }); return false; } }); //detector.setProcessor(new MultiProcessor.Builder<Face>()); //detector.setProcessor(new MultiProcessor.Builder<Face>().build(new GraphicFaceTrackerFactory())); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case RequestCameraPermissionID: { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { return; } try { cameraSource.start(cameraView.getHolder()); } catch (IOException e) { e.printStackTrace(); } } } break; } } @Override protected void onDestroy() { if(tvvs!=null) { tvvs.stop(); tvvs.shutdown(); tvvs=null; } super.onDestroy(); } @Override public void onInit(int status) { } @Override public void onUtteranceCompleted(String utteranceId) { } public boolean onKeyDown(int keyCode,KeyEvent event) { if(keyCode==KeyEvent.KEYCODE_VOLUME_UP){ event.startTracking(); return true; } return super.onKeyDown(keyCode,event); } public boolean onKeyLongPress(int keycode,KeyEvent event){ if(keycode==KeyEvent.KEYCODE_VOLUME_UP){ startActivity(new Intent(cloudcamera.this,MyLocationGetter.class)); return true; } return onKeyLongPress(keycode, event); } }
package com.eigenmusik.api.sources.dropbox; import com.dropbox.core.*; import com.dropbox.core.v1.DbxClientV1; import com.dropbox.core.v1.DbxEntry; import com.dropbox.core.v2.DbxClientV2; import com.eigenmusik.api.config.EigenMusikConfiguration; import com.eigenmusik.api.sources.*; import com.eigenmusik.api.tracks.Track; import com.eigenmusik.api.tracks.TrackSource; import com.eigenmusik.api.tracks.TrackStreamUrl; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.stream.Collectors; /** * DropBox implementation of the Source abstract. */ @Service public class Dropbox extends Source { private static Logger log = Logger.getLogger(Dropbox.class); private final DbxRequestConfig config; private final DropboxUserRepository dropboxUserRepository; private final DropboxAccessTokenRepository dropboxAccessTokenRepository; private final DbxWebAuth webAuth; @Autowired public Dropbox( DropboxUserRepository dropboxUserRepository, DropboxConfiguration dropboxConfiguration, DropboxAccessTokenRepository dropboxAccessTokenRepository ) { this.dropboxUserRepository = dropboxUserRepository; this.dropboxAccessTokenRepository = dropboxAccessTokenRepository; DbxAppInfo appInfo = new DbxAppInfo(dropboxConfiguration.getClientId(), dropboxConfiguration.getClientSecret()); this.config = new DbxRequestConfig(EigenMusikConfiguration.APP_NAME, Locale.getDefault().toString()); DbxSessionStore dbxSessionStore = new DropboxUserSessionStore(); this.webAuth = new DbxWebAuth(config, appInfo, dropboxConfiguration.getRedirectUrl(), dbxSessionStore); } @Override public TrackStreamUrl getStreamUrl(Track track) { DropboxUser dropboxUser = dropboxUserRepository.findOne(track.getTrackSource().getOwner().getUri()); DropboxAccessToken accessToken = dropboxUser.getAccessToken(); DbxClientV1 dbxClient = new DbxClientV1(config, accessToken.getAccessToken()); try { return new TrackStreamUrl(dbxClient.createTemporaryDirectUrl(track.getTrackSource().getUri()).url); } catch (DbxException e) { e.printStackTrace(); } return null; } @Override public SourceAccount getAccount(SourceAccountAuthentication auth) throws SourceAuthenticationException { try { Map<String, String[]> params = auth.toParameterMap(); // Inject a fake csrf token to authenticate the client, I know this is naughty :) // TODO figure out session handling with Spring. params.put("state", new String[]{DropboxUserSessionStore.fakeCsrfToken}); DbxAuthFinish authFinish = webAuth.finish(params); DbxClientV2 dbxClient = new DbxClientV2(config, authFinish.accessToken); // Instantiate the dropbox access token. DropboxAccessToken dropboxAccessToken = new DropboxAccessToken(authFinish.accessToken); DropboxUser dropboxUser = new DropboxUser(dbxClient.users.getCurrentAccount()); dropboxUser.setAccessToken(dropboxAccessToken); // Save the token and dropbox user account. dropboxAccessTokenRepository.save(dropboxAccessToken); dropboxUserRepository.save(dropboxUser); // Instantiate and return the EigenMusik source account object. SourceAccount account = new SourceAccount(); account.setUri(dropboxUser.getId()); account.setSource(SourceType.DROPBOX); return account; } catch (DbxWebAuth.BadRequestException | DbxException | DbxWebAuth.ProviderException | DbxWebAuth.CsrfException | DbxWebAuth.NotApprovedException | DbxWebAuth.BadStateException e) { // TODO bit of a code smell catching all these messages, perhaps it's a third party inevitability. throw new SourceAuthenticationException(SourceType.DROPBOX); } } @Override public List<Track> getTracks(SourceAccount account) { DropboxUser dropboxUser = dropboxUserRepository.findOne(account.getUri()); DropboxAccessToken accessToken = dropboxUser.getAccessToken(); // Using the V1 client, couldn't get V2 to work :( // TODO further investigate DropBox V2. DbxClientV1 clientv1 = new DbxClientV1(config, accessToken.getAccessToken()); try { return clientv1.searchFileAndFolderNames("/", "mp3").stream().map(mp3 -> mapToTrack(mp3, account)).collect(Collectors.toList()); } catch (DbxException e) { log.error(e.getMessage()); } return null; } /** * Help classer to map a DropBox track entity to an EigenMusik one. * * @param dbxEntry * @param sourceAccount * @return */ private Track mapToTrack(DbxEntry dbxEntry, SourceAccount sourceAccount) { TrackSource trackSource = new TrackSource(); trackSource.setUri(dbxEntry.path); trackSource.setSource(SourceType.DROPBOX); trackSource.setOwner(sourceAccount); Track track = new Track(); track.setName(dbxEntry.path); // TODO how do we handle files without artist and track names? track.setArtist("Drive File"); track.setTrackSource(trackSource); return track; } @Override public String getName() { return "Dropbox"; } @Override public String getAuthUrl() { return webAuth.start(); } public SourceType getType() { return SourceType.DROPBOX; } }
package ntou.cs.java2021.ex6; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.NoSuchElementException; import java.util.Scanner; public class PlayerInfoReader { private Scanner input; private String fileName; // target file name public PlayerInfoReader(String fileName) { this.fileName = fileName; } public String[][] readAllPlayers() { openFile(); ArrayList<Player> list = readRecords(); String[][] listArray = convertArrayList2Array(list); closeFile(); return listArray; } public void openFile() { try { input = new Scanner(Paths.get(fileName)); //input = new Scanner(new File(fileName)); } catch (IOException ioException) { System.err.println("Error opening file. Terminating."); System.exit(1); } } // Read all records and return an ArrayList of Player Objects public ArrayList<Player> readRecords() { ArrayList<Player> list = new ArrayList<Player>(); //System.out.printf("%-12s%-12s%10s%n", "First Name", "Last Name", "Balance"); try { while (input.hasNext()) // while there is more to read { list.add(new Player(input.next(), input.next(), input.nextLong())); } } catch (NoSuchElementException elementException) { System.err.println("File improperly formed. Terminating."); } catch (IllegalStateException stateException) { System.err.println("Error reading from file. Terminating."); } return list; } // end method readRecords public String[][] convertArrayList2Array(ArrayList<Player> list) { int size = list.size(); String[][] listArray = new String[size][]; for (int i = 0; i < size; i++) { String[] record = new String[3]; Player account = list.get(i); record[0] = account.getFirstName(); record[1] = account.getLastName(); record[2] = String.format("%,d", account.getSalary()); listArray[i] = record; } return listArray; } // close file and terminate application public void closeFile() { if (input != null) input.close(); } }
public class Boss4 extends Alien { public static int speed = 1; public static final int tSpeed = 1; public int i = 0; private int mHealth; public Boss4(int x, int y, int health) { super(x, y, health); this.mHealth = health; initAlien(); } private void initAlien() { loadImage("boss4.gif"); getImageDimensions(); } public void move() { i++; if(i>=4) { x -= speed; i=0; } } }
package laptrinhjavaweb.service; import java.util.List; import laptrinhjavaweb.model.CategoryModel; public interface ICategoryService { List<CategoryModel> findAll(); CategoryModel findOne(Long id); CategoryModel findOneByCode(String code); }
package com.asterixcode.asterixfoodapi.infrastructure.repository; import com.asterixcode.asterixfoodapi.domain.model.Kitchen; import com.asterixcode.asterixfoodapi.domain.repository.KitchenRepository; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.stereotype.Component; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; import java.util.List; @Component public class KitchenRepo implements KitchenRepository { @PersistenceContext private EntityManager manager; @Override public List<Kitchen> listAll(){ return manager.createQuery("from Kitchen", Kitchen.class).getResultList(); } @Override public Kitchen getBy(Long id){ return manager.find(Kitchen.class, id); } @Transactional @Override public Kitchen add(Kitchen kitchen){ return manager.merge(kitchen); } @Transactional @Override public void remove(Long id){ Kitchen kitchen = getBy(id); if (kitchen == null){ throw new EmptyResultDataAccessException(1); // 1 => expected size; 1 = at least one kitchen (as getting by id) // it's an exception from Spring Framework, when trying to remove something and this doesn't exist. } manager.remove(kitchen); } }
package org.point85.domain.plant; import java.util.ArrayList; import java.util.List; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import org.point85.domain.dto.EnterpriseDto; @Entity @DiscriminatorValue(Enterprise.ENTER_VALUE) public class Enterprise extends PlantEntity { public static final String ENTER_VALUE = "ENTER"; public static final String DEFAULT_NAME = "Enterprise"; public static final String DEFAULT_DESC = "Default enterprise"; public Enterprise() { this(ENTER_VALUE, null); } public Enterprise(String name, String description) { super(name, description, EntityLevel.ENTERPRISE); } public Enterprise(EnterpriseDto dto) throws Exception { super(dto); setLevel(EntityLevel.ENTERPRISE); } public List<Site> getSites() { List<Site> sites = new ArrayList<>(getChildren().size()); for (PlantEntity object : getChildren()) { sites.add((Site) object); } return sites; } public void addSite(Site site) { addChild(site); } public void removeSite(Site site) { removeChild(site); } }
package com.example.asus.myapp.Student; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Base64; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.asus.myapp.R; import com.example.asus.myapp.Teacher.Add_info; import com.example.asus.myapp.Teacher.Add_students; import com.example.asus.myapp.Teacher.All_students; import com.example.asus.myapp.Teacher.Show_Message_Activity; import com.example.asus.myapp.Teacher.TeacherAreaActivity; import com.firebase.client.Firebase; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.InputStream; public class StudentActivity extends AppCompatActivity { private TextView tname; private TextView name; private TextView tintitution; private TextView institution; private TextView tyear; private TextView year; private TextView tterm; private TextView term; private TextView troll; private TextView roll; private TextView tphone; private TextView phone; private FirebaseAuth auth; private DatabaseReference mdatabase; private Firebase firebase; private Button upload,update; private String pic,user_id; private final int SELECT_PHOTO = 1; private ImageView picture; private String shpic; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_student); update = (Button) findViewById(R.id.update); upload=(Button)findViewById(R.id.up); picture=(ImageView) findViewById(R.id.pic); tname = (TextView) findViewById(R.id.tname); name = (TextView) findViewById(R.id.name); tintitution = (TextView) findViewById(R.id.tins); institution = (TextView) findViewById(R.id.institution); tterm = (TextView) findViewById(R.id.tterm); term = (TextView) findViewById(R.id.term); tyear = (TextView) findViewById(R.id.tyear); year = (TextView) findViewById(R.id.year); troll = (TextView) findViewById(R.id.troll); roll = (TextView) findViewById(R.id.roll); tphone = (TextView) findViewById(R.id.tphone); phone = (TextView) findViewById(R.id.phone); auth = FirebaseAuth.getInstance(); mdatabase = FirebaseDatabase.getInstance().getReference().child("Students"); shpic="dasj"; user_id = auth.getCurrentUser().getUid(); DatabaseReference current_user_db = mdatabase.child(user_id); upload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent photoPickerIntent = new Intent(Intent.ACTION_PICK); photoPickerIntent.setType("image/*"); startActivityForResult(photoPickerIntent, SELECT_PHOTO); } }); update.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent update = new Intent(StudentActivity.this,Update_Student_Activity.class); StudentActivity.this.startActivity(update); } }); current_user_db.child("name").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String value1 =(String) dataSnapshot.getValue(); name.setText(value1); } @Override public void onCancelled(DatabaseError databaseError) { } }); current_user_db.child("propic").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { try{ shpic =(String) dataSnapshot.getValue(); byte[] decodedString = Base64.decode(shpic, Base64.DEFAULT); Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); picture.setImageBitmap(decodedByte); } catch (Exception e) { e.printStackTrace(); } } @Override public void onCancelled(DatabaseError databaseError) { } }); current_user_db.child("institution").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String value2 =(String) dataSnapshot.getValue(); institution.setText(value2); } @Override public void onCancelled(DatabaseError databaseError) { } }); current_user_db.child("year").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String value3 =(String) dataSnapshot.getValue(); year.setText(value3); } @Override public void onCancelled(DatabaseError databaseError) { } }); current_user_db.child("term").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String value4 =(String) dataSnapshot.getValue(); term.setText(value4); } @Override public void onCancelled(DatabaseError databaseError) { } }); current_user_db.child("roll").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String value5 =(String) dataSnapshot.getValue(); roll.setText(value5); } @Override public void onCancelled(DatabaseError databaseError) { } }); current_user_db.child("phone").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String value6 =(String) dataSnapshot.getValue(); phone.setText(value6); } @Override public void onCancelled(DatabaseError databaseError) { } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { super.onActivityResult(requestCode, resultCode, imageReturnedIntent); switch (requestCode) { case SELECT_PHOTO: if (resultCode == RESULT_OK) { try { final Uri imageUri = imageReturnedIntent.getData(); final InputStream imageStream = getContentResolver().openInputStream(imageUri); final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream); ByteArrayOutputStream bos = new ByteArrayOutputStream(); selectedImage.compress(Bitmap.CompressFormat.PNG, 100, bos); if (selectedImage.getByteCount() < 1500000) { byte[] img = bos.toByteArray(); String encodedImage = Base64.encodeToString(img, Base64.DEFAULT); pic = encodedImage; byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT); Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); picture.setImageBitmap(decodedByte); DatabaseReference current_user_db = mdatabase.child(user_id); current_user_db.child("propic").setValue(pic); } else Toast.makeText(StudentActivity.this, "Please select a profile picture less than 3500000 byte" , Toast.LENGTH_LONG).show(); } catch (FileNotFoundException e) { e.printStackTrace(); } } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.add_course,menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId() == R.id.all_courses){ Intent all = new Intent(StudentActivity.this,All_classroom.class); StudentActivity.this.startActivity(all); } if(item.getItemId() == R.id.pending){ Intent notapp=new Intent(StudentActivity.this,Not_Approved_Classrooms.class); startActivity(notapp); } if(item.getItemId() == R.id.add_courses){ Intent add = new Intent(StudentActivity.this,Apply_classroom.class); StudentActivity.this.startActivity(add); } return super.onOptionsItemSelected(item); } }
package com.mycompany.time_table_management_system.db.model; // Generated Aug 2, 2015 2:18:56 PM by Hibernate Tools 3.6.0 /** * EquipmentId generated by hbm2java */ public class EquipmentId implements java.io.Serializable { private String serialNo; private String modelNo; public EquipmentId() { } public EquipmentId(String serialNo, String modelNo) { this.serialNo = serialNo; this.modelNo = modelNo; } public String getSerialNo() { return this.serialNo; } public void setSerialNo(String serialNo) { this.serialNo = serialNo; } public String getModelNo() { return this.modelNo; } public void setModelNo(String modelNo) { this.modelNo = modelNo; } public boolean equals(Object other) { if ( (this == other ) ) return true; if ( (other == null ) ) return false; if ( !(other instanceof EquipmentId) ) return false; EquipmentId castOther = ( EquipmentId ) other; return ( (this.getSerialNo()==castOther.getSerialNo()) || ( this.getSerialNo()!=null && castOther.getSerialNo()!=null && this.getSerialNo().equals(castOther.getSerialNo()) ) ) && ( (this.getModelNo()==castOther.getModelNo()) || ( this.getModelNo()!=null && castOther.getModelNo()!=null && this.getModelNo().equals(castOther.getModelNo()) ) ); } public int hashCode() { int result = 17; result = 37 * result + ( getSerialNo() == null ? 0 : this.getSerialNo().hashCode() ); result = 37 * result + ( getModelNo() == null ? 0 : this.getModelNo().hashCode() ); return result; } }
package com.st.common.util; import org.dom4j.*; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.util.*; import java.util.Map.Entry; /** * 提供Map<String,Object>转XML,XML转Map<String,Object> * * @author MOSHUNWEI * @version 5.0 * @since 2018-03-09 */ public class XmlMapUtil { private XmlMapUtil() { } /********************************** 标签格式 **********************************/ /** * 格式化xml,显示为容易看的XML格式 * * @param inputXML * @return */ public static String formatXML(String inputXML) { String requestXML = null; XMLWriter writer = null; Document document = null; try (StringWriter stringWriter = new StringWriter()) { SAXReader reader = new SAXReader(); document = reader.read(new StringReader(inputXML)); if (document != null) { OutputFormat format = new OutputFormat(" ", true);// 格式化,每一级前的空格 format.setNewLineAfterDeclaration(false); // xml声明与内容是否添加空行 format.setSuppressDeclaration(false); // 是否设置xml声明头部 format.setNewlines(true); // 设置分行 writer = new XMLWriter(stringWriter, format); writer.write(document); writer.flush(); requestXML = stringWriter.getBuffer().toString(); } return requestXML; } catch (Exception e1) { return null; } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } } } /** * 将Map转换为XML,Map可以多层转 * * @param map 需要转换的map。 * @param parentName 就是map的根key,如果map没有根key,就输入转换后的xml根节点。 * @return String-->XML */ @SuppressWarnings("unchecked") public static String mapToXml(Map<String, Object> map, String parentName) { // 获取map的key对应的value Map<String, Object> rootMap = (Map<String, Object>) map.get(parentName); if (rootMap == null) { rootMap = map; } Document doc = DocumentHelper.createDocument(); // 设置根节点 Element element = doc.addElement(parentName); iteratorXml(element, rootMap); return element.asXML(); } /** * 将Map转换为XML,Map可以多层转 * * @param map 需要转换的map。 * @param parentName 就是map的根key,如果map没有根key,就输入转换后的xml根节点。 * @return String-->XML */ @SuppressWarnings("unchecked") public static String mapToCDATEXml(Map<String, Object> map, String parentName) { // 获取map的key对应的value Map<String, Object> rootMap = (Map<String, Object>) map.get(parentName); if (rootMap == null) { rootMap = map; } Document doc = DocumentHelper.createDocument(); // 设置根节点 Element element = doc.addElement(parentName); iteratorCDATAXml(element, rootMap); return element.asXML(); } /** * 循环遍历params创建xml节点 * * @param element 根节点 * @param params map数据 * @return String-->Xml */ @SuppressWarnings("unchecked") private static void iteratorCDATAXml(Element element, Map<String, Object> params) { Set<Entry<String, Object>> entries = params.entrySet(); Element child = null; for (Entry<String, Object> entry : entries) { String key = entry.getKey(); Object value = entry.getValue(); if (value instanceof Map) { child = element.addElement(key); iteratorCDATAXml(child, (Map<String, Object>) entry.getValue()); } else if (value instanceof List) { List<Object> list = (ArrayList<Object>) value; for (int i = 0; i < list.size(); i++) { child = element.addElement(key); iteratorCDATAXml(child, (Map<String, Object>) list.get(i)); } } else { child = element.addElement(key); child.addCDATA(value.toString()); } } } /** * 循环遍历params创建xml节点 * * @param element 根节点 * @param params map数据 * @return String-->Xml */ @SuppressWarnings("unchecked") private static void iteratorXml(Element element, Map<String, Object> params) { Set<Entry<String, Object>> entries = params.entrySet(); Element child = null; for (Entry<String, Object> entry : entries) { String key = entry.getKey(); Object value = entry.getValue(); if (value instanceof Map) { child = element.addElement(key); iteratorXml(child, (Map<String, Object>) entry.getValue()); } else if (value instanceof List) { List<Object> list = (ArrayList<Object>) value; for (int i = 0; i < list.size(); i++) { child = element.addElement(key); iteratorXml(child, (Map<String, Object>) list.get(i)); } } else { child = element.addElement(key); child.addText(value.toString()); } } } /** * xml转map * * @param xml xml * @return map */ public static Map<String, Object> xmlToMap(String xml) { Document doc = null; try { doc = DocumentHelper.parseText(xml); } catch (DocumentException e) { e.printStackTrace(); return null; } Map<String, Object> map = new HashMap<>(); elementToMap(map, doc.getRootElement()); return map; } /** * 使用递归调用将多层级xml转为map * * @param map * @param element */ private static void elementToMap(Map<String, Object> map, Element element) { // 获得当前节点的子节点 List<Element> childElements = element.elements(); for (Element childElement : childElements) { // 判断有没有子元素 if (!childElement.elements().isEmpty()) { Map<String, Object> childMap = new HashMap<>(); elementToMap(childMap, childElement); Object o = map.get(childElement.getName()); if (o != null) { if (o instanceof List) { ((List<Map>) o).add(childMap); } else { List list = new ArrayList<Map>(); list.add(childMap); list.add(o); map.put(childElement.getName(), list); } } else { map.put(childElement.getName(), childMap); } } else { map.put(childElement.getName(), childElement.getText()); } } } /********************************** 属性格式 **********************************/ /** * element属性转Map * * @param xml * @return */ public static Map<String, Object> xmlPropToMap(String xml) { try { Document document = DocumentHelper.parseText(xml); document.setXMLEncoding("UTF-8"); Element rootElement = document.getRootElement(); HashMap<String, Object> xmlPropToMap = new HashMap<>(); elementPropToMap(rootElement, xmlPropToMap); return xmlPropToMap; } catch (DocumentException e) { return null; } } /** * element属性转Map 递归调用 * * @param element 元素 * @param propMap 存放结果的map */ @SuppressWarnings("unchecked") private static void elementPropToMap(Element element, Map<String, Object> propMap) { List<Attribute> attributes = element.attributes(); for (Attribute attribute : attributes) { propMap.put(attribute.getName(), attribute.getValue()); } List<Element> elements = element.elements(); for (Element child : elements) { String name = child.getName(); Object object = propMap.get(name); HashMap<String, Object> childMap = new HashMap<>(); elementPropToMap(child, childMap); if (object != null) { if (object instanceof List) { ((ArrayList<Map<String, Object>>) object).add(childMap); } else { ArrayList<Map<String, Object>> arrayList = new ArrayList<>(); arrayList.add((Map<String, Object>) object); arrayList.add(childMap); propMap.put(name, arrayList); } } else { propMap.put(name, childMap); } } } /** * map转element属性 * * @param map 参数map * @param rootName 根节点名称 * @return xml字符串 */ public static String mapToXmlProp(Map<String, Object> map, String rootName) { // 新建一个document 设置输出字符集 Document document = DocumentHelper.createDocument(); document.setXMLEncoding("UTF-8"); Element rootElement = document.addElement(rootName); mapToElementProp(map, rootElement); return rootElement.asXML(); } /** * map转属性element属性 递归调用 * * @param map 参数map * @param element 元素 */ @SuppressWarnings("unchecked") private static void mapToElementProp(Map<String, Object> map, Element element) { Set<Entry<String, Object>> entrySet = map.entrySet(); for (Entry<String, Object> entry : entrySet) { Object value = entry.getValue(); if (value instanceof String) { element.addAttribute(entry.getKey(), value.toString()); } if (value instanceof List<?>) { for (Map<String, Object> valueMap : (List<Map<String, Object>>) value) { Element ele = element.addElement(entry.getKey()); ele.addText(""); mapToElementProp(valueMap, ele); } } if (value instanceof Map<?, ?>) { Element ele = element.addElement(entry.getKey()); ele.addText(""); mapToElementProp((Map<String, Object>) entry.getValue(), ele); } } } public static void main(String[] args) { String aString = "<persons id=\"1\">\r\n" + " <person id=\"1\" sex=\"女\">\r\n" + " <name>person1</name>\r\n" + " </person>\r\n" + " <person id=\"2\" sex=\"女\">\r\n" + " <name>person2</name>\r\n" + " </person>\r\n" + " <person id=\"3\" sex=\"女\">\r\n" + " <name>person3</name>\r\n" + " </person>\r\n" + " <person id=\"4\" sex=\"女\">\r\n" + " <name>person4</name>\r\n" + " </person>\r\n" + " <person id=\"5\" sex=\"女\">\r\n" + " <name>person5</name>\r\n" + " </person>\r\n" + "</persons>"; Map<String, Object> xmlPropToMap = xmlPropToMap(aString); System.out.println(xmlPropToMap); String mapToXmlProp = mapToXmlProp(xmlPropToMap, "persons"); System.out.println(mapToXmlProp); } }
package com.example.reminiscence; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class GalleryActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gallery); } public void onSeeGalleryClick(View view){ Intent intent = new Intent(this, GalleryShowActivity.class); startActivity(intent); } public void onAddPhotoClick(View view){ Intent intent = new Intent(this, GalleryAddPhotoActivity.class); startActivity(intent); } }
package net.depaoli.googlebook.application; import android.app.Application; import com.squareup.leakcanary.LeakCanary; import net.depaoli.googlebook.application.dagger.AppComponent; import net.depaoli.googlebook.application.dagger.AppModule; import net.depaoli.googlebook.application.dagger.DaggerAppComponent; public class GoogleBookApplication extends Application { private AppComponent mAppComponent; public GoogleBookApplication() { } @Override public void onCreate() { super.onCreate(); if (LeakCanary.isInAnalyzerProcess(this)) { // This process is dedicated to LeakCanary for heap analysis. // You should not init your app in this process. return; } LeakCanary.install(this); resolveDependency(); } public AppComponent getAppComponent() { return mAppComponent; } protected void resolveDependency() { mAppComponent = DaggerAppComponent.builder() .appModule(new AppModule(this.getApplicationContext())) .build(); } }
package br.edu.unoescsmo.aluga.repository; import org.springframework.data.jpa.repository.JpaRepository; import br.edu.unoescsmo.aluga.model.Cliente; public interface ClienteRepository extends JpaRepository<Cliente, Long> { }
package com.gsitm.auth.service; import com.gsitm.auth.dao.AuthDao; import com.gsitm.reserv.vo.EmpVO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; /** * @author : 이창주 * @programName : AuthService.java * @date : 2018-06-16 * @function : 권한 관리 기능 service * <p> * [이름] [수정일] [내용] * ---------------------------------------------------------- * 이창주 2018-06-16 권한 관리 기능 완료 * 허빛찬샘 2018-06-18 예산 금액 수정 기능 */ @Service public class AuthService { private static final Logger logger = LoggerFactory.getLogger(AuthService.class); @Resource(name = "authDao") private AuthDao authDao; /** * @methodName : getAuthList * @author : 이창주 * @date : 2018-06-16 * @function : 권한 조회 * ${tags} */ public List<EmpVO> getAuthList() { List<EmpVO> resultList = authDao.getAuthList(); return resultList; } /** * @methodName : getEmp * @author : 이창주 * @date : 2018-06-16 * @function : 사원목록 가져오기 * ${tags} */ public List<EmpVO> getEmp() { List<EmpVO> resultList = authDao.getEmp(); return resultList; } /** * @methodName : modifyAuth * @author : 이창주 * @date : 2018-06-16 * @function : 권한 수정 * ${tags} */ public void modifyAuth(EmpVO empVO) { authDao.modifyAuth(empVO); } /** * @methodName : removeAuth * @author : 이창주 * @date : 2018-06-16 * @function : 권한 삭제 * ${tags} */ public void removeAuth(EmpVO empVO) { authDao.removeAuth(empVO); } /** * @methodName : budgetMod * @author : 허빛찬샘 * @date : 2018. 6. 18. * @function : 예산 정보 수정 * @param budget * @return */ public int budgetMod(int budget) { return authDao.budgetMod(budget); } /** * @methodName : getBudget * @author : 허빛찬샘 * @date : 2018. 6. 19. * @function : 예산 정보 조회 * @return */ public int getBudget() { return authDao.getBudget(); } }
package com.zjf.myself.codebase.fragment; import android.text.Html; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; import com.zjf.myself.codebase.R; import com.zjf.myself.codebase.activity.LoginAct; import com.zjf.myself.codebase.application.AppAccount; import com.zjf.myself.codebase.application.AppConstants; import com.zjf.myself.codebase.application.UserDataManager; import com.zjf.myself.codebase.model.UserData; import com.zjf.myself.codebase.util.StringUtil; import com.zjf.myself.codebase.util.ViewUtils; import static com.zjf.myself.codebase.application.Config.getConfig; /** * Created by Administrator on 2016/12/3. */ public class RegestFragment extends BaseFragment implements View.OnClickListener { private EditText eTxtUserName,eTxtPassWd,eTxtVerificationCode,eTxtConfirnPassWd; private View btnRegest; private CheckBox chkAgreement; private String teleCodeNum; private TextView txtAgreement; private UserDataManager mUserDataManager; private String phoneNo,passWd,confirnPassWd,verificationCode; public static RegestFragment newInstance() { RegestFragment f = new RegestFragment(); return f; } @Override protected void initView() { eTxtUserName= (EditText) findViewById(R.id.eTxtPhoneNo); eTxtVerificationCode= (EditText) findViewById(R.id.eTxtVerificationCode); eTxtPassWd= (EditText) findViewById(R.id.eTxtPassWd); eTxtConfirnPassWd= (EditText) findViewById(R.id.eTxtConfirnPassWd); chkAgreement = (CheckBox) findViewById(R.id.chkAgreement); btnRegest=findViewById(R.id.btnRegest); btnRegest.setOnClickListener(this); txtAgreement = (TextView)findViewById(R.id.txtAgreement); txtAgreement.setText(Html.fromHtml("<font color=\'#00923f\'><U>用户协议</U></font>")); txtAgreement.setOnClickListener(this); setRegestEnable(true); if (mUserDataManager == null) { mUserDataManager = new UserDataManager(getActivity()); mUserDataManager.openDataBase(); //建立本地数据库 } } private void setRegestEnable(boolean enable){ if(enable){ btnRegest.setBackgroundResource(R.drawable.icon_button); }else { btnRegest.setBackgroundResource(R.drawable.button_dis); } btnRegest.setEnabled(enable); } private boolean phoneNoIsReady(){ phoneNo=eTxtUserName.getText().toString().trim(); if(StringUtil.isNull(phoneNo)){ ViewUtils.showToast("手机号码不能为空!"); return false; }else if(!StringUtil.isMobileNO(phoneNo)){ ViewUtils.showToast("请输入正确的手机号码!"); return false; } return true; } private boolean regestDataIsReady(){ passWd=eTxtPassWd.getText().toString().trim(); verificationCode=eTxtVerificationCode.getText().toString().trim(); confirnPassWd=eTxtConfirnPassWd.getText().toString().trim(); if(!phoneNoIsReady()){ return false; }else if(StringUtil.isNull(verificationCode)){ ViewUtils.showToast("邀请码不能为空"); return false; }else if(StringUtil.isNull(passWd)){ ViewUtils.showToast("密码不能为空"); return false; }else if((eTxtPassWd.getText().toString().trim().length()< 6)){ ViewUtils.showToast("密码格式有误,请输入6~16位密码!"); return false; }else if(StringUtil.isNull(confirnPassWd)){ ViewUtils.showToast("请输入确认密码"); return false; }else if (!passWd.equals(confirnPassWd)){ ViewUtils.showToast("两次输入密码不一致"); return false; }else if(!chkAgreement.isChecked()){ ViewUtils.showToast("请阅读并同意用户协议"); return false; } return true; } private void startRegester() { if (!regestDataIsReady()) return; String userName = eTxtUserName.getText().toString().trim(); String InvitationCode = eTxtVerificationCode.getText().toString().trim(); String userPwd = eTxtPassWd.getText().toString().trim(); //检查用户是否存在 int count=mUserDataManager.findUserByName(userName); //用户已经存在时返回,给出提示文字 if(count>0){ ViewUtils.showToast("用户名已存在,请重新输入"); return ; } if (InvitationCode.equals(AppConstants.INVITATION_CODE)){ UserData mUser = new UserData(userName, userPwd); mUserDataManager.openDataBase(); long flag = mUserDataManager.insertUserData(mUser); //新建用户信息 if (flag == -1) { ViewUtils.showToast("注册用户失败,请重新尝试!"); }else{ ViewUtils.showToast("注册成功!"); ((LoginAct)getActivity()).fragmentContorler.showTab(0); } }else{ ViewUtils.showToast("邀请码错误,请重新输入"); } } @Override public void onResume() { super.onResume(); ((LoginAct)getActivity()).setTitle("注册"); ((LoginAct)getActivity()).hideBtnBack(false); eTxtUserName.setText(""); eTxtVerificationCode.setText(""); eTxtPassWd.setText(""); eTxtConfirnPassWd.setText(""); } @Override protected int layoutId() { return R.layout.fragment_regest; } @Override public void onClick(View v) { switch (v.getId()){ case R.id.btnRegest: startRegester(); break; case R.id.txtAgreement: // WebviewAct.start("用户协议", "http://laole.yinengsz.com/agreement.php", getActivity()); break; default: break; } } }
package com.esum.framework.jdbc; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import java.util.Map; /** * Jdbc Operations. */ public interface JdbcOperations { //------------------------------------------------------------------------- // execute methods //------------------------------------------------------------------------- void execute(String query) throws SQLException; <T> T execute(PreparedStatementCreator psc, PreparedStatementCallback<T> action) throws SQLException; <T> T execute(StatementCallback<T> action) throws SQLException; <T> T execute(Connection con, StatementCallback<T> action) throws SQLException; <T> T execute(String sql, PreparedStatementCallback<T> action) throws SQLException; <T> T execute(Connection con, String sql, PreparedStatementCallback<T> action) throws SQLException; <T> T execute(String callString, CallableStatementCallback<T> action) throws SQLException; <T> T execute(Connection con, String callString, CallableStatementCallback<T> action) throws SQLException; //------------------------------------------------------------------------- // update methods //------------------------------------------------------------------------- int update(final String query) throws SQLException; int update(Connection con, final String query) throws SQLException; int update(Connection con, final String query, SqlParameterValues params) throws SQLException; //------------------------------------------------------------------------- // select methods //------------------------------------------------------------------------- <T> T select(final String sql, final ResultSetExtractor<T> rse) throws SQLException; <T> T select(Connection con, final String sql, final ResultSetExtractor<T> rse) throws SQLException; <T> List<T> selectList(String sql, RowMapper<T> rowMapper) throws SQLException; <T> List<T> selectList(String sql, SqlParameterValues params, RowMapper<T> rowMapper) throws SQLException; <T> List<T> selectList(Connection con, String sql, RowMapper<T> rowMapper) throws SQLException; <T> List<T> selectList(Connection con, String sql, SqlParameterValues params, RowMapper<T> rowMapper) throws SQLException; <T> T selectOne(final String sql, final RowMapper<T> rowMapper) throws SQLException; <T> T selectOne(Connection con, final String sql, final RowMapper<T> rowMapper) throws SQLException; <T> T selectOne(Connection con, String sql, SqlParameterValues params, RowMapper<T> rowMapper) throws SQLException; Map<String, Object> selectOne(String sql, SqlParameterValues params) throws SQLException; Map<String, Object> selectOne(Connection con, String sql, SqlParameterValues params) throws SQLException; //------------------------------------------------------------------------- // batchUpdate methods //------------------------------------------------------------------------- int[] batchUpdate(String sql, List<SqlParameterValues> paramList) throws SQLException; int[] batchUpdate(Connection con, String sql, List<SqlParameterValues> paramList) throws SQLException; //------------------------------------------------------------------------- // call methods //------------------------------------------------------------------------- Map<String, Object> call(String callString, List<SqlParameterValue> declaredParameters) throws SQLException; Map<String, Object> call(Connection con, String callString, List<SqlParameterValue> declaredParameters) throws SQLException; }
package clone.timesheet; import java.time.LocalDate; import java.time.LocalDateTime; public class TimeSheetItem { private String employee; private String project; private LocalDateTime from; private LocalDateTime to; public TimeSheetItem(String employee, String project, LocalDateTime from, LocalDateTime to) { this.employee = employee; this.project = project; this.from = from; this.to = to; } public TimeSheetItem(TimeSheetItem timeSheetItem) { this(timeSheetItem.employee, timeSheetItem.project, timeSheetItem.from, timeSheetItem.to); // this.employee = employee; // this.project = project; // this.from = from; // this.to = to; } public String getEmployee() { return employee; } public String getProject() { return project; } public LocalDateTime getFrom() { return from; } public LocalDateTime getTo() { return to; } public static TimeSheetItem withDifferentDay(TimeSheetItem timeSheetItem, LocalDate date) { TimeSheetItem retVal = new TimeSheetItem(timeSheetItem); retVal.from = LocalDateTime.of(date.getYear(), date.getMonth(), date.getDayOfMonth(), retVal.from.getHour(), retVal.from.getMinute(), retVal.from.getSecond()); retVal.to = LocalDateTime.of(date.getYear(), date.getMonth(), date.getDayOfMonth(), retVal.to.getHour(), retVal.to.getMinute(), retVal.to.getSecond()); return retVal; } }
package com.mc.library.domain; import com.google.gson.annotations.SerializedName; /** * Created by dinghui on 2016/10/27. */ public class Result<T> { @SerializedName("code") public int code; @SerializedName("message") public String msg; @SerializedName("result") public T data; @Override public String toString() { return "Result{" + "code=" + code + ", msg='" + msg + '\'' + ", data=" + data + '}'; } }
import java.util.ArrayList; /** * Eine Klasse zur Verwaltung von Audiotracks. * Die einzelnen Tracks können abgespielt werden. * * @author David J. Barnes und Michael Kölling. * @version 31.07.2011 */ public class MusikSammlung { // Eine ArrayList, in der die Musik-Tracks gespeichert werden können. private ArrayList<Track> tracks; // Ein Player zum Abspielen der Musik-Tracks. private MusikPlayer player; // Ein Reader, der Musikdateien lesen und als Tracks laden kann private TrackReader reader; /** * Erzeuge eine MusikSammlung */ public MusikSammlung() { tracks = new ArrayList<Track>(); player = new MusikPlayer(); reader = new TrackReader(); liesBibliothek("audio"); System.out.println("Musikbibliothek wurde geladen. " + gibAnzahlTracks() + " Tracks."); System.out.println(); } /** * Füge der Sammlung eine Track-Datei hinzu. * @param dateiname der Dateiname des hinzuzufügenden Tracks. */ public void dateiHinzufuegen(String dateiname) { tracks.add(new Track(dateiname)); } /** * Füge der Sammlung einen Track hinzu. * @param dateiname der hinzuzufügende Track. */ public void trackHinzufuegen(Track track) { tracks.add(track); } /** * Spiele einen Track aus der Sammlung. * @param index der Index des abzuspielenden Tracks. */ public void spieleTrack(int index) { if(gueltigerIndex(index)) { Track track = tracks.get(index); player.starteAbspielen(track.gibDateiname()); System.out.println("Sie hoeren gerade: " + track.gibInterpret() + " - " + track.gibTitel()); } } /** * Liefere die Anzahl der Tracks in dieser Sammlung. * @return die Anzahl der tracks in dieser Sammlung. */ public int gibAnzahlTracks() { return tracks.size(); } /** * Gib einen Track aus der Sammlung auf die Konsole aus. * @param index der Index des auszugebenden Tracks. */ public void trackAusgeben(int index) { System.out.print("Track " + index + ": "); Track track = tracks.get(index); System.out.println(track.gibDetails()); } /** * Gib eine Liste aller Tracks in der Sammlung aus. */ public void alleTracksAusgeben() { System.out.println("Track-Liste: "); for(Track track : tracks) { System.out.println(track.gibDetails()); } System.out.println(); } /** * Liste alle Tracks zu einem gegebenen Interpreten. * @param interpret der Name des Interpreten. */ public void bestimmteTracksAusgeben(String interpret) { for(Track track : tracks) { if(track.gibInterpret().contains(interpret)) { System.out.println(track.gibDetails()); } } } /** * Entferne einen Track aus der Sammlung. * @param index der Index, des zu entfernenden Tracks. */ public void entferneTrack(int index) { if(gueltigerIndex(index)) { tracks.remove(index); } } /** * Spiele den ersten Track aus der Sammlung, falls vorhanden. */ public void spieleErsten() { if(tracks.size() > 0) { player.starteAbspielen(tracks.get(0).gibDateiname()); } } /** * Stoppt den Player. */ public void beendeAbspielen() { player.stop(); } /** * Stelle fest, ob der gegebene Index für die Sammlung gültig ist. * Falls nicht, wird eine Fehlermeldung ausgegeben. * @param index der zu prüfende Index. * @return true, wenn der Index gültig ist, andernfalls false. */ private boolean gueltigerIndex(int index) { // Der R�ckgabewert. // Setze den R�ckgabewert abhängig davon, ob der Index gültig ist oder nicht. boolean gueltig; if(index < 0) { System.out.println("Indizes koennen nicht negativ sein: " + index); gueltig = false; } else if(index >= tracks.size()) { System.out.println("Index ist zu gross: " + index); gueltig = false; } else { gueltig = true; } return gueltig; } private void liesBibliothek(String ordnerName) { ArrayList<Track> tempTracks = reader.liesTracks(ordnerName, ".mp3"); // Alle Tracks in die Sammlung einfügen. for(Track track : tempTracks) { trackHinzufuegen(track); } } }
package com.yuneec.widget; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.ViewConfiguration; import android.view.ViewParent; import android.widget.SeekBar; public class VerticalSeekBar extends SeekBar { private boolean isInScrollingContainer = false; private boolean mIsDragging; private int mScaledTouchSlop; private float mTouchDownY; float mTouchProgressOffset; public boolean isInScrollingContainer() { return this.isInScrollingContainer; } public void setInScrollingContainer(boolean isInScrollingContainer) { this.isInScrollingContainer = isInScrollingContainer; } public VerticalSeekBar(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); this.mScaledTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); } public VerticalSeekBar(Context context, AttributeSet attrs) { super(context, attrs); } public VerticalSeekBar(Context context) { super(context); } protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(h, w, oldh, oldw); } protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(heightMeasureSpec, widthMeasureSpec); setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth()); } protected synchronized void onDraw(Canvas canvas) { canvas.rotate(-90.0f); canvas.translate((float) (-getHeight()), 0.0f); super.onDraw(canvas); } public boolean onTouchEvent(MotionEvent event) { if (!isEnabled()) { return false; } switch (event.getAction()) { case 0: if (!isInScrollingContainer()) { setPressed(true); invalidate(); onStartTrackingTouch(); trackTouchEvent(event); attemptClaimDrag(); onSizeChanged(getWidth(), getHeight(), 0, 0); break; } this.mTouchDownY = event.getY(); break; case 1: if (this.mIsDragging) { trackTouchEvent(event); onStopTrackingTouch(); setPressed(false); } else { onStartTrackingTouch(); trackTouchEvent(event); onStopTrackingTouch(); } onSizeChanged(getWidth(), getHeight(), 0, 0); invalidate(); break; case 2: if (this.mIsDragging) { trackTouchEvent(event); } else if (Math.abs(event.getY() - this.mTouchDownY) > ((float) this.mScaledTouchSlop)) { setPressed(true); invalidate(); onStartTrackingTouch(); trackTouchEvent(event); attemptClaimDrag(); } onSizeChanged(getWidth(), getHeight(), 0, 0); break; } return true; } private void trackTouchEvent(MotionEvent event) { float scale; int height = getHeight(); int top = getPaddingTop(); int bottom = getPaddingBottom(); int available = (height - top) - bottom; int y = (int) event.getY(); float progress = 0.0f; if (y > height - bottom) { scale = 0.0f; } else if (y < top) { scale = 1.0f; } else { scale = ((float) ((available - y) + top)) / ((float) available); progress = this.mTouchProgressOffset; } setProgress((int) (progress + (((float) getMax()) * scale))); } void onStartTrackingTouch() { this.mIsDragging = true; } void onStopTrackingTouch() { this.mIsDragging = false; } private void attemptClaimDrag() { ViewParent p = getParent(); if (p != null) { p.requestDisallowInterceptTouchEvent(true); } } public synchronized void setProgress(int progress) { super.setProgress(progress); onSizeChanged(getWidth(), getHeight(), 0, 0); } }
/* * Copyright (c) 2003 - 2016 Tyro Payments Limited. * Lv1, 155 Clarence St, Sydney NSW 2000. * All rights reserved. */ package com.github.rogeralmeida.faulttolerance.yelp.model; import lombok.Data; @Data public class Business { private Integer rating; private String price; private String phone; private String id; private Integer review_count; private String name; private String url; private String image_url; }
package coinpurse; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import coinpurse.strategy.GreedyWithdraw; import coinpurse.strategy.RecursiveWithdraw; import coinpurse.strategy.WithdrawStrategy; /** * A purse contains coins and banknote. * You can insert money, withdraw money, check the balance, * and check if the purse is full. * * @author Tanasorn Tritawisup */ public class Purse { /** Collection of objects in the purse. */ private static List<Valuable> money; /** Capacity is maximum number of items the purse can hold. * Capacity is set when the purse is created and cannot be changed. */ private final int capacity; private Comparator<Valuable> comparator = new ValueComparator(); /**Type of WithdrawStrategy*/ private WithdrawStrategy strategy; /** * Create a purse with a specified capacity. * @param capacity is maximum number of money you can put in purse. */ public Purse( int capacity ) { this.capacity = capacity; money = new ArrayList<Valuable>(capacity); strategy = new GreedyWithdraw(); } /** * Count and return the number of coins in the purse. * This is the number of coins, not their value. * @return the number of coins in the purse. */ public int count() { return money.size(); } /** * Get the total value of all items in the purse. * @return the total value of items in the purse. */ public static double getBalance() { double totalValue = 0.0; for(Valuable v : money) totalValue += v.getValue(); return totalValue; } /** * Return the capacity of the purse. * @return the capacity. */ public int getCapacity() { return capacity; } /** * Test whether the purse is full. * The purse is full if number of items in purse equals * or greater than the purse capacity. * @return true if purse is full. */ public boolean isFull() { return count() >= capacity; } /** * Insert a value into the purse. * The value is only inserted if the purse has space for it * and the value is positive. * @param value is a Valuable interface to insert into purse * @return true if value inserted, false if can't insert */ public boolean insert( Valuable value ) { if(isFull() || value.getValue() <= 0) return false; else { money.add(value); return true; } } /** * Withdraw the amount, using only items that have * the same currency as the parameter(amount). * amount must not be null and amount.getValue() > 0. * @param amount * @return array of Valuable class for money withdrawn, * or null if cannot withdraw requested amount. */ public Valuable[] withdraw(Valuable amount ) { setWithdrawStrategy(new RecursiveWithdraw()); List<Valuable> withdraw = strategy.withdraw(amount, money); if (withdraw == null) return null; for(Valuable v : withdraw) money.remove(v); Valuable[] withdrawArray = new Valuable[withdraw.size()]; return withdraw.toArray(withdrawArray); } /** * Withdraw the requested amount of money. * Return an array of Valuable withdrawn from purse, * or return null if cannot withdraw the amount requested. * @param amount is the amount to withdraw * @return array of Valuable class for money withdrawn, * or null if cannot withdraw requested amount. */ public Valuable[] withdraw( double amount ) { Money amountM = new Money(amount, "Baht"); return withdraw(amountM); } /** * toString returns a string description of the purse contents. * It can return whatever is a useful description. */ @Override public String toString() { return money.toString(); } /** * Set the withdraw strategy. * @param strategy is a withdraw strategy that you want to set. */ public void setWithdrawStrategy(WithdrawStrategy strategy){ this.strategy = strategy; } }
package com.alex.pets; public interface Alive { void kill(); boolean isAlive(); }
package com.alibaba.druid.pool.ha.node; import org.junit.Test; import java.util.List; import java.util.Properties; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class NodeEventTest { @Test public void testGetEventListFromProperties_emptyProperties() { Properties p1 = new Properties(); Properties p2 = new Properties(); List<NodeEvent> list = NodeEvent.getEventsByDiffProperties(p1, p2); assertTrue(list.isEmpty()); p1.setProperty("foo.url", "foo_url"); p1.setProperty("foo.username", "foo_username"); p1.setProperty("foo.password", "foo_password"); list = NodeEvent.getEventsByDiffProperties(p1, p2); assertEquals(1, list.size()); NodeEvent event = list.get(0); assertEquals(NodeEventTypeEnum.DELETE, event.getType()); assertEquals("foo", event.getNodeName()); assertEquals("foo_url", event.getUrl()); assertEquals("foo_username", event.getUsername()); assertEquals("foo_password", event.getPassword()); list = NodeEvent.getEventsByDiffProperties(p2, p1); assertEquals(1, list.size()); event = list.get(0); assertEquals(NodeEventTypeEnum.ADD, event.getType()); assertEquals("foo", event.getNodeName()); assertEquals("foo_url", event.getUrl()); assertEquals("foo_username", event.getUsername()); assertEquals("foo_password", event.getPassword()); } }
package coin.coininventory.entity; import javax.persistence.*; @Entity @Table(name = "coinlocation") public class CoinLocation { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long coinlocationid; @ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.EAGER) @JoinColumn(name = "userfk") private User user; @ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.EAGER) @JoinColumn(name = "locationfk") private Location location; @ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.EAGER) @JoinColumn(name = "sublocationfk") private SubLocation subLocation; public CoinLocation() { } public long getCoinlocationid() { return coinlocationid; } public void setCoinlocationid(long coinlocationid) { this.coinlocationid = coinlocationid; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } public SubLocation getSubLocation() { return subLocation; } public void setSubLocation(SubLocation subLocation) { this.subLocation = subLocation; } }
import java.io.BufferedReader; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; public class BlockHandler { private BlockChain blockChain = BlockChain.getInstance(); public void createTransaction(BufferedReader input) throws IOException { String from, to; double amount; System.out.println("Transfer Money from : "); from = input.readLine(); System.out.println("Transfer Money To : "); to = input.readLine(); System.out.println("Transfer amount : "); amount = Double.parseDouble(input.readLine()); Transaction transaction = new Transaction(); transaction.setFrom(from); transaction.setTo(to); transaction.setAmount(amount); createBlock(transaction); } /** * Create Block * @param transaction */ public void createBlock(Transaction transaction) { Block block=new Block(blockChain.getPreviousBlockId(),transaction,getDate(),"0"); System.out.println("Adding Block to Block Chain"); blockChain.addBlock(block); System.out.println("Block added"); } public String getDate(){ Date dateNow = new Date( ); SimpleDateFormat format = new SimpleDateFormat ("E dd.MM.yyyy @ hh:mm:ss a Z"); return format.format(dateNow); } }
package model_checker; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collection; import java.util.EmptyStackException; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Scanner; import java.util.Set; import java.util.Stack; import java.io.DataInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; public class PropertyEvaluation { public HashMap<String, Set<StateNode>> atomicPropertyStateSet = new HashMap<String, Set<StateNode>>(); class WrongFormatException extends Exception { } class AtomicPropertyNotExistException extends Exception{ } checker c = new checker(); //constructor public PropertyEvaluation(HashMap<String, Set<StateNode>> atomicPropertyStateSet){ this.atomicPropertyStateSet = atomicPropertyStateSet; } // method to convert the property string to a parse tree public TreeNode parse(String property) throws WrongFormatException { String s = removeSpace(property); Stack<TreeNode> values = new Stack<TreeNode>(); Stack<Character> operators = new Stack<Character>(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { Character c = s.charAt(i); if(Character.isLowerCase(c)){ TreeNode tree = new TreeNode(true, Character.toString(c), null); pushValue(tree, values, operators); }else if(Character.isDigit(c)){ sb.append(c); continue; }else { if(sb.length() != 0){ TreeNode tree = new TreeNode(true, sb.toString(), null); pushValue(tree, values, operators); sb = new StringBuilder(); } if (c != ')') // when char is not ')', put it into stack operators operators.push(c); else { // when char is ')', deal with operations until “(” || “EU” || "AU" while (true) { String operator = popOperator(operators); buildTree(operator, values, operators); if (operator.equals("(") || operator.equals("EU") || operator.equals("AU")) break; } try { TreeNode temp = values.pop(); pushValue(temp, values, operators); } catch (EmptyStackException e) { throw new WrongFormatException(); } } } } if(sb.length() != 0){ TreeNode tree = new TreeNode(true, sb.toString(), null); pushValue(tree, values, operators); sb = new StringBuilder(); } while (operators.size() != 0) { String operator = popOperator(operators);// ?????? buildTree(operator, values, operators); } if (values.size() != 1){ throw new WrongFormatException(); } return values.pop(); } // method to evaluate the parse tree public Set<StateNode> evaluate(Set<StateNode> allinput, TreeNode tree) throws AtomicPropertyNotExistException{ Set<StateNode> result = new HashSet<StateNode>(); if (tree.isAtomicProperty) { if(atomicPropertyStateSet.containsKey(tree.atomicProperty)) return atomicPropertyStateSet.get(tree.atomicProperty); else throw new AtomicPropertyNotExistException(); } if (tree.operator.equals("EX")) { result = c.nextChecker(allinput, evaluate(allinput, tree.right)); } if (tree.operator.equals("EU")) { result = c.untilChecker(evaluate(allinput, tree.left), evaluate(allinput, tree.right)); } if (tree.operator.equals("EF")) { result = c.finallyChecker(allinput, evaluate(allinput,tree.right)); } if (tree.operator.equals("EG")) { result = c.alwaysChecker(allinput, evaluate(allinput,tree.right)); } if (tree.operator.equals("AX")) { result = c.notOperator( allinput, c.nextChecker(allinput, c.notOperator(allinput, evaluate(allinput, tree.right)))); } if (tree.operator.equals("AU")) { Set<StateNode> temp1 = c.andOperator(c.notOperator(allinput, evaluate(allinput, tree.left)), c.notOperator(allinput, evaluate(allinput, tree.right)));//(!p & !q) Set<StateNode> temp2 = c.notOperator(allinput, c.untilChecker(c.notOperator(allinput, evaluate(allinput, tree.right)), temp1 )); //!E(!q U temp1); Set<StateNode> temp3 = c.notOperator(allinput, c.alwaysChecker(allinput, c.notOperator(allinput, evaluate(allinput, tree.right))));//!EG !q result = c.andOperator(temp2, temp3); } if (tree.operator.equals("AF")) { //equivalent to !EG !p result = c.notOperator(allinput, c.alwaysChecker(allinput, c.notOperator(allinput, evaluate(allinput, tree.right)))); } if (tree.operator.equals("AG")) { // equivalent to !EF !p result = c.notOperator(allinput, c.finallyChecker(allinput, c.notOperator(allinput, evaluate(allinput, tree.right)))); } if (tree.operator.equals("&")) { result = c.andOperator(evaluate(allinput, tree.left), evaluate(allinput, tree.right)); } if (tree.operator.equals("|")) { result = c.orOperator(evaluate(allinput, tree.left), evaluate(allinput, tree.right)); } if (tree.operator.equals("!")) { result = c.notOperator(allinput, evaluate(allinput, tree.right)); } if (tree.operator.equals("->")) { result = c.implyOperator(allinput, evaluate(allinput, tree.left), evaluate(allinput, tree.right)); } return result; } // remove all spaces from the String public String removeSpace(String s) { StringBuilder result = new StringBuilder(); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) != (' ')) result.append(s.charAt(i)); } return result.toString(); } // method to recognize each operator and pop each operator from stack // operators, such as "EU", "EF" public String popOperator(Stack<Character> operators) throws WrongFormatException { StringBuilder sb = new StringBuilder(); try { Character top = operators.pop(); if (top == 'F' || top == 'G' || top == 'X') { if (operators.peek() != 'A' && operators.peek() != 'E') { throw new WrongFormatException(); } sb.append(operators.pop()); // A or E sb.append(top); } else if (top == 'U') { if (operators.peek() != '(') { throw new WrongFormatException(); } operators.pop(); // '(' if (operators.peek() != 'A' && operators.peek() != 'E') { throw new WrongFormatException(); } sb.append(operators.pop()); // A or E sb.append(top); } else if (top == '>') { if (operators.peek() != '-') { throw new WrongFormatException(); } sb.append(operators.pop()); // '-' sb.append(top); } else { if (top != '&' && top != '|' && top != '!' && top != '(') { throw new WrongFormatException(); } sb.append(top); } } catch (EmptyStackException e) { throw new WrongFormatException(); } return sb.toString(); } // method to push treenode to stack values, including checking the priority of // the top element of stack operators before putting the treenode into the // stack // if the top operators is "!" || "^", deal with the operation immediately public void pushValue(TreeNode tree, Stack<TreeNode> values, Stack<Character> operators) throws WrongFormatException { if (operators.size() == 0) { values.push(tree); return; } if (operators.peek() == '!') { TreeNode newTree = new TreeNode(false, null, Character.toString(operators .pop())); newTree.right = tree; pushValue(newTree, values, operators); } else if (operators.peek() == '&') { TreeNode newTree = new TreeNode(false, null, Character.toString(operators .pop())); newTree.right = tree; if (values.size() == 0) { throw new WrongFormatException(); } newTree.left = values.pop(); pushValue(newTree, values, operators); } else { values.push(tree); } } // method to build the treenode public void buildTree(String operator, Stack<TreeNode> values, Stack<Character> operators) throws WrongFormatException { try { if (operator.equals("EG") || operator.equals("EF") || operator.equals("EX") || operator.equals("AG") || operator.equals("AF") || operator.equals("AX") || operator.equals("!")) { TreeNode tree = new TreeNode(false, null, operator); tree.right = values.pop(); pushValue(tree, values, operators); } else if (operator.equals("EU") || operator.equals("AU") || operator.equals("&") || operator.equals("|") || operator.equals("->")) { TreeNode tree = new TreeNode(false, null, operator); tree.right = values.pop(); tree.left = values.pop(); pushValue(tree, values, operators); } } catch (EmptyStackException e) { throw new WrongFormatException(); } } public static Set<StateNode> getReachableState(HashMap<Integer,StateNode> nodeResult, StateNode initialState){ HashSet<StateNode> result = new HashSet<StateNode>(); Stack<StateNode> retrivalStack = new Stack<StateNode>(); if (nodeResult == null){ System.out.println("No node returned!"); return null; } else { retrivalStack.add(initialState); int count = 0; while (!retrivalStack.isEmpty()) { StateNode current = retrivalStack.pop(); if(count !=0 ){ result.add(current); } count++; if (current.getChildren()!=null) { for (StateNode child:current.getChildren()){ if(!result.contains(child) && !retrivalStack.contains(child)){ retrivalStack.add(child); } } } } return result; } } public static HashMap<Integer,StateNode> createStateNode(String pathname) throws IOException{ HashMap<Integer,StateNode> result = new HashMap<Integer,StateNode>(); Hashtable<Integer,ArrayList<Integer>> nodeResult = new Hashtable<>(); int nodeSetSize = 0; Boolean isFirstLine = true; try{ FileInputStream fstream = new FileInputStream(pathname); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { String[] tokens = strLine.split(" "); if (isFirstLine){ nodeSetSize = Integer.parseInt(tokens[0]); isFirstLine = false; } else { if (nodeResult.containsKey(Integer.parseInt(tokens[0]))) { nodeResult.get(Integer.parseInt(tokens[0])).add(Integer.parseInt(tokens[1])); } else{ StateNode newNode = new StateNode(); newNode.setId(Integer.parseInt(tokens[0])); result.put(Integer.parseInt(tokens[0]), newNode); ArrayList<Integer> children = new ArrayList<Integer>(); children.add(Integer.parseInt(tokens[1])); nodeResult.put(Integer.parseInt(tokens[0]),children); } if(!result.containsKey(Integer.parseInt(tokens[1]))){ StateNode newNode = new StateNode(); newNode.setId(Integer.parseInt(tokens[1])); result.put(Integer.parseInt(tokens[1]), newNode); } } } in.close(); }catch (Exception e){ System.err.println("Error: " + e.getMessage()); } Set<Integer> keys = nodeResult.keySet(); for(int key: keys){ for (int child:nodeResult.get(key)) { result.get(key).addChildren(result.get(child)); } } if (result.size() == nodeSetSize) { return result; } else { System.out.println("not equivalant nodeSize"); return null; } } public static HashMap<String, Set<StateNode>> createAtomicPropertyStateSet(HashMap<Integer, StateNode> stateTable, String pathname){ HashMap<String, Set<StateNode>> atomicPropertyStateSet = new HashMap<String, Set<StateNode>>(); try{ //if there is property file FileInputStream fstream1 = new FileInputStream(pathname); DataInputStream in1 = new DataInputStream(fstream1); BufferedReader br1 = new BufferedReader(new InputStreamReader(in1)); String strLine; while ((strLine = br1.readLine()) != null) { int spaceIndex = strLine.indexOf(" "); String key = strLine.substring(0,spaceIndex); String left = strLine.substring(spaceIndex+1, strLine.length()); String[] states = left.split("\\,"); Set<StateNode> value = new HashSet<StateNode>(); for(int i=0; i<states.length; i++){ value.add(stateTable.get(Integer.parseInt(states[i]))); } atomicPropertyStateSet.put(key,value); } }catch(FileNotFoundException f){ //if there is no property file for(Integer nodeId : stateTable.keySet()){ String key = Integer.toString(nodeId); Set<StateNode> value = new HashSet<StateNode>(); value.add(stateTable.get(nodeId)); atomicPropertyStateSet.put(key, value); } return atomicPropertyStateSet; }catch(Exception e){ System.out.println("ErrorMessage:"); } return atomicPropertyStateSet; } private static List<Integer> sortResult (Set<StateNode> input){ List<Integer> list = new ArrayList<Integer>(); for(StateNode node : input){ list.add(node.getId()); } java.util.Collections.sort(list); return list; } public static void main(String args[]) { //Iteractive Terminal while(true){ System.out.println("*************************************"); System.out.println("Welcome to use Model Checker"); System.out.println("*************************************"); Scanner scanner = new Scanner(System.in); System.out.println("Path of State Number and Transition File (required):"); String filePath1 = scanner.nextLine(); System.out.println("Path of Atomic Proposition File (optional):"); String filePath2 = scanner.nextLine(); System.out.println("Function: (1) Reachbility Check (2) Property Check"); int index = scanner.nextInt(); int initialStateIndex = 0; String testProperty = null; if(index == 1){ System.out.println("Initial State:"); initialStateIndex = scanner.nextInt(); }else{ System.out.println("Property to be tested:"); scanner.nextLine(); testProperty =scanner.nextLine(); } //build stateTable HashMap<Integer, StateNode> stateTable = new HashMap<Integer, StateNode>(); try{ stateTable = createStateNode(filePath1); } catch(IOException i){ System.out.println("Error:IOException"); } //build inputAll Set<StateNode> inputAll = new HashSet<StateNode>(); for(Integer i : stateTable.keySet()){ inputAll.add(stateTable.get(i)); } //build atomicPropertyStateSet HashMap<String, Set<StateNode>> atomicPropertyStateSet = createAtomicPropertyStateSet(stateTable, filePath2); PropertyEvaluation t = new PropertyEvaluation(atomicPropertyStateSet); try { if(index == 1){ Set<StateNode> reachableSet = getReachableState(stateTable, stateTable.get(initialStateIndex)); for(Integer each : PropertyEvaluation.sortResult(reachableSet)){ System.out.println("Reachable:" + each); } }else if(index == 2){ TreeNode r = t.parse(testProperty); Set<StateNode> result = t.evaluate(inputAll, r); if (result == null) { System.out.println("there is no result that satisfies the rule"); } else { if(result.size() == 0) System.out.println("False: no staetes satisfying the rule!"); else { System.out.println("True: states satisfying the rule are"); for(Integer i : PropertyEvaluation.sortResult(result)){ System.out.println(i); } } } } } catch (WrongFormatException e) { System.out.println("Wrong Format!"); } catch (AtomicPropertyNotExistException a){ System.out.println("Error: Atomic Property not Exist"); } } } /****************** Code for testing ******************/ /* Test Case 1: "EG((EF p) & (EG q))" done */ /* Test Case 2: "E((EX(p ^ q)) U (AF E(p U q)))" done */ /* Test Case 3: "E((EX(p -> q)) U (AF E(p U q)))" done */ /* Test Case 4: "E((EX(p -> q)) U (AF !E(p U q)))" done */ public void preOrder(TreeNode node) { if (node == null) { // System.out.println("node == null"); return; } if (node.isAtomicProperty) System.out.println(node.atomicProperty); else System.out.println(node.operator); preOrder(node.left); preOrder(node.right); } }
package iit.android.settings; import iit.android.swarachakra.R; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceFragment; public class UserSettings extends PreferenceFragment { private static SharedPreferences prefs; SharedPreferences.Editor editor; public static SharedPreferences getPrefs() { return prefs; } public static void setPrefs(SharedPreferences prefs) { UserSettings.prefs = prefs; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.settings); SharedPreferences settings = getPreferenceManager().getSharedPreferences(); prefs = settings; editor = settings.edit(); String key = this.getResources().getString( R.string.tablet_layout_setting_key); boolean isFirstRun = settings.getBoolean("is_first_run", true); if (isFirstRun) { editor.putBoolean("is_first_run", false); editor.putBoolean(key, SettingsActivity.isTablet); editor.commit(); } } public void setPreferenceValue(String boolName, boolean boolValue) { editor.putBoolean(boolName, boolValue); editor.commit(); } }