text
stringlengths 10
2.72M
|
|---|
package it.univaq.rtv.Model;
import it.univaq.rtv.Model.FactoryCitta.ICitta;
import java.util.ArrayList;
import java.util.Random;
public class SingletonMazzoObiettivo {
private static SingletonMazzoObiettivo istance = null;
private ArrayList<CartaObiettivo> Carte= new ArrayList<CartaObiettivo>();
/**
*
* @param Cit
* @return
*/
public static SingletonMazzoObiettivo getIstance(ArrayList<ICitta> Cit){
if(istance==null){
istance = new SingletonMazzoObiettivo();
for(int i=0;i<Cit.size();i++){
ICitta c= Cit.get(i);
CartaObiettivo c1;
c1=new CartaObiettivo(i, c);
istance.addCarta(c1);
}
}
return istance;
}
/**
* @return
*/
public static SingletonMazzoObiettivo getIstance1(){
return istance;
}
/**
*
*/
public SingletonMazzoObiettivo(){
}
/**
* @param c
*/
public void addCarta(CartaObiettivo c){
this.Carte.add((CartaObiettivo) c);
}
/**
* @return
*/
public CartaObiettivo pescaCarta() {
int num1=this.mischiaMazzo();
CartaObiettivo c=this.Carte.get(num1);
this.Carte.remove(num1);
return c;
}
/**
* @param c
*/
public void reinserisciCarta(CartaObiettivo c){
this.Carte.add(c);
}
/**
* @return
*/
public int mischiaMazzo() {
Random r= new Random();
int num=0;
int n=this.Carte.size();
if(n!=0)num= r.nextInt(n);
return num;
}
}
|
package com.tencent.mm.ui.chatting;
import android.widget.ScrollView;
import com.tencent.mm.ui.base.CustomScrollView.a;
class TextPreviewUI$2 implements a {
final /* synthetic */ TextPreviewUI tNo;
TextPreviewUI$2(TextPreviewUI textPreviewUI) {
this.tNo = textPreviewUI;
}
public final void a(ScrollView scrollView, int i, int i2) {
int i3 = i - i2;
TextPreviewUI.f(this.tNo);
if (scrollView.getChildAt(0).getMeasuredHeight() == scrollView.getHeight() + scrollView.getScrollY()) {
TextPreviewUI.a(this.tNo, scrollView.getScrollY());
}
if (scrollView.getScrollY() <= 0 || (scrollView.getScrollY() >= TextPreviewUI.g(this.tNo) - 10 && TextPreviewUI.g(this.tNo) > 0)) {
TextPreviewUI.h(this.tNo);
} else if (TextPreviewUI.i(this.tNo)) {
if (i2 > i) {
TextPreviewUI.h(this.tNo);
} else if (i2 < i) {
TextPreviewUI.j(this.tNo);
}
TextPreviewUI.a(this.tNo, false);
}
TextPreviewUI.b(this.tNo, i3);
}
}
|
package com.tencent.mm.plugin.appbrand.o;
import android.database.Cursor;
import com.tencent.mm.g.c.am;
import com.tencent.mm.g.c.cm;
import com.tencent.mm.kernel.g;
import com.tencent.mm.model.s;
import com.tencent.mm.plugin.messenger.foundation.a.i;
import com.tencent.mm.plugin.wxpay.a$k;
import com.tencent.mm.pointers.PInt;
import com.tencent.mm.pointers.PString;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.bl;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.ab;
import com.tencent.mm.storage.ai;
import com.tencent.mm.storage.az;
import com.tencent.mm.storage.az.b;
import java.util.Map;
public final class a implements com.tencent.mm.storage.az.a {
public final void a(ai aiVar, az azVar) {
if (aiVar != null && !bi.oW(aiVar.field_username)) {
String str = aiVar.field_username;
ab Yg = ((i) g.l(i.class)).FR().Yg(str);
if (Yg == null || ((int) Yg.dhP) == 0) {
x.e("MicroMsg.AppBrandConversionExtension", "contact is null or contactId is 0 for %s", new Object[]{str});
} else if (ab.gr(str) && !s.hr(str)) {
x.i("MicroMsg.AppBrandConversionExtension", "this conversation is a app brand contact!");
aiVar.ef("appbrandcustomerservicemsg");
ai Yq = ((i) g.l(i.class)).FW().Yq("appbrandcustomerservicemsg");
if (Yq == null) {
x.i("MicroMsg.AppBrandConversionExtension", "create parentConv");
Yq = new ai("appbrandcustomerservicemsg");
Yq.clx();
a(aiVar, Yq);
((i) g.l(i.class)).FW().d(Yq);
return;
}
x.i("MicroMsg.AppBrandConversionExtension", "appBrandSuperConv is created");
Yq.ef(null);
a(aiVar, Yq);
((i) g.l(i.class)).FW().a(Yq, "appbrandcustomerservicemsg");
} else if (s.hN(str)) {
x.i("MicroMsg.AppBrandConversionExtension", "appBrandSuperConv is created");
aiVar.ef(null);
}
}
}
private static void a(ai aiVar, ai aiVar2) {
am amVar;
cm GE;
String str = null;
Cursor b = ((i) g.l(i.class)).FW().b(s.dAT, null, "appbrandcustomerservicemsg");
if (b != null) {
ai aiVar3;
if (b.getCount() <= 0 || !b.moveToFirst()) {
aiVar3 = null;
} else {
aiVar3 = new ai();
aiVar3.d(b);
}
b.close();
amVar = aiVar3;
} else {
amVar = null;
}
if (amVar != null) {
x.e("MicroMsg.AppBrandConversionExtension", "The lastest app brand conversation username is %s", new Object[]{amVar.field_username});
GE = ((i) g.l(i.class)).bcY().GE(amVar.field_username);
} else {
x.e("MicroMsg.AppBrandConversionExtension", "The lastest app brand conversation is null");
GE = ((i) g.l(i.class)).bcY().GE(aiVar.field_username);
}
if (GE == null || GE.field_msgId <= 0) {
x.e("MicroMsg.AppBrandConversionExtension", "the last of msg is null'");
aiVar2.clx();
return;
}
aiVar2.aj(GE);
aiVar2.setContent(GE.field_talker + ":" + GE.field_content);
aiVar2.ec(Integer.toString(GE.getType()));
b vu = ((i) g.l(i.class)).FW().vu();
if (vu != null) {
PString pString = new PString();
PString pString2 = new PString();
PInt pInt = new PInt();
GE.ep(aiVar.field_parentRef);
GE.setContent(aiVar2.field_content);
vu.a(GE, pString, pString2, pInt, true);
int type = GE.getType();
String str2 = GE.field_content;
if (!bi.oW(str2)) {
switch (type) {
case a$k.AppCompatTheme_actionButtonStyle /*49*/:
Map z = bl.z(str2, "msg");
if (z != null) {
x.d("MicroMsg.AppBrandConversionExtension", "[oneliang][parseConversationMsgContentTitle] title:%s", new Object[]{(String) z.get(".msg.appmsg.title")});
str = r0;
break;
}
break;
}
}
aiVar2.ed(bi.oV(pString.value).concat(bi.oW(str) ? "" : " " + bi.oV(str)));
aiVar2.ee(pString2.value);
aiVar2.eY(pInt.value);
}
}
}
|
package com.tencent.mm.plugin.appbrand.wxawidget.console;
import com.tencent.mm.plugin.appbrand.wxawidget.console.SettingsPanel.4;
import com.tencent.mm.ui.widget.picker.b;
import com.tencent.mm.ui.widget.picker.b.a;
class SettingsPanel$4$1 implements a {
final /* synthetic */ b gQT;
final /* synthetic */ 4 gQV;
SettingsPanel$4$1(4 4, b bVar) {
this.gQV = 4;
this.gQT = bVar;
}
public final void h(boolean z, Object obj) {
this.gQT.hide();
if (z) {
SettingsPanel.c(this.gQV.gQR).setText((CharSequence) obj);
}
SettingsPanel.b(this.gQV.gQR, this.gQT.cAP());
}
}
|
package shared;
/*
* u_Inducer.java
*
* Created on January 29, 2002, 1:39 PM
*/
/**
*
* @author User
*/
import java.io.IOException;
public class u_Inducer {
static String TRAIN_WITHOUT_LOSS_HELP = "Set if you want to disable "+
"any loss matrix which is specified in the .names file.";
static boolean DEFAULT_COMPUTE_LOG_LOSS = false;
static String COMPUTE_LOG_LOSS_HELP = "Set to compute the log-loss of the "+
"classifier. This will only work if the classifier never assigns a "+
"probability of zero to the correct class.";
static GetEnv getenv = new GetEnv();
/** Creates a new instance of u_Inducer */
public u_Inducer() {
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
GlobalOptions.printPerfPrecision = 3; // We want higher precision
CmdLine.process_mlc_cmdline(args);
try{
BaseInducer baseInducer = Env_Inducer.env_inducer();
FileNames files = new FileNames();
InstanceList trainList = new InstanceList(Globals.EMPTY_STRING, files.names_file(), files.data_file());
boolean suppressLoss = getenv.get_option_bool("TRAIN_WITHOUT_LOSS", false, TRAIN_WITHOUT_LOSS_HELP, true);
if (suppressLoss && trainList.get_schema().has_loss_matrix()) {
// remove the loss matrix from the inducer's schema
Globals.Mcout.write("Suppressing the loss matrix for training\n");
Schema schema = trainList.get_schema();
schema.remove_loss_matrix();
trainList.set_schema(schema);
}
if (baseInducer.can_cast_to_inducer()) {
Inducer inducer = baseInducer.cast_to_inducer();
inducer.assign_data(trainList);
//MLJ.ASSERT(trainList == null,"u_inducer.main(): trainList != null");
inducer.train();
InstanceList testList = null;
if (files.test_file(false) != Globals.EMPTY_STRING) {
InstanceList il = inducer.instance_list();
testList = new InstanceList(il.get_schema(),
il.get_original_schema(),
files.test_file());
if (suppressLoss && testList.get_schema().has_loss_matrix()) {
Globals.Mcout.write("Suppressing the loss matrix for testing\n");
Schema schema = testList.get_schema();
schema.remove_loss_matrix();
testList.set_schema(schema);
}
boolean computeLogLoss = getenv.get_option_bool("COMPUTE_LOG_LOSS", DEFAULT_COMPUTE_LOG_LOSS, COMPUTE_LOG_LOSS_HELP);
CatTestResult.set_compute_log_loss(computeLogLoss);
CatTestResult result = new CatTestResult(inducer.get_categorizer(), il, testList);
Globals.Mcout.write(result + "\n");
// display_lift_curve(result);
}
Categorizer categorizer = inducer.release_categorizer();
// backfit_categorizer(categorizer, inducer.instance_list(), testList);
// display_categorizer(categorizer, testList);
// make_persistent_categorizer(categorizer);
categorizer = null;
testList = null;
} else {
if (files.test_file(false) == Globals.EMPTY_STRING)
Error.fatalErr("Inducer: external inducers must use a test file");
InstanceList testSet = new InstanceList(trainList.get_schema(),
trainList.get_original_schema(),
files.test_file());
if (suppressLoss && trainList.get_schema().has_loss_matrix()) {
Globals.Mcout.write("Supressing the loss matrix for testing\n");
Schema schema = testSet.get_schema();
schema.remove_loss_matrix();
testSet.set_schema(schema);
}
if (baseInducer.supports_full_testing()) {
boolean computeLogLoss =
getenv.get_option_bool("COMPUTE_LOG_LOSS", DEFAULT_COMPUTE_LOG_LOSS, COMPUTE_LOG_LOSS_HELP);
CatTestResult.set_compute_log_loss(computeLogLoss);
CatTestResult result = baseInducer.train_and_perf(trainList, testSet);
// display_lift_curve(result);
// display_tableviz_from_inducer(baseInducer);
Globals.Mcout.write(result+"\n");
result = null;
} else {
double error = baseInducer.train_and_test(trainList, testSet);
// display_tableviz_from_inducer(baseInducer);
DoubleRef confLow = new DoubleRef();
DoubleRef confHigh = new DoubleRef();
CatTestResult.confidence(confLow, confHigh, error,
testSet.total_weight());
Globals.Mcout.write("Error: "
+ MLJ.numberToString(error*100, GlobalOptions.printPerfPrecision)
+ "% +- "
+ MLJ.numberToString(CatTestResult.theoretical_std_dev(error,
testSet.total_weight())*100,
GlobalOptions.printPerfPrecision) + "% ["
+ MLJ.numberToString(confLow.value*100,
GlobalOptions.printPerfPrecision) +"% - "
+ MLJ.numberToString(confHigh.value*100,
GlobalOptions.printPerfPrecision) +"%]" + "\n");
}
}
trainList = null;
baseInducer = null;
System.exit(0); // return success to shell
}catch(CloneNotSupportedException e){
Error.err("u_inducer.main(): CloneNotSupportedException occurs "
+"during removal of loss matrix from inducer's schema.");
}catch(IOException e){
Error.err("u_inducer.main(): IOException occurs "
+"during removal of loss matrix from inducer's schema.");
}
}
}
|
/*
* 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 zombies;
import data.DataSetComponent;
import interfaces.IDataSet;
import interfaces.IDoctor;
import interfaces.IPatient;
/**
*
* @author ra222142
*/
public class ZombieHealth {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
IDataSet dataset = new DataSetComponent();
dataset.setDataSource("/home/ec2018-fra/ra222142/Documents/mc322/zombie/zombie_health/ZombieHealth/src/data/tables/zombie-health-new-cases500.csv");
// instanciando o componente paciente
IPatient aPatient = new Patient("Santanche");
// conectando-o no componente DataSet
aPatient.connect(dataset);
// instanciando o componente doutor louco
IDoctor cDoctor = new Doctor("Marcos");
// conectando-o ao componente DataSet
cDoctor.connect(dataset);
// conectando-o ao componente paciente
cDoctor.connect(aPatient);
// executando a entrevista
cDoctor.startInterview();
}
}
|
package Queue;
public class Queue {
public ListNode head;
public ListNode tail;
public Queue(){
head = null;
tail = null;
}
//poll at head
public Integer poll(ListNode head){
if(head == null){
return null;
}
else{
ListNode node = head;
head = head.next;
if(head == null){
tail = null;
}
node.next = null;
return node.value;
}
}
//offer at tail
public void offer(Integer ele){
if(head == null){
ListNode newNode = new ListNode(ele);
head = newNode;
tail = newNode;
}
tail.next = new ListNode(ele);
tail = tail.next;
}
//peek
public Integer peek(ListNode head){
if(head == null){
return null;
}
return head.value;
}
}
|
package app.data;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import app.model.Ticket;
public interface ITicketRepository extends CrudRepository<Ticket, Long> {
List<Ticket> findByFlightId(Long id);
}
|
package Presentacion;
import Logica.RNA;
import javax.swing.JOptionPane;
/**
*
* @author CristianCamilo
*/
public class TipoRNA extends javax.swing.JFrame {
private RNA red;
private int opc;
private MenuInicio menu;
public TipoRNA(RNA red, MenuInicio m) {
initComponents();
jToggleButton1.setEnabled(false);
this.red = red;
opc = -1;
menu = m;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
jToggleButton1 = new javax.swing.JToggleButton();
jRadioButton3 = new javax.swing.JRadioButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Tipo RNA");
setAlwaysOnTop(true);
setResizable(false);
setType(java.awt.Window.Type.POPUP);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel1.setText("SELECCIONA EL TIPO DE RED NEURONAL");
jRadioButton1.setText("Red SOM");
jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton1ActionPerformed(evt);
}
});
jRadioButton2.setText("Red Multicapa");
jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton2ActionPerformed(evt);
}
});
jToggleButton1.setText("Aceptar");
jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton1ActionPerformed(evt);
}
});
jRadioButton3.setText("Cargar Anterior");
jRadioButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton3ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jRadioButton1)
.addGap(18, 18, 18)
.addComponent(jRadioButton2)
.addGap(18, 18, 18)
.addComponent(jRadioButton3))
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jToggleButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 295, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jRadioButton1)
.addComponent(jRadioButton2)
.addComponent(jRadioButton3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jToggleButton1)
.addContainerGap(12, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton2ActionPerformed
this.jRadioButton1.setSelected(false);
this.jRadioButton2.setSelected(true);
opc = 0;
jToggleButton1.setEnabled(true);
}//GEN-LAST:event_jRadioButton2ActionPerformed
private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed
this.jRadioButton1.setSelected(true);
this.jRadioButton2.setSelected(false);
opc = 1;
jToggleButton1.setEnabled(true);
}//GEN-LAST:event_jRadioButton1ActionPerformed
private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton1ActionPerformed
if(red == null)
menu.setRed(new RNA(opc));
else
if(JOptionPane.showConfirmDialog(rootPane, "La Red Ya Existe, Desea eliminar la anterior?") == JOptionPane.OK_OPTION)
menu.setRed(new RNA(opc));
dispose();
Entrenamiento training = new Entrenamiento(menu);
training.setVisible(true);
}//GEN-LAST:event_jToggleButton1ActionPerformed
private void jRadioButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton3ActionPerformed
if(red == null)
menu.setRed(new RNA(-1));
else
if(JOptionPane.showConfirmDialog(rootPane, "La Red Ya Existe, Desea eliminar la anterior?") == JOptionPane.OK_OPTION)
menu.setRed(new RNA(-1));
dispose();
menu.setVisible(true);
}//GEN-LAST:event_jRadioButton3ActionPerformed
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
menu.setVisible(true);
}//GEN-LAST:event_formWindowClosing
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JRadioButton jRadioButton3;
private javax.swing.JToggleButton jToggleButton1;
// End of variables declaration//GEN-END:variables
}
|
package com.demo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class MyReceive1 extends BroadcastReceiver{
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Toast.makeText(context, "MyReceive1接收到:"+action, 1000).show();
Log.i("MyReceive1","current priority is 0");
//获取上一receiver的处理结果
Bundle b = getResultExtras(true);
if(b!=null){
String name=(String)b.getString("name");
Toast.makeText(context, "上一节点处理数据:"+name, 1000).show();
if(name!=null){
if(name.equals("hyl"))abortBroadcast();}
}
}
}
|
package com.clay.claykey.object.parse;
import com.clay.claykey.constant.ParseConstants;
import com.parse.ParseClassName;
import com.parse.ParseObject;
import com.parse.ParseUser;
import java.io.Serializable;
import java.util.List;
/**
* Created by Mina Fayek on 1/15/2016.
*/
@ParseClassName(ParseConstants.DOOR)
public class Door extends ParseObject implements Serializable{
List<ParseUser> parseUserList;
public Door() {
super();
}
public String getName() {
return getString(ParseConstants.DOOR_NAME);
}
public void setName(String name) {
put(ParseConstants.DOOR_NAME, name);
}
public String getDescription() {
return getString(ParseConstants.DOOR_DESCRIPTION);
}
public void setDescription(String description) {
put(ParseConstants.DOOR_DESCRIPTION, description);
}
public String getTag() {
return getString(ParseConstants.DOOR_TAG);
}
public void setTag(String tag) {
put(ParseConstants.DOOR_TAG, tag);
}
public List<ParseUser> getParseUserList() {
return parseUserList;
}
public void setParseUserList(List<ParseUser> parseUserList) {
this.parseUserList = parseUserList;
}
}
|
package GameLogic;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class Dice
{
private Random random;
private ArrayList<Integer> rolls;
public Dice(){
random = new Random();
rolls = new ArrayList<Integer>();
}
//generates a random number between 1 and 6 (dice)
public int throwDice(){
int dice = random.nextInt(6) + 1;
return dice;
}
public ArrayList<Integer> getRolls()
{
return rolls;
}
//pass in defenders dice and it will update armies appropriately
public void determineRollWinner(Dice defender)
{
ArrayList<Integer> defenderRolls = defender.getRolls();
if(rolls.size() > defenderRolls.size())
{
for(int i=0;i<defenderRolls.size();i++)
{
if(rolls.get(i) <= defenderRolls.get(i))
{
//attacker loses piece
}else
{
//defender losses piece
}
}
}else
{
for(int i=0;i<rolls.size();i++)
{
if(rolls.get(i) <= defenderRolls.get(i))
{
//attacker loses piece
}else
{
//defender losses piece
}
}
}
}
//rolls X number of dice and stores them in the rolls instance variable
//every call clears the old rolls
public ArrayList<Integer> rollXDice(int x)
{
rolls.clear();
for(int i=0 ; i<x; i++)
{
rolls.add(throwDice());
}
Collections.sort(rolls, Collections.reverseOrder());
return rolls;
}
}
|
package tree;
/**
* @author: ZhiHao
* @date: 2021/1/7
* @version: 1.0
*/
class SubStudent {
private int id;
private String name;
private SubStudent left;
private SubStudent right;
/**
* 左、右指针的类型,0-->指向的是左右孩子,1-->指向的是前驱、后续节点
*/
private int leftType = 0;
private int rightType = 0;
public SubStudent(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public SubStudent getLeft() {
return left;
}
public void setLeft(SubStudent left) {
this.left = left;
}
public SubStudent getRight() {
return right;
}
public void setRight(SubStudent right) {
this.right = right;
}
public int getLeftType() {
return leftType;
}
public void setLeftType(int leftType) {
this.leftType = leftType;
}
public int getRightType() {
return rightType;
}
public void setRightType(int rightType) {
this.rightType = rightType;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
|
package collection;
import java.util.ArrayList;
public class ArrayList3 {
public static void main(String []args) {
ArrayList<String> a1 = new ArrayList<String>();
a1.add("Jayanta");
a1.add("Arijit");
a1.add("Abhijoy");
ArrayList<String> a2 = new ArrayList<String>();
a2.add("Avi");
a2.add("Som");
a1.addAll(a2);
System.out.println(a1);
ArrayList<String> a3 = new ArrayList();
a3.add("Sudipta");
a3.add("Swati");
a3.add("Soma");
a1.addAll(2, a3);
System.out.println(a1);
a1.remove("Soma");
a1.remove("Som");
System.out.println(a1);
a1.removeAll(a3);
System.out.println(a1);
a1.clear();
System.out.println(a1);
}
}
|
package logic;
import model.Ally;
public class OperationAlly {
public static boolean effectiveAtack(Ally aliado1, int attack) {
boolean effectiveAttack;
if (attack > aliado1.getArmour()) {
effectiveAttack = true;
System.out.println("Tu ataque ha sido efectivo");
} else {
effectiveAttack= false;
System.out.println("Tu ataque no ha tenido efecto");
}
return effectiveAttack;
}
public static int calculationLife(Ally aliado1, int attack) {
int lifeAfterAttack = aliado1.getTotalLife() - (attack/2);
if((attack/2)>=aliado1.getTotalLife()) {
System.out.println(aliado1.getName() + " está muerto");
}else {
System.out.println("Tu ataque ha infringido daño a " + aliado1.getName());
}
return lifeAfterAttack;
}
public static int extraLife(int life) {
int extraLife=100-life;
life=extraLife+life;
return life;
}
}
|
package com.moon.netty.dto;
/**
* Created by maguoqiang on 2016/3/16.
* 服务端客户端消息类型
*/
public enum Msg_Type {
TYPE_TEST01,
TYPE_TEST02;
}
|
package com.gzone.ecommerce.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.gzone.ecommerce.dao.PaisDAO;
import com.gzone.ecommerce.dao.util.JDBCUtils;
import com.gzone.ecommerce.exceptions.DataException;
import com.gzone.ecommerce.model.Pais;
public class PaisDAOImpl implements PaisDAO {
public PaisDAOImpl() {}
private static Logger logger = LogManager.getLogger(PaisDAOImpl.class.getName());
@Override
public List<Pais> findByIdioma(Connection connection, String idiomaId)
throws DataException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// Create "preparedStatement"
String queryString =
"SELECT p.COD_PAIS, p.PAIS, p.COD_IDIOMA " +
"FROM PAIS_IDIOMA p " +
"WHERE COD_IDIOMA = ? "+
"ORDER BY p.PAIS ASC ";
preparedStatement = connection.prepareStatement(queryString,
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
int i = 1;
preparedStatement.setString(i++, idiomaId);
resultSet = preparedStatement.executeQuery();
// Recupera la pagina de resultados
List<Pais> results = new ArrayList<Pais>();
Pais p = null;
while (resultSet.next()) {
p = loadNext (connection,resultSet);
results.add(p);
}
return results;
} catch (SQLException e) {
logger.fatal("idIdioma :"+idiomaId);
throw new DataException(e);
} finally {
JDBCUtils.closeResultSet(resultSet);
JDBCUtils.closeStatement(preparedStatement);
}
}
private Pais loadNext(Connection connection, ResultSet resultSet)
throws SQLException, DataException {
int i = 1;
String idPais = resultSet.getString(i++);
String pais = resultSet.getString(i++);
String idIdioma = resultSet.getString(i++);
Pais p = new Pais();
p.setCodPais(idPais);;
p.setPais(pais);
p.setCodPais(idIdioma);
return p;
}
}
|
package com.codeup.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MathController {
@GetMapping("/add/{numOne}/and/{numTwo}")
@ResponseBody
public String add(@PathVariable int numOne, @PathVariable int numTwo) {
return String.format("The result is: " + (numOne + numTwo));
}
@GetMapping("/subtract/{numOne}/from/{numTwo}")
@ResponseBody
public String subtract(@PathVariable float numOne, @PathVariable float numTwo) {
return String.format("%.2f - %.2f is %.2f.", numTwo, numOne, (numTwo-numOne));
}
@GetMapping("/multiply/{numOne}/and/{numTwo}")
@ResponseBody
public String multiply(@PathVariable float numOne, @PathVariable float numTwo) {
return String.format("%.2f x %.2f is %.2f.", numOne, numTwo, (numOne * numTwo));
}
@GetMapping("/divide/{numOne}/by/{numTwo}")
@ResponseBody
public String divide(@PathVariable float numOne, @PathVariable float numTwo) {
return String.format("%.2f divided by %.2f = %.2f", numOne, numTwo, (numOne/numTwo));
}
@GetMapping("/roll-dice/{number}")
public String diceRoll(@PathVariable int number, Model model) {
int randomNum = (int) Math.floor(Math.random() * 6) + 1;
String msg;
if(randomNum == number)
{msg = "Woot! You escaped the trap!";}
else {msg = "You got killed-ed";}
model.addAttribute("number", number);
model.addAttribute("randomNum", randomNum);
model.addAttribute("msg", msg);
return "roll-dice";
}
}
|
package com.tencent.mm.plugin.wallet_core.ui;
import android.view.View;
import android.view.View.OnClickListener;
class o$7 implements OnClickListener {
final /* synthetic */ o pxX;
o$7(o oVar) {
this.pxX = oVar;
}
public final void onClick(View view) {
this.pxX.bQv();
}
}
|
package com.team_linne.digimov.repository;
import com.team_linne.digimov.model.Cinema;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CinemaRepository extends MongoRepository<Cinema, String> {
}
|
package com.pike;
import java.util.Arrays;
import java.util.List;
// Algorithm to calculate how long adjacent objects are updated / replaced
// this model is use for servers but can be adjusted for bacteria
// assumptions that it takes 1 ms for replication
public class ServerBinaryList {
boolean checkServer(List<List<Integer>> manyRacks) {
boolean fileCopied = true;
for (List<Integer> serversChk : manyRacks) {
if (fileCopied) {
for (Integer serverChk : serversChk) {
if (serverChk==0) {
fileCopied = false;
break;
}
}
}
}
return fileCopied;
}
void updateServer(List<List<Integer>> manyRacks) {
// loop through the servers once and change (copy file) from 0 to 1
for (int i=0; i<manyRacks.size(); i++) {
List<Integer> servers = manyRacks.get(i);
// has to be while loop to loop thru once for every 1 ms
int idx = 0;
boolean updatePrior = false;
boolean updateNext = false;
while (idx<servers.size()-1) {
int priorIDX = 0;
if (idx>0) {
priorIDX = servers.get(idx-1);
}
int currIDX = servers.get(idx);
int nextIDX = servers.get(idx+1);
if (idx>0 && !updatePrior && priorIDX==0 && currIDX==1) {
servers.set(idx-1, 1);
updatePrior = true;
} else {
updatePrior = false;
}
if (!updateNext && currIDX==1 && nextIDX==0) {
servers.set(idx+1, 1);
updateNext = true;
} else {
updateNext = false;
}
idx++;
}
}
}
public static void main(String[] args) {
// Test for now, later expect user input or file extraction
List<Integer> rack1 = Arrays.asList(1,0,0,0,1,0,1,0);
List<Integer> rack2 = Arrays.asList(0,0,1,0,0,0,1,0);
List<Integer> rack3 = Arrays.asList(0,0,1,0,1,0,0,1);
List<Integer> rack4 = Arrays.asList(0,0,0,0,0,1,0,0);
List<List<Integer>> racks = Arrays.asList(rack1, rack2, rack3, rack4);
boolean complete = false;
int time_ms = 0;
ServerBinaryList sb = new ServerBinaryList();
while(!complete) {
complete = sb.checkServer(racks);
System.out.println("("+time_ms+") "+racks);
sb.updateServer(racks);
time_ms++;
}
time_ms--;
//System.out.println("All Files Copied to Every Server in "+time_ms+" ms!");
System.out.println("All Object Replicated and Replace Adjacent Objects in "+time_ms+" ms!");
}
}
|
package com.tencent.mm.app.plugin.a;
import android.os.Looper;
import com.tencent.mm.R;
import com.tencent.mm.ac.d;
import com.tencent.mm.ac.f;
import com.tencent.mm.g.a.cx;
import com.tencent.mm.g.a.dw;
import com.tencent.mm.g.a.jd;
import com.tencent.mm.g.a.qt;
import com.tencent.mm.model.au;
import com.tencent.mm.model.s;
import com.tencent.mm.sdk.b.b;
import com.tencent.mm.sdk.b.c;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import java.util.HashMap;
import java.util.Map;
public final class a {
public com.tencent.mm.ui.chatting.c.a bAG;
public b bAH;
public a bAI;
private String bAJ;
public Map<String, Boolean> bAK;
public boolean bAL = true;
class a extends c<cx> {
a() {
this.sFo = cx.class.getName().hashCode();
}
public final /* bridge */ /* synthetic */ boolean a(b bVar) {
((cx) bVar).bKs.bAL = a.this.bAL;
return true;
}
}
public a(com.tencent.mm.ui.chatting.c.a aVar) {
x.d("MicroMsg.exdevice.ChattingUIExDeviceLogic", "now init the event listener");
this.bAG = aVar;
if (this.bAH == null) {
this.bAH = new b(this);
}
com.tencent.mm.sdk.b.a.sFg.b(this.bAH);
if (this.bAI == null) {
this.bAI = new a();
}
com.tencent.mm.sdk.b.a.sFg.b(this.bAI);
}
final synchronized void d(int i, String str, String str2) {
x.i("MicroMsg.exdevice.ChattingUIExDeviceLogic", "now connect state : %d", new Object[]{Integer.valueOf(i)});
if (this.bAG != null && !bi.oW(str)) {
d kH = f.kH(str);
if (a(kH)) {
if (this.bAK == null) {
this.bAK = new HashMap();
}
Map map = this.bAK;
if (!str.equals(this.bAJ)) {
this.bAJ = str;
map.clear();
}
if (kH.bG(false).Ms().dLz != 1) {
x.d("MicroMsg.exdevice.ChattingUIExDeviceLogic", "connDeviceIds : (%s) , deviceId : (%s)", new Object[]{map, str2});
switch (i) {
case -1:
this.bAG.tTq.setMMSubTitle(null);
break;
case 0:
if (map.size() == 0) {
this.bAG.tTq.setMMSubTitle(R.l.exdevice_device_status_none);
break;
}
break;
case 1:
if (map.size() == 0) {
this.bAG.tTq.setMMSubTitle(R.l.exdevice_device_status_connecting);
break;
}
break;
case 2:
map.put(str2, Boolean.valueOf(true));
this.bAG.tTq.setMMSubTitle(this.bAG.tTq.getString(R.l.exdevice_device_status_connected, new Object[]{Integer.valueOf(map.size())}));
x.i("MicroMsg.exdevice.ChattingUIExDeviceLogic", "now connected(deviceId : %s), set the tips gone", new Object[]{str2});
break;
case 4:
if (map.remove(str2) != null) {
x.i("MicroMsg.exdevice.ChattingUIExDeviceLogic", "disconnected(deviceId : %s) successfully.", new Object[]{str2});
}
this.bAG.tTq.setMMSubTitle(this.bAG.tTq.getString(R.l.exdevice_device_status_connected, new Object[]{Integer.valueOf(map.size())}));
break;
}
}
this.bAG.tTq.setMMSubTitle(null);
} else {
x.w("MicroMsg.exdevice.ChattingUIExDeviceLogic", "It's not a biz, brandName(%s).", new Object[]{str});
}
} else {
x.w("MicroMsg.exdevice.ChattingUIExDeviceLogic", "context is null or brandName is null or nil.");
}
}
public final void a(final int i, d dVar) {
if (this.bAG == null) {
x.e("MicroMsg.exdevice.ChattingUIExDeviceLogic", "notifySwitchView, context is null, maybe has been released");
} else if (s.hf(this.bAG.getTalkerUserName()) && a(dVar)) {
au.Em().H(new Runnable() {
public final void run() {
if (1 == i) {
dw dwVar = new dw();
dwVar.bLH.op = 0;
dwVar.bLH.userName = a.this.bAG.getTalkerUserName();
dwVar.bLH.context = a.this.bAG.tTq.getContext();
com.tencent.mm.sdk.b.a.sFg.m(dwVar);
if (a.this.bAG.getTalkerUserName().equals("gh_43f2581f6fd6")) {
qt qtVar = new qt();
qtVar.cbp.action = 1;
com.tencent.mm.sdk.b.a.sFg.a(qtVar, Looper.getMainLooper());
}
}
jd jdVar = new jd();
jdVar.bSI.opType = i;
jdVar.bSI.bSK = 1;
jdVar.bSI.bSJ = a.this.bAG.getTalkerUserName();
com.tencent.mm.sdk.b.a.sFg.m(jdVar);
}
});
}
}
public static boolean a(d dVar) {
if (dVar == null || dVar == null) {
return false;
}
d.b bG = dVar.bG(false);
if (bG == null || bG.Ms() == null || !bG.Ms().MC()) {
return false;
}
return true;
}
}
|
package Query.Execution;
import Entity.QueryConstraints;
import Query.Entities.RelationEdge;
import Query.Plan.Plan;
import Query.Plan.RangeExpandIntoPlan;
import Utility.DBUtil;
import java.util.*;
/**
* Created by liuche on 6/12/17.
*
*/
public class RangeExpandIntoExec extends Execution {
private List<RangePath> pathMem;
public RangeExpandIntoExec(DBUtil util, Plan plan, List<RangePath> pathMem) {
super(util, plan);
this.operandCount = 1;
this.pathMem = pathMem;
}
@Override
public ResultTable execute(ResultTable table) {
QueryConstraints relationConstraints = ((RangeExpandIntoPlan)plan).getRelationConstraint();
RelationEdge edge = ((RangeExpandIntoPlan)plan).getRelationEdge();
List<String> relationTypes = relationConstraints.getEdgeLabels();
Integer rangeStart = ((RangeExpandIntoPlan)plan).getRange().getV0();
Integer rangeEnd = ((RangeExpandIntoPlan)plan).getRange().getV1();
String edgeDirection = edge.direction.equals("--") ? "<-->" : edge.direction;
Set<String> startNodes = new HashSet<>(table.getAll(edge.start));
Set<String> endNodes = new HashSet<>(table.getAll(edge.end));
Map<String, Map<String, List<String>>> resultPaths = new HashMap<>();
Map<String, Queue<RangePath>> nodePaths = new HashMap<>();
if(edgeDirection.contains("-->")){
for (String startNode : startNodes) {
Queue<RangePath> initPath = new LinkedList<>();
initPath.add(new RangePath(RangePath.Direction.FROM, startNode));
nodePaths.put(startNode, initPath);
}
for(int i = 0 ; i <= rangeEnd ; i++){
if(i >= rangeStart && i <= rangeEnd){
for(String startNode : nodePaths.keySet()){
for(RangePath path : nodePaths.get(startNode)){
String endNode = path.backNode();
if(endNodes.contains(endNode)){
if(!resultPaths.containsKey(startNode)){
resultPaths.put(startNode, new HashMap<>());
}
if(!resultPaths.get(startNode).containsKey(endNode)){
resultPaths.get(startNode).put(endNode, new ArrayList<>());
}
String pathIdx = String.valueOf(pathMem.size());
pathMem.add(path);
resultPaths.get(startNode).get(endNode).add(pathIdx);
}
}
}
}
if(nodePaths.size() == 0){
break;
}
List<String> removed = new ArrayList<>();
for(String key : nodePaths.keySet()){
Queue<RangePath> q = nodePaths.get(key);
int index = q.size();
if(index == 0){
removed.add(key);
}
while(index > 0){
index--;
RangePath path = q.remove();
String lastNode = path.backNode();
//TODO: Add a cache here.
List<List<String>> rows = exeUtil.getEdgeEndByStart(lastNode, relationTypes);
for(List<String> row : rows){
String nextEdge = row.get(0);
String nextNode = row.get(1);
RangePath newPath = new RangePath(path);
newPath.put(nextNode, nextEdge);
q.add(newPath);
}
}
}
for(String key : removed){
nodePaths.remove(key);
}
}
}
if(edgeDirection.contains("<--")){
nodePaths = new HashMap<>();
for (String startNode : startNodes) {
Queue<RangePath> initPath = new LinkedList<>();
initPath.add(new RangePath(RangePath.Direction.TO, startNode));
nodePaths.put(startNode, initPath);
}
for(int i = 0 ; i <= rangeEnd ; i++){
if(i >= rangeStart && i <= rangeEnd){
for(String startNode : nodePaths.keySet()){
for(RangePath path : nodePaths.get(startNode)){
String endNode = path.backNode();
if(endNodes.contains(endNode)){
if(!resultPaths.containsKey(startNode)){
resultPaths.put(startNode, new HashMap<>());
}
if(!resultPaths.get(startNode).containsKey(endNode)){
resultPaths.get(startNode).put(endNode, new ArrayList<>());
}
String pathIdx = String.valueOf(pathMem.size());
pathMem.add(path);
resultPaths.get(startNode).get(endNode).add(pathIdx);
}
}
}
}
if(nodePaths.size() == 0){
break;
}
List<String> removed = new ArrayList<>();
for(String key : nodePaths.keySet()){
Queue<RangePath> q = nodePaths.get(key);
int index = q.size();
if(index == 0){
removed.add(key);
}
while(index > 0){
index--;
RangePath path = q.remove();
String lastNode = path.backNode();
//TODO: Add a cache here.
List<List<String>> rows = exeUtil.getEdgeStartByEnd(lastNode, relationTypes);
for(List<String> row : rows){
String nextEdge = row.get(0);
String nextNode = row.get(1);
RangePath newPath = new RangePath(path);
newPath.put(nextNode, nextEdge);
q.add(newPath);
}
}
}
for(String key : removed){
nodePaths.remove(key);
}
}
}
table.expandIntoPaths(edge.start, edge.end, edge.name, ResultTable.ObjectType.RangePath, resultPaths);
this.querySQL = exeUtil.getHistory();
return table;
}
}
|
package com.itbank.food;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
public class SellerRowMapper implements RowMapper<SellerDTO> {
@Autowired
SellerDTO selDTO;
/*
* @Override public SellerDTO mapRow(ResultSet rs, int rowNum) throws
* SQLException { selDTO.setSelId(rs.getString(1));
* selDTO.setSelPw(rs.getString(2)); selDTO.setSelName(rs.getString(3));
*
* String[] SelAddr = rs.getString(4).split("/");
* selDTO.setSelAddr1(SelAddr[0]); selDTO.setSelAddr2(SelAddr[1]);
* selDTO.setSelAddr3(SelAddr[2]);
*
* String[] SelTel = rs.getString(5).split("-"); selDTO.setSelTel1(SelTel[0]);
* selDTO.setSelTel2(SelTel[1]); selDTO.setSelTel3(SelTel[2]);
*
* return selDTO; }
*/
@Override
public SellerDTO mapRow(ResultSet rs, int arg1) throws SQLException {
SellerDTO selDTO = new SellerDTO();
selDTO.setSelId(rs.getString(1));
selDTO.setSelPw(rs.getString(2));
selDTO.setSelName(rs.getString(3));
selDTO.setSelAddr(rs.getString(4));
selDTO.setSelTel(rs.getString(5));
return selDTO;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package it.geosolutions.fra2015.services.rest.impl;
import it.geosolutions.fra2015.server.model.user.Token;
import it.geosolutions.fra2015.services.exception.BadRequestServiceEx;
import it.geosolutions.fra2015.services.exception.IllegalAccessServiceException;
import it.geosolutions.fra2015.services.exception.NotFoundServiceEx;
import it.geosolutions.fra2015.services.rest.AuthenticationService;
import it.geosolutions.fra2015.services.rest.exception.BadRequestWebEx;
import it.geosolutions.fra2015.services.rest.exception.IllegalAccessWebExpection;
import it.geosolutions.fra2015.services.rest.exception.NotFoundWebEx;
import javax.ws.rs.core.SecurityContext;
import org.apache.log4j.Logger;
/**
*
* @author marco
*/
public class AuthenticationServiceImpl implements AuthenticationService {
private final static Logger LOGGER = Logger.getLogger(AuthenticationServiceImpl.class);
private it.geosolutions.fra2015.services.AuthenticationService authService;
public void setAuthenticationService(it.geosolutions.fra2015.services.AuthenticationService authService) {
this.authService = authService;
}
@Override
public Token login(SecurityContext sc, String username, String password) throws NotFoundWebEx {
try {
return authService.login(username, password);
} catch (BadRequestServiceEx ex) {
throw new BadRequestWebEx(ex.getMessage());
} catch (NotFoundServiceEx ex) {
throw new NotFoundWebEx(ex.getMessage());
} catch (IllegalAccessServiceException ex) {
throw new IllegalAccessWebExpection(ex.getMessage());
}
}
@Override
public Boolean validate(SecurityContext sc, String token) throws NotFoundWebEx {
try {
return authService.verify(token);
} catch (BadRequestServiceEx ex) {
throw new BadRequestWebEx(ex.getMessage());
} catch (NotFoundServiceEx ex) {
throw new NotFoundWebEx(ex.getMessage());
}
}
@Override
public Boolean invalidate(SecurityContext sc, String token) throws NotFoundWebEx {
try {
return authService.invalidate(token);
} catch (BadRequestServiceEx ex) {
throw new BadRequestWebEx(ex.getMessage());
} catch (NotFoundServiceEx ex) {
throw new NotFoundWebEx(ex.getMessage());
}
}
}
|
// $Id: wc.java,v 1.2 2001/05/31 22:56:19 doug Exp $
// http://www.bagley.org/~doug/shootout/
// with help from Dirus@programmer.net
package com.harris.mobihoc;
import java.io.*;
import java.util.*;
import java.text.*;
// this program modified from:
// http://cm.bell-labs.com/cm/cs/who/bwk/interps/pap.html
// Timing Trials, or, the Trials of Timing: Experiments with Scripting
// and User-Interface Languages</a> by Brian W. Kernighan and
// Christopher J. Van Wyk.
public class wc implements Runnable{
private boolean contin = false;
private int n = 10;
public wc(boolean contin, int n){
this.contin = contin;
this.n = n;
}
@Override
public void run(){
int nl = 0, nw = 0, nc = 0;
try {
byte[] buff = new byte[4096];
boolean inword = false;
int length;
while ((length = System.in.read(buff)) != -1) {
nc += length;
for(int i = 0; i < length; i++) {
char c = (char)buff[i];
if (c == '\n')
++nl;
if (Character.isWhitespace(c))
inword = false;
else if (inword == false) {
++nw;
inword = true;
}
}
}
} catch (IOException e) {
System.err.println(e);
return;
}
System.out.println(Integer.toString(nl) + " " +
Integer.toString(nw) + " " +
Integer.toString(nc));
}
}
|
package com.example.mayank.rock_paper_scissor;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
public class Logout extends AppCompatActivity {
TextView tv;
Button button4;
DatabaseHelper db;
private Session session;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
button4=(Button)findViewById(R.id.button4);
tv=(TextView) findViewById(R.id.tv);
db= new DatabaseHelper(this);
String str="";
File file=getFilesDir();
try{
FileInputStream fis=openFileInput("pvg.txt");
BufferedReader bfr=new BufferedReader(new InputStreamReader(fis));
do{
String t=bfr.readLine();
if(t==null)
break;
str+=t;
}while(true);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
// Intent i=getIntent();
// String email=i.getStringExtra("mail");
String name=db.getall(str);
tv.setText("Good Bye "+name);
session=new Session(this);
if(!session.loggedin())
{
logout();
}
button4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
logout();
}
});
}
private void logout()
{
session.setLoggedin(false);
finish();
startActivity(new Intent(Logout.this,Login.class));
}
@Override
public void onBackPressed() {
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("EXIT").setMessage("Want to Exit ?").setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent i=new Intent(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}
}).setNegativeButton("No",null).show();
}
}
|
package com.wangyuelin.easybug.aop;
import org.objectweb.asm.Opcodes;
public class Util {
/**
* 判断访问标志是否有静态标志
* @param access
* @return
*/
public static boolean isStatic(int access) {
//STATIC 0x0008 修饰 方法和字段
return ((access & Opcodes.ACC_STATIC) != 0);
}
}
|
package cn.wolfcode.crm.mapper;
import cn.wolfcode.crm.domain.Salary;
import cn.wolfcode.crm.query.QueryObject;
import java.util.List;
public interface SalaryMapper {
int insert(Salary record);
List<Salary> selectForList(QueryObject qo);
int updateByPrimaryKey(Salary record);
}
|
package de.mufl.sandbox.osm.api.data;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import de.mufl.sandbox.geo.common.BoundingBox;
import de.mufl.sandbox.geo.common.Position;
/**
* SAX-Handler zum parsen des OSM-Datenformats
*
* @author Florian Müller
*/
public class OSMSAXHandler extends DefaultHandler {
/**
* Gefundene OSM-Daten
*/
private OSMData data = null;
/**
* Parser ist in einem Node
*/
private boolean isInNode = false;
/**
* Parser ist in einem Way
*/
private boolean isInWay = false;
/**
* Parser ist in einer Relation
*/
private boolean isInRelation = false;
/**
* Wurden OSM-Daten gefunden?
*/
private boolean isValid = false;
/**
* Zeischenspeicher für Nodes
*/
private Node tmp_node = null;
/**
* Zwischenspeicher für Ways
*/
private Way tmp_way = null;
/**
* Zwischenspeicher für Relationen
*/
private Relation tmp_relation = null;
/**
* @return gefundene OSM-Daten
*/
public OSMData getData(){
return data;
}
/**
* @return Enthält {@link OSMSAXHandler#getData()} gültige Werte
*/
public boolean isValid(){
return isValid;
}
/**
* @see DefaultHandler#startDocument()
*/
@Override
public void startDocument() throws SAXException {
data = new OSMData();
isInNode = false;
isInWay = false;
isInRelation = false;
isValid = false;
tmp_node = null;
tmp_way = null;
tmp_relation = null;
}
/**
* @see DefaultHandler#endDocument()
*/
@Override
public void endDocument() throws SAXException {
isValid = true;
}
/**
* @see DefaultHandler#startElement(String, String, String, Attributes)
*/
@Override
public void startElement(String uri, String name, String qName,
Attributes atts) throws SAXException {
// OSM Rootelement gefunden
if(qName.equals("osm")){
data.setVersion(atts.getValue("version"));
data.setGenerator(atts.getValue("generator"));
return;
}
// Bounding gefunden
if(qName.equals("bounds")){
try{
data.setBoundingBox(new BoundingBox(
new Position(
Double.parseDouble(atts.getValue("minlat")),
Double.parseDouble(atts.getValue("minlon"))),
new Position(
Double.parseDouble(atts.getValue("maxlat")),
Double.parseDouble(atts.getValue("maxlon")))));
}
catch(NumberFormatException ex){
ex.printStackTrace();
}
return;
}
// Node gefunden
if(qName.equals("node")){
tmp_node = new Node();
try{
tmp_node.setId(Integer.parseInt(atts.getValue("id")));
tmp_node.setPosition(new Position(
Double.parseDouble(atts.getValue("lat")),
Double.parseDouble(atts.getValue("lon"))));
}
catch(NumberFormatException ex){
ex.printStackTrace();
return;
}
isInNode = true;
return;
}
// Way gefunden
if(qName.equals("way")){
tmp_way = new Way();
try{
tmp_way.setId(Integer.parseInt(atts.getValue("id")));
}
catch(NumberFormatException ex){
ex.printStackTrace();
return;
}
isInWay = true;
return;
}
/**
* Relation gefunden
*/
if(qName.equals("relation")){
tmp_relation = new Relation();
try{
tmp_relation.setId(Integer.parseInt(atts.getValue("id")));
}
catch(NumberFormatException ex){
ex.printStackTrace();
return;
}
isInRelation = true;
}
// Node-Ref eines Ways gefunden
if(qName.equals("nd")){
try{
if(null != tmp_way)
tmp_way.addNode(Integer.parseInt(atts.getValue("ref")));
}
catch(NumberFormatException ex){
ex.printStackTrace();
}
return;
}
// Tag gefunden
if(qName.equals("tag")){
Tag tag = new Tag();
tag.setKey(atts.getValue("k"));
tag.setValue(atts.getValue("v"));
// Sind gerade in einem Node
if(isInNode && null != tmp_node)
tmp_node.addTag(tag);
// Sind gerade in einem Way
else if(isInWay && null != tmp_way )
tmp_way.addTag(tag);
// Sind gerae in einer Relation
else if(isInRelation && null != tmp_relation)
tmp_relation.addTag(tag);
return;
}
// Member einer Relation gefunden
if(qName.equals("member")){
Member member = new Member();
member.setType(atts.getValue("type"));
member.setRole(atts.getValue("role"));
try{
member.setRef(Integer.parseInt(atts.getValue("ref")));
}
catch(NumberFormatException ex){
ex.printStackTrace();
return;
}
tmp_relation.addMember(member);
}
}
/**
* @see DefaultHandler#endElement(String, String, String)
*/
@Override
public void endElement(String uri, String name, String qName)
throws SAXException {
// Ende eines Nodes gefunden
if(qName.equals("node") && isInNode){
if(null != tmp_node)
data.addNode(tmp_node);
isInNode = false;
return;
}
// Ende eines Ways gefunden
if(qName.equals("way") && isInWay){
if(null != tmp_way)
data.addWay(tmp_way);
isInWay = false;
return;
}
// Ende einer Relation gefunden
if(qName.equals("relation") && isInRelation){
if(null != tmp_relation)
data.addRealation(tmp_relation);
isInRelation = false;
}
}
}
|
package com.polaris.pay.logic.database;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import com.polaris.pay.logic.model.Record;
import java.util.List;
/**
* @Date 2021/2/24 21:10
* @Author toPolaris
* @Description 数据库操作接口
*/
@Dao
public interface RecordDao {
/**
* 向数据库中插入数据,存在则替换
* @param records 被插入的数据
*/
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertRecords(Record... records);
/**
* 以LiveData的形式返回所有记录
* @return LiveData<List<Record>>类型的数据
*/
@Query("select * from records order by id desc")
LiveData<List<Record>> queryAllRecordsLive();
/**
* 删除数据
* @param records 需要被删除的数据
*/
@Delete
void deleteRecord(Record... records);
}
|
package fr.clivana.lemansnews.utils.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import fr.clivana.lemansnews.utils.database.NomsSQL;
public class DatabaseLeMansNews extends SQLiteOpenHelper{
public DatabaseLeMansNews(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
// creation des tables
db.execSQL(NomsSQL.QUERY_CREATE_TABLE_ARTICLE);
db.execSQL(NomsSQL.QUERY_CREATE_TABLE_EVENEMENT);
db.execSQL(NomsSQL.QUERY_CREATE_TABLE_CATEGORIE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// if (oldVersion < newVersion){
//
// }
}
}
|
import java.util.*;
class Checksum{
public static void main(String args[]){
int section[48]={0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1};
int checksum[16]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int i;
int sum;
int carry=0;
for(i=0;i<16;i++){
sum=section[i]+section[i+16]+section[i+32]+carry;
switch(sum)
{
case 0:
checksum[i]=0;
carry=0;
case 1:
checksum[i]=1;
carry=0;
case 2:
checksum[i]=1;
carry=1;
}
}
for(i=0;i<16;i++)
{
System.out.print(checksum[i]);
}
}
}
|
package com.dev.jdbc;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MyFirstJDBC {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//step:1 load the driver
Driver div = new com.mysql.jdbc.Driver();
DriverManager.registerDriver(div);
System.out.println("Driver Loaded...");
//step:2 get the connection via driver
String url="jdbc:mysql://localhost:3306/caps_buggers?user=root&password=root";
conn = DriverManager.getConnection(url);
System.out.println("Connection Estd...");
//step:3 issue SQL query via connection
String query="select * from users_info";
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
System.out.println("Query issued and executed...");
System.out.println("--------------------------------------------------------");
//step: 4 process the result
while(rs.next())
{
System.out.println("user id is: "+rs.getInt(1));
System.out.println("username is: "+rs.getString("username"));
System.out.println("email id is: "+rs.getString("email"));
// System.out.println("password is: "+rs.getString("password"));
System.out.println("-------------------------------------------------------");
}
} catch (SQLException e) {
e.printStackTrace();
}
//step 5:close all JDBC objects
finally {
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt!=null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
|
package org.sankozi.rogueland.model;
import org.sankozi.rogueland.model.coords.Coords;
import org.sankozi.rogueland.model.coords.Dim;
import static com.google.common.base.Preconditions.checkState;
/**
*
* @author sankozi
*/
public final class Level {
private final Dim dim;
Tile[][] tiles;
public Level(int width, int height) {
this.dim = new Dim(width, height);
tiles = new Tile[width][];
for(int x =0; x<width; ++x){
tiles[x] = new Tile[height];
for(int y = 0; y < height; ++ y){
tiles[x][y] = new Tile();
}
}
}
/**
* Changing location of actor
* @param actor
* @param toCoords
*/
public void changeActorLocation(Actor actor, Coords toCoords){
Tile from = getTile(actor.getLocation());
Tile to = getTile(toCoords);
checkState(from.actor == actor, "invalid actor/level state [actor=%s]", actor.getLocation());
checkState(to.actor == null, "target location is not empty [target=%s]", toCoords);
to.actor = from.actor;
from.actor = null;
actor.setLocation(toCoords);
}
public boolean validActionLocation(Coords actionCoords) {
//location outside level
if(!dim.containsCoordinates(actionCoords)) {
return false;
} else {
//location inaccessible and that cannot be intercarted with
Tile tile = tiles[actionCoords.x][actionCoords.y];
return tile.type != Tile.Type.ROCK;
}
}
public Tile getTile(Coords p){
return tiles[p.x][p.y];
}
public Tile[][] getTiles(){
return tiles;
}
public Dim getDim(){
return dim;
}
}
|
package com.example.opilane.buttons;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MusicActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music);
}
//start music
public void play(View view) {
if (mediaPlayer == null)
mediaPlayer = MediaPlayer.create(this, R.raw.tsirkus);
mediaPlayer.start();
}
//pause music
public void pause(View view) {
mediaPlayer.pause();
}
//stop music
public void stop(View view) {
mediaPlayer.stop();
mediaPlayer = null;
}
}
|
package com.realestatemanager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
@Configuration
@PropertySource("classpath:properties/sqlquery.properties")
public class ResourceLoader {
@Autowired
Environment env;
public String getSql(String key)
{
return env.getProperty(key);
}
}
|
package lambdas;
public class CalculoTeste2 {
public static void main(String[] args) {
Calculo calculo = (x,y) -> { return x + y; };
Calculo calculo2 = (x,y) -> { return x * y; };
System.out.println(calculo.excecutar(2, 3));
System.out.println(calculo2.excecutar(2, 3));
}
}
|
import java.awt.Color;
public class Rectangle {
private double x, y, width, height;
Color color;
public Rectangle(double x, double y, double width, double height, Color color) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.color = color;
}
public double calculatePerimeter() {
return (2 * (width + height));
}
public double calculateArea() {
return width * height;
}
public void setColor(Color color) {
this.color = color;
}
public void setPos(double x, double y) {
this.x = x;
this.y = y;
}
public void setHeight(double height) {
this.height = height;
}
public void setWidth(double width) {
this.width = width;
}
public Color getColor() {
return this.color;
}
public double getXPos() {
return this.x;
}
public double getYPos() {
return this.y;
}
public double getHeight() {
return this.height;
}
public double getWidth() {
return this.width;
}
// public static void main(String[] args) {
// }
}
// Written by Matthew Vilaysack, vilay016
|
package de.raidcraft.skillsandeffects.pvp.skills.magical;
import com.sk89q.minecraft.util.commands.CommandContext;
import de.raidcraft.skills.api.character.CharacterTemplate;
import de.raidcraft.skills.api.combat.EffectType;
import de.raidcraft.skills.api.effect.Effect;
import de.raidcraft.skills.api.exceptions.CombatException;
import de.raidcraft.skills.api.hero.Hero;
import de.raidcraft.skills.api.persistance.SkillProperties;
import de.raidcraft.skills.api.profession.Profession;
import de.raidcraft.skills.api.skill.AbstractSkill;
import de.raidcraft.skills.api.skill.SkillInformation;
import de.raidcraft.skills.api.trigger.CommandTriggered;
import de.raidcraft.skills.tables.THeroSkill;
import de.raidcraft.skills.util.ConfigUtil;
import org.bukkit.configuration.ConfigurationSection;
/**
* @author Silthus
*/
@SkillInformation(
name = "Remove Effects",
description = "Removes harmfull effects from the target."
)
public class RemoveEffects extends AbstractSkill implements CommandTriggered {
private boolean harmfull;
private boolean helpfull;
private boolean self;
private ConfigurationSection amount;
public RemoveEffects(Hero hero, SkillProperties data, Profession profession, THeroSkill database) {
super(hero, data, profession, database);
}
@Override
public void load(ConfigurationSection data) {
harmfull = data.getBoolean("harmfull", true);
helpfull = data.getBoolean("helpfull", false);
self = data.getBoolean("self", false);
amount = data.getConfigurationSection("amount");
}
@Override
public void runCommand(CommandContext args) throws CombatException {
CharacterTemplate target = getTarget(args, !helpfull && harmfull, self);
int amount = getAmount();
int removedEffects = 0;
if (helpfull) {
for (Effect effect : target.getEffects(EffectType.HELPFUL, EffectType.PURGEABLE)) {
if (removedEffects >= amount) {
break;
}
target.removeEffect(effect);
removedEffects++;
}
}
if (harmfull) {
for (Effect effect : target.getEffects(EffectType.HARMFUL, EffectType.PURGEABLE)) {
if (removedEffects >= amount) {
break;
}
target.removeEffect(effect);
removedEffects++;
}
}
}
public int getAmount() {
return (int) ConfigUtil.getTotalValue(this, amount);
}
}
|
package pluralsight.airportman.queries;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import pluralsight.airportman.domain.FlightInfo;
import pluralsight.airportman.domain.FlightType;
import java.util.List;
@Service
public class FlightInfoQuery {
private MongoTemplate mongoTemplate;
public FlightInfoQuery(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
public long countAll() {
return this.mongoTemplate.count(new Query(), FlightInfo.class);
}
// 1. Find all flight with paging and sorting
public List<FlightInfo> findAll(String filed, int pageNumber, int pageSize) {
Query allPageAndOrdered = new Query()
.with(Sort.by(Direction.DESC, filed))
.with(PageRequest.of(pageNumber, pageSize));
return this.mongoTemplate.find(allPageAndOrdered, FlightInfo.class);
}
// 2. Find the flight by ID
public FlightInfo findById(String id) {
return this.mongoTemplate.findById(id, FlightInfo.class);
}
// 3. Count all international flights
public long countInternationalFlights() {
Query findInternationalFlight = Query.query(Criteria.where("type")
.is(FlightType.INTERNATIONAL));
return this.mongoTemplate.count(findInternationalFlight, FlightInfo.class);
}
// 4. Find all flight by departure city
public List<FlightInfo> findByDepartureCity(String departure) {
Query findInternationalFlight = Query.query(
Criteria.where("departure").is(departure));
return this.mongoTemplate.find(findInternationalFlight, FlightInfo.class);
}
// 5. Find all flight by duration between min and max
public List<FlightInfo> findByDurationBetween(int durationMin, int durationMax) {
Query findDurationBetween = Query.query(
Criteria.where("durationMin")
.gte(durationMin)
.lte(durationMax))
.with(Sort.by(Direction.DESC, "durationMin"));
return this.mongoTemplate.find(findDurationBetween, FlightInfo.class);
}
// 6. Find all flight delayed at a particular departure city
public List<FlightInfo> findDelayedByDeparture(String departure) {
Query findDelayByDeparture = Query.query(Criteria
.where("departure").is(departure)
.and("isDelayed").is(true));
return this.mongoTemplate.find(findDelayByDeparture, FlightInfo.class);
}
// 7. Find all flight that are on time and relate to a city
public List<FlightInfo> findNotDelayedByCity(String city) {
Query findNotDelayedAndRelateToCity = Query.query(
new Criteria()
.orOperator(
Criteria.where("departure").is(city),
Criteria.where("destination").is(city))
.andOperator(Criteria.where("isDelayed").is(false)));
return this.mongoTemplate.find(findNotDelayedAndRelateToCity, FlightInfo.class);
}
// 8. Find by aircraft model
public List<FlightInfo> findByAircraftModel(String code) {
Query findByAircraftModel = Query.query(Criteria
.where("aircraft.code").is(code));
return this.mongoTemplate.find(findByAircraftModel, FlightInfo.class);
}
}
|
package com.allisonmcentire.buildingtradesandroid;
/**
* Created by allisonmcentire on 12/6/17.
*/
public class Video {
public String name;
public String field_media_video_embed_field;
public Video() {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public Video(String name, String field_media_video_embed_field) {
this.name = name;
this.field_media_video_embed_field = field_media_video_embed_field;
}
}
|
package com.hservice.grpc.client;
import com.hservice.grpc.client.GrpcClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GrpcClientController {
@Autowired
private GrpcClientService grpcClientService;
@RequestMapping("/")
public String printMessage(@RequestParam(defaultValue = "Zhang,Xiaonan") String name) {
return grpcClientService.sendMessage(name);
}
}
|
package com.duanxr.yith.midium;
/**
* @author 段然 2021/3/10
*/
public class ProductOfTheLastKNumbers {
/**
* Implement the class ProductOfNumbers that supports two methods:
*
* 1. add(int num)
*
* Adds the number num to the back of the current list of numbers.
* 2. getProduct(int k)
*
* Returns the product of the last k numbers in the current list.
* You can assume that always the current list has at least k numbers.
* At any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing.
*
*
*
* Example:
*
* Input
* ["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"]
* [[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]
*
* Output
* [null,null,null,null,null,null,20,40,0,null,32]
*
* Explanation
* ProductOfNumbers productOfNumbers = new ProductOfNumbers();
* productOfNumbers.add(3); // [3]
* productOfNumbers.add(0); // [3,0]
* productOfNumbers.add(2); // [3,0,2]
* productOfNumbers.add(5); // [3,0,2,5]
* productOfNumbers.add(4); // [3,0,2,5,4]
* productOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 * 4 = 20
* productOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 * 5 * 4 = 40
* productOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 * 2 * 5 * 4 = 0
* productOfNumbers.add(8); // [3,0,2,5,4,8]
* productOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 * 8 = 32
*
*
* Constraints:
*
* There will be at most 40000 operations considering both add and getProduct.
* 0 <= num <= 100
* 1 <= k <= 40000
*
* 请你实现一个「数字乘积类」ProductOfNumbers,要求支持下述两种方法:
*
* 1. add(int num)
*
* 将数字 num 添加到当前数字列表的最后面。
* 2. getProduct(int k)
*
* 返回当前数字列表中,最后 k 个数字的乘积。
* 你可以假设当前列表中始终 至少 包含 k 个数字。
* 题目数据保证:任何时候,任一连续数字序列的乘积都在 32-bit 整数范围内,不会溢出。
*
*
*
* 示例:
*
* 输入:
* ["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"]
* [[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]
*
* 输出:
* [null,null,null,null,null,null,20,40,0,null,32]
*
* 解释:
* ProductOfNumbers productOfNumbers = new ProductOfNumbers();
* productOfNumbers.add(3); // [3]
* productOfNumbers.add(0); // [3,0]
* productOfNumbers.add(2); // [3,0,2]
* productOfNumbers.add(5); // [3,0,2,5]
* productOfNumbers.add(4); // [3,0,2,5,4]
* productOfNumbers.getProduct(2); // 返回 20 。最后 2 个数字的乘积是 5 * 4 = 20
* productOfNumbers.getProduct(3); // 返回 40 。最后 3 个数字的乘积是 2 * 5 * 4 = 40
* productOfNumbers.getProduct(4); // 返回 0 。最后 4 个数字的乘积是 0 * 2 * 5 * 4 = 0
* productOfNumbers.add(8); // [3,0,2,5,4,8]
* productOfNumbers.getProduct(2); // 返回 32 。最后 2 个数字的乘积是 4 * 8 = 32
*
*
* 提示:
*
* add 和 getProduct 两种操作加起来总共不会超过 40000 次。
* 0 <= num <= 100
* 1 <= k <= 40000
*/
class ProductOfNumbers {
int start = 0;
int end = 0;
int[] nums = new int[40000];
public ProductOfNumbers() {
}
public void add(int num) {
end++;
if (num == 0) {
start = end;
} else if (num == 1) {
nums[end] = num;
} else {
nums[end] = num;
for (int i = start + 1; i < end; i++) {
nums[i] = nums[i] * num;
}
}
}
public int getProduct(int k) {
return end - k < start ? 0 : nums[end - k + 1];
}
}
class ProductOfNumbers1 {
int baseNum = 0;
int[] nums = new int[0];
public ProductOfNumbers1() {
}
public void add(int num) {
if (num == 0) {
nums = new int[0];
} else {
int[] nnums = new int[nums.length + 1];
for (int i = 0; i < nums.length; i++) {
nnums[i] = nums[i] * num;
}
nnums[nums.length] = num;
nums = nnums;
}
}
public int getProduct(int k) {
return k > nums.length ? 0 : nums[nums.length - k];
}
}
}
|
package com.android.vending.expansion.zipfile;
import android.content.res.AssetFileDescriptor;
import android.os.ParcelFileDescriptor;
import java.io.EOFException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.zip.ZipFile;
public final class b {
public HashMap<File, ZipFile> a = new HashMap<File, ZipFile>();
ByteBuffer b = ByteBuffer.allocate(4);
private HashMap<String, a> c = new HashMap<String, a>();
public b(String paramString) throws IOException {
b(paramString);
}
private static int a(RandomAccessFile paramRandomAccessFile) throws EOFException, IOException {
int i = paramRandomAccessFile.readInt();
return ((i & 0xFF) << 24) + ((0xFF00 & i) << 8) + ((0xFF0000 & i) >>> 8) + (i >>> 24 & 0xFF);
}
public final AssetFileDescriptor a(String paramString) {
a a = this.c.get(paramString);
return (a != null) ? a.a() : null;
}
final void b(String paramString) throws IOException {
File file = new File(paramString);
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
long l = randomAccessFile.length();
if (l >= 22L) {
long l1 = 65557L;
if (65557L > l)
l1 = l;
randomAccessFile.seek(0L);
int i = a(randomAccessFile);
if (i != 101010256) {
if (i == 67324752) {
randomAccessFile.seek(l - l1);
ByteBuffer byteBuffer = ByteBuffer.allocate((int)l1);
byte[] arrayOfByte = byteBuffer.array();
randomAccessFile.readFully(arrayOfByte);
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
for (i = arrayOfByte.length - 22; i >= 0 && (arrayOfByte[i] != 80 || byteBuffer.getInt(i) != 101010256); i--);
short s = byteBuffer.getShort(i + 8);
l1 = byteBuffer.getInt(i + 12) & 0xFFFFFFFFL;
long l2 = byteBuffer.getInt(i + 16) & 0xFFFFFFFFL;
if (l2 + l1 <= l) {
if (s != 0) {
MappedByteBuffer mappedByteBuffer = randomAccessFile.getChannel().map(FileChannel.MapMode.READ_ONLY, l2, l1);
mappedByteBuffer.order(ByteOrder.LITTLE_ENDIAN);
byte[] arrayOfByte1 = new byte[65535];
ByteBuffer byteBuffer1 = ByteBuffer.allocate(30);
byteBuffer1.order(ByteOrder.LITTLE_ENDIAN);
i = 0;
int j = 0;
while (i < s) {
if (mappedByteBuffer.getInt(j) == 33639248) {
int k = mappedByteBuffer.getShort(j + 28) & 0xFFFF;
short s1 = mappedByteBuffer.getShort(j + 30);
short s2 = mappedByteBuffer.getShort(j + 32);
mappedByteBuffer.position(j + 46);
mappedByteBuffer.get(arrayOfByte1, 0, k);
mappedByteBuffer.position(0);
String str = new String(arrayOfByte1, 0, k);
a a = new a(paramString, file, str);
a.e = mappedByteBuffer.getShort(j + 10) & 0xFFFF;
a.f = mappedByteBuffer.getInt(j + 12) & 0xFFFFFFFFL;
a.g = mappedByteBuffer.getLong(j + 16) & 0xFFFFFFFFL;
a.h = mappedByteBuffer.getLong(j + 20) & 0xFFFFFFFFL;
a.i = mappedByteBuffer.getLong(j + 24) & 0xFFFFFFFFL;
a.d = mappedByteBuffer.getInt(j + 42) & 0xFFFFFFFFL;
byteBuffer1.clear();
a.a(randomAccessFile, byteBuffer1);
this.c.put(str, a);
j += k + 46 + (s1 & 0xFFFF) + (s2 & 0xFFFF);
i++;
continue;
}
throw new IOException();
}
return;
}
throw new IOException();
}
throw new IOException();
}
throw new IOException();
}
throw new IOException();
}
IOException iOException = new IOException();
throw iOException;
}
public static final class a {
public final File a;
public final String b;
public final String c;
public long d;
public int e;
public long f;
public long g;
public long h;
public long i;
public long j = -1L;
public a(String param1String1, File param1File, String param1String2) {
this.b = param1String2;
this.c = param1String1;
this.a = param1File;
}
public final AssetFileDescriptor a() {
if (this.e == 0)
try {
return new AssetFileDescriptor(ParcelFileDescriptor.open(this.a, 268435456), this.j, this.i);
} catch (FileNotFoundException fileNotFoundException) {
fileNotFoundException.printStackTrace();
}
return null;
}
public final void a(RandomAccessFile param1RandomAccessFile, ByteBuffer param1ByteBuffer) throws IOException {
long l = this.d;
try {
param1RandomAccessFile.seek(l);
param1RandomAccessFile.readFully(param1ByteBuffer.array());
if (param1ByteBuffer.getInt(0) == 67324752) {
short s1 = param1ByteBuffer.getShort(26);
short s2 = param1ByteBuffer.getShort(28);
this.j = l + 30L + (s1 & 0xFFFF) + (s2 & 0xFFFF);
return;
}
throw new IOException();
} catch (FileNotFoundException fileNotFoundException) {
fileNotFoundException.printStackTrace();
return;
} catch (IOException iOException) {
iOException.printStackTrace();
return;
}
}
}
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\android\vending\expansion\zipfile\b.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package com.tencent.mm.plugin.luckymoney.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import com.tencent.mm.sdk.platformtools.x;
class LuckyMoneyNewYearSendUI$2 implements OnCancelListener {
final /* synthetic */ LuckyMoneyNewYearSendUI kWx;
LuckyMoneyNewYearSendUI$2(LuckyMoneyNewYearSendUI luckyMoneyNewYearSendUI) {
this.kWx = luckyMoneyNewYearSendUI;
}
public final void onCancel(DialogInterface dialogInterface) {
if (LuckyMoneyNewYearSendUI.k(this.kWx) != null && LuckyMoneyNewYearSendUI.k(this.kWx).isShowing()) {
LuckyMoneyNewYearSendUI.k(this.kWx).hide();
}
if (LuckyMoneyNewYearSendUI.q(this.kWx).getVisibility() == 8 || LuckyMoneyNewYearSendUI.r(this.kWx).getVisibility() == 4) {
x.i("MicroMsg.LuckyMoneyNewYearSendUI", "usr cancel, & visibility not visiable, so finish");
this.kWx.finish();
}
this.kWx.kUg.baT();
}
}
|
package com.yjjyjy.yjj.controller;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;
import com.yjjyjy.yjj.common.config.AppConfig;
import com.yjjyjy.yjj.common.utils.ResponseUtil;
import com.yjjyjy.yjj.entity.User;
import com.yjjyjy.yjj.repository.UserRepository;
import com.yjjyjy.yjj.service.impl.UserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
/***
* Description: 用户模块<br/>
* Copyright: Copyright (c) 2018- <br/>
* Date:2018-05-21
* @author dongyujun
* @version v1
*
*/
@RestController
@RequestMapping(value="/user")
@Api("用户模块")
public class UserController {
@Autowired
private UserServiceImpl userServiceImpl;
@Autowired
private AppConfig appConfig;
@RequestMapping(value = "/managelist",method = RequestMethod.GET)
@ApiOperation(value = "分页查询", notes = "根据pageNumber和pageSize")
@ResponseBody
public String getList(HttpServletRequest request,HttpServletResponse response,
@RequestParam("pageNumber") int pageNumber,
@RequestParam("pageSize") int pageSize)
{
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT");
// int pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
// int pageSize = Integer.parseInt(request.getParameter("pageSize"));
@SuppressWarnings("deprecation")
// Pageable pageRequest = new PageRequest(pageNumber-1,pageSize);
Sort sort = new Sort(Direction.DESC,"regTime");
Page<User> userList = userServiceImpl.getUserList(new PageRequest(pageNumber-1,pageSize,sort));
// return ResponseUtil.responseFindResult(postList);
//// return newsList;
String total = "" + userList.getTotalElements();
String result = "{\"total\":" + total +",\"rows\":"+JSON.toJSONString(userList.getContent()) +"}";
return result;
}
@RequestMapping(value = "/modify/{id:.+}",method = RequestMethod.POST)
@ApiOperation(value = "修改用户", notes = "修改用户信息")
@ResponseBody
public Map<String, Object> modifyUser(HttpServletRequest request,HttpServletResponse response,@PathVariable final long id,
@RequestParam("cellphone") String cellphone,
@RequestParam("email") String email,
@RequestParam("nickname") String nickname,
@RequestParam("userno") String userno,
@RequestParam("password") String password,
@RequestParam("usertype") long userType,
@RequestParam("sex") String sex)
{
//解决跨域问题出
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT");
// Long id = Long.parseLong(request.getParameter("id"));
// String cellphone = request.getParameter("cellphone");
// String email = request.getParameter("email");
// String nickname = request.getParameter("nickname");
// String userno = request.getParameter("userno");
// String password = request.getParameter("password");
// Long userType= Long.parseLong(request.getParameter("usertype"));
// String sex = request.getParameter("sex");
User existuser = userServiceImpl.findOne(id);
if(existuser == null){
return ResponseUtil.responseResultByBoolean(false);
}
else{
existuser.setCellphone(cellphone);
existuser.setEmail(email);
existuser.setNickname(nickname);
existuser.setUserNo(userno);
existuser.setPassword(password);
existuser.setType_id(userType);
existuser.setSex(sex);
return ResponseUtil.responseResultByBoolean(userServiceImpl.modifyUser(existuser));
}
}
/**
*
* @param id
* @return
*/
@RequestMapping(value = "/reset",method = RequestMethod.POST)
@ApiOperation(value = "修改用户密码", notes = "修改用户信息")
@ResponseBody
public Map<String, Object> resetPassword(HttpServletRequest request,HttpServletResponse response,
@RequestParam("cellphone") String cellphone,@RequestParam("password") String password)
{
//解决跨域问题出
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT");
// String cellphone = request.getParameter("cellphone");
// String password = request.getParameter("password");
return ResponseUtil.responseResultByBoolean(userServiceImpl.resetPwd(cellphone, password));
}
/**
*
* @param id
* @return
*/
@RequestMapping(value = "/delete/{id}",method = RequestMethod.DELETE)
@ApiOperation(value = "删除", notes = "")
@ResponseBody
public String deleteUser(@ApiParam(name = "id", value = "用户序号", required = true)@PathVariable("id") Long id){
int flag = userServiceImpl.deleteUserById(id);
String result = "{\"flag\":" + Integer.toString(flag) +"}";
return result;
}
/**
* 根据id返回语录内容
* @param id
* @param response
* @return
*/
@RequestMapping(value = "/{cellphone}",method = RequestMethod.GET)
@ApiOperation(value = "获取用户信息", notes = "")
@ResponseBody
public Map<String,Object> getPost(@ApiParam(name = "cellphone", value = "用户手机号", required = true)@PathVariable("cellphone") String cellphone,
HttpServletResponse response)
{
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT");
return ResponseUtil.responseFindResult(userServiceImpl.findUserByCellphone(cellphone));
}
}
|
// Sun Certified Java Programmer
// Chapter 4, P295_2
// Operators
class B extends A {
public static void main(String[] args) {
A myA = new B();
m2(myA);
A myA2 = new A();
m2(myA2);
}
public static void m2(A a) {
if (a instanceof B)
((B) a).doBStuff(); // downcasting an A reference
// to a B reference
if (a instanceof A)
doAStuff();
}
public static void doBStuff() {
System.out.println("'a' refers to a B");
System.out.println("1");
}
public static void doAStuff() {
System.out.println("'a' refers to an A");
System.out.println("2");
}
}
|
package programmers;
import java.util.Arrays;
import java.util.Comparator;
public class StringDesc {
public static void main(String[] args) {
System.out.println(solution("Zbcdefg"));
}
public static String solution(String s) {
String[] arr = s.split("");
Arrays.sort(arr, new Comparator<String>(){
@Override
public int compare(String o1, String o2) {
return o2.charAt(0)-o1.charAt(0);
}
});
StringBuilder sb = new StringBuilder();
for(String p : arr){
sb.append(p);
}
return sb.toString();
}
}
|
package pt.ist.sonet.service;
import pt.ist.fenixframework.FenixFramework;
import pt.ist.largacaixa.InexistentBoxContentException;
import pt.ist.largacaixa.InexistentBoxException;
import pt.ist.largacaixa.LargaCaixa;
import pt.ist.largacaixa.PaymentProofRejectedException;
import pt.ist.sonet.domain.Agent;
import pt.ist.sonet.domain.Sonet;
import pt.ist.sonet.service.dto.AgentDto;
public class BuyContentService extends SonetService {
private AgentDto buyer;
private AgentDto seller;
private String contentId;
private String paymentProof;
public BuyContentService(AgentDto buyer, AgentDto seller, String contentId,
String paymentProof) {
this.buyer = buyer;
this.seller = seller;
this.contentId = contentId;
this.paymentProof = paymentProof;
}
public final void dispatch(){
Sonet sonet = FenixFramework.getRoot();
LargaCaixa largacaixa = sonet.getLargaCaixa();
Agent buyer = sonet.getAgentByUsername(this.buyer.getUsername());
Agent seller = sonet.getAgentByUsername(this.seller.getUsername());
try{
largacaixa.shareContent(this.contentId, seller.getUsername(), buyer.getUsername(), this.paymentProof);
} catch (InexistentBoxException e) {
System.out.println("Couldn't transfer content: " +
"no such user " + e.getInexistentUsername());
} catch (InexistentBoxContentException e) {
System.out.println("Couldn't transfer content: " +
"no such content " + e.getInexistentID());
} catch (PaymentProofRejectedException e) {
System.out.println("Couldn't transfer content: " +
"invalid payment proof");
}
}
}
|
package Marketing.Wrapping.Converter;
import Manufacturing.CanEntity.Can;
import Marketing.Wrapping.WrappingCanInfo;
import java.util.function.Function;
/**
* 转换器模式
*
* @Author 王立友
* 读取Can内容转换到WrappingCanInfo.
*/
public class WrappingConverter {
private Function<Can, WrappingCanInfo> fromCanEntityFunction;
public WrappingConverter() {
fromCanEntityFunction = new FromCanEntityFunction();
}
public Function<Can, WrappingCanInfo> getFromCanEntityFunction() {
return fromCanEntityFunction;
}
static class FromCanEntityFunction implements Function<Can, WrappingCanInfo> {
/**
* 转换器模式,将罐头实例转化为包装罐头信息.
*
* @param can : 罐头
* @return : Marketing.Wrapping.WrappingCanInfo 包装罐头信息
* @author "王立友"
* @date 2021-10-24 11:18
*/
@Override
public WrappingCanInfo apply(Can can) {
WrappingCanInfo wrappingCanInfo = new WrappingCanInfo();
wrappingCanInfo.setCanName(can.getCanName());
wrappingCanInfo.setIngredients(can.getIngredients());
wrappingCanInfo.setSize(can.getSize().getSize());
wrappingCanInfo.setManufactureTime(can.getManufactureTime());
wrappingCanInfo.setShelfTime(can.getShelfTime());
return wrappingCanInfo;
}
}
}
|
package com.liwei.activity;
import io.rong.imkit.fragment.ConversationFragment;
import io.rong.imlib.model.Conversation;
import java.util.Locale;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import com.liwei.application.MyApplation;
import com.liwei.teachsystem.R;
public class ConversationActivity extends FragmentActivity{
/**
* 目标 Id
*/
private String mTargetId;
/**
* 刚刚创建完讨论组后获得讨论组的id 为targetIds,需要根据 为targetIds 获取 targetId
*/
private String mTargetIds;
/**
* 会话类型
*/
private Conversation.ConversationType mConversationType;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.conversation);
MyApplation.setActivity(this);
ImageView close=(ImageView)findViewById(R.id.bjmgf_sdk_closeAboutBtnId);
/**
* 返回按钮
*/
close.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
Intent intent = getIntent();
getIntentDate(intent);
}
/**
* 展示如何从 Intent 中得到 融云会话页面传递的 Uri
*/
private void getIntentDate(Intent intent) {
mTargetId = intent.getData().getQueryParameter("targetId");
mTargetIds = intent.getData().getQueryParameter("targetIds");
//intent.getData().getLastPathSegment();//获得当前会话类型
mConversationType = Conversation.ConversationType.valueOf(intent.getData().getLastPathSegment().toUpperCase(Locale.getDefault()));
enterFragment(mConversationType, mTargetId);
}
/**
* 加载会话页面 ConversationFragment
*
* @param mConversationType 会话类型
* @param mTargetId 目标 Id
*/
private void enterFragment(Conversation.ConversationType mConversationType, String mTargetId) {
ConversationFragment fragment = (ConversationFragment) getSupportFragmentManager().findFragmentById(R.id.conversation);
Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon()
.appendPath("conversation").appendPath(mConversationType.getName().toLowerCase())
.appendQueryParameter("targetId", mTargetId).build();
fragment.setUri(uri);
}
}
|
package cn.timebusker.service.user;
public interface UserInfoService {
String addUserInfo(String name) throws IllegalArgumentException;
}
|
package meaningfulname.disinformation;
import java.util.List;
public class Example1 {
//it is very bad because it references to unix system
private String hp, aix, sco;chrome
//it is bad.The word list means something specific to programmers
private List<String> accountList;
//it is better
private List<String> accountGroup,accounts,groupofAccount ;
}
|
package diary.src;
// import javax.swing.*;
import java.awt.*;
import java.util.Calendar;
public class OperateWindow {
// 今日の日付を取得
// メイン画面
public void CreateDiaryWindow() {
// ウィンドウ設定
final String window_title = Setting.window_title; // タイトル
final int window_width = Setting.window_width; // 高さ
final int window_height = Setting.window_height; // 幅
final DiaryWindow diary_window = new DiaryWindow(window_title, window_width, window_height);
// 初期日付設定
diary_window.setNowDate(String.valueOf(Calendar.getInstance().get(Calendar.YEAR)),
String.valueOf(Calendar.getInstance().get(Calendar.MONTH) + 1),
String.valueOf(Calendar.getInstance().get(Calendar.DAY_OF_MONTH)));
diary_window.setImageIcon(Setting.icon_path); // アイコンを設定
diary_window.setBackground(Color.RED); // 背景設定 ×
diary_window.setTextWindow(); // ウィンドウにテキストを表示
diary_window.setButtonWindow(); // ウィンドウにボタンを表示
diary_window.setVisible(); // 最後にウィンドウを表示
}
}
|
package org.simpleflatmapper.reflect;
public interface IndexedSetterFactory<T, A> {
<P> IndexedSetter<T, P> getIndexedSetter(A arg);
}
|
package com.omnicuris.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.omnicuris.dto.OrderDto;
import com.omnicuris.dto.ProductDto;
import com.omnicuris.entities.Order;
import com.omnicuris.entities.Product;
import com.omnicuris.repository.OrderRepository;
import com.omnicuris.repository.ProductRepository;
@Service
public class OrderProductsServiceImpl implements OrderProductsService {
@Autowired
OrderRepository orderRepository;
@Autowired
ProductRepository productRepository;
@Override
public void addItems(OrderDto orderDto) {
try {
Order order = new Order();
Product product = null;
order.setCustomerNo(orderDto.getCustomerNo());
order.setOrderDate(orderDto.getOrderDate());
// iterating over the products items
for (ProductDto productDto : orderDto.getProducts()) {
product = new Product();
product.setName(productDto.getName());
product.setDescription(productDto.getDescription());
product.setPrice(productDto.getPrice());
product.setQuantity(productDto.getQuantity());
product.setProductNo(productDto.getProductNo());
product.setOrder(order);
order.addProduct(product);
}
orderRepository.save(order);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public OrderDto getOrder(int orderId) {
OrderDto orderDto = null;
List<ProductDto> productList = null;
try {
Order order = orderRepository.findByOrderId(orderId);
if (order != null) {
orderDto=new OrderDto();
productList = new ArrayList<>();
ProductDto productDto = null;
for (Product product : order.getProductItems()) {
productDto = new ProductDto();
productDto.setName(product.getName());
productDto.setDescription(product.getDescription());
productDto.setPrice(product.getPrice());
productDto.setQuantity(product.getQuantity());
productDto.setProductNo(product.getProductNo());
productList.add(productDto);
}
orderDto.setProducts(productList);
orderDto.setCustomerNo(order.getCustomerNo());
orderDto.setOrderDate(order.getOrderDate());
return orderDto;
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
|
package gil.action;
import bol.BOLObject;
import gil.MainFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ButNextStep implements ActionListener {
private BOLObject obj;
private MainFrame frame;
public ButNextStep(BOLObject obj, MainFrame frame) {
this.obj = obj;
this.frame = frame;
}
@Override
public void actionPerformed(ActionEvent e) {
if (obj.getStep().getRemainingTime() != 0) {
this.obj.getStep().nextStep(obj, frame);
}
}
}
|
package com.tencent.mm.plugin.appbrand.h;
import com.tencent.mm.modelappbrand.i;
import com.tencent.mm.modelappbrand.i.a;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.y.a.b;
import com.tencent.mm.y.a.c;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public final class e implements i {
private static Map<String, Object> gjZ = new HashMap();
private static Map<String, List<a>> gka = new HashMap();
public final b jm(String str) {
c abe = com.tencent.mm.plugin.appbrand.app.e.abe();
int hashCode = str.hashCode();
b bVar = new b();
bVar.field_shareKeyHash = hashCode;
if (!abe.b(bVar, new String[]{"shareKeyHash"})) {
x.e("MicroMsg.WxaUpdateableMsgStorage", "WxaUpdateableMsg is null");
bVar = null;
}
if (bVar == null) {
x.e("MicroMsg.WxaUpdateableMsgService", "shareKey:%s, shareKeyHash:%d, wxaUpdateableMsg is null", new Object[]{str, Integer.valueOf(str.hashCode())});
return null;
}
x.d("MicroMsg.WxaUpdateableMsgService", "shareKey:%s, shareKeyHash:%d status:%s", new Object[]{str, Integer.valueOf(str.hashCode()), Integer.valueOf(bVar.field_btnState)});
return bVar;
}
public final boolean I(String str, int i) {
boolean z;
c abe = com.tencent.mm.plugin.appbrand.app.e.abe();
if (bi.oW(str)) {
x.e("MicroMsg.WxaUpdateableMsgStorage", "shareKey is null, err");
z = false;
} else {
b bVar = new b();
bVar.field_shareKeyHash = str.hashCode();
boolean b = abe.b(bVar, new String[0]);
bVar.field_btnState = i;
z = b ? abe.c(bVar, new String[0]) : abe.b(bVar);
}
x.d("MicroMsg.WxaUpdateableMsgService", "shareKey:%s, shareKeyHash:%d, btnState:%d isOk:%b", new Object[]{str, Integer.valueOf(str.hashCode()), Integer.valueOf(i), Boolean.valueOf(z)});
if (z) {
gjZ.get(str);
}
return z;
}
public final boolean a(String str, String str2, String str3, int i, int i2) {
boolean z;
c abe = com.tencent.mm.plugin.appbrand.app.e.abe();
if (bi.oW(str)) {
x.e("MicroMsg.WxaUpdateableMsgStorage", "shareKey is null, err");
z = false;
} else {
b bVar = new b();
bVar.field_shareKeyHash = str.hashCode();
boolean b = abe.b(bVar, new String[0]);
bVar.field_updatePeroid = i;
bVar.field_msgState = i2;
bVar.field_content = str2;
bVar.field_contentColor = str3;
z = b ? abe.c(bVar, new String[0]) : abe.b(bVar);
}
x.d("MicroMsg.WxaUpdateableMsgService", "shareKey:%s, shareKeyHash:%d, content:%s contentColor:%s isOk:%b", new Object[]{str, Integer.valueOf(str.hashCode()), str2, str3, Boolean.valueOf(z)});
return z;
}
public final synchronized void a(String str, String str2, String str3, int i, a aVar) {
if (bi.oW(str) || bi.oW(str2) || bi.oW(str3)) {
x.e("MicroMsg.WxaUpdateableMsgService", "token appId or shareKey is null, return");
} else {
List list = (List) gka.get(str);
if (list == null) {
x.i("MicroMsg.WxaUpdateableMsgService", "addOnUpdatbleMsgInfoChange token:%s", new Object[]{str});
list = new ArrayList();
gka.put(str, list);
}
x.i("MicroMsg.WxaUpdateableMsgService", "addOnUpdatbleMsgInfoChange shareKeyHash:%d", new Object[]{Integer.valueOf(str3.hashCode())});
x.d("MicroMsg.WxaUpdateableMsgService", "addOnUpdatbleMsgInfoChange shareKey:%s", new Object[]{str3});
a aVar2 = new a((byte) 0);
aVar2.appId = str2;
aVar2.dzR = str3;
aVar2.gkb = i;
aVar2.gkc = aVar;
if (bi.oW(aVar2.appId) || bi.oW(aVar2.dzR)) {
x.w("MicroMsg.WxaUpdateableMsgService", "appId or shareKey is null, return");
} else {
x.d("MicroMsg.WxaUpdateableMsgService", "[addWorker]getUpdatableMsgWorkerList size:%d", new Object[]{Integer.valueOf(b.gkd.gke.size())});
r2.gke.put(Integer.valueOf(aVar2.dzR.hashCode()), aVar2);
b.gkd.alo();
}
list.add(aVar2);
}
}
public final synchronized void jn(String str) {
x.i("MicroMsg.WxaUpdateableMsgService", "removeOnUpdatbleMsgInfoChange token:%s", new Object[]{str});
List<a> list = (List) gka.get(str);
if (list == null) {
x.w("MicroMsg.WxaUpdateableMsgService", "[removeOnUpdatbleMsgInfoChange]getUpdatableMsgWorkers is null, err");
} else {
for (a aVar : list) {
x.d("MicroMsg.WxaUpdateableMsgService", "[removeWorker]getUpdatableMsgWorkerList size:%d", new Object[]{Integer.valueOf(b.gkd.gke.size())});
r2.gke.remove(Integer.valueOf(aVar.dzR.hashCode()));
}
gka.remove(str);
}
}
}
|
package demo.rabbit.message;
import static com.google.common.base.Preconditions.checkNotNull;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import demo.rabbit.cache.CacheMessageListenerContext;
/**
* Processes incoming cache-related messages from the RabbitMQ exchange.
* @author jjacobs@credera.com
* @version 11/9/12
*/
@Component("cacheMessageListener")
public class CacheMessageListenerImpl implements CacheMessageListener{
private static final Logger LOG = Logger.getLogger(CacheMessageListenerImpl.class);
@Value("${tomcat.server.name}")
private String serverName;
@Value("#{@appName}")
private String appName;
@Override
public void onMessage(CacheEvictionMessage message) {
checkNotNull(message, "null message received");
CacheMessageListenerContext.setEventListenerNotification(true);
if (serverName.equals(message.getServerName()) && appName.equals(message.getAppName())) {
if(LOG.isDebugEnabled()) {
LOG.debug("[" + appName + "] Ignoring cache eviction message sent from [" + serverName + "] [" + appName + "] instance for key: [" + message.getKey() + "], cache: [" + message.getCacheName() + "]");
}
} else {
if(LOG.isDebugEnabled()) {
LOG.debug("[" + appName + "] Cache eviction message received from server: [" + message.getServerName() + "], application: [" + message.getAppName() + "]");
}
Ehcache cache = CacheManager.getInstance().getEhcache(message.getCacheName());
if (cache == null) {
LOG.warn("[" + appName + "] No Ehcache found for cacheName: [" + message.getCacheName() + "]");
return;
}
if(message.isEvictAll()) {
cache.removeAll();
if(LOG.isDebugEnabled()) {
LOG.debug("[" + appName + "] All elements removed from cache: [" + message.getCacheName() + "]");
}
} else {
boolean result = cache.removeQuiet(message.getKey());
if (LOG.isDebugEnabled()) {
if (result) {
LOG.debug("[" + appName + "] Element with key: [" + message.getKey() + "] removed from cache: [" + message.getCacheName() + "]");
} else {
LOG.debug("[" + appName + "] Element with key: [" + message.getKey() + "] not found in cache: [" + message.getCacheName() + "]");
}
}
}
}
CacheMessageListenerContext.clear();
}
}
|
package com.example.watcher;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import com.example.watcher.Model.ApiGeneralRespuesta;
import com.example.watcher.Model.Confirmacion;
import com.example.watcher.Model.Resultado;
import com.example.watcher.Utils.SupervisionService;
import org.json.JSONObject;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Map;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import static com.example.watcher.Utils.Apis.URL_BASE;
public class Supervision extends AppCompatActivity {
Spinner spinner;
ImageView mImagenview;
Button mChooseBtn, btn_guardar, btn_mapa;
Uri imageUri;
TextView tv_abonado, tv_riesgo;
Context context;
SupervisionService supervisionService;
Bitmap bitmap;
int PICK_IMAGE_REQUEST = 1;
String UPLOAD_URL = "http://IP_DEL_WEBSERVICE/ARCHIVO_QUE_RECIBE_LA_PETICION.php";
String KEY_IMAGE = "foto";
String KEY_NOMBRE = "nombre";
private Retrofit retrofit;
private static final int PICK_IMAGE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_supervision );
spinner = findViewById( R.id.sp_resultado );
mImagenview = findViewById( R.id.iv_imagen );
mChooseBtn = findViewById( R.id.btn_changeImg );
btn_guardar = findViewById( R.id.btn_guardar );
btn_mapa = findViewById( R.id.btn_mapa );
tv_abonado = findViewById( R.id.tv_abonado );
tv_riesgo = findViewById( R.id.tv_riesgo );
retrofit = new Retrofit.Builder()
.baseUrl(URL_BASE)
.addConverterFactory( GsonConverterFactory.create() )
.build();
Bundle objetoEnviado = getIntent().getExtras();
com.example.watcher.Model.Supervision supervision = null;
if(objetoEnviado != null) {
supervision = (com.example.watcher.Model.Supervision) objetoEnviado.getSerializable("supervision");
tv_abonado.setText( supervision.getId() + " - " + supervision.getAbonado().replace("- ", "") );
tv_riesgo.setText( supervision.getEstado() );
}
btn_guardar.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
Resultado resultado = new Resultado(1, "");
supervisionService = retrofit.create( SupervisionService.class );
Call<ApiGeneralRespuesta> call = supervisionService.postResultado(resultado);
call.enqueue( new Callback<ApiGeneralRespuesta>() {
@Override
public void onResponse(Call<ApiGeneralRespuesta> call, Response<ApiGeneralRespuesta> response) {
if(response.isSuccessful()) {
ApiGeneralRespuesta respuesta = response.body();
Toast.makeText(getApplicationContext(), respuesta.getMessage(), Toast.LENGTH_SHORT).show();
enviarImagenData();
}
}
@Override
public void onFailure(Call<ApiGeneralRespuesta> call, Throwable t) {
}
} );
}
} );
btn_mapa.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
Confirmacion confirmacion = new Confirmacion(true, "", 1, "", "");
supervisionService = retrofit.create( SupervisionService.class );
Call<ApiGeneralRespuesta> call = supervisionService.postConfirmacion(confirmacion);
call.enqueue( new Callback<ApiGeneralRespuesta>() {
@Override
public void onResponse(Call<ApiGeneralRespuesta> call, Response<ApiGeneralRespuesta> response) {
if(response.isSuccessful()) {
ApiGeneralRespuesta respuesta = response.body();
Toast.makeText(getApplicationContext(), respuesta.getMessage(), Toast.LENGTH_SHORT).show();
Intent intent =new Intent(Supervision.this, DestinoRonda.class);
startActivity(intent);
}
}
@Override
public void onFailure(Call<ApiGeneralRespuesta> call, Throwable t) {
}
} );
}
} );
mChooseBtn.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent galeria = new Intent();
galeria.setType( "image/*" );
galeria.setAction( Intent.ACTION_GET_CONTENT );
startActivityForResult( Intent.createChooser( galeria, "Seleccionar Imagen" ), PICK_IMAGE );
}
} );
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.Resultado, android.R.layout.simple_spinner_item );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
spinner.setAdapter( adapter );
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult( requestCode, resultCode, data );
if( requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null ) {
imageUri = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
mImagenview.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getStringImagen(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
public void enviarImagenData(){
try{
File file = bitmapToFile(getApplicationContext(), bitmap, "test");
OkHttpClient client = new OkHttpClient();
RequestBody body = new MultipartBody.Builder().setType( MultipartBody.FORM)
.addFormDataPart("UploadedImage", file.getName(), RequestBody.create( MediaType.parse("application/octet-stream"), file))
.build();
okhttp3.Request request = new okhttp3.Request.Builder().url( URL_BASE + "FileUpload").post(body).build();
client.newCall( request ).enqueue( new okhttp3.Callback() {
@Override
public void onFailure(okhttp3.Call call, IOException e) {
Log.e("uploadFile", "44.Error:" + e.getMessage()); //Error antes de consumir
}
@Override
public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
if(response.isSuccessful()){
Toast.makeText(getApplicationContext(), "Imagen guardada", Toast.LENGTH_LONG).show();
}
}
} );
} catch(Exception exc) {
Log.e("ExecptionSendImage", "" + exc.getMessage());
}
}
public File bitmapToFile(Context context,Bitmap bitmap, String fileNameToSave) { // File name like "image.png"
//create a file to write bitmap data
File file = null;
try {
file = new File( Environment.getExternalStorageDirectory() + File.separator + fileNameToSave);
file.createNewFile();
//Convert bitmap to byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0 , bos); // YOU can also save it in JPEG
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(file);
fos.write(bitmapdata);
fos.flush();
fos.close();
return file;
}catch (Exception e){
e.printStackTrace();
return file; // it will return null
}
}
}
|
package me.t.stydy.junit.demo1;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
/**
* 打包测试
* 如果一个项目中有许多个测试类,一个一个去运行会非常繁琐,这个时候就可以考虑使用打包测试。
* 将所有需要运行的测试类集中起来,一次性的运行完毕,大大的方便了我们的测试工作。
*
*/
@RunWith(Suite.class)
@SuiteClasses({ CalculatorSquareTest.class, CalculatorTest.class })
public class AllTests {
}
|
package com.bingo.code.example.design.command.reset;
/**
* ���������ʵ�֣�ʵ��Command�ӿڣ�
* ���п������������ʵ�֣�ͨ�����ý����ߵķ�����ʵ������
*/
public class OpenCommand implements Command{
/**
* ��������ʵ������Ľ����ߡ����������
*/
private MainBoardApi mainBoard = null;
/**
* ���췽���������������
* @param mainBoard �������
*/
public OpenCommand(MainBoardApi mainBoard) {
this.mainBoard = mainBoard;
}
public void execute() {
//���������������֪����ο�������ת���������
//������ȥ��ɿ����Ĺ���
this.mainBoard.open();
}
}
|
package com.tencent.mm.plugin.ipcall.ui;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.tencent.mm.R;
import com.tencent.mm.compatible.util.d;
public class DialNumberButton extends RelativeLayout {
TextView ksJ;
TextView ksK;
private boolean ksL = false;
public DialNumberButton(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
LayoutInflater.from(getContext()).inflate(R.i.dial_number_button, this);
this.ksJ = (TextView) findViewById(R.h.dial_button_number);
this.ksK = (TextView) findViewById(R.h.dial_button_text);
if (d.fR(16)) {
this.ksJ.setTypeface(Typeface.create("sans-serif-light", 0));
this.ksK.setTypeface(Typeface.create("sans-serif-normal", 0));
}
setClipChildren(false);
setClipToPadding(false);
}
public String getNumberText() {
return this.ksJ.getText().toString();
}
public String getOtherText() {
return this.ksK.getText().toString();
}
public void setInTalkUIMode(boolean z) {
this.ksL = z;
if (this.ksL) {
if ("#".equals(this.ksJ.getText()) || "*".equals(this.ksJ.getText())) {
this.ksJ.setTextColor(getContext().getResources().getColor(R.e.dial_number_button_other_text_color));
} else {
this.ksJ.setTextColor(getContext().getResources().getColor(R.e.dial_number_button_text_color_white));
}
this.ksK.setTextColor(getContext().getResources().getColor(R.e.dial_number_button_other_text_color));
setBackgroundDrawable(getResources().getDrawable(R.g.dial_number_button_background_black));
return;
}
if ("#".equals(this.ksJ.getText()) || "*".equals(this.ksJ.getText())) {
this.ksJ.setTextColor(getContext().getResources().getColor(R.e.dial_number_button_other_text_color));
} else {
this.ksJ.setTextColor(getContext().getResources().getColor(R.e.dial_number_button_text_color));
}
this.ksK.setTextColor(getContext().getResources().getColor(R.e.dial_number_button_other_text_color));
setBackgroundDrawable(getResources().getDrawable(R.g.dial_number_button_background_white));
}
}
|
package com.example.demo.services;
import com.example.demo.clients.country.CountryClient;
import com.example.demo.clients.rates.ExchangeRateClient;
import com.example.demo.domain.Country;
import com.example.demo.utilities.CountryFileReader;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.test.mock.mockito.MockBean;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
class CountryServiceTest {
private final CountryClient countryClient = Mockito.mock(CountryClient.class);
private final ExchangeRateClient exchangeRateClient = Mockito.mock(ExchangeRateClient.class);
private CountryService countryService;
private final CountryFileReader countryFileReader;
public CountryServiceTest() {
countryService = new CountryService(countryClient,exchangeRateClient);
countryFileReader = new CountryFileReader();
}
@Test
void getAllCountries() throws IOException {
}
@Test
void getCountryByName() {
}
@Test
void calculateBudget() {
}
}
|
import java.util.*;
class Recursion_InClass
{
public static void main(String arg[])
{
Scanner in =new Scanner(System.in);
int WAT = in.nextInt();
//find the factorial of 3
int result = factorial(WAT);
//print the result
System.out.println(result);
}
public static int factorial(int count)
{
//if it is 1 return 1
if(count == 1)
{
return 1;
}
else
{
//subtract one
int temp = count-1;
//multiply with one less
count = count + factorial(temp);
//return result
return count;
}
}
}
|
package de.madjosz.adventofcode.y2020;
import static org.junit.jupiter.api.Assertions.assertEquals;
import de.madjosz.adventofcode.AdventOfCodeUtil;
import java.util.List;
import org.junit.jupiter.api.Test;
class Day22Test {
@Test
void day22() {
List<String> lines = AdventOfCodeUtil.readLines(2020, 22);
Day22 day22 = new Day22(lines);
assertEquals(30197, day22.a1());
assertEquals(34031, day22.a2());
}
@Test
void day22_exampleInput() {
List<String> lines = AdventOfCodeUtil.readLines(2020, 22, "test");
Day22 day22 = new Day22(lines);
assertEquals(306, day22.a1());
assertEquals(291, day22.a2());
}
}
|
package prob6;
public class Rectangle extends Shape implements Resizable {
public Rectangle ( int width, int height ) {
super.setWidth(width);
super.setHeight(height);
}
@Override
public void resize(double d) {
super.setHeight( super.getHeight() * d );
super.setWidth( super.getWidth() * d );
}
@Override
public double getArea() {
return ( super.getHeight() * super.getWidth() );
}
@Override
public double getPerimeter() {
return ( (super.getHeight() * 2 ) + ( super.getWidth() * 2 ) ) ;
}
}
|
package baadraan.u.batman.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBase extends SQLiteOpenHelper {
private final static String DB_NAME = "Batman";
private final static int DB_VERSION = 1;
public static final String MYTB = "Movie";
public static final String IMDBID = "ImdbId";
public static final String TITLE = "Title";
public static final String YEAR = "Year";
public static final String POSTER = "Poster";
public static final String TYPE = "Type";
public static final String RUNTIME = "Runtime";
public static final String GENRE = "Genre";
public static final String DIRECTOR = "Director";
public static final String WRITER = "WRITER";
public static final String ACTORS = "Actors";
public static final String PLOT = "Plot";
public static final String LANGUAGE = "Language";
public static final String COUNTRY = "Country";
public static final String IMDBRATING = "ImdbRating";
public static final String IMDBVOTE = "ImdbVote";
public static final String BOXOFFICE = "Boxoffice";
public DataBase(Context context){
super(context , DB_NAME , null , DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase mydb) {
mydb.execSQL("CREATE TABLE IF NOT EXISTS " + MYTB + " (" +
IMDBID + " TEXT UNIQUE, " +
TITLE + " TEXT , "+
YEAR + " TEXT , "+
POSTER + " TEXT , "+
TYPE + " TEXT , " +
RUNTIME + " TEXT , " +
GENRE + " TEXT , " +
DIRECTOR + " TEXT , " +
WRITER + " TEXT , " +
ACTORS + " TEXT , " +
PLOT + " TEXT , " +
LANGUAGE + " TEXT , " +
COUNTRY + " TEXT , " +
IMDBRATING + " TEXT , " +
IMDBVOTE + " TEXT , " +
BOXOFFICE + " TEXT );");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
|
//John Aspinwall
//Zachary Zembower
package experiment;
import static org.junit.Assert.*;
import java.util.LinkedList;
import java.util.Set;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
public class IntBoardTests {
IntBoard board;
@Before
public void init() {
board = new IntBoard();
board.calcAdjacencies();
}
@Test
public void testCalcIndex11() {
int location = board.calcIndex(1,1);
assertEquals(location, 5);
}
@Test
public void testCalcIndex03() {
int location = board.calcIndex(0,3);
assertEquals(location, 3);
}
@Test
public void testCalcIndex23() {
int location = board.calcIndex(2,3);
assertEquals(location, 11);
}
@Test
public void testAdjacency0()
{
LinkedList testList = board.getAdjList(0);
Assert.assertTrue(testList.contains(4));
Assert.assertTrue(testList.contains(1));
Assert.assertEquals(2, testList.size());
}
@Test
public void testAdjacency15()
{
LinkedList testList = board.getAdjList(15);
Assert.assertTrue(testList.contains(11));
Assert.assertTrue(testList.contains(14));
Assert.assertEquals(2, testList.size());
}
@Test
public void testAdjacency7()
{
LinkedList testList = board.getAdjList(7);
Assert.assertTrue(testList.contains(3));
Assert.assertTrue(testList.contains(6));
Assert.assertTrue(testList.contains(11));
Assert.assertEquals(3, testList.size());
}
@Test
public void testAdjacency8()
{
LinkedList testList = board.getAdjList(8);
Assert.assertTrue(testList.contains(4));
Assert.assertTrue(testList.contains(9));
Assert.assertTrue(testList.contains(12));
Assert.assertEquals(3, testList.size());
}
@Test
public void testAdjacency5()
{
LinkedList testList = board.getAdjList(5);
Assert.assertTrue(testList.contains(1));
Assert.assertTrue(testList.contains(4));
Assert.assertTrue(testList.contains(6));
Assert.assertTrue(testList.contains(9));
Assert.assertEquals(4, testList.size());
}
@Test
public void testAdjacency10()
{
LinkedList testList = board.getAdjList(10);
Assert.assertTrue(testList.contains(6));
Assert.assertTrue(testList.contains(9));
Assert.assertTrue(testList.contains(11));
Assert.assertTrue(testList.contains(14));
Assert.assertEquals(4, testList.size());
}
@Test
public void testTargets0_3()
{
board.startTargets(0, 3);
Set targets= board.getTargets();
Assert.assertEquals(6, targets.size());
Assert.assertTrue(targets.contains(12));
Assert.assertTrue(targets.contains(9));
Assert.assertTrue(targets.contains(1));
Assert.assertTrue(targets.contains(6));
Assert.assertTrue(targets.contains(3));
Assert.assertTrue(targets.contains(4));
}
@Test
public void testTargets15_2()
{
board.startTargets(15, 2);
Set targets= board.getTargets();
Assert.assertEquals(3, targets.size());
Assert.assertTrue(targets.contains(13));
Assert.assertTrue(targets.contains(10));
Assert.assertTrue(targets.contains(7));
}
@Test
public void testTargets5_6()
{
board.startTargets(5, 6);
Set targets= board.getTargets();
Assert.assertEquals(7, targets.size());
Assert.assertTrue(targets.contains(0));
Assert.assertTrue(targets.contains(2));
Assert.assertTrue(targets.contains(7));
Assert.assertTrue(targets.contains(10));
Assert.assertTrue(targets.contains(8));
Assert.assertTrue(targets.contains(13));
Assert.assertTrue(targets.contains(15));
}
@Test
public void testTargets7_3()
{
board.startTargets(7, 3);
Set targets= board.getTargets();
Assert.assertEquals(7, targets.size());
Assert.assertTrue(targets.contains(4));
Assert.assertTrue(targets.contains(1));
Assert.assertTrue(targets.contains(9));
Assert.assertTrue(targets.contains(14));
Assert.assertTrue(targets.contains(11));
Assert.assertTrue(targets.contains(3));
Assert.assertTrue(targets.contains(6));
}
@Test
public void testTargets8_3()
{
board.startTargets(8, 3);
Set targets= board.getTargets();
Assert.assertEquals(7, targets.size());
Assert.assertTrue(targets.contains(6));
Assert.assertTrue(targets.contains(11));
Assert.assertTrue(targets.contains(14));
Assert.assertTrue(targets.contains(12));
Assert.assertTrue(targets.contains(4));
Assert.assertTrue(targets.contains(1));
Assert.assertTrue(targets.contains(9));
}
@Test
public void testTargets10_2()
{
board.startTargets(10, 2);
Set targets= board.getTargets();
Assert.assertEquals(6, targets.size());
Assert.assertTrue(targets.contains(2));
Assert.assertTrue(targets.contains(5));
Assert.assertTrue(targets.contains(7));
Assert.assertTrue(targets.contains(15));
Assert.assertTrue(targets.contains(13));
Assert.assertTrue(targets.contains(8));
}
}
|
package com.grability.test.dlmontano.grabilitytest.interfaces;
import com.grability.test.dlmontano.grabilitytest.model.ReleaseDate;
import java.util.Map;
/**
* Created by Diego Montano on 05/06/2016.
*/
public interface ReleaseDateDataSource extends DataSource {
boolean defaultSourceContentHasReleaseDates();
boolean sourceContentHasContentReleaseDates(String sourceContentName, boolean open);
int getReleaseDatesCount();
Map<Long, ReleaseDate> getAllReleaseDates();
ReleaseDate getReleaseDateByAppId(long appId);
boolean addReleaseDate(ReleaseDate releaseDate);
boolean updateReleaseDate(ReleaseDate releaseDate);
boolean deleteReleaseDate(ReleaseDate releaseDate);
}
|
package com.tinyurl.utils;
import io.seruco.encoding.base62.Base62;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;
import org.springframework.stereotype.Service;
@Service
public class TinyUrlConverter {
public String convertToBase62Url(String urlToConvert) throws NoSuchAlgorithmException{
MessageDigest md = MessageDigest.getInstance("md5");
md.update(urlToConvert.getBytes());
byte[] digest = md.digest();
String myHash = DatatypeConverter.printHexBinary(digest).toUpperCase();
Base62 base62 = Base62.createInstance();
final byte[] encoded = base62.encode(myHash.getBytes());
return new String(encoded).substring(0, 7);
}
}
|
package com.vilio.plms.service.test;
import com.vilio.plms.exception.ErrorException;
import com.vilio.plms.service.base.BaseService;
import com.vilio.plms.service.base.CommonService;
import com.vilio.plms.service.quartz.BmsSynchronizeService;
import com.vilio.plms.util.SpringContextUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import java.util.Map;
/**
* Created by martin on 2017/9/16.
*/
@Service
public class Plms900009 extends BaseService {
private static final Logger logger = Logger.getLogger(Plms900009.class);
public void busiServiceNoTransaction(Map<String, Object> head, Map<String, Object> body, Map<String, Object> resultMap) throws ErrorException {
try{
logger.info("开始同步bms数据定时任务");
// SchedulerContext skedCtx = jobExecutionContext.getScheduler().getContext();
BmsSynchronizeService bmsSynchronizeService = (BmsSynchronizeService) SpringContextUtil.getBean("bmsSynchronizeService");
bmsSynchronizeService.execute();
logger.info("完成同步bms数据定时任务");
}catch(Exception ex){
logger.info("同步bms数据定时任务执行出现异常:" + ex);
ex.printStackTrace();
CommonService commonService = (CommonService) SpringContextUtil.getBean("commonService");
commonService.monitorEmail("同步bms数据定时任务", ex.getMessage());
}
}
}
|
package com.packers.movers.commons.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class StreamUtils {
public static void copy(InputStream source, OutputStream destination) throws IOException {
byte[] buffer = new byte[4096];
int bytesRead = source.read(buffer);
while (bytesRead != -1) {
destination.write(buffer, 0, bytesRead);
bytesRead = source.read(buffer);
}
}
public static byte[] getBytes(InputStream inputStream) throws IOException {
try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
copy(inputStream, output);
return output.toByteArray();
}
}
public static String toString(InputStream inputStream, Charset charset) throws IOException {
return new String(getBytes(inputStream), charset);
}
public static String toString(InputStream inputStream) throws IOException {
return toString(inputStream, StandardCharsets.UTF_8);
}
}
|
package io.bega.kduino.activities;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import io.bega.kduino.IClickable;
import io.bega.kduino.R;
import io.bega.kduino.fragments.UserActivityFragment;
public class UserActivity extends BaseActivity implements IClickable {
UserActivityFragment userActivityFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
setTitle(getString(R.string.activity_title_user));
setOnlyToolbar();
userActivityFragment = new UserActivityFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(
android.R.anim.slide_in_left,
android.R.anim.slide_out_right,
android.R.anim.slide_in_left,
android.R.anim.slide_out_right
);
ft.replace(R.id.fragment_container_user, userActivityFragment);
ft.setTransition(FragmentTransaction.TRANSIT_NONE);
ft.commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
return true;
}
public boolean onPrepareOptionsMenu (Menu menu) {
/*Boolean enabled = this.bluetoothService.isEnabledBluetooth();
menu.getItem(1).setVisible(!enabled);
menu.getItem(2).setVisible(enabled && !this.bluetoothService.isConnected());
menu.getItem(3).setVisible(this.bluetoothService.isConnected()); */
/*if (this.bluetoothService.isConnected()) {
menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.ic_action_connect));
}
else
{
menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.ic_action_disconnect_white_off));
} */
super.onPrepareOptionsMenu(menu);
return true;
}
@Override
public void clickView(View v) {
if (userActivityFragment != null)
{
userActivityFragment.clickView(v);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR
&& keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
// Take care of calling this method on earlier versions of
// the platform where it doesn't exist.
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onBackPressed() {
// This will be called either automatically for you on 2.0
// or later, or by the code above on earlier versions of the
// platform.
finish();
}
}
|
package rent.common.projection;
import org.springframework.data.rest.core.config.Projection;
import rent.common.entity.RoleEntity;
@Projection(types = {RoleEntity.class})
public interface RoleBasic extends AbstractBasic {
String getName();
String getDescription();
}
|
package com.github.stathvaille.marketimports.items;
import com.github.stathvaille.marketimports.items.staticdataexport.Group;
import com.github.stathvaille.marketimports.items.staticdataexport.Groups;
import com.github.stathvaille.marketimports.items.staticdataexport.Item;
import com.github.stathvaille.marketimports.items.staticdataexport.Items;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class ItemConfiguration {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
Groups groups;
@Bean
public Items items() throws IOException {
String itemsFileLocation = "typeIDs.yaml";
logger.info("Reading item types map from " + itemsFileLocation + ". This can take a while...");
ObjectMapper yamlObjectMapper = new ObjectMapper(new YAMLFactory());
InputStream inputStream = new ClassPathResource(itemsFileLocation).getInputStream();
Map<Long, Item> itemMap = yamlObjectMapper.readValue(inputStream, new TypeReference<Map<Long, Item>>() {});
itemMap.keySet().forEach(itemId -> itemMap.get(itemId).setTypeId(itemId));
overrideVolumeForShips(itemMap);
logger.info("Read in " + itemMap.size() + " items.");
return new Items(itemMap);
}
private void overrideVolumeForShips(Map<Long, Item> itemMap){
System.out.println("thing");
Map<String, Integer> volumeOverrideMap = new HashMap<>();
volumeOverrideMap.put("Frigate", 2500);
volumeOverrideMap.put("Destroyer", 5000);
volumeOverrideMap.put("Cruiser", 10000);
volumeOverrideMap.put("Combat Battlecruiser", 15000);
volumeOverrideMap.put("Battleship", 50000);
volumeOverrideMap.put("Industrial", 20000);
volumeOverrideMap.put("Shuttle", 500);
volumeOverrideMap.put("Assault Frigate", 2500);
volumeOverrideMap.put("Heavy Assault Cruiser", 10000);
volumeOverrideMap.put("Deep Space Transport", 20000);
volumeOverrideMap.put("Elite Battleship", 50000);
volumeOverrideMap.put("Mining Barge", 3750);
volumeOverrideMap.put("Command Ship", 15000);
volumeOverrideMap.put("Interdictor", 5000);
volumeOverrideMap.put("Covert Ops", 2500);
volumeOverrideMap.put("Interceptor", 2500);
volumeOverrideMap.put("Logistics", 10000);
volumeOverrideMap.put("Force Recon Ship", 10000);
volumeOverrideMap.put("Stealth Bomber", 2500);
volumeOverrideMap.put("Electronic Attack Ship", 2500);
volumeOverrideMap.put("Heavy Interdiction Cruiser", 10000);
volumeOverrideMap.put("Black Ops", 50000);
volumeOverrideMap.put("Marauder", 50000);
volumeOverrideMap.put("Combat Recon Ship", 10000);
volumeOverrideMap.put("Strategic Cruiser", 10000);
volumeOverrideMap.put("Prototype Exploration Ship", 2500);
volumeOverrideMap.put("Attack Battlecruiser", 15000);
volumeOverrideMap.put("Blockade Runner", 20000);
volumeOverrideMap.put("Tactical Destroyer", 5000);
volumeOverrideMap.put("Logistics Frigate", 2500);
volumeOverrideMap.put("Command Destroyer", 5000);
itemMap.keySet().forEach(itemId -> {
Item item = itemMap.get(itemId);
Group group = groups.getGroups().get(item.getGroupID());
if (group == null) {
throw new RuntimeException("Could not find group for item " + item);
}
if (volumeOverrideMap.containsKey(group.getName().getEn())) {
int actualItemSize = volumeOverrideMap.get(group.getName().getEn());
logger.info("Overriding volume for " + item + " to " + actualItemSize);
item.setVolume(actualItemSize);
}
});
}
}
|
package com.example.onlineshop.viewmodel;
import android.app.Application;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import com.example.onlineshop.model.CategoriesItem;
import com.example.onlineshop.model.Product;
import com.example.onlineshop.model.category.Categories;
import com.example.onlineshop.network.ItemShopFetcher;
import com.example.onlineshop.view.fragments.DetailListCategoryFragment;
import java.util.List;
import java.util.Observable;
public class ViewPagerCategViewModel extends AndroidViewModel {
private MutableLiveData<List<Categories>> mListCategoryMutableLiveData;
private MutableLiveData<List<Categories>> mListSubCategoryMutableLiveData;
private MutableLiveData<List<Product>> mListProMutableLiveData;
private ItemShopFetcher mShopFetcher;
public ViewPagerCategViewModel(@NonNull Application application) {
super(application);
mShopFetcher = ItemShopFetcher.getInstance();
}
public MutableLiveData<List<Categories>> getSubCategoriesMutableLiveData(String displayCatg , int parentCateg){
mShopFetcher.getAllCategory(displayCatg,parentCateg);
mListSubCategoryMutableLiveData = mShopFetcher.getListSubCategoryLiveData();
return mListSubCategoryMutableLiveData;
}
public MutableLiveData<List<Product>> getListProMutableLiveData(String categoryName,int categoryId) {
mShopFetcher.getProductsSubCategory(categoryName,String.valueOf(categoryId));
mListProMutableLiveData = mShopFetcher.getProductListSubCategMLiveData();
return mListProMutableLiveData;
}
public MutableLiveData<List<Product>> getListProByPageMutableLiveData(String namecateg,int idCateg,int pageNumber) {
MutableLiveData<List<Product>> mLisProMutableLiveData;
mLisProMutableLiveData = mShopFetcher.getProductsSubCategoryByPage(namecateg,String.valueOf(idCateg),pageNumber);
return mLisProMutableLiveData;
}
public List<Categories> getBasicCategories() {
return mShopFetcher.getBasicCategoriesList();
}
}
|
package my.application.repository;
import my.application.entity.Training;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface TrainingRepository extends JpaRepository<Training, Long> {
Training findTopById(Long id);
}
|
package com.sa.java;
public class SumCommandLine {
public static void main(String[] args) {
if(args.length==2) {
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
int s=a+b;
System.out.println("Sum Of Two Num:"+a+" and "+b+" is: "+s);
}
else
{
System.out.println("Wrong number:");
}
}
}
|
import java.util.Random;
public class SimpleRandom {
public static void main(String[] args) {
// TODO Auto-generated method stub
Random random1 = new Random(1000);
for(int i =0;i<50;i++) {
System.out.print(random1.nextInt(100)+" ");
if(i>9 && i%10==0)
System.out.println();
}
}
}
|
package offer;
/**
* @author kangkang lou
*/
public class HasSubTreeTest {
public static boolean hasSubTree(TreeNode root1, TreeNode root2) {
boolean result = false;
if (root2 != null && root1 != null) {
if (root1.val == root2.val) {
result = doesTree1HaveTree2(root1, root2);
}
if (!result) {
result = hasSubTree(root1.left, root2);
}
if (!result) {
result = hasSubTree(root1.right, root2);
}
}
return result;
}
public static boolean doesTree1HaveTree2(TreeNode node1, TreeNode node2) {
if (node2 == null) {
return true;
}
if (node1 == null) {
return false;
}
if (node1.val != node2.val) {
return false;
}
return doesTree1HaveTree2(node1.left, node2.left) && doesTree1HaveTree2(node1.right, node2.right);
}
}
|
package net.shortround.rose;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
public class RoseActivity extends Activity {
// Debug
private static final String TAG = "RoseActivity";
// Intent request codes
private static final int REQUEST_ENABLE_BT = 1;
// Messages sent from the Bluetooth Service
public static final int MESSAGE_FAILURE = 3;
public static final int MESSAGE_GET_DATA = 4;
public static final int MESSAGE_READ = 5;
public static final int MESSAGE_STATE_CHANGE = 6;
public static final int MESSAGE_WRITE = 7;
private BroadcastReceiver batteryReceiver;
private RoseView roseView;
private StringBuffer outputStringBuffer;
private BluetoothAdapter bluetoothAdapter = null;
private BluetoothService bluetoothService = null;
/*** Lifecycle Callbacks ***/
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_ENABLE_BT:
if (resultCode == Activity.RESULT_OK) {
setupBluetoothService();
} else {
Log.e(TAG, "Bluetooth not enabled");
finish();
}
break;
}
}
public void onBackPress() {
finish();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hide the title
requestWindowFeature(Window.FEATURE_NO_TITLE);
// Get the local Bluetooth Adapter
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (bluetoothAdapter == null) {
Log.e(TAG, "No bluetooth adapter");
finish();
return;
}
// Build the view
roseView = new RoseView(this);
roseView.setFocusable(true);
// Build the battery receiver
batteryReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int rawLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = -1;
if (rawLevel >= 0 && scale > 0) {
level = (rawLevel * 100) / scale;
}
roseView.setBattery(level);
}
};
// Show the view
setContentView(roseView);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onPause() {
super.onPause();
// Unregister the battery receiver
unregisterReceiver(batteryReceiver);
}
@Override
protected void onResume() {
super.onResume();
// Register the battery receiver
registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
// Go full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
// Keep the screen on
roseView.setKeepScreenOn(true);
// Hide the soft buttons
// roseView.setSystemUiVisibility(View.STATUS_BAR_HIDDEN);
roseView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
// Restart Bluetooth if we need to
if (bluetoothService != null) {
if (bluetoothService.getState() == BluetoothService.STATE_NONE) {
bluetoothService.start();
}
}
}
@Override
public void onStart() {
super.onStart();
// Request bluetooth
if (bluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} else {
if (bluetoothService == null) setupBluetoothService();
}
}
/*** Actions ***/
private void decay() {
roseView.decay();
// Send a bluetooth message with the current data
sendMessage(roseView.getSerializedData().toString());
}
private void revert() {
roseView.revert();
// Send a bluetooth message with the current data
sendMessage(roseView.getSerializedData().toString());
}
private void toggleDisplay() {
roseView.toggleDisplay();
// Send a bluetooth message with the current data
sendMessage(roseView.getSerializedData().toString());
}
/*** Bluetooth Methods ***/
private final Handler bluetoothHandler = new Handler() {
@Override
public void handleMessage(Message message) {
switch (message.what) {
case MESSAGE_FAILURE:
break;
case MESSAGE_GET_DATA:
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) message.obj;
String readMessage = new String(readBuf, 0, message.arg1);
parseMessage(readMessage);
break;
case MESSAGE_STATE_CHANGE:
switch(message.arg1) {
case BluetoothService.STATE_NONE:
case BluetoothService.STATE_LISTEN:
break;
case BluetoothService.STATE_CONNECTING:
break;
case BluetoothService.STATE_CONNECTED:
break;
}
break;
case MESSAGE_WRITE:
break;
}
}
};
public void ensureDiscoverable() {
if (bluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
private void parseMessage(String message) {
if (message.equals("decay")) {
decay();
} else if (message.equals("revert")) {
revert();
} else if (message.equals("display")) {
toggleDisplay();
} else if (message.equals("data")) {
sendMessage(roseView.getSerializedData().toString());
}
}
private void sendMessage(String message) {
// Check that we have a connection
if (bluetoothService != null && bluetoothService.getState() != BluetoothService.STATE_CONNECTED) {
Log.e(TAG, "Send message with no connection");
return;
}
// Check that there's something to send
if (message.length() > 0) {
// Get the message as bytes
byte[] send = message.getBytes();
bluetoothService.write(send);
// Clean up
outputStringBuffer.setLength(0);
}
}
private void setupBluetoothService() {
// Initialize the bluetooth service
bluetoothService = new BluetoothService(this, bluetoothHandler);
// Build the outgoing buffer
outputStringBuffer = new StringBuffer("");
}
}
|
package util;
import java.lang.Math;
import java.net.DatagramSocket;
import java.net.DatagramPacket;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
/**
* This class contains some core methods for sending and receving data in either
* packet or string formats, as well as some parsers for socket address.
*/
public class SocketUtil {
public static InetSocketAddress parseInetSocketAddress(String s)
throws IllegalArgumentException {
String[] sockAddr = s.split(":");
if (sockAddr.length !=2 ) {
throw new IllegalArgumentException(s);
}
int port;
try {
port = Integer.parseInt(sockAddr[1]);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(s);
}
return new InetSocketAddress(sockAddr[0], port);
}
public static ArrayList<InetSocketAddress> parseInetSocketAddress(String[] socketAddressStrings) {
ArrayList<InetSocketAddress> results = new ArrayList<InetSocketAddress>();
for (String socketAddressString : socketAddressStrings) {
String[] s = socketAddressString.split(":");
if (s.length !=2 ) {
System.err.println("Socket address "+socketAddressString+" is not valid");
} else {
try {
int port = Integer.parseInt(s[1]);
results.add(new InetSocketAddress(s[0], port));
} catch (NumberFormatException e) {
System.err.println("Port number in socket address "+socketAddressString+" is not valide");
}
}
}
return results;
}
public static ArrayList<InetSocketAddress> parseInetSocketAddresses(String s) {
return parseInetSocketAddress(s.split(","));
}
// The tail of a received string has padding '\0'. This returns one with all
// padding '\0' removed.
public static String packetToString(DatagramPacket packet) {
byte[] buf = packet.getData();
int end = 0;
while (buf[end++] != '\0') {}
return new String(buf, 0, end-1);
}
public static DatagramPacket receivePacket(DatagramSocket socket, int bufLen)
throws Exception {
byte[] buf = new byte[bufLen];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
return packet;
}
public static String receiveString(DatagramSocket socket, int bufLen)
throws Exception {
DatagramPacket packet = receivePacket(socket, bufLen);
return packetToString(packet);
}
// The caller should have the socket connected already.
public static void sendString(DatagramSocket socket, String s)
throws Exception {
byte[] buf = s.getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.send(packet);
}
public static void sendStringArray(DatagramSocket socket, String[] array, int bufLen)
throws Exception {
byte[] buf = new byte[bufLen];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
for (String s : array) {
buf = s.getBytes();
packet.setData(buf);
try {
socket.send(packet);
} catch (Exception e) {
continue;
}
}
}
public static String inetSocketAddressToString(InetSocketAddress sockAddr) {
return sockAddr.getAddress().getHostAddress()+":"+sockAddr.getPort();
}
}
|
package com.sergiossj.jobfunnel.entities;
import org.springframework.stereotype.Component;
@Component
public class SearchParamsEntity {
private String keywords;
private String location;
public SearchParamsEntity(String keywords, String location) {
this.keywords = keywords;
this.location = location;
}
public SearchParamsEntity() {
}
public String getKeywords() {
return keywords;
}
public void setKeywords(String keywords) {
this.keywords = keywords;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
@Override
public String toString() {
return "SearchParams{" +
"keywords='" + keywords + '\'' +
", location='" + location + '\'' +
'}';
}
}
|
package com.tt.miniapphost.feedback;
import com.tt.miniapp.feedback.screenrecord.ScreenRecordControl;
public class FeedbackRecordBridge {
private static IFeedbackRecordControl getInstance() {
return Holder.INSTANCE;
}
public static void start(IFeedbackRecordCallback paramIFeedbackRecordCallback) {
if (getInstance() != null)
getInstance().start(paramIFeedbackRecordCallback);
}
public static void stop(IFeedbackRecordCallback paramIFeedbackRecordCallback) {
if (getInstance() != null)
getInstance().stop(paramIFeedbackRecordCallback);
}
static class Holder {
public static IFeedbackRecordControl INSTANCE = init();
private static IFeedbackRecordControl init() {
return (IFeedbackRecordControl)new ScreenRecordControl();
}
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapphost\feedback\FeedbackRecordBridge.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package v1;
import java.util.Random;
public class Dice {
private final int MAX_VALUE = 6;
private int rollValue;
public Dice() { // does this class need a constructor - should we do the thing we did in SDP for only allowing one instance? Singleton Pattern?
}
private int roll() {
Random rand = new Random();
int value = rand.nextInt(MAX_VALUE+1);
return value;
}
public int getRollValue() {
// TODO Auto-generated method stub
int totalRoll = 0;
int roll1 = roll();
System.out.print("You rolled a " + roll1);
int roll2 = roll();
System.out.print(" and a " + roll2);
totalRoll = roll1 + roll2;
System.out.println(" = " + totalRoll + "\n");
rollValue = totalRoll;
return totalRoll;
}
}
|
package com.zmyaro.ltd;
public class Level {
public static final int FORMATION_MIDDLE = 0;
public static final int FORMATION_RANDOM = 1;
public static final int FORMATION_WAVE = 2;
public static final int FORMATION_WORM = 3;
public static final Level[] LEVELS = {
new Level( // 1
R.drawable.thumb_enemy_wrecking_ball,
"Wrecking Balls",
"Remember to spread your turrets out to cover the city.",
WreckingBall.class,
10,
Level.FORMATION_RANDOM,
"sky2"),
new Level( // 2
R.drawable.thumb_enemy_coconut,
"Coconuts",
"Towers in the middle will get more action, so upgrade them first.",
Coconut.class,
20,
Level.FORMATION_RANDOM,
"sky3"),
new Level( // 3
R.drawable.thumb_enemy_piano,
"Pianos",
"There is no rush; you will only need around six turrets by level 10 to be on track.",
Piano.class,
10,
Level.FORMATION_RANDOM,
"sky4"),
new Level( // 4
R.drawable.thumb_enemy_egg,
"Eggs",
"Rapid turrets may be helpful here.",
Egg.class,
30,
Level.FORMATION_WAVE,
"sky5"),
new Level( // 5
R.drawable.thumb_enemy_wrecking_ball,
"Wrecking Balls",
"Turrets with longer ranges may be more effective toward the middle and toward the bottom.",
WreckingBall.class,
20,
Level.FORMATION_MIDDLE,
"sky6"),
new Level( // 6
R.drawable.thumb_enemy_helicopter,
"Helicopters",
"If an explosive enemy hits a tower, it damages the surrounding towers too.",
Helicopter.class,
10,
Level.FORMATION_RANDOM,
"sky7"),
new Level( // 7
R.drawable.thumb_enemy_worm,
"Worm",
"Missile turrets are useful against worm enemies since they can damage multiple segments at once.",
Worm.class,
50,
Level.FORMATION_WORM,
"sky7"),
new Level( // 8
R.drawable.thumb_enemy_question_mark,
"Unknown",
"That is never really a good sign is it, the whole red sky thing?",
Nuke.class,
1,
Level.FORMATION_MIDDLE,
"sky8"),
new Level( // 9
R.drawable.thumb_enemy_ferrari,
"Ferrari SUVs",
"I don't know whether these exist, but you'll be surprised how much damage they can do to a tower.",
Ferrari.class,
15,
Level.FORMATION_RANDOM,
"sky9"),
new Level( // 10
R.drawable.thumb_enemy_bus,
"School Bus",
"I spend too much time on detail you will never see.",
Bus.class,
30,
Level.FORMATION_WORM,
"sky9"),
new Level( // 11
R.drawable.thumb_enemy_smart_car,
"Smart Cars",
"These are the only way to survive.",
SmartCar.class,
50,
Level.FORMATION_RANDOM,
"sky9"),
new Level( // 12
R.drawable.thumb_enemy_comp_cube,
"Companion Cubes",
"\u201c...eight out of ten Aperture Science engineers believe that the Companion Cube is most likely incapable of feeling much pain.\u201d",
CompanionCube.class,
200,
Level.FORMATION_RANDOM,
"sky9"),
new Level( // 13
R.drawable.thumb_enemy_hydrant,
"Fire Hydrant",
"Normally these save buildings, not wreck them.",
Hydrant.class,
20,
Level.FORMATION_RANDOM,
"sky9"),
new Level( // 14
R.drawable.thumb_enemy_binary,
"Binary",
"There are 10 kinds of people: those who understand binary and those who do not.",
Binary.class,
54,
Level.FORMATION_WAVE,
"sky9"),
new Level( // 15
R.drawable.thumb_enemy_cow,
"Cows",
"\u201cFetchez la vache!\u201d",
Cow.class,
50,
Level.FORMATION_RANDOM,
"sky9"),
new Level( // 16
R.drawable.thumb_enemy_balloon_blue,
"Water Balloons",
"Every year, approximately 1.8 birds die from balloon poisoning.",
Balloon.class,
25,
Level.FORMATION_RANDOM,
"sky9"),
new Level( // 17
R.drawable.thumb_enemy_bumper_sticker,
"Obmper Stickers",
"Even if you hate Obama, you are guaranteed to hate the next level more.",
BumperSticker.class,
50,
Level.FORMATION_RANDOM,
"sky9"),
new Level( // 18
R.drawable.thumb_enemy_trump,
"Donald Trump",
"He shows the world what America is really about.",
Trump.class,
1,
Level.FORMATION_MIDDLE,
"sky7"),
new Level( // 19
R.drawable.thumb_enemy_molecule,
"Water Molecules",
"Some of the proceeds from this game will go to dihydrogen monoxide research!",
Molecule.class,
40,
Level.FORMATION_RANDOM,
"sky9"),
new Level( // 20
R.drawable.thumb_enemy_paper_clip,
"Paper Clips",
"There are more paperclips in the world than humans. Watch your back!",
PaperClip.class,
60,
Level.FORMATION_RANDOM,
"sky9"),
new Level( // 21
R.drawable.thumb_enemy_koopa_shell,
"Koopa Shells",
"Where is Mario when you need him?!",
KoopaShell.class,
100,
Level.FORMATION_RANDOM,
"sky9"),
new Level( // 22
R.drawable.thumb_enemy_eye,
"Eyeballs",
"\u201cI see dead towers.\u201d",
EyeBall.class,
20,
Level.FORMATION_RANDOM,
"sky9"),
new Level( // 23
R.drawable.thumb_enemy_spork,
"Sporks",
"Half spoon, half fork...ALL EVIL!",
Spork.class,
20,
Level.FORMATION_RANDOM,
"sky9"),
new Level( // 24
R.drawable.thumb_enemy_vending_machine,
"Vending Machines",
"Approximately two people die each year from \u201cvending machine related\u201d accidents.",
VendingMachine.class,
10,
Level.FORMATION_RANDOM,
"sky9")
};
private int mEnemyDrawableId;
private String mEnemyName;
private String mQuote;
private Class mEnemyClass;
private int mEnemyCount;
private int mEnemyFormation;
private String mSkyDrawableName;
public Level(int enemyDrawableId, String enemyName, String quote, Class enemyClass, int enemyCount, int enemyFormation, String skyDrawableName) {
mEnemyDrawableId = enemyDrawableId;
mEnemyName = enemyName;
mQuote = quote;
mEnemyClass = enemyClass;
mEnemyCount = enemyCount;
mEnemyFormation = enemyFormation;
mSkyDrawableName = skyDrawableName;
}
public int getEnemyDrawableId() {
return mEnemyDrawableId;
}
public String getEnemyName() {
return mEnemyName;
}
public String getQuote() {
return mQuote;
}
public Class getEnemyClass() {
return mEnemyClass;
}
public int getEnemyCount() {
return mEnemyCount;
}
public int getEnemyFormation() {
return mEnemyFormation;
}
public String getSkyDrawableName() {
return mSkyDrawableName;
}
}
|
package MongoDB;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import org.bson.Document;
import org.bson.types.ObjectId;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Filters.gt;
public class MainMongoDB {
public static void main(String[] args) {
Logger logger = Logger.getLogger("");
logger.setLevel(Level.OFF);
String user = "user";
String password = "user";
String host = "localhost";
int port = 27017;
String database = "database01";
String clientURI = "mongodb://" + user + ":" + password + "@" + host + ":" + port + "/" + database;
MongoClientURI uri = new MongoClientURI(clientURI);
MongoClient mongoClient = new MongoClient(uri);
MongoDatabase db = mongoClient.getDatabase(database);
//db.getCollection("student").drop();
//db.getCollection("order").drop();
MongoCollection<Document> studentsCollection = db.getCollection("student");
MongoCollection<Document> orderCollection = db.getCollection("order");
Scanner scanner = new Scanner(System.in);
do {
System.out.println("|=================> System zarządzania dziekanatem <=================|");
System.out.println("1.Studenci");
System.out.println("===> 1a.Dodaj studenta");
System.out.println("===> 1b.Wyświetl wszystkich studentów");
System.out.println("===> 1c.Usuń studenta");
System.out.println("===> 1d.Szukaj studenta po id");
System.out.println("===> 1e.Wyszukiwanie studentów po imieniu, nazwisku i kierunku studiów");
System.out.println("===> 1f.Wyszukiwanie studentów po przedmiocie i ocenie większej niż wybrana");
System.out.println("===> 1g.Edytuj studenta studenta");
System.out.println("2.Podania studentów");
System.out.println("===> 2a.Dodaj podanie");
System.out.println("===> 2b.Wyświetl wszystkie podania");
System.out.println("===> 2c.Usuń wybrane podanie");
System.out.println("===> 2d.Szukaj podania po id");
System.out.println("===> 2e.Szukaj podania po statusie i danych osoby");
System.out.println("===> 2f.Edytuj wybrane podanie");
System.out.println("Wybór:");
String choice = scanner.nextLine();
switch (choice) {
case "1a":
addStudent(studentsCollection, scanner);
break;
case "1b":
viewAllStudents(studentsCollection);
break;
case "1c":
viewAllStudents(studentsCollection);
deleteStudent(studentsCollection, scanner);
break;
case "1d":
viewAllStudents(studentsCollection);
findStudentByID(studentsCollection, scanner);
break;
case "1e":
findStudentByFirsNameSecondNameSpec(studentsCollection, scanner);
break;
case "1f":
findStudentBySubjectAndGrade(studentsCollection, scanner);
break;
case "1g":
viewAllStudents(studentsCollection);
editStudent(studentsCollection, scanner);
break;
case "2a":
addOrder(orderCollection, scanner);
break;
case "2b":
viewAllOrders(orderCollection);
break;
case "2c":
deleteOrder(orderCollection, scanner);
break;
case "2d":
findOrderById(orderCollection, scanner);
break;
case "2e":
findOrderByStatusAndPersonData(orderCollection, scanner);
break;
case "2f":
editOrder(orderCollection, scanner);
break;
}
} while (true);
}
private static void addStudent(MongoCollection<Document> studentsCollection, Scanner scanner) {
String firstName, lastName, specialization, group;
int studyYear;
double mathGrade, programmingGrade, physicsGrade;
Integer indexNumber;
System.out.println("Wpisz imię");
firstName = scanner.nextLine();
System.out.println("Wpisz nazwisko");
lastName = scanner.nextLine();
System.out.println("Wpisz kierunek");
specialization = scanner.nextLine();
System.out.println("Wpisz grupę");
group = scanner.nextLine();
System.out.println("Wpisz rok studiów");
studyYear = scanner.nextInt();
System.out.println("Wpisz numer indeksu");
indexNumber = scanner.nextInt();
System.out.println("Wpisz ocenę z matematki");
mathGrade = scanner.nextDouble();
System.out.println("Wpisz ocenę z programowania");
programmingGrade = scanner.nextDouble();
System.out.println("Wpisz ocenę z fizyki");
physicsGrade= scanner.nextDouble();
scanner.nextLine();
Document studentDocument = new Document("Imie", firstName )
.append("Nazwisko", lastName)
.append("Kierunek", specialization)
.append("Grupa", group)
.append("Rok studiow", studyYear)
.append("Numer indeksu", indexNumber)
.append("Oceny", new Document("matematyka", mathGrade)
.append("programowanie", programmingGrade)
.append("fizyka", physicsGrade));
studentsCollection.insertOne(studentDocument);
System.out.println("Dane zostały dodane");
}
private static void viewAllStudents(MongoCollection<Document> studentsCollection){
for (Document doc : studentsCollection.find())
System.out.println(doc.toJson());
}
private static void deleteStudent(MongoCollection<Document> studentsCollection, Scanner scanner){
String idStudent;
System.out.println("Wpisz id studenta, który ma być usunięty");
idStudent = scanner.nextLine();
studentsCollection.deleteOne(new Document("_id", new ObjectId(idStudent)));
for (Document doc : studentsCollection.find())
System.out.println(doc.toJson());
}
private static void findStudentByID(MongoCollection<Document> studentsCollection, Scanner scanner){
String idStudent;
System.out.println("Wpisz id studenta");
idStudent = scanner.nextLine();
Document studentDoc = studentsCollection.find(Filters.eq("_id", new ObjectId(idStudent))).first();
System.out.println("Znaleziony student to:");
System.out.println(studentDoc.toJson());
}
private static void findStudentByFirsNameSecondNameSpec(MongoCollection<Document> studentsCollection, Scanner scanner) {
String firstName, lastName, specialization;
System.out.println("Wyszukiwanie studentów po imieniu, nazwisku i kierunku studiów");
System.out.println("Wpisz imię");
firstName = scanner.nextLine();
System.out.println("Wpisz nazwisko");
lastName = scanner.nextLine();
System.out.println("Wpisz kierunek");
specialization = scanner.nextLine();
for (Document doc : studentsCollection.find(Filters.and(
eq("Imie", firstName),
eq("Nazwisko", lastName),
eq("Kierunek", specialization))))
System.out.println(doc.toJson());
}
private static void findStudentBySubjectAndGrade(MongoCollection<Document> studentsCollection, Scanner scanner){
String subject;
double grade;
System.out.println("Wyszukiwanie studentów po przedmiocie i ocenie większej niż wybrana");
System.out.println("Wpisz przedmiot");
subject = scanner.nextLine();
System.out.println("Wpisz ocenę od jakiej ma być znaleziony");
grade = scanner.nextDouble();
scanner.nextLine();
for (Document doc : studentsCollection.find((
gt("Oceny." + subject, grade))))
System.out.println(doc.toJson());
}
private static void viewStudentByIdEdited(MongoCollection<Document> studentsCollection, String idStudent){
Document studentDoc = studentsCollection.find(Filters.eq("_id", new ObjectId(idStudent))).first();
System.out.println("Dane zostały aktualizowane");
System.out.println(studentDoc.toJson());
}
private static void editStudent(MongoCollection<Document> studentsCollection, Scanner scanner) {
System.out.println("Wpisz id studenta którego dane chcesz edytować");
String idStudent = scanner.nextLine();
System.out.println("Wybierz pole które chcesz edytować");
System.out.println("1. Imię");
System.out.println("2. Nazwisko");
System.out.println("3. Kierunek");
System.out.println("4. Grupa");
System.out.println("5. Rok studiów");
System.out.println("6. Numer indeksu");
System.out.println("7. Ocenę z matematyki");
System.out.println("8. Ocenę z programowania");
System.out.println("9. Ocenę z fizyki");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 1:
System.out.println("Wpisz nowe imię");
String newFirstName = scanner.nextLine();
studentsCollection.updateOne(eq("_id", new ObjectId(idStudent)), new Document("$set", new Document("Imie", newFirstName)));
viewStudentByIdEdited(studentsCollection, idStudent);
break;
case 2:
System.out.println("Wpisz nowe nazwisko");
String newLastName = scanner.nextLine();
studentsCollection.updateOne(eq("_id", new ObjectId(idStudent)), new Document("$set", new Document("Nazwisko", newLastName)));
viewStudentByIdEdited(studentsCollection, idStudent);
break;
case 3:
System.out.println("Wpisz nowy kierunek");
String newSpecialization = scanner.nextLine();
studentsCollection.updateOne(eq("_id", new ObjectId(idStudent)), new Document("$set", new Document("Kierunek", newSpecialization)));
viewStudentByIdEdited(studentsCollection, idStudent);
break;
case 4:
System.out.println("Wpisz nową grupa");
String newGroup = scanner.nextLine();
studentsCollection.updateOne(eq("_id", new ObjectId(idStudent)), new Document("$set", new Document("Grupa", newGroup)));
viewStudentByIdEdited(studentsCollection, idStudent);
break;
case 5:
System.out.println("Wpisz nowy rok studiów");
int newStudyYear = scanner.nextInt();
studentsCollection.updateOne(eq("_id", new ObjectId(idStudent)), new Document("$set", new Document("Rok studiow", newStudyYear)));
viewStudentByIdEdited(studentsCollection, idStudent);
break;
case 6:
System.out.println("Wpisz nowy numer indeksu");
String newIndexNumber = scanner.nextLine();
studentsCollection.updateOne(eq("_id", new ObjectId(idStudent)), new Document("$set", new Document("Numer indeksu", newIndexNumber)));
viewStudentByIdEdited(studentsCollection, idStudent);
break;
case 7:
System.out.println("Wpisz nową ocenę z matematyki");
double newMathGrade = scanner.nextDouble();
scanner.nextLine();
studentsCollection.updateOne(eq("_id", new ObjectId(idStudent)), new Document("$set", new Document("Oceny.matematyka", newMathGrade)));
viewStudentByIdEdited(studentsCollection, idStudent);
break;
case 8:
System.out.println("Wpisz nową ocenę z programowania");
double newProgrammingGrade = scanner.nextDouble();
scanner.nextLine();
studentsCollection.updateOne(eq("_id", new ObjectId(idStudent)), new Document("$set", new Document("Oceny.programowanie", newProgrammingGrade)));
viewStudentByIdEdited(studentsCollection, idStudent);
break;
case 9:
System.out.println("Wpisz nową ocenę z fizyki");
double newPhysicsGrade = scanner.nextDouble();
scanner.nextLine();
studentsCollection.updateOne(eq("_id", new ObjectId(idStudent)), new Document("$set", new Document("Oceny.fizyka", newPhysicsGrade)));
viewStudentByIdEdited(studentsCollection, idStudent);
break;
}
}
private static void addOrder(MongoCollection<Document> orderCollection, Scanner scanner){
String orderName, nameOfOrderingPerson, specialization, decision, status;
int indexNumber;
System.out.println("Wpisz treść podania");
orderName = scanner.nextLine();
System.out.println("Wpisz decyzję");
decision = scanner.nextLine();
System.out.println("Status podania");
status = scanner.nextLine();
System.out.println("Imię i nazwisko składającego podanie");
nameOfOrderingPerson = scanner.nextLine();
System.out.println("Numer indeksu");
indexNumber = scanner.nextInt();
scanner.nextLine();
System.out.println("Kierunek studenta");
specialization = scanner.nextLine();
Document studentDocument = new Document("Tresc podania", orderName )
.append("Decyzja", decision)
.append("Status", status)
.append("Osoba",
new Document("Dane osoby", nameOfOrderingPerson)
.append("Numer indeksu", indexNumber)
.append("Kierunek", specialization));
orderCollection.insertOne(studentDocument);
System.out.println("Dane zostały dodane");
}
private static void viewAllOrders(MongoCollection<Document> orderCollection){
for (Document doc : orderCollection.find())
System.out.println(doc.toJson());
}
private static void deleteOrder(MongoCollection<Document> orderCollection, Scanner scanner) {
String idOrder;
System.out.println("Wpisz id podania, które ma być usunięte");
idOrder = scanner.nextLine();
orderCollection.deleteOne(new Document("_id", new ObjectId(idOrder)));
for (Document doc : orderCollection.find())
System.out.println(doc.toJson());
}
private static void findOrderById(MongoCollection<Document> orderCollection, Scanner scanner) {
String idOrder;
System.out.println("Wpisz id podania");
idOrder = scanner.nextLine();
Document studentDoc = orderCollection.find(Filters.eq("_id", new ObjectId(idOrder))).first();
System.out.println("Znalezione podanie to:");
System.out.println(studentDoc.toJson());
}
private static void findOrderByStatusAndPersonData(MongoCollection<Document> orderCollection, Scanner scanner){
System.out.println("Wyszukiwanie podania po statusie i danych osoby");
String status, nameOfOrderingPerson;
System.out.println("Wpisz status podania");
status = scanner.nextLine();
System.out.println("Wpisz dane osoby składającej podanie");
nameOfOrderingPerson = scanner.nextLine();
for (Document doc : orderCollection.find(Filters.and(
eq("Status", status),
eq("Osoba.Dane osoby", nameOfOrderingPerson))))
System.out.println(doc.toJson());
}
private static void viewOrderByIdEdited(MongoCollection<Document> orderCollection, String idStudent){
Document orderDoc = orderCollection.find(Filters.eq("_id", new ObjectId(idStudent))).first();
System.out.println("Dane podania aktualizowane");
System.out.println(orderDoc.toJson());
}
private static void editOrder(MongoCollection<Document> orderCollection, Scanner scanner){
System.out.println("Wpisz id podania którego dane chcesz edytować");
String idOrder = scanner.nextLine();
System.out.println("1. Treść podania");
System.out.println("2. Decyzja");
System.out.println("3. Status podania");
System.out.println("4. Imię i nazwisko składającego podanie");
System.out.println("5. Numer indeksu");
System.out.println("6. Kierunek studenta");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 1:
System.out.println("Wpisz nową treść podania");
String orderName = scanner.nextLine();
orderCollection.updateOne(eq("_id", new ObjectId(idOrder)), new Document("$set", new Document("Tresc podania", orderName)));
viewOrderByIdEdited(orderCollection, idOrder);
break;
case 2:
System.out.println("Wpisz nową decyzję");
String decision = scanner.nextLine();
orderCollection.updateOne(eq("_id", new ObjectId(idOrder)), new Document("$set", new Document("Decyzja", decision)));
viewOrderByIdEdited(orderCollection, idOrder);
break;
case 3:
System.out.println("Wpisz nowy status");
String status = scanner.nextLine();
orderCollection.updateOne(eq("_id", new ObjectId(idOrder)), new Document("$set", new Document("Status", status)));
viewOrderByIdEdited(orderCollection, idOrder);
break;
case 4:
System.out.println("Wpisz nowe imię i nazwisko osoby składającej podanie");
String nameOfOrderingPerson = scanner.nextLine();
orderCollection.updateOne(eq("_id", new ObjectId(idOrder)), new Document("$set", new Document("Osoba.Dane osoby", nameOfOrderingPerson)));
viewOrderByIdEdited(orderCollection, idOrder);
break;
case 5:
System.out.println("Wpisz nowy numer indeksu");
int indexNumber = scanner.nextInt();
orderCollection.updateOne(eq("_id", new ObjectId(idOrder)), new Document("$set", new Document("Osoba.Numer indeksu", indexNumber)));
viewOrderByIdEdited(orderCollection, idOrder);
break;
case 6:
System.out.println("Wpisz nowy kierunek");
String specialization = scanner.nextLine();
orderCollection.updateOne(eq("_id", new ObjectId(idOrder)), new Document("$set", new Document("Osoba.Kierunek", specialization)));
viewOrderByIdEdited(orderCollection, idOrder);
break;
}
}
}
|
package task84;
import java.util.Arrays;
import static task84.CardDeck.Card.*;
import static task84.Square.SquareType.*;
/**
* @author Igor
*/
class CardDeck {
Card[] cards = new Card[Constants.DECK_SIZE];
private int index = 0;
private CardDeck() {
Arrays.fill(cards, EMPTY);
}
public void add(int index, Card card) {
cards[index] = card;
}
public boolean nextCard(Board board) {
index = (index + 1) % Constants.DECK_SIZE;
if (cards[index] == Card.EMPTY) {
return false;
}
cards[index].execute(board);
return true;
}
public static CardDeck communityChest() {
CardDeck deck = new CardDeck();
deck.add(0, C1);
deck.add(1, C2);
return deck;
}
public static CardDeck chance() {
CardDeck deck = new CardDeck();
int i = 0;
for (Card card : Card.values()) {
deck.add(i++, card);
}
return deck;
}
public static enum Card {
C1 {
@Override
void execute(Board board) {
board.goTo(Constants.GO);
}
},
C2 {
@Override
void execute(Board board) {
board.goTo(Constants.JAIL);
}
},
C3 {
@Override
void execute(Board board) {
board.goTo(Constants.C1);
}
},
C4 {
@Override
void execute(Board board) {
board.goTo(Constants.E3);
}
},
C5 {
@Override
void execute(Board board) {
board.goTo(Constants.H2);
}
},
C6 {
@Override
void execute(Board board) {
board.goTo(Constants.R1);
}
},
C7 {
@Override
void execute(Board board) {
board.goTo(R);
}
},
C8 {
@Override
void execute(Board board) {
board.goTo(R);
}
},
C9 {
@Override
void execute(Board board) {
board.goTo(U);
}
},
C10 {
@Override
void execute(Board board) {
board.index = board.index - 3;
}
},
EMPTY;
void execute(Board board) {
}
}
}
|
package ch.bbw.mastermind_new;
import java.util.Random;
public class Generation {
public int [] generateNumberRow() {
int max = 6;
int min = 1;
int[] numberRow = new int[4];
Random rn = new Random();
numberRow[0] = rn.nextInt(max - min + 1) + min;
numberRow[1] = rn.nextInt(max - min + 1) + min;
numberRow[2] = rn.nextInt(max - min + 1) + min;
numberRow[3] = rn.nextInt(max - min + 1) + min;
// zum testen -> wird im echten Spiel nicht gebraucht
System.out.println(numberRow[0]+""+numberRow[1]+""+numberRow[2]+""+numberRow[3]);
return numberRow;
}
}
|
package com.tt.miniapp.base.report;
import com.bytedance.sandboxapp.b.a;
import com.bytedance.sandboxapp.protocol.service.n.b;
import com.tt.miniapphost.monitor.AppBrandMonitor;
import d.f.b.l;
import org.json.JSONObject;
public final class MonitorReportService implements b {
private final a context;
public MonitorReportService(a parama) {
this.context = parama;
}
public final a getContext() {
return this.context;
}
public final void onDestroy() {}
public final void reportInvokeApiFail(int paramInt, JSONObject paramJSONObject) {
l.b(paramJSONObject, "param");
AppBrandMonitor.statusRate("mp_invoke_api_failed", 7000, paramJSONObject);
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\base\report\MonitorReportService.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package com.example.lib.assit;
import android.app.Activity;
import android.app.Dialog;
import com.example.lib.ReportLog;
import com.example.lib.core.ReportCenterAPI;
import com.example.lib.event.Event;
import org.json.JSONException;
import org.json.JSONObject;
public class DialogReportAssit {
ReportCenterAPI reportCenterAPI;
public DialogReportAssit(ReportCenterAPI reportCenterAPI) {
this.reportCenterAPI = reportCenterAPI;
}
public void handleDialogShowed(Dialog dialog) {
ReportLog.logD("handleActivity appStart");
JSONObject object = new JSONObject();
reportCenterAPI.trackEvent(Event.APP_START, object);
}
public void handleAlertDialogClicked(Dialog dialog,int which) {
ReportLog.logD("handleActivity appStart");
JSONObject object = new JSONObject();
reportCenterAPI.trackEvent(Event.APP_START, object);
}
}
|
package com.linda.framework.rpc.nio;
import org.apache.log4j.Logger;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.LinkedList;
public class NioByteBufferTest {
static Logger logger = Logger.getLogger(NioByteBufferTest.class);
public static void testBuf() throws IOException {
String str = "this is a test";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
WritableByteChannel writeChannel = Channels.newChannel(bos);
ByteBuffer buffer = ByteBuffer.allocate(256);
buffer.putInt(21);
buffer.putInt(43);
byte[] bytes = str.getBytes();
buffer.putInt(bytes.length);
buffer.put(bytes);
infoBuffer(buffer);
buffer.flip();
buffer.position(4);
int write = writeChannel.write(buffer);
infoBuffer(buffer);
byte[] dest = bos.toByteArray();
logger.info("dest len:" + dest.length);
ByteArrayInputStream bis = new ByteArrayInputStream(dest);
ReadableByteChannel readChannel = Channels.newChannel(bis);
infoBuffer(buffer);
buffer.clear();
int read = readChannel.read(buffer);
infoBuffer(buffer);
buffer.flip();
infoBuffer(buffer);
int int1 = buffer.getInt();
int int2 = buffer.getInt();
int len = buffer.getInt();
byte[] sss = new byte[len];
buffer.get(sss, 0, len);
logger.info("int1:" + int1 + " int2:" + int2 + " len:" + len);
logger.info("str:" + new String(sss));
}
public static void main(String[] args) throws IOException {
LinkedList<String> list = new LinkedList<String>();
list.offer("123");
list.offer("234");
String peek = list.peek();
String peek2 = list.peek();
logger.info("peak:" + peek + " " + peek2);
}
public static void infoBuffer(ByteBuffer buffer) {
logger.info(
"position:" + buffer.position() + " limit:" + buffer.limit() + " mark:" + buffer.mark() + " capacity:" +
buffer.capacity());
}
}
|
package com.yunhe.cargomanagement.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
/**
* @program: tradesteward
* @description: 史江浩
* @author: 史江浩
* @create: 2019-01-17 16:12
**/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@TableName("warehouse_receipt")
public class WarehouseReceipt implements Serializable {
private static final long serialVersionUID = 1L;
public WarehouseReceipt() {
}
/**
* id
*/
@TableId(value = "id",type = IdType.AUTO)
private Integer id;
/**
* 业务日期
*/
@TableField(value = "wre_date")
private String wreDate;
/**
* 单据编号
*/
@TableField(value = "wre_number")
private String wreNumber;
/**
* 类型
*/
@TableField(value = "wre_type")
private String wreType;
/**
* 往来单位名称
*/
@TableField(value = "wre_current_unit")
private String wreCurrentUnit;
/**
* 入库仓库
*/
@TableField(value = "wre_warehost_name")
private String wreWarehostName;
/**
* 入库商品
*/
@TableField(value = "wre_storage")
private String wreStorage;
/**
* 入库量
*/
@TableField(value = "wre_scheduled_receipt")
private Integer wreScheduledReceipt;
/**
* 制单日期
*/
@TableField(value = "wre_date_order")
private String wreDateOrder;
/**
* 制单人
*/
@TableField(value = "wre_single_person")
private String wreSinglePerson;
/**
* 经手人
*/
@TableField(value = "wre_experienced_person")
private String wreExperiencedPerson;
/**
* 状态
*/
@TableField(value = "wre_state")
private String wreState;
public static long getSerialVersionUID() {
return serialVersionUID;
}
}
|
package test.question.answer.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import test.controller.Action;
import test.controller.ActionForward;
import test.question.answer.dao.QAWriterDao;
import test.question.answer.dto.QAWriterDto;
public class QuestionAUpdateAction extends Action{
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) {
//저장할 num값과 그외의 정보 값들 불러오기
int num=Integer.parseInt(request.getParameter("num"));
String mainquestion=request.getParameter("mainquestion");
String detailquestion=request.getParameter("detailquestion");
//dto 객체 생성
QAWriterDto dto=new QAWriterDto();
dto.setWriterNum(num);
dto.setWriterMainquestion(mainquestion);
dto.setWriterDetailquestion(detailquestion);
//dao에서 update 메소드 실행
QAWriterDao.getInstance().update(dto);
//redirect 이동
return new ActionForward("list.do",true);
}
}
|
package com.args.cineduniya;
import android.content.Context;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private Context mContext;
private List<Upload> muploads;
private OnItemClickListener mListener;
//to display the product images to home activity
//this works has an adapted between the app and the firebase
public ImageAdapter(Context context, List<Upload> uploads) {
mContext = context;
muploads = uploads;
}
@NonNull
@Override
public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
return new ImageViewHolder(v);
}
//this part helps us to show the images in the recycler view...
@Override
public void onBindViewHolder(@NonNull ImageViewHolder holder, int position) {
Upload uploadCusrrent = muploads.get(position);
//url for text name
holder.textViewName.setText(uploadCusrrent.getmName());
//for movie name
holder.textViewName_movie_name.setText(uploadCusrrent.getMovie_name());
//for movie poster
holder.textView_url_of_image.setText(uploadCusrrent.getmImageUrl());
//for movie banner
holder.Textview_banner_url.setText(uploadCusrrent.getMposterurl());
//for movie description
holder.TextView_description.setText(uploadCusrrent.getDescription());
//for movie rating
holder.Textview_rating.setText(uploadCusrrent.getRating().toString());
//for release date
holder.Textview_release_year.setText(uploadCusrrent.getRelease_year().toString());
//for trailer url
holder.Textview_trailer.setText(uploadCusrrent.getTrailer().toString());
Glide.with(mContext)
.load(uploadCusrrent.getmImageUrl())
.centerInside()
.into(holder.imageView);
}
@Override
public int getItemCount() {
return muploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnCreateContextMenuListener {
public ImageView imageView;
public LinearLayout vid_play;
public TextView textViewName;
public TextView textViewName_movie_name,textView_url_of_image,Textview_banner_url,TextView_description,Textview_rating,Textview_release_year,Textview_trailer;
public ImageViewHolder(View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image_view_upload);
vid_play = itemView.findViewById(R.id.onclick_linear);
textViewName = itemView.findViewById(R.id.textview_name);
textViewName_movie_name = itemView.findViewById(R.id.textview_name2);
textView_url_of_image = itemView.findViewById(R.id.textview_imageurl);
Textview_banner_url = itemView.findViewById(R.id.textview_banner_url);
TextView_description = itemView.findViewById(R.id.textview_description);
Textview_rating = itemView.findViewById(R.id.textview_rating);
Textview_release_year = itemView.findViewById(R.id.textview_release_year);
Textview_trailer = itemView.findViewById(R.id.textview_trailer);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
@Override
public void onClick(View v) {
if(mListener != null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
String vid_url = textViewName.getText().toString();
String vid_name = textViewName_movie_name.getText().toString();
String poster_url = textView_url_of_image.getText().toString();
String banner_url = Textview_banner_url.getText().toString();
String Description = TextView_description.getText().toString();
String trailer_url = Textview_trailer.getText().toString();
Float rating_movie = Float.parseFloat(Textview_rating.getText().toString());
Float release_year = Float.parseFloat(Textview_release_year.getText().toString());
mListener . OnItemClick(vid_url,vid_name,poster_url,banner_url,Description,rating_movie,release_year,trailer_url);
}
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
}
}
public interface OnItemClickListener{
//,int release_date
void OnItemClick(String url,String mov_name,String poster_url, String banner_url, String description,Float rating,Float release_date,String trailer);
}
public void setOnItemClickListener(OnItemClickListener listener)
{
mListener = listener;
}
public void filerList(ArrayList<Upload> filterList)
{
try {
muploads = filterList;
notifyDataSetChanged();
}catch (Exception e)
{
Toast.makeText(mContext, ""+e, Toast.LENGTH_SHORT).show();
}
}
}
|
/*package com.selfridges.test;
import junit.framework.Assert;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.support.PageFactory;
import com.selfridges.pages.GlobalMenu;
import com.selfridges.pages.HomePage;
import com.selfridges.pages.OrderConfirmationPage;
import com.selfridges.pages.PaymentPage;
import com.selfridges.util.WebController;
import cucumber.api.Scenario;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
@SuppressWarnings("deprecation")
public class vijay1 {
WebController controller=WebController.getInstance();
GlobalMenu gm = null;
HomePage hp = PageFactory.initElements(controller.driver, HomePage.class);
PaymentPage pp = PageFactory.initElements(controller.driver, PaymentPage.class);
OrderConfirmationPage ocp = PageFactory.initElements(controller.driver, OrderConfirmationPage.class);
@Before
public void setUp(){
System.out.println("Running before method");
controller.invokeBrowser();
controller.goToURL("HomePageURL");
@After
public void tearDown(Scenario scenario){
System.out.println("Running after method");
//Embed the screenshots to the report if scenario is failed
if (scenario.isFailed()) {
final byte[] screenshot = ((TakesScreenshot) controller.driver).getScreenshotAs(OutputType.BYTES);
scenario.embed(screenshot, "image/png");
}
//controller.closeBrowser();
}
@SuppressWarnings("deprecation")
@Given("^Im on Selfridges website$")
public void Im_on_Selfridges_website() throws Throwable {
//Assert.assertTrue("Sorry You are not on the home page", ((hp.GetHomePageUrl().contains("selfridges.com")) && (!hp.GetHomePageUrl().contains("selfridges.com/"))));
}
@When("^I add \"([^\"]*)\" to the basket$")
public void I_add_to_the_basket(String arg1) throws Throwable {
gm = PageFactory.initElements(controller.driver, GlobalMenu.class);
//gm.clickMensL1link();
gm.searchProduct(arg1).goToPDPOfSecondProduct().addToBag();
}
@When("^I choose collection point as \"([^\"]*)\" with deliver to \"([^\"]*)\", \"([^\"]*)\",\"([^\"]*)\",\"([^\"]*)\",\"([^\"]*)\"$")
public PaymentPage I_choose_collection_point_as_with_deliver_to_(String storename, String title, String fname, String lname, String email, String phonenum) throws Throwable {
pp = gm.clickBasketIcon().continueToCheckOut().guestCheckOut().clickAndCollectAsGuest(title,fname,lname,email,phonenum).
clickOnOrderSummaryButtonOnRight().selectFirstAvailableCollectionDate().clickOnPayNowButton1();
return pp;
}
@When("^I paid towards my product with \"([^\"]*)\",\"([^\"]*)\",\"([^\"]*)\",\"([^\"]*)\",\"([^\"]*)\",\"([^\"]*)\",\"([^\"]*)\",\"([^\"]*)\",\"([^\"]*)\",\"([^\"]*)\"$")
public void I_paid_towards_my_product_with_(String cardNumber, String nameOnCard, String expMonth, String expYear, String cvv, String postcode, String line1, String line2, String line3, String line4) throws Throwable {
pp.payWithNewCard(cardNumber,nameOnCard,expMonth,expYear,cvv,postcode,line1,line2,line3,line4);
}
@Then("^I should get an order confirmation$")
public void I_should_get_an_order_confirmation() throws Throwable {
System.out.println(ocp.getOrderConfirmationNumer());
Assert.assertTrue("Order not placed successfully", ocp.isConfirmationNumerGenerated());
Assert.assertTrue("ThankYou Message not displayed", ocp.isThankYouMessageTextDispalyed());
Assert.assertTrue("Email sent confirmation information not displayed", ocp.isEmailConfirmationTextDispalyed());
}
@When("^I hover over \"([^\"]*)\" and I selected \"([^\"]*)\" and added a first item in the basket$")
public void I_hover_over_Mens_and_I_selected_All_categories_and_added_a_first_item_in_the_basket(String arg1, String arg2) throws Throwable {
}
}
*/
|
package com.adm.bamboo.plugin.uft.api;
import com.adm.bamboo.plugin.uft.capability.CapabilityUftDefaultsHelper;
import com.adm.bamboo.plugin.uft.helpers.HpTasksArtifactRegistrator;
import com.atlassian.bamboo.build.Job;
import com.atlassian.bamboo.collections.ActionParametersMap;
import com.atlassian.bamboo.plan.artifact.ArtifactDefinitionManager;
import com.atlassian.bamboo.task.AbstractTaskConfigurator;
import com.atlassian.bamboo.task.TaskDefinition;
import com.atlassian.bamboo.task.TaskRequirementSupport;
import com.atlassian.bamboo.v2.build.agent.capability.Requirement;
import com.atlassian.bamboo.v2.build.agent.capability.RequirementImpl;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class AbstractLauncherTaskConfigurator extends AbstractTaskConfigurator implements TaskRequirementSupport {
private static final String BUILD_WORKING_DIR = "bamboo.agentId";
private ArtifactDefinitionManager artifactDefinitionManager;
public void setArtifactDefinitionManager(ArtifactDefinitionManager artifactDefinitionManager) {
this.artifactDefinitionManager = artifactDefinitionManager;
}
public Map<String, String> generateTaskConfigMap(@NotNull final ActionParametersMap params, @Nullable final TaskDefinition previousTaskDefinition) {
final Map<String, String> config = super.generateTaskConfigMap(params, previousTaskDefinition);
config.put(BUILD_WORKING_DIR, "${bamboo.build.working.directory}");
return config;
}
@Override
public void populateContextForEdit(@NotNull final Map<String, Object> context, @NotNull final TaskDefinition taskDefinition) {
super.populateContextForEdit(context, taskDefinition);
context.put(BUILD_WORKING_DIR, taskDefinition.getConfiguration().get(BUILD_WORKING_DIR));
}
@Override
public void populateContextForCreate(@NotNull final Map<String, Object> context) {
super.populateContextForCreate(context);
(new HpTasksArtifactRegistrator()).registerCommonArtifact((Job) context.get("plan"), getI18nBean(), this.artifactDefinitionManager);
}
@NotNull
@Override
public Set<Requirement> calculateRequirements(TaskDefinition taskDefinition) {
RequirementImpl uftReq = new RequirementImpl(CapabilityUftDefaultsHelper.CAPABILITY_UFT, true, ".*");
Set<Requirement> result = new HashSet<Requirement>();
result.add(uftReq);
return result;
}
}
|
/*
* UniTime 3.5 (University Timetabling Application)
* Copyright (C) 2014, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.unitime.timetable.gwt.client.widgets;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.logical.shared.HasSelectionHandlers;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.event.shared.HasHandlers;
import com.google.gwt.user.client.TakesValue;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.IsWidget;
/**
* @author Tomas Muller
*/
public interface CourseFinder extends HasValue<String>, HasSelectionHandlers<String>, IsWidget {
public void findCourse();
public void setTabs(CourseFinderTab... tabs);
public interface CourseFinderTab<E> extends HasValue<String>, HasSelectionHandlers<String>, IsWidget, KeyUpHandler, HasResponseHandlers {
public String getName();
public void setDataProvider(DataProvider<String, E> provider);
public boolean isCourseSelection();
public void setCourseDetails(CourseFinderCourseDetails... details);
public void changeTip();
}
public interface CourseFinderCourseDetails<E> extends TakesValue<String>, IsWidget {
public void setDataProvider(DataProvider<String, E> provider);
public String getName();
}
public interface HasResponseHandlers extends HasHandlers {
HandlerRegistration addResponseHandler(ResponseHandler handler);
}
public interface ResponseHandler extends EventHandler {
void onResponse(ResponseEvent event);
}
public class ResponseEvent extends GwtEvent<ResponseHandler> {
static Type<ResponseHandler> TYPE = new Type<ResponseHandler>();
private boolean iValid;
public ResponseEvent(boolean valid) { iValid = valid; }
public boolean isValid() { return iValid; }
@Override
public Type<ResponseHandler> getAssociatedType() { return TYPE; }
public static Type<ResponseHandler> getType() { return TYPE; }
@Override
protected void dispatch(ResponseHandler handler) {
handler.onResponse(this);
}
public static void fire(HasHandlers source, boolean valid) {
source.fireEvent(new ResponseEvent(valid));
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.