text
stringlengths
10
2.72M
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; public class JFrameDocente extends javax.swing.JFrame { protected Professor professor; protected String login; protected String senha; protected DataInputStream in; protected DataOutputStream out; public JFrameDocente() { initComponents(); // Centraliza a janela setLocationRelativeTo(null); } public JFrameDocente(Professor professor, String login, String senha, DataInputStream in, DataOutputStream out) { initComponents(); // Centraliza a janela setLocationRelativeTo(null); // Seta as streams de entrada e saída try { this.professor = professor; this.senha = senha; this.login = login; this.in = in; this.out = out; } catch (Exception e) { JOptionPane.showMessageDialog(this, "Falha no servidor.", "Erro", JOptionPane.ERROR_MESSAGE); } } /** * 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() { jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); jMenuItem3 = new javax.swing.JMenuItem(); jMenuItem4 = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jMenu1.setText("Menu"); jMenuItem1.setText("Criar Nova Prova"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu1.add(jMenuItem1); jMenuItem2.setText("Consultar Prova(s)"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); jMenu1.add(jMenuItem2); jMenuItem3.setText("Resultado(s)"); jMenuItem3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem3ActionPerformed(evt); } }); jMenu1.add(jMenuItem3); jMenuItem4.setText("Sair"); jMenuItem4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem4ActionPerformed(evt); } }); jMenu1.add(jMenuItem4); jMenuBar1.add(jMenu1); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 480, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 303, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents // Consultar resultados private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed try { out.writeInt(36); out.writeUTF(login); out.writeUTF(senha); in.readBoolean(); int tam = in.readInt(); byte[] bytes = new byte[tam]; in.read(bytes); professor = (Professor) Serializador.converterByteArrayParaObjeto(bytes); } catch (Exception e) { System.out.println(e.getMessage()); JOptionPane.showMessageDialog(this, "Falha no servidor.", "Erro", JOptionPane.ERROR_MESSAGE); } JFrameConsulta janelaConsulta = new JFrameConsulta(professor, in, out); pack(); janelaConsulta.setVisible(true); janelaConsulta.setDefaultCloseOperation(JFrameInicial.DISPOSE_ON_CLOSE); }//GEN-LAST:event_jMenuItem3ActionPerformed // Consultar provas private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed try { out.writeInt(36); out.writeUTF(login); out.writeUTF(senha); in.readBoolean(); int tam = in.readInt(); byte[] bytes = new byte[tam]; in.read(bytes); professor = (Professor) Serializador.converterByteArrayParaObjeto(bytes); } catch (Exception e) { System.out.println(e.getMessage()); JOptionPane.showMessageDialog(this, "Falha no servidor.", "Erro", JOptionPane.ERROR_MESSAGE); } JFrameConsulta janelaConsulta = new JFrameConsulta(professor, in, out); pack(); janelaConsulta.setVisible(true); janelaConsulta.setDefaultCloseOperation(JFrameInicial.DISPOSE_ON_CLOSE); }//GEN-LAST:event_jMenuItem2ActionPerformed // Criar nova prova private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed JFrameCriarNovaProva janelaCriarNovaProva = new JFrameCriarNovaProva(professor, in, out); pack(); janelaCriarNovaProva.setVisible(true); janelaCriarNovaProva.setDefaultCloseOperation(JFrameInicial.DISPOSE_ON_CLOSE); }//GEN-LAST:event_jMenuItem1ActionPerformed // Sair private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed try { in.close(); out.close(); System.exit(0); } catch (IOException ex) { JOptionPane.showMessageDialog(this, "Falha no servidor.", "Erro", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jMenuItem4ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(JFrameDocente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(JFrameDocente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(JFrameDocente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(JFrameDocente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new JFrameDocente().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JMenu jMenu1; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JMenuItem jMenuItem4; // End of variables declaration//GEN-END:variables }
package charset_test; import java.io.UnsupportedEncodingException; public class Test1 { public static void main(String[] args) throws UnsupportedEncodingException { String str = "中文"; System.out.println(new String(str.getBytes("ISO-8859-1"), "UTF-8")); System.out.println(new String(str.getBytes("UTF-8"), "UTF-8"));// 中文 System.out.println(new String(str.getBytes("GBK"), "UTF-8")); System.out.println(new String(str.getBytes("ISO-8859-1"), "GBK")); System.out.println(new String(str.getBytes("UTF-8"), "ISO-8859-1")); System.out.println(new String(str.getBytes("UTF-8"), "GBK")); System.out.println(new String(str.getBytes("GBK"), "GBK"));// 中文 System.out.println(new String(str.getBytes("ISO-8859-1"), "ISO-8859-1")); } }
package com.mes.old.meta; // Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final import java.util.Date; /** * WOrderflow generated by hbm2java */ public class WOrderflow implements java.io.Serializable { private String uniqueid; private String billuid; private long billtype; private String sender; private Date sendtime; private String acceptor; private Long isineffect; private String notes; private String deptid; private String wtaskid; private String wtaskname; private String dealtype; private String excutionid; private String taskuid; private String checkbilltype; private String piid; private String processname; private String billnumber; public WOrderflow() { } public WOrderflow(String uniqueid, String billuid, long billtype, String sender, Date sendtime) { this.uniqueid = uniqueid; this.billuid = billuid; this.billtype = billtype; this.sender = sender; this.sendtime = sendtime; } public WOrderflow(String uniqueid, String billuid, long billtype, String sender, Date sendtime, String acceptor, Long isineffect, String notes, String deptid, String wtaskid, String wtaskname, String dealtype, String excutionid, String taskuid, String checkbilltype, String piid, String processname, String billnumber) { this.uniqueid = uniqueid; this.billuid = billuid; this.billtype = billtype; this.sender = sender; this.sendtime = sendtime; this.acceptor = acceptor; this.isineffect = isineffect; this.notes = notes; this.deptid = deptid; this.wtaskid = wtaskid; this.wtaskname = wtaskname; this.dealtype = dealtype; this.excutionid = excutionid; this.taskuid = taskuid; this.checkbilltype = checkbilltype; this.piid = piid; this.processname = processname; this.billnumber = billnumber; } public String getUniqueid() { return this.uniqueid; } public void setUniqueid(String uniqueid) { this.uniqueid = uniqueid; } public String getBilluid() { return this.billuid; } public void setBilluid(String billuid) { this.billuid = billuid; } public long getBilltype() { return this.billtype; } public void setBilltype(long billtype) { this.billtype = billtype; } public String getSender() { return this.sender; } public void setSender(String sender) { this.sender = sender; } public Date getSendtime() { return this.sendtime; } public void setSendtime(Date sendtime) { this.sendtime = sendtime; } public String getAcceptor() { return this.acceptor; } public void setAcceptor(String acceptor) { this.acceptor = acceptor; } public Long getIsineffect() { return this.isineffect; } public void setIsineffect(Long isineffect) { this.isineffect = isineffect; } public String getNotes() { return this.notes; } public void setNotes(String notes) { this.notes = notes; } public String getDeptid() { return this.deptid; } public void setDeptid(String deptid) { this.deptid = deptid; } public String getWtaskid() { return this.wtaskid; } public void setWtaskid(String wtaskid) { this.wtaskid = wtaskid; } public String getWtaskname() { return this.wtaskname; } public void setWtaskname(String wtaskname) { this.wtaskname = wtaskname; } public String getDealtype() { return this.dealtype; } public void setDealtype(String dealtype) { this.dealtype = dealtype; } public String getExcutionid() { return this.excutionid; } public void setExcutionid(String excutionid) { this.excutionid = excutionid; } public String getTaskuid() { return this.taskuid; } public void setTaskuid(String taskuid) { this.taskuid = taskuid; } public String getCheckbilltype() { return this.checkbilltype; } public void setCheckbilltype(String checkbilltype) { this.checkbilltype = checkbilltype; } public String getPiid() { return this.piid; } public void setPiid(String piid) { this.piid = piid; } public String getProcessname() { return this.processname; } public void setProcessname(String processname) { this.processname = processname; } public String getBillnumber() { return this.billnumber; } public void setBillnumber(String billnumber) { this.billnumber = billnumber; } }
package pl.java.scalatech.camel; import static org.apache.camel.component.jms.JmsComponent.jmsComponentAutoAcknowledge; import javax.jms.ConnectionFactory; import javax.jms.Message; import javax.jms.TextMessage; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.camel.CamelContext; import org.apache.camel.ExchangePattern; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.jms.JmsComponent; import org.apache.camel.component.jms.JmsMessage; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.assertj.core.api.Assertions; import org.junit.Test; import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.core.MessageCreator; import lombok.extern.slf4j.Slf4j; @Slf4j public class JmsJMSReplyToEndpointUsingInOutTest2 extends CamelTestSupport { private JmsComponent amq; @Test public void testCustomJMSReplyToInOut() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("My name is Slawek"); String response = template.requestBody("activemq:queue:hello","What's your name",String.class); Assertions.assertThat(response).isEqualTo("My name is Slawek"); assertMockEndpointsSatisfied(); } protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { JmsTemplate jms = new JmsTemplate(amq.getConfiguration().getConnectionFactory()); public void configure() throws Exception { from("activemq:queue:hello") .to(ExchangePattern.InOut, "activemq:queue:serviceRequestor?replyTo=queue:serviceReplyQueue") .to("mock:result"); from("activemq:queue:serviceRequestor").process(exchange -> { Message message = ((JmsMessage) exchange.getIn()).getJmsMessage(); String question = ((TextMessage)message).getText(); jms.send(message.getJMSReplyTo(), (MessageCreator) session -> { TextMessage replyMsg = session.createTextMessage(); replyMsg.setText("My name is Slawek"); replyMsg.setJMSCorrelationID(message.getJMSCorrelationID()); return replyMsg; }); }); } }; } protected CamelContext createCamelContext() throws Exception { CamelContext camelContext = super.createCamelContext(); ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616"); camelContext.addComponent("activemq", jmsComponentAutoAcknowledge(connectionFactory)); amq = camelContext.getComponent("activemq", JmsComponent.class); return camelContext; } }
package solution.cs3330.hw3; public class Health { private int health_points; private boolean alive; public Health () { setHealth(100); setAlive(true); } public Health (int hp) { setHealth(hp); setAlive(true); } private void setHealth(int hp) { if (hp >= 1) { this.health_points = hp; } else { setAlive(false); } } private void setAlive(boolean a) { this.alive = a; } public int getHealthPoints() { return this.health_points; } public boolean getAlive() { return this.alive; } public void hit(int hitPoints) { setHealth(getHealthPoints() + hitPoints); } public void heal(int healPoints) { setHealth (getHealthPoints() + healPoints); } }
import java.util.Scanner; public class Example2_7 // Find the number of years { public static void main(String[] args) { Scanner input = new Scanner(System.in); // prompt the user to enter the minutes System.out.print(" Enter the number of minutes:"); int minutes = input.nextInt(); int days= 1, years= 0; // calculate no .of years // year has 365 days,24 hours and one hour is 60 min years = minutes /(365*24*60); int d = minutes - (years *365*24*60); //calculate days days = d/(24*60); System.out.println( +minutes + " minutes is approximately " +years +" years and " +days +" days"); } }
package de.fatoak.engine.actor.components; import de.fatoak.engine.actor.Actor; import de.fatoak.engine.ai.State; import de.fatoak.engine.resource.DataElement; /** * Created by Markus on 09.05.2014. */ public final class AIComponent extends ActorComponent { private State mCurrentState; public final static String NAME = "AIComponent"; private Actor mParentActor; public AIComponent(Actor actor) { mParentActor = actor; } public AIComponent(Actor actor, DataElement componentElement) { this(actor); } public void init() { } public String getName() { return NAME; } }
package umbrella; import javax.swing.JOptionPane; public class Umbrella2 { public static void main(String[] args) { { int questionraining = JOptionPane.showConfirmDialog(null, "Is it raining ?"); // Question to determine if it is raining if (questionraining == JOptionPane.YES_OPTION) { JOptionPane.showMessageDialog(null, "Put up the umbrella "); // output } else if (questionraining == JOptionPane.CANCEL_OPTION) { } else { int mightitrain = JOptionPane.showConfirmDialog(null, "Does it look like it will rain ?"); // Question to determine if it looks like it will rain if (mightitrain == JOptionPane.YES_OPTION) { JOptionPane.showMessageDialog(null, "Bring an umbrella "); // Output } else if (mightitrain == JOptionPane.CANCEL_OPTION) { } else { JOptionPane.showMessageDialog(null ,"Do not bring an umbrella"); } } } } }
package com.resumenpit.interfaces; import java.util.List; import com.resumenpit.models.EstadoDTO; public interface EstadoDAO { List<EstadoDTO> listarEstados(); }
package com.haidroid.duoihinhbatbong.utils; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; public class PREF { private static PREF PREP; private SharedPreferences _pref; private Editor editor; public static PREF getInstance(Context context) { if (PREP == null) { PREP = new PREF(context); } return PREP; } public PREF(Context context) { super(); _pref = context.getSharedPreferences(CONST.PREF_KEY_NAME, Context.MODE_PRIVATE); editor = _pref.edit(); } public boolean getGuide() { return _pref.getBoolean(CONST.PREF_KEY_GUIDE, true); } public void setGuide(boolean value) { editor.putBoolean(CONST.PREF_KEY_GUIDE, value); editor.commit(); } public boolean getComingSoon() { return _pref.getBoolean(CONST.PREF_KEY_COMINGSOON, true); } public void setComingSoon(boolean value) { editor.putBoolean(CONST.PREF_KEY_COMINGSOON, value); editor.commit(); } public boolean isShared() { return _pref.getBoolean(CONST.PREF_KEY_SHARED, false); } public void setShared(boolean value) { editor.putBoolean(CONST.PREF_KEY_SHARED, value); editor.commit(); } /**/ public boolean getSoundConfig() { return _pref.getBoolean(CONST.PREF_KEY_SOUND, true); } public void setSoundConfig(boolean value) { editor.putBoolean(CONST.PREF_KEY_SOUND, value); editor.commit(); } public int getCurCoin() { return _pref.getInt(CONST.PREF_KEY_COIN, CONST.DEFAULT_COIN); } public void setCoin(int value) { editor.putInt(CONST.PREF_KEY_COIN, value); editor.commit(); } public int getCurQuiz() { return _pref.getInt(CONST.PREF_KEY_STAGE, 0); } public void setQuiz(int value) { editor.putInt(CONST.PREF_KEY_STAGE, value); editor.commit(); } public int getTheme() { return _pref.getInt(CONST.PREF_KEY_THEME, CONST.THEME_BLACK); } public void setTheme(int value) { editor.putInt(CONST.PREF_KEY_THEME, value); editor.commit(); } // public String getAppInstalled() { return _pref.getString(CONST.PREF_KEY_GIFT_INSTALL, "dhbb_"); } public void setAppInstalled(String value) { editor.putString(CONST.PREF_KEY_GIFT_INSTALL, value); editor.commit(); } }
package net.youzule.spring.chapter04.app1; /** * @description: * @company: * @author:Sean * @date:2018/7/4 18:56 **/ /*Wheel类*/ public class Wheel { private int count; public Wheel() { } public int getCount() { return count; } public void setCount(int count) { this.count = count; } @Override public String toString() { return "Wheel{" + "count=" + count + '}'; } }
package schr0.tanpopo.init; import net.minecraft.block.Block; import net.minecraft.block.BlockCauldron; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.monster.EntityEnderman; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.init.SoundEvents; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.stats.StatList; import net.minecraft.util.EnumHand; import net.minecraft.util.ResourceLocation; import net.minecraft.util.SoundCategory; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.World; import net.minecraft.world.storage.loot.LootEntryItem; import net.minecraft.world.storage.loot.LootPool; import net.minecraft.world.storage.loot.LootTableList; import net.minecraft.world.storage.loot.conditions.LootCondition; import net.minecraft.world.storage.loot.functions.LootFunction; import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.common.ForgeModContainer; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.AnvilUpdateEvent; import net.minecraftforge.event.AttachCapabilitiesEvent; import net.minecraftforge.event.LootTableLoadEvent; import net.minecraftforge.event.entity.living.LivingDropsEvent; import net.minecraftforge.event.entity.living.LivingFallEvent; import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.fluids.UniversalBucket; import net.minecraftforge.fml.client.event.ConfigChangedEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import schr0.tanpopo.Tanpopo; import schr0.tanpopo.TanpopoVanillaHelper; import schr0.tanpopo.block.BlockEssenceCauldron; import schr0.tanpopo.block.BlockFluffCushion; import schr0.tanpopo.capabilities.FluidHandlerItemEssenceGlassBottle; import schr0.tanpopo.item.ItemModeTool; import schr0.tanpopo.item.ItemModeToolAttachment; public class TanpopoEvent { public void init() { MinecraftForge.EVENT_BUS.register(this); } @SubscribeEvent public void onConfigChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event) { if (event.getModID().equals(Tanpopo.MOD_ID)) { TanpopoConfig.syncConfig(); } } @SubscribeEvent public void onLootTableLoadEvent(LootTableLoadEvent event) { ResourceLocation resLootTable = event.getName(); if (resLootTable.equals(LootTableList.CHESTS_STRONGHOLD_LIBRARY) || resLootTable.equals(LootTableList.CHESTS_STRONGHOLD_CROSSING) || resLootTable.equals(LootTableList.CHESTS_STRONGHOLD_CORRIDOR)) { final LootPool pool = event.getTable().getPool("main"); if (pool != null) { pool.addEntry(new LootEntryItem(Item.getItemFromBlock(TanpopoBlocks.PLANT_ROOTS), 100, 0, new LootFunction[0], new LootCondition[0], Tanpopo.MOD_ID + ":" + TanpopoBlocks.NAME_PLANT_ROOTS)); } } } @SubscribeEvent public void onLivingDropsEvent(LivingDropsEvent event) { EntityLivingBase entityLivingBase = event.getEntityLiving(); World world = entityLivingBase.worldObj; if (world.isRemote) { return; } if ((entityLivingBase instanceof EntityEnderman) && (event.getSource().getSourceOfDamage() instanceof EntityLivingBase)) { int chance = 50; if (((EntityEnderman) entityLivingBase).getHeldBlockState() != null) { chance += 30; } if (world.rand.nextInt(100) < chance) { BlockPos pos = new BlockPos(entityLivingBase); event.getDrops().add(new EntityItem(world, pos.getX(), pos.getY(), pos.getZ(), new ItemStack(TanpopoBlocks.PLANT_ROOTS))); } } } @SubscribeEvent public void onItemAttachCapabilitiesEvent(AttachCapabilitiesEvent.Item event) { ItemStack stack = event.getItemStack(); if (!TanpopoVanillaHelper.isNotEmptyItemStack(stack)) // if (stack == null) { return; } if (event.getItem().equals(Items.GLASS_BOTTLE)) { event.addCapability(new ResourceLocation(Tanpopo.MOD_ID, "FluidHandlerItemEssenceGlassBottle"), new FluidHandlerItemEssenceGlassBottle(stack)); } } @SubscribeEvent public void onLivingFallEvent(LivingFallEvent event) { EntityLivingBase entityLivingBase = event.getEntityLiving(); World world = entityLivingBase.worldObj; BlockPos posDown = (new BlockPos(entityLivingBase)).down(); if (world.isAirBlock(posDown)) { for (BlockPos posAround : BlockPos.getAllInBox(posDown.add(-1, 0, -1), posDown.add(1, 0, 1))) { Block blockAround = world.getBlockState(posAround).getBlock(); if (blockAround.equals(TanpopoBlocks.FLUFF_CUSHION)) { ((BlockFluffCushion) blockAround).onSpring(world, entityLivingBase); event.setDamageMultiplier(0.0F); } } } } @SubscribeEvent public void onPlayerDestroyItemEvent(PlayerDestroyItemEvent event) { EntityPlayer player = event.getEntityPlayer(); ItemStack stackOriginal = event.getOriginal(); Item itemOriginal = stackOriginal.getItem(); EnumHand hand = event.getHand(); if (itemOriginal instanceof ItemModeTool) { ItemStack stackModeAttachment = new ItemStack(((ItemModeTool) itemOriginal).getModeAttachment(), 1, 1); ItemModeToolAttachment itemModeToolAttachment = (ItemModeToolAttachment) stackModeAttachment.getItem(); itemModeToolAttachment.setContainerModeTool(stackModeAttachment, stackOriginal); if (!player.worldObj.isRemote && !player.capabilities.isCreativeMode) { if (TanpopoVanillaHelper.isNotEmptyItemStack(player.getHeldItem(hand))) // if (player.getHeldItem(hand) == null) { if (!player.inventory.addItemStackToInventory(stackModeAttachment)) { player.dropItem(stackModeAttachment, false); } } else { player.setHeldItem(hand, stackModeAttachment); } } } } @SubscribeEvent public void onAnvilUpdateEvent(AnvilUpdateEvent event) { ItemStack stackLeft = event.getLeft(); ItemStack stackRight = event.getRight(); if ((stackLeft.getItem() instanceof ItemModeToolAttachment) && (stackRight.getItem().equals(TanpopoItems.MATERIAL_STALK))) { if (ItemModeToolAttachment.isBroken(stackLeft)) { return; } event.setCost(5); event.setMaterialCost(1); event.setOutput(((ItemModeToolAttachment) stackLeft.getItem()).getContainerModeTool(stackLeft)); } } @SubscribeEvent public void onRightClickBlockEvent(PlayerInteractEvent.RightClickBlock event) { ItemStack stack = event.getItemStack(); if (!TanpopoVanillaHelper.isNotEmptyItemStack(stack)) // if (stack == null) { return; } World world = event.getWorld(); BlockPos pos = event.getPos(); IBlockState state = world.getBlockState(pos); boolean isCauldronBlock = (state.getBlock().equals(Blocks.CAULDRON) || state.getBlock().equals(TanpopoBlocks.ESSENCE_CAULDRON)); if (isCauldronBlock && (stack.getItem().equals(TanpopoItems.ESSENCE_GLASS_BOTTLE))) { boolean isSuccess = false; if (state.getBlock().equals(TanpopoBlocks.ESSENCE_CAULDRON)) { int level = ((Integer) state.getValue(BlockCauldron.LEVEL)).intValue(); if (level < 3) { isSuccess = true; ((BlockEssenceCauldron) state.getBlock()).setEssenceLevel(world, pos, state, (level + 1)); } } else { isSuccess = true; world.setBlockState(pos, TanpopoBlocks.ESSENCE_CAULDRON.getDefaultState(), 2); } if (isSuccess) { this.fillCauldronBlock(world, pos, event.getEntityPlayer(), event.getHand(), stack); world.playSound(null, pos, SoundEvents.BLOCK_BREWING_STAND_BREW, SoundCategory.BLOCKS, 1.0F, 1.0F); } } } @SubscribeEvent public void onRightClickItemEvent(PlayerInteractEvent.RightClickItem event) { ItemStack stack = event.getItemStack(); if (!TanpopoVanillaHelper.isNotEmptyItemStack(stack)) // if (stack == null) { return; } if (ItemStack.areItemStackTagsEqual(stack, UniversalBucket.getFilledBucket(ForgeModContainer.getInstance().universalBucket, TanpopoFluids.ESSENCE))) { EntityPlayer player = event.getEntityPlayer(); RayTraceResult mop = ForgeHooks.rayTraceEyes(player, 5.0D); if ((mop != null) && mop.typeOfHit.equals(RayTraceResult.Type.BLOCK)) { World world = event.getWorld(); BlockPos posMop = mop.getBlockPos(); if (world.getBlockState(posMop).getBlock().equals(Blocks.CAULDRON)) { event.setCanceled(true); world.setBlockState(posMop, TanpopoBlocks.ESSENCE_CAULDRON.getDefaultState().withProperty(BlockCauldron.LEVEL, TanpopoBlocks.META_ESSENCE_CAULDRON), 2); this.fillCauldronBlock(world, posMop, player, event.getHand(), stack); world.playSound(null, posMop, SoundEvents.BLOCK_BREWING_STAND_BREW, SoundCategory.BLOCKS, 1.0F, 1.0F); } } } } // TODO /* ======================================== MOD START =====================================*/ private void fillCauldronBlock(World world, BlockPos pos, EntityPlayer player, EnumHand hand, ItemStack stack) { player.swingArm(hand); if (!player.capabilities.isCreativeMode) { ItemStack newHeldItem = stack.getItem().getContainerItem(stack); --stack.stackSize; if (stack.stackSize <= 0) { player.setHeldItem(hand, newHeldItem); } else if (!player.inventory.addItemStackToInventory(newHeldItem)) { player.dropItem(newHeldItem, false); } } player.addStat(StatList.CAULDRON_USED); } }
package com.ha.cn.controller; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.ha.cn.model.CallCenterManagement; import com.ha.cn.model.ShArea; import com.ha.cn.service.ICallCenterManagementService; import com.ha.cn.service.IShAreaService; import org.apache.ibatis.annotations.Param; import org.sonatype.inject.Parameters; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; 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 java.util.ArrayList; import java.util.List; /** * Author: Jage.Chen * Email: JageChen@yeah.com * Date: 18/4/8 * Time: 下午4:23 * Describe: 省市级三级联动控制器s */ @Controller @RequestMapping("sharea") public class ShAreaController extends BaseController { private final IShAreaService shAreaService; @Autowired public ShAreaController(IShAreaService shAreaService) { this.shAreaService = shAreaService; } @ResponseBody @RequestMapping(value = "findbyid",method = RequestMethod.GET) public Object save(@RequestParam(value = "id",defaultValue = "0") int id) { EntityWrapper<ShArea> ew = new EntityWrapper<ShArea>(); if (id!=0) { ew.eq("pid",id); } List<ShArea> shareas = shAreaService.selectList(ew); List<ShArea> leves1 = new ArrayList<>(); //省级 List<ShArea> leves2 = new ArrayList<>(); //市级 List<ShArea> leves3 = new ArrayList<>(); //区县 List<List<ShArea>> collect = new ArrayList<>(); //汇总 for (ShArea sharea : shareas) { if (sharea.getLevel()==1) leves1.add(sharea); if (sharea.getLevel()==2) leves2.add(sharea); if (sharea.getLevel()==3) leves3.add(sharea); } collect.add(leves1); collect.add(leves2); collect.add(leves3); return shareas ==null ? renderError() : renderSuccess(collect); //还回结果 } }
package com.bingo.code.example.design.command.cook; /** * ��ʦ�������Ȳ˵ij�ʦ */ public class HotCook implements CookApi,Runnable{ /** * ��ʦ���� */ private String name; /** * ���췽���������ʦ���� * @param name ��ʦ���� */ public HotCook(String name){ this.name = name; } public void cook(int tableNum,String name) { //ÿ�����˵�ʱ���Dz�һ���ģ��ø��������ģ��һ�� int cookTime = (int)(20 * Math.random()); System.out.println(this.name+"��ʦ����Ϊ"+tableNum+"��������"+name); try { //���߳���Ϣ��ô��ʱ�䣬��ʾ�������� Thread.sleep(cookTime); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(this.name+"��ʦΪ"+tableNum+"���������ˣ�"+name+",���ƺ�ʱ="+cookTime+"��"); } public void run() { while(true){ //��������������ȡ������� Command cmd = CommandQueue.getOneCommand(); if(cmd != null){ //˵��ȡ����������ˣ�����������û�����ý����� //��Ϊǰ�涼����֪��������һ����ʦ������ִ��������� //����֪���ˣ����ǵ�ǰ��ʦʵ�������õ������������ cmd.setCookApi(this); //Ȼ������ִ��������� cmd.execute(); } else { // this.wait(); } //��Ϣ1�� try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } } } }
package comp01_analisadorlexico; public class Comp01_AnalisadorLexico { public static void main(String[] args) { AlgumaLexico lexico = new AlgumaLexico("/home/marcel/NetBeansProjects/Comp01_AnalisadorLexico/src/comp01_analisadorlexico/fatorial.alguma"); Token t = null; while((t = lexico.proximoToken()).nome != TipoToken.Fim) { System.out.println(t); } } }
package edu.mines.msmith1.universepoint.dto; /** * POJO representation of Team table. * @author vanxrice */ public class Team extends BaseDTO { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return getName(); } }
/* * ********************************************************* * Copyright (c) 2019 @alxgcrz All rights reserved. * This code is licensed under the MIT license. * Images, graphics, audio and the rest of the assets be * outside this license and are copyrighted. * ********************************************************* */ package com.codessus.ecnaris.ambar.fragments; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import com.codessus.ecnaris.ambar.R; import com.codessus.ecnaris.ambar.activities.MainActivity; import com.codessus.ecnaris.ambar.helpers.AmbarManager; import org.apache.commons.lang3.StringUtils; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.Unbinder; import static com.codessus.ecnaris.ambar.helpers.LogManager.log; public class AyudaFragment extends Fragment { private static final String TAG = AyudaFragment.class.getSimpleName(); // NAVEGACIÓN (ocultos por defecto) @BindView(R.id.include_navigation_cancel) ImageButton cancelImageButton; private Unbinder unbinder; // --- CONSTRUCTOR --- // public AyudaFragment() { // Required empty public constructor } @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) { // Inflate the layout for this fragment View rootView = inflater.inflate( R.layout.fragment_ayuda, container, false ); // Inyectar las Views unbinder = ButterKnife.bind( this, rootView ); // Mostrar el botón 'CANCEL' cancelImageButton.setVisibility( View.VISIBLE ); return rootView; } /** * Método que se ejecuta al pulsar en el título de alguna sección de ayuda * * @param section selected */ @OnClick({R.id.fragment_ayuda_textView_content_elem_0, R.id.fragment_ayuda_textView_content_elem_1, R.id.fragment_ayuda_textView_content_elem_2, R.id.fragment_ayuda_textView_content_elem_3, R.id.fragment_ayuda_textView_content_elem_4, R.id.fragment_ayuda_textView_content_elem_5, R.id.fragment_ayuda_textView_content_elem_6, R.id.fragment_ayuda_textView_content_elem_7, R.id.fragment_ayuda_textView_content_elem_8, R.id.fragment_ayuda_textView_content_elem_9, R.id.fragment_ayuda_textView_content_elem_10, R.id.fragment_ayuda_textView_content_elem_11, R.id.fragment_ayuda_textView_content_elem_12, R.id.fragment_ayuda_textView_content_elem_13, R.id.fragment_ayuda_textView_content_elem_14, R.id.fragment_ayuda_textView_content_elem_15}) public void helpSelected( View section ) { // Tag String tag = (String) section.getTag(); if ( StringUtils.isNotBlank( tag ) ) { // Value int value = Integer.valueOf( tag ); // Sección int sectionSelected = AmbarManager.instance().getHelpLayout( value ); // Load next fragment ((MainActivity) getActivity()).loadNextFragment( section, AyudaSectionFragment.newInstance( sectionSelected, value ) ); } } /** * Método que se ejecuta al pulsar en el botón 'CANCEL' * * @param button clicked */ @OnClick(R.id.include_navigation_cancel) public void navigation( View button ) { // Load next fragment ((MainActivity) getActivity()).loadNextFragment( button, new HomeFragment() ); } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } /** * onCreate -> onCreateView -> onResume */ @Override public void onResume() { super.onResume(); log( TAG + " --> onResume" ); // Reiniciar la reproducción (si ya se estuviera reproduciendo no pasa nada) AmbarManager.instance().playMusic( R.raw.main, true ); } }
package com.ibeiliao.pay.admin.utils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.FastDateFormat; import javax.servlet.http.HttpServletRequest; import java.text.ParseException; import java.util.Date; /** * * 请求工具类 * Created by jingyesi on 16/8/10. */ public class RequestUtils { /** * 获取客户端IP地址,此方法用在proxy环境中 * @param request * @return */ public static String getRemoteAddr(HttpServletRequest request) { String ip = request.getHeader("X-Forwarded-For"); if(StringUtils.isEmpty(ip) || ip.equalsIgnoreCase("unknown")) { ip = request.getHeader("Proxy-Client-IP"); } if (StringUtils.isEmpty(ip) || ip.equalsIgnoreCase("unknown")) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (StringUtils.isEmpty(ip) || ip.equalsIgnoreCase("unknown")) { ip = request.getHeader("X-Real-IP"); } if (StringUtils.isEmpty(ip) || ip.equalsIgnoreCase("unknown")) { ip = request.getRemoteAddr(); } // 多级反向代理检测 if (ip != null && ip.indexOf(",") > 0) { ip = ip.trim().split(",")[0]; } return ip; } /** * 把输入的时间范围转换成 Date 数组 * @param dateRange 格式:yyyy-MM-dd - yyyy-MM-dd * @return */ public static Date[] toDateArray(String dateRange) { String[] array = dateRange.split(" - "); FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd"); try { Date startTime = fdf.parse(array[0]); Date endTime = fdf.parse(array[1]); return new Date[] { startTime, endTime }; } catch (ParseException e) { throw new IllegalArgumentException("错误的时间范围: " + dateRange); } } }
package com.boot.spring.utils; public class StatusUtil { //statics status static public int SUCCESS = 200; static public int NOT_FOUND = 404; static public int WRONG_PASSWORD = 405; static public int DUPLICATE_EMAIL = 406; static public int INTERNAL_SERVER_ERROR = 500; }
package ru.innopolis; public class Question { private final int id; private final int id_sample; private String question; private String answer; private String criterion; public Question(int id, int id_sample, String question, String answer, String criterion) { this.id = id; this.id_sample = id_sample; this.question = question; this.answer = answer; this.criterion = criterion; } public int getId() { return id; } public int getId_sample() { return id_sample; } public String getQuestion() { return question; } public void setQuestion(String question) { this.question = question; } public String getAnswer() { return answer; } public void setAnswer(String answer) { this.answer = answer; } public String getCriterion() { return criterion; } public void setCriterion(String criterion) { this.criterion = criterion; } }
package com.conglomerate.dev.models; import lombok.*; import javax.persistence.*; import java.time.LocalDateTime; import java.util.Set; @Entity @Table(name = "messages") @Data @Builder @NoArgsConstructor @AllArgsConstructor public class Message { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) int id; String content; LocalDateTime timestamp; int likes; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "sender_id") private User sender; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "group_id") private Grouping grouping; @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "user_read_messages_mappings", joinColumns=@JoinColumn(name="message_id"), inverseJoinColumns=@JoinColumn(name="user_id")) private Set<User> read; }
package cn.canlnac.onlinecourse.data.entity; import com.google.gson.annotations.SerializedName; /** * 目录. */ public class CatalogIdEntity { @SerializedName("catalogId") private int catalogId; public int getCatalogId() { return catalogId; } public void setCatalogId(int catalogId) { this.catalogId = catalogId; } }
/* * 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 algorithmlab; import java.util.HashMap; import java.util.Map; /** * * @author pigrick */ public class SelfAwareArray { public static boolean selfAwareArray1(int[] arr){ Map<Integer,Integer> tempmap = new HashMap<>(); for(int i = 0; i < arr.length; i++){ tempmap.put(arr[i], tempmap.getOrDefault(arr[i], 0)+1); } for(int i = 0; i < arr.length; i++){ System.out.println(i + " " + tempmap.getOrDefault(i, 0)); if(arr[i] != tempmap.getOrDefault(i, 0)){ return false; } } return true; } public static void main(String[] args) { int[] check = {6,1,0,0,0,0,1,0}; System.out.println(selfAwareArray1(check)); } }
package com.lucas; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import javax.imageio.ImageIO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; // Controlador, define as operacoes HTTPS de POST e GET e seus parâmetros @Controller @RequestMapping(path="/cadastro") public class Controlador { @Autowired private Repositorio userRepository; // POST com parametros de nome, nascimento e path @PostMapping(path="/adicionar") public @ResponseBody String novoUsuario (@RequestParam String nome, @RequestParam String nascimento, @RequestParam String path) { Date data; BufferedImage foto; Usuario usuario = new Usuario(); try { data = new SimpleDateFormat("dd/MM/yyyy").parse(nascimento); foto = ImageIO.read(new File(path)); } catch (ParseException e) { // Caso a data esteja em um formato errado retorna um erro return "Erro ao digitar a data"; } catch (IOException e) { // Caso tenha alguma problema ao ler o arquivo retorna um erro return "Erro ao ler a imagem"; } // Com os dados prontos usa os setters com os parâmetros usuario.setFoto(foto); usuario.setNome(nome); usuario.setNascimento(data); userRepository.save(usuario); return "Sucesso"; } // GET para ler todos os usuarios do banco de dados @GetMapping(path="/ler") public @ResponseBody Iterable<Usuario> listarTodosUsuarios() { return userRepository.findAll(); } }
package com.mx.profuturo.bolsa.model.service.sample; public class SamplePojo { private String message; private int i; private double y; private boolean b; public SamplePojo(String message, int i, double v, boolean b) { this.message = message; this.i = i; this.y = v; this.b = b; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public int getI() { return i; } public void setI(int i) { this.i = i; } public double getY() { return y; } public void setY(double y) { this.y = y; } public boolean isB() { return b; } public void setB(boolean b) { this.b = b; } }
package backjoon.math; import java.io.*; import java.util.StringTokenizer; public class Backjoon6064 { private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); public static void main(String[] args) throws IOException { int testCnt = Integer.parseInt(br.readLine()); for(int i = 0 ; i < testCnt; i++){ StringTokenizer st = new StringTokenizer(br.readLine(), " "); int m = Integer.parseInt(st.nextToken()); int n = Integer.parseInt(st.nextToken()); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); bw.write(calcYear(m, n, x, y) + "\n"); bw.flush(); } } private static int calcYear(int m, int n, int x, int y){ int cnt = lcm(m, n) / m; int a = 0; int k = 1; boolean flag = false; if(y == n) flag = true; if(flag){ while(cnt-- > 0){ if((a * m + x) % n == 0) return a * m + x; a++; } }else{ while(cnt-- > 0){ if((a * m + x) % n == y) return m * a + x; a++; } } return -1; } private static int gcd(int a, int b){ while(b != 0){ int r = a % b; a = b; b = r; } return a; } private static int lcm(int a, int b){ return a * b / gcd(a, b); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package core.preProcessamentos; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; import util.banco.GravaReviews; import util.banco.HandleSentiLex; import util.preprocessamentos.LemmaTexto; /** * * @author User */ public class ExtracaoFinalVarPadroes { private final Map<String, Integer> lexico; private final LemmaTexto lemmatizador; public ExtracaoFinalVarPadroes() { this.lexico = HandleSentiLex.selectLexico(); this.lemmatizador = new LemmaTexto(); } /** * Contar a quantidade de padrões válidos para cada lista de acordo com as * features passadas por parâmetro * * @param pares * @param hashPares * @param padroes * @param hashPadroes * @param features * @return */ public List<String> contagemPadroes(List<String> pares, HashMap<String, String> hashPares, List<String> padroes, HashMap<String, String> hashPadroes, List<String> features) { List<String> retorno = new ArrayList<>(); int total = 0; //Primeiros pares total = pares.size(); for (String carac : pares) { boolean found = false; for (String feature : features) { if (carac.indexOf(feature) != -1) { found = true; break; } } if (!found) { total--; }else{ retorno.add(carac.trim()+" "+hashPares.get(carac).trim()); } } //Padroes serão verificados agora total = total + padroes.size(); for (String carac : padroes) { boolean found = false; for (String feature : features) { if (carac.indexOf(feature) != -1) { found = true; break; } } if (hashPadroes.get(carac).equals("padrao5")) { if (!lexico.keySet().contains(lemmatizador.lemmaTxt(carac).get(1))) { found = false; }else{ found = true; } } else if (hashPadroes.get(carac).equals("padrao6")) { if (!lexico.keySet().contains(lemmatizador.lemmaTxt(carac).get(0))) { found = false; }else{ found = true; } } if (!found) { total--; }else{ retorno.add(carac); } } return retorno; } /** * * @return */ public static List<String> carregaFeatures(){ Scanner sc = null; try { sc = new Scanner(new File("recursos/características.txt")); } catch (FileNotFoundException ex) { Logger.getLogger(ExtracaoFinalVarPadroes.class.getName()).log(Level.SEVERE, null, ex); } List<String> lista = new ArrayList<>(); while (sc.hasNextLine()) { lista.add(sc.nextLine()); } return lista; } }
package com.example.headfirst.factory; /** * create by Administrator : zhanghechun on 2020/3/26 */ public class SimplePizzaFactory { public Pizza createPizza(String type){ Pizza pizza=null; if (type.equals("cheese")){ pizza=new CheesePizza(); }else if (type.equals("pepperoni")){ pizza=new Pepperoni(); }else if (type.equals("veggie")){ pizza=new VeggiePizza(); } return pizza; } }
package org.magnum.mobilecloud.video.controller; import org.magnum.mobilecloud.video.client.VideoSvcApi; import org.magnum.mobilecloud.video.repository.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.security.Principal; import java.util.Set; @Controller public class Likes { @Autowired VideoRepository repository; @RequestMapping(value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}/like", method = RequestMethod.POST) public void like(@PathVariable("id") long id, Principal user, HttpServletResponse response) throws IOException { Video v = repository.findOne(id); String userName = user.getName(); if (v == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } if (v.getLikedBy().contains(userName)) { response.sendError(400, "You have already liked this video before."); } else { likeAction(v, userName); } } @RequestMapping(value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}/unlike", method = RequestMethod.POST) public void unlike(@PathVariable("id") long id, Principal user, HttpServletResponse response) throws IOException { Video v = repository.findOne(id); String userName = user.getName(); if (v == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } if (v.getLikedBy().contains(userName)) { likeAction(v, userName); } else { response.sendError(400, "You haven't already liked this video before."); } } private Video likeAction(Video v, String userName) { Set<String> likedBy = v.getLikedBy(); if (likedBy.contains(userName)) likedBy.remove(userName); else likedBy.add(userName); v.setLikedBy(likedBy); v.setLikes(likedBy.size()); return repository.save(v); } }
package ec.com.yacare.y4all.lib.activities; import java.util.Locale; import ec.com.yacare.y4all.lib.dto.Dispositivo; import android.app.Activity; import android.speech.tts.TextToSpeech; import android.util.Log; public abstract class BaseTextSpeechActivity extends Activity implements android.speech.tts.TextToSpeech.OnInitListener{ private TextToSpeech textToSpeech; private Dispositivo dispositivoActual; private String ultimoMensaje; @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { Locale locSpanish = new Locale("es"); int result = textToSpeech.setLanguage(locSpanish); // textToSpeech.setSpeechRate(0.95f); if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { Log.e("error", "This Language is not supported"); } else { } } else { Log.e("error", "Initilization Failed!"); } } public void convertTextToSpeech(String textoLeer) { if(dispositivoActual != null){ textoLeer = dispositivoActual.getNombreDispositivo() + " dice .. " + textoLeer; textToSpeech.speak(textoLeer, TextToSpeech.QUEUE_FLUSH, null); } } public TextToSpeech getTextToSpeech() { return textToSpeech; } public void setTextToSpeech(TextToSpeech textToSpeech) { this.textToSpeech = textToSpeech; } public Dispositivo getDispositivoActual() { return dispositivoActual; } public void setDispositivoActual(Dispositivo dispositivoActual) { this.dispositivoActual = dispositivoActual; } public String getUltimoMensaje() { return ultimoMensaje; } public void setUltimoMensaje(String ultimoMensaje) { this.ultimoMensaje = ultimoMensaje; } }
package com.pcms.domain; import java.util.List; /** * 分页信息 */ public class Pageable<T> { private List<T> data; private Long total; private Integer draw; public List<T> getData() { return data; } public void setData(List<T> data) { this.data = data; } public Long getTotal() { return total; } public void setTotal(Long total) { this.total = total; } public Integer getDraw() { return draw; } public void setDraw(Integer draw) { this.draw = draw; } }
package org.mess110.jrattrack.models; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Random; import javax.swing.ImageIcon; import org.mess110.jrattrack.util.Util; public class MovieMeta { private String inputPath; private String outputPath; private int cX; private int cY; private int cR; private int ratSize; private ArrayList<PossibleRat> resultSet; private int analyzeFps = 1; public MovieMeta(String inputPath) { mkdir(Util.OUTPUT); this.inputPath = inputPath; this.resultSet = new ArrayList<PossibleRat>(); int folderCount = Util.contentsOf(Util.OUTPUT).length + 1; prepareFolders(String.valueOf(folderCount)); } public MovieMeta(String inputPath, String folderName) { this.inputPath = inputPath; this.resultSet = new ArrayList<PossibleRat>(); prepareFolders(folderName); } public void setCircle(int cX, int cY, int cR) { this.cX = cX; this.cY = cY; this.cR = cR; } private void prepareFolders(String folderName) { outputPath = Util.OUTPUT + "/" + folderName; } public void mkdirs() { mkdir(getFramesPath()); mkdir(getProcessedPath()); } public String getFramesPath() { return outputPath + "/frames"; } public String getProcessedPath() { return outputPath + "/processed"; } public String getOutputLogPath() { return outputPath + "/output.log"; } private String getMetaPath() { return outputPath + "/meta"; } private void mkdir(String path) { File folder = new File(path); folder.mkdirs(); } public String getInputPath() { return inputPath; } public File getProcessedEquivalent(File file) { String newPath = file.getPath(); return new File(newPath.replaceAll("frames", "processed")); } public boolean isInCircle(int x, int y) { return (((x - cX) * (x - cX)) + ((y - cY) * (y - cY))) < (cR * cR); } public String toString() { return cX + " - " + cY + " - " + cR; } public void setRatSize(int i) { this.ratSize = i; } public int getRatSize() { return ratSize; } public void addResultSet(ResultSet<PossibleRat> rs) { if (resultSet == null) { resultSet = new ArrayList<PossibleRat>(); } for (PossibleRat pr : rs.getElements()) { resultSet.add(pr); } } public ArrayList<PossibleRat> getResultSet() { return resultSet; } public void setAnalyzeFps(int i) { this.analyzeFps = i; } public void readMetaFromDisk() { File file = new File(getMetaPath()); try { BufferedReader br = new BufferedReader(new FileReader(file)); setAnalyzeFps(Integer.valueOf(br.readLine())); setRatSize(Integer.valueOf(br.readLine())); cX = Integer.valueOf(br.readLine()); cY = Integer.valueOf(br.readLine()); cR = Integer.valueOf(br.readLine()); br.close(); } catch (IOException e) { e.printStackTrace(); } } public int getAnalyzeFps() { return analyzeFps; } public void readLog(File selectedFile) { readLog(selectedFile.getPath()); } public void readLog(String olp) { clearResultSet(); File file = new File(olp); try { BufferedReader br = new BufferedReader(new FileReader(file)); String line; int count = 0; while ((line = br.readLine()) != null) { count++; switch (count) { case 1: setAnalyzeFps(Integer.valueOf(line)); break; case 2: setRatSize(Integer.valueOf(line)); break; case 3: cX = Integer.valueOf(line); break; case 4: cY = Integer.valueOf(line); break; case 5: cR = Integer.valueOf(line); break; default: resultSet.add(new PossibleRat(line)); break; } } br.close(); } catch (IOException e) { e.printStackTrace(); } } public void readLog() { readLog(getOutputLogPath()); } public void writeLog(String outputLogPath) { try { FileWriter fstream = new FileWriter(outputLogPath); BufferedWriter out = new BufferedWriter(fstream); out.write(String.valueOf(getAnalyzeFps()) + Util.NEWLINE); out.write(String.valueOf(getRatSize()) + Util.NEWLINE); out.write(String.valueOf(cX) + Util.NEWLINE); out.write(String.valueOf(cY) + Util.NEWLINE); out.write(String.valueOf(cR) + Util.NEWLINE); for (PossibleRat pr : resultSet) { out.write(pr.toString() + Util.NEWLINE); } out.close(); } catch (Exception e) { e.printStackTrace(); } } public void writeLog() { writeLog(getOutputLogPath()); } public void writeMeta() { try { FileWriter fstream = new FileWriter(getMetaPath()); BufferedWriter out = new BufferedWriter(fstream); out.write(String.valueOf(getAnalyzeFps()) + Util.NEWLINE); out.write(String.valueOf(getRatSize()) + Util.NEWLINE); out.write(String.valueOf(cX) + Util.NEWLINE); out.write(String.valueOf(cY) + Util.NEWLINE); out.write(String.valueOf(cR) + Util.NEWLINE); out.close(); } catch (Exception e) { e.printStackTrace(); } } public ImageIcon getRandomFrame() { File[] possibleFrames = new File(getFramesPath()).listFiles(); int r = new Random().nextInt(possibleFrames.length); return new ImageIcon(possibleFrames[r].getPath()); } public boolean framesAreExtracted() { return new File(getFramesPath()).listFiles().length != 0; } public int getCircleX() { return cX; } public int getCircleY() { return cY; } public int getCircleR() { return cR; } public boolean isCircleSet() { return !(cX == 0 && cY == 0 && cR == 0); } public void clearResultSet() { resultSet.clear(); } }
package com.hit.demo; /** * Creat by thinkl on 2018/06/04 */ public class HelloWorld { public static void main(String[] args){ System.out.println("Hello World"); } }
package com.leafye.speex; public class Hello { public void hello(){ HelloUtils utils = new HelloUtils(); utils.sayHello(); } }
package com.mlm.entity; import com.mlm.db.FPelanggan; import com.orientechnologies.orient.core.metadata.schema.OType; import com.orientechnologies.orient.core.record.impl.ODocument; import java.util.ArrayList; import java.util.List; public class Pelanggan { private String namaToko; private String jenisIdentitas; private String namaPemilik; private String noIdentitas; private String alamat; private String kota; private String noTelp; private String noFax; private String noHp1; private String noHp2; private String pinBb1; private String pinBb2; private int status; private List<Pp> pakets; private ODocument doc; public Pelanggan(ODocument doc) { super(); setDoc(doc); } public String getNamaToko() { return namaToko; } public void setNamaToko(String namaToko) { doc.field(FPelanggan.NAMA_TOKO, namaToko, OType.STRING); this.namaToko = namaToko; } public String getJenisIdentitas() { return jenisIdentitas; } public void setJenisIdentitas(String jenisIdentitas) { doc.field(FPelanggan.JENIS_IDENTITAS, jenisIdentitas, OType.STRING); this.jenisIdentitas = jenisIdentitas; } public String getNamaPemilik() { return namaPemilik; } public void setNamaPemilik(String namaPemilik) { doc.field(FPelanggan.NAMA_PEMILIK, namaPemilik, OType.STRING); this.namaPemilik = namaPemilik; } public String getNoIdentitas() { return noIdentitas; } public void setNoIdentitas(String noIdentitas) { doc.field(FPelanggan.NO_IDENTITAS, noIdentitas, OType.STRING); this.noIdentitas = noIdentitas; } public String getAlamat() { return alamat; } public void setAlamat(String alamat) { doc.field(FPelanggan.ALAMAT, alamat, OType.STRING); this.alamat = alamat; } public String getKota() { return kota; } public void setKota(String kota) { doc.field(FPelanggan.KOTA, kota, OType.STRING); this.kota = kota; } public String getNoTelp() { return noTelp; } public void setNoTelp(String noTelp) { doc.field(FPelanggan.NO_TELP, noTelp, OType.STRING); this.noTelp = noTelp; } public String getNoFax() { return noFax; } public void setNoFax(String noFax) { doc.field(FPelanggan.NO_FAX, noFax, OType.STRING); this.noFax = noFax; } public String getNoHp1() { return noHp1; } public void setNoHp1(String noHp1) { doc.field(FPelanggan.NO_HP1, noHp1, OType.STRING); this.noHp1 = noHp1; } public String getNoHp2() { return noHp2; } public void setNoHp2(String noHp2) { doc.field(FPelanggan.NO_HP2, noHp2, OType.STRING); this.noHp2 = noHp2; } public String getPinBb1() { return pinBb1; } public void setPinBb1(String pinBb1) { doc.field(FPelanggan.PIN_BB1, pinBb1, OType.STRING); this.pinBb1 = pinBb1; } public String getPinBb2() { return pinBb2; } public void setPinBb2(String pinBb2) { doc.field(FPelanggan.PIN_BB2, pinBb2, OType.STRING); this.pinBb2 = pinBb2; } public int getStatus() { return status; } public void setStatus(int status) { doc.field(FPelanggan.STATUS, status, OType.INTEGER); this.status = status; } public List<Pp> getPakets() { return pakets; } public void setPakets(List<ODocument> pakets) { doc.field(FPelanggan.PAKETS, pakets, OType.LINKSET); List<Pp> pps=new ArrayList<>(); for (ODocument o : pakets) { pps.add(new Pp(o)); } this.pakets = pps; } public ODocument getDoc() { return doc; } public void setDoc(ODocument doc) { this.namaToko = doc.field(FPelanggan.NAMA_TOKO); this.jenisIdentitas = doc.field(FPelanggan.JENIS_IDENTITAS); this.namaPemilik = doc.field(FPelanggan.NAMA_PEMILIK); this.noIdentitas = doc.field(FPelanggan.NO_IDENTITAS); this.alamat = doc.field(FPelanggan.ALAMAT); this.kota = doc.field(FPelanggan.KOTA); this.noTelp = doc.field(FPelanggan.NO_TELP); this.noFax = doc.field(FPelanggan.NO_FAX); this.noHp1 = doc.field(FPelanggan.NO_HP1); this.noHp2 = doc.field(FPelanggan.NO_HP2); this.pinBb1 = doc.field(FPelanggan.PIN_BB1); this.pinBb2 = doc.field(FPelanggan.PIN_BB2); this.status = doc.field(FPelanggan.STATUS); this.pakets = doc.field(FPelanggan.PAKETS); this.doc = doc; } }
package com.tencent.mm.bi; import com.tencent.mm.d.b; import java.util.Comparator; class a$2 implements Comparator<b> { final /* synthetic */ a qVu; a$2(a aVar) { this.qVu = aVar; } public final /* synthetic */ int compare(Object obj, Object obj2) { return ((b) obj).vE().value - ((b) obj2).vE().value; } }
package cn.zhoudbw.config; import org.springframework.boot.web.server.ConfigurableWebServerFactory; import org.springframework.boot.web.server.WebServerFactory; import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author zhoudbw * @Configuration 声明该类是一个配置类 */ @Configuration public class WebConfig { /** * @Bean 声明bean放入spring容器,让我们可以使用 * WebServerFactoryCustomer允许我们自己定制配置 * 传递泛型和配置有关ConfigurableWebServerFactory */ @Bean public WebServerFactoryCustomizer<ConfigurableWebServerFactory> customizer() { /** @FunctionalInterface 函数型接口,只有一个方法,只是为了声明这个方法的。 public interface WebServerFactoryCustomizer<T extends WebServerFactory> { // Customize the specified {@link WebServerFactory}. // @param factory the web server factory to customize void customize(T factory); } 本质是一个接口,泛型需要去实现WebServerFactory,其实就是WebServer的一个工厂 其中只有唯一一个定制的方法,定制方法所操作的方法也就是它的泛型 */ // 因为我们需要创建一个WebServerFactoryCustomizer<ConfigurableWebServerFactory>的bean // 所以我们new,但由于是一个接口,所以需要我们实现这个接口的方法 // 我们通过customize就可以操作这个factory了。 return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() { @Override public void customize(ConfigurableWebServerFactory factory) { // 设置端口 factory.setPort(8899); } }; } }
package com.kumar.penguingame; import java.io.IOException; import android.media.MediaPlayer; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; public class AdelieActivity extends Activity { MediaPlayer mPlayer; TextView sc; RadioGroup radiogroup; RadioButton rb1, rb2, rb3; Button b1; int counter = 1; int score = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.adelie); sc = (TextView)findViewById(R.id.txt2); sc.setText("Score : " + score ); mPlayer = MediaPlayer.create(AdelieActivity.this, R.raw.bg_music); mPlayer.setLooping(true); try { mPlayer.prepare(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } mPlayer.start(); radiogroup = (RadioGroup) findViewById(R.id.rg1); rb1 = (RadioButton) findViewById(R.id.adeliebutton); rb2 = (RadioButton) findViewById(R.id.africanbutton); rb3 = (RadioButton) findViewById(R.id.bluebutton); b1 = (Button)findViewById(R.id.button1); if (counter == 1){ rb1.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (counter == 1){ score = score + 5; counter ++; sc.setText("Score : " + score ); Toast.makeText(AdelieActivity.this,rb1.getText(), Toast.LENGTH_SHORT).show(); Intent intent = new Intent(AdelieActivity.this, AfricanActivity.class); intent.putExtra("val", score); startActivity(intent); } else if (counter >1){ Toast.makeText(AdelieActivity.this," Please Try again ", Toast.LENGTH_SHORT).show(); } } }); rb2.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (counter == 1){ counter ++; Toast.makeText(AdelieActivity.this,rb2.getText(), Toast.LENGTH_SHORT).show(); } else if (counter >1){ Toast.makeText(AdelieActivity.this," Please Try again ", Toast.LENGTH_SHORT).show(); } } }); rb3.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (counter == 1){ counter ++; Toast.makeText(AdelieActivity.this,rb3.getText(), Toast.LENGTH_SHORT).show(); } else if (counter >1){ Toast.makeText(AdelieActivity.this," Please Try again ", Toast.LENGTH_SHORT).show(); } } }); b1.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Toast.makeText(AdelieActivity.this," Named after Ad�lie Land ", Toast.LENGTH_SHORT).show(); } }); } else if (counter >1){ Toast.makeText(AdelieActivity.this," Please Try again ", Toast.LENGTH_SHORT).show(); } } }
package hearthstone; import java.util.ArrayList; public class Survival extends Puzzles { public Survival(ArrayList<Card> d, ArrayList<Card> ed, Card[] h, Card[] eh, Card[] fc, Card[] efc, int cp, int sm, int cm, Hero aHero, Hero eHero) { super(d, ed, h, eh, fc, efc, cp, sm, cm, aHero, eHero); } public Survival(){ super(null, null, null, null, null, null, 0, 0, 0, null, null); } public boolean checkWin(Hero h1) {//checks all enemy minions have been removed if(h1.hp > 0){ return true; }else{ return false; } } }
package com.tt.miniapp.msg; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.text.TextUtils; import com.tt.frontendapiinterface.a; import com.tt.frontendapiinterface.b; import com.tt.miniapp.AppbrandApplicationImpl; import com.tt.miniapp.event.InnerEventHelper; import com.tt.miniapp.share.ShareLoading; import com.tt.miniapp.share.ShareRequestHelper; import com.tt.miniapphost.AppBrandLogger; import com.tt.miniapphost.AppbrandContext; import com.tt.miniapphost.MiniappHostBase; import com.tt.miniapphost.host.HostDependManager; import com.tt.miniapphost.util.JsonBuilder; import com.tt.miniapphost.util.TimeMeter; import com.tt.miniapphost.util.UIUtils; import com.tt.option.e.e; import com.tt.option.w.f; import com.tt.option.w.g; import com.tt.option.w.h; import java.util.concurrent.atomic.AtomicBoolean; import org.json.JSONException; import org.json.JSONObject; public abstract class ApiShareBaseCtrl extends b implements g { protected static String mSharePosition = "inside"; protected static int sClickPosition; public boolean canCallback; public boolean isForeground = true; protected boolean isNormalShare; public AtomicBoolean isWaitImgSolidify; public long mClickShareDialogTime; public AtomicBoolean mGetDefaultShareInfoEnd; public AtomicBoolean mGetShareMsgEnd; public AtomicBoolean mIsShareCancel; private AppbrandApplicationImpl.ILifecycleObserver mLifecycleObserver = new AppbrandApplicationImpl.ILifecycleObserver() { public void onHide() { ApiShareBaseCtrl.this.isForeground = false; } public void onShow() { ApiShareBaseCtrl apiShareBaseCtrl = ApiShareBaseCtrl.this; apiShareBaseCtrl.isForeground = true; if (apiShareBaseCtrl.mNeedShare && ApiShareBaseCtrl.this.mShareInfoModel != null) { ApiShareBaseCtrl.this.mNeedShare = false; AppbrandContext.mainHandler.postDelayed(new Runnable() { public void run() { ApiShareBaseCtrl.this.doShare(ApiShareBaseCtrl.this.mShareInfoModel); } }, 200L); } } }; public boolean mNeedShare; private long mRealStartShareTime; public h mShareInfoModel; public ShareLoading mShareLoading; public UploadImgListener mUploadImgListener; protected ApiShareBaseCtrl(String paramString, int paramInt, e parame) { super(paramString, paramInt, parame); AppbrandApplicationImpl.getInst().registerLifecycleObserver(this.mLifecycleObserver); this.mShareLoading = new ShareLoading(); this.mShareLoading.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface param1DialogInterface) { if (ApiShareBaseCtrl.this.mIsShareCancel == null) ApiShareBaseCtrl.this.mIsShareCancel = new AtomicBoolean(true); ApiShareBaseCtrl.this.callbackCancel(); ApiShareBaseCtrl.this.showFailToast(); } }); } public static int getClickPosition() { return sClickPosition; } private void normalShare() { this.isNormalShare = true; mSharePosition = "inside"; InnerEventHelper.mpShareClickEvent("inside", isTokenShare()); solidifyImgUrl(); showShareDialog((Activity)AppbrandContext.getInst().getCurrentActivity()); } public static void setClickPosition(int paramInt) { sClickPosition = paramInt; } private void showCommonShareDialog(Activity paramActivity, f paramf) { this.mGetShareMsgEnd = new AtomicBoolean(false); HostDependManager.getInst().showShareDialog(paramActivity, paramf); } private void showPictureTokenShareDialog(final Activity activity, final f dialogEventListener) { final GetDefaultShareInfoListener getDefaultShareInfoListener = new GetDefaultShareInfoListener() { public void onFail() { if (ApiShareBaseCtrl.this.mGetDefaultShareInfoEnd != null) ApiShareBaseCtrl.this.mGetDefaultShareInfoEnd.set(true); ApiShareBaseCtrl.this.mShareLoading.hide("fail", "showPictureTokenShareDialog fail"); } public void onSuccess(final h shareInfoModel) { AppbrandContext.mainHandler.post(new Runnable() { public void run() { if (ApiShareBaseCtrl.this.mGetDefaultShareInfoEnd != null) ApiShareBaseCtrl.this.mGetDefaultShareInfoEnd.set(true); HostDependManager.getInst().openShareDialog(activity, shareInfoModel, dialogEventListener); } }); } }; this.mGetDefaultShareInfoEnd = new AtomicBoolean(false); AppbrandContext.mainHandler.postDelayed(new Runnable() { public void run() { if (ApiShareBaseCtrl.this.mGetDefaultShareInfoEnd != null && !ApiShareBaseCtrl.this.mGetDefaultShareInfoEnd.get()) ApiShareBaseCtrl.this.mShareLoading.show(); } }, 1000L); AtomicBoolean atomicBoolean = this.isWaitImgSolidify; if (atomicBoolean == null || !atomicBoolean.get()) { getDefaultShareInfo(getDefaultShareInfoListener); return; } this.mUploadImgListener = new UploadImgListener() { public void onUploadEnd() { ApiShareBaseCtrl.this.getDefaultShareInfo(getDefaultShareInfoListener); } }; setUploadImgTimeOutAction(); } private void showShareDialog(Activity paramActivity) { f f = new f() { public void onCancel() { ApiShareBaseCtrl.this.callbackCancel(); } public void onItemClick(String param1String, boolean param1Boolean) { if (TextUtils.equals(param1String, ApiShareBaseCtrl.this.mShareInfoModel.shareType) && ApiShareBaseCtrl.this.canCallback == param1Boolean && ApiShareBaseCtrl.this.mGetShareMsgEnd != null && ApiShareBaseCtrl.this.mGetShareMsgEnd.get()) { AppbrandContext.mainHandler.post(new Runnable() { public void run() { ApiShareBaseCtrl.this.doShare(ApiShareBaseCtrl.this.mShareInfoModel); } }); return; } ApiShareBaseCtrl.this.mClickShareDialogTime = TimeMeter.currentMillis(); ApiShareBaseCtrl.this.mShareLoading.initLoading(param1String, ApiShareBaseCtrl.mSharePosition, ApiShareBaseCtrl.this.mClickShareDialogTime, ApiShareBaseCtrl.this.isTokenShare()); ApiShareBaseCtrl.this.mShareInfoModel.shareType = param1String; ApiShareBaseCtrl.this.canCallback = param1Boolean; AppbrandContext.mainHandler.postDelayed(new Runnable() { public void run() { if (ApiShareBaseCtrl.this.mGetShareMsgEnd != null && !ApiShareBaseCtrl.this.mGetShareMsgEnd.get()) ApiShareBaseCtrl.this.mShareLoading.show(); } }, 1000L); if (ApiShareBaseCtrl.this.isWaitImgSolidify == null || !ApiShareBaseCtrl.this.isWaitImgSolidify.get()) { ApiShareBaseCtrl.this.beforeGetShareInfo(); ApiShareBaseCtrl.this.requestShareInfo(); return; } ApiShareBaseCtrl.this.mUploadImgListener = new ApiShareBaseCtrl.UploadImgListener() { public void onUploadEnd() { ApiShareBaseCtrl.this.beforeGetShareInfo(); ApiShareBaseCtrl.this.requestShareInfo(); } }; ApiShareBaseCtrl.this.setUploadImgTimeOutAction(); } }; if (isTokenShare() && HostDependManager.getInst().isHostOptionShareDialogDependEnable()) { showPictureTokenShareDialog(paramActivity, f); return; } showCommonShareDialog(paramActivity, f); } private void solidifyImgUrl() { this.isWaitImgSolidify = new AtomicBoolean(false); if (TextUtils.isEmpty(this.mShareInfoModel.imageUrl)) return; this.isWaitImgSolidify.set(true); final long uploadStartTime = TimeMeter.currentMillis(); ShareRequestHelper.uploadShareImgAsync(this.mShareInfoModel, 1, new ShareRequestHelper.OnShareRequestListener() { public void onException(Exception param1Exception) { if (ApiShareBaseCtrl.this.isWaitImgSolidify != null) ApiShareBaseCtrl.this.isWaitImgSolidify.set(false); if (ApiShareBaseCtrl.this.mUploadImgListener != null) { ApiShareBaseCtrl.this.mUploadImgListener.onUploadEnd(); ApiShareBaseCtrl.this.mUploadImgListener = null; } } public void onFail(String param1String) { if (ApiShareBaseCtrl.this.isWaitImgSolidify != null) ApiShareBaseCtrl.this.isWaitImgSolidify.set(false); InnerEventHelper.mpShareUpload(ApiShareBaseCtrl.mSharePosition, uploadStartTime, "fail", param1String, ApiShareBaseCtrl.this.isTokenShare()); if (ApiShareBaseCtrl.this.mUploadImgListener != null) { ApiShareBaseCtrl.this.mUploadImgListener.onUploadEnd(); ApiShareBaseCtrl.this.mUploadImgListener = null; } } public void onSuccess(h param1h) { if (ApiShareBaseCtrl.this.isWaitImgSolidify != null) ApiShareBaseCtrl.this.isWaitImgSolidify.set(false); if (!TextUtils.equals(ApiShareBaseCtrl.this.mShareInfoModel.imageUrl, param1h.imageUrl)) ApiShareBaseCtrl.this.mShareInfoModel.imageUrl = param1h.imageUrl; InnerEventHelper.mpShareUpload(ApiShareBaseCtrl.mSharePosition, uploadStartTime, "success", null, ApiShareBaseCtrl.this.isTokenShare()); if (ApiShareBaseCtrl.this.mUploadImgListener != null) { ApiShareBaseCtrl.this.mUploadImgListener.onUploadEnd(); ApiShareBaseCtrl.this.mUploadImgListener = null; } } }); } public void act() { beforeAct(); this.mShareInfoModel = h.parse(this.mArgs); if (this.mShareInfoModel == null) { AppBrandLogger.d("ApiHandler", new Object[] { "shareInfoModel is null" }); callbackFail(a.c("shareInfoModel")); return; } if (interceptNormalShare()) return; beforeNormalShare(); normalShare(); afterNormalShare(); } protected void afterGetShareInfo(h paramh) {} protected void afterNormalShare() {} protected void beforeAct() {} protected void beforeGetShareInfo() {} protected void beforeNormalShare() {} protected void clearShareMember() { this.isNormalShare = false; this.canCallback = false; this.isWaitImgSolidify = null; this.mGetShareMsgEnd = null; this.mGetDefaultShareInfoEnd = null; this.mIsShareCancel = null; this.mUploadImgListener = null; } protected void doShare(h paramh) { AtomicBoolean atomicBoolean = this.mIsShareCancel; if (atomicBoolean != null && atomicBoolean.get()) return; if (!this.isForeground) { this.mShareInfoModel = paramh; this.mNeedShare = true; return; } if (!this.canCallback) callbackOk(); String str = paramh.channel; MiniappHostBase miniappHostBase = AppbrandContext.getInst().getCurrentActivity(); if (miniappHostBase != null) { HostDependManager.getInst().share((Activity)miniappHostBase, paramh, this); AppbrandApplicationImpl.getInst().getForeBackgroundManager().pauseBackgroundOverLimitTimeStrategy(); } InnerEventHelper.mpShareToPlatform(str, mSharePosition, isTokenShare()); AppbrandApplicationImpl.getInst().ungisterLifecycleObserver(this.mLifecycleObserver); } protected String getChannel() { h h1 = this.mShareInfoModel; return (h1 != null) ? h1.channel : ""; } public void getDefaultShareInfo(final GetDefaultShareInfoListener listener) { ShareRequestHelper.getDefaultShareInfo(this.mShareInfoModel, new ShareRequestHelper.OnShareRequestListener() { public void onException(Exception param1Exception) { ShareLoading shareLoading = ApiShareBaseCtrl.this.mShareLoading; StringBuilder stringBuilder = new StringBuilder("get share info exception: "); stringBuilder.append(param1Exception.toString()); shareLoading.hide("fail", stringBuilder.toString()); ApiShareBaseCtrl.this.callbackFail(param1Exception); ApiShareBaseCtrl.this.showFailToast(); ApiShareBaseCtrl.GetDefaultShareInfoListener getDefaultShareInfoListener = listener; if (getDefaultShareInfoListener != null) getDefaultShareInfoListener.onFail(); } public void onFail(String param1String) { ApiShareBaseCtrl.this.mShareLoading.hide("fail", param1String); ApiShareBaseCtrl.this.callbackFail(param1String); ApiShareBaseCtrl.this.showFailToast(); ApiShareBaseCtrl.GetDefaultShareInfoListener getDefaultShareInfoListener = listener; if (getDefaultShareInfoListener != null) getDefaultShareInfoListener.onFail(); } public void onSuccess(h param1h) { ApiShareBaseCtrl.this.mShareLoading.hide("success", null); ApiShareBaseCtrl.GetDefaultShareInfoListener getDefaultShareInfoListener = listener; if (getDefaultShareInfoListener != null) getDefaultShareInfoListener.onSuccess(param1h); } }); } protected h getShareInfoModel() { if (this.mShareInfoModel == null) this.mShareInfoModel = h.parse(this.mArgs); return this.mShareInfoModel; } protected ShareLoading getShareLoading() { return this.mShareLoading; } public boolean handleActivityResult(int paramInt1, int paramInt2, Intent paramIntent) { return HostDependManager.getInst().handleActivityShareResult(paramInt1, paramInt2, paramIntent); } protected boolean interceptNormalShare() { return false; } protected boolean isArticleShare() { h h1 = this.mShareInfoModel; return (h1 == null) ? false : (TextUtils.isEmpty(h1.channel) ? false : this.mShareInfoModel.channel.equals("article")); } protected boolean isTokenShare() { h h1 = this.mShareInfoModel; return (h1 == null) ? false : (TextUtils.isEmpty(h1.channel) ? false : this.mShareInfoModel.channel.equals("token")); } protected boolean isVideoShare() { h h1 = this.mShareInfoModel; return (h1 == null) ? false : (TextUtils.isEmpty(h1.channel) ? false : this.mShareInfoModel.channel.equals("video")); } public void onCancel(String paramString) {} public void onFail(String paramString) {} public void onSuccess(String paramString) {} public void requestShareInfo() { this.mRealStartShareTime = TimeMeter.currentMillis(); long l1 = 6000L - this.mRealStartShareTime - this.mClickShareDialogTime; long l2 = 3000L; if (l1 < 3000L) l1 = l2; ShareRequestHelper.getNormalShareInfoAsync(this.mShareInfoModel, l1, new ShareRequestHelper.OnShareRequestListener() { public void onException(Exception param1Exception) { if (ApiShareBaseCtrl.this.mGetShareMsgEnd != null) ApiShareBaseCtrl.this.mGetShareMsgEnd.set(true); ShareLoading shareLoading = ApiShareBaseCtrl.this.mShareLoading; StringBuilder stringBuilder = new StringBuilder("get share info exception: "); stringBuilder.append(param1Exception.toString()); shareLoading.hide("fail", stringBuilder.toString()); ApiShareBaseCtrl.this.callbackFail(param1Exception); ApiShareBaseCtrl.this.showFailToast(); ApiShareBaseCtrl.this.clearShareMember(); } public void onFail(String param1String) { if (ApiShareBaseCtrl.this.mGetShareMsgEnd != null) ApiShareBaseCtrl.this.mGetShareMsgEnd.set(true); ApiShareBaseCtrl.this.mShareLoading.hide("fail", param1String); ApiShareBaseCtrl.this.callbackFail(param1String); ApiShareBaseCtrl.this.showFailToast(); ApiShareBaseCtrl.this.clearShareMember(); } public void onSuccess(final h shareInfoModel) { if (ApiShareBaseCtrl.this.mGetShareMsgEnd != null) ApiShareBaseCtrl.this.mGetShareMsgEnd.set(true); if (ApiShareBaseCtrl.this.mShareInfoModel != shareInfoModel) ApiShareBaseCtrl.this.mShareInfoModel = shareInfoModel; ApiShareBaseCtrl.this.mShareLoading.hide("success", null); ApiShareBaseCtrl.this.afterGetShareInfo(shareInfoModel); AppbrandContext.mainHandler.post(new Runnable() { public void run() { ApiShareBaseCtrl.this.doShare(shareInfoModel); } }); } }); } protected void sendStateWithShareTicket(String paramString) { try { callbackOk(new JSONObject(paramString)); return; } catch (JSONException jSONException) { AppBrandLogger.e("ApiHandler", new Object[] { "sendStateWithShareTicket", jSONException }); callbackOk(); return; } } protected void setCanCallback(boolean paramBoolean) { this.canCallback = paramBoolean; } public void setUploadImgTimeOutAction() { AppbrandContext.mainHandler.postDelayed(new Runnable() { public void run() { if (ApiShareBaseCtrl.this.isWaitImgSolidify != null && !ApiShareBaseCtrl.this.isWaitImgSolidify.get()) return; if (ApiShareBaseCtrl.this.mUploadImgListener != null) { ApiShareBaseCtrl.this.mUploadImgListener.onUploadEnd(); ApiShareBaseCtrl.this.mUploadImgListener = null; AppBrandLogger.d("ApiHandler", new Object[] { "upload img timeout, forward..." }); } } }6000L); } public boolean shouldHandleActivityResult() { return true; } public void showFailToast() { final String msg = UIUtils.getString(2097742027); AppbrandContext.mainHandler.post(new Runnable() { public void run() { MiniappHostBase miniappHostBase = AppbrandContext.getInst().getCurrentActivity(); if (miniappHostBase == null) return; JSONObject jSONObject = (new JsonBuilder()).put("title", msg).put("duration", Integer.valueOf(1500)).build(); HostDependManager.getInst().showToast((Context)miniappHostBase, jSONObject.toString(), msg, 1000L, null); } }); } public static interface GetDefaultShareInfoListener { void onFail(); void onSuccess(h param1h); } public static interface UploadImgListener { void onUploadEnd(); } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\msg\ApiShareBaseCtrl.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package org.suirui.drouter.common.callback; import android.content.Context; public interface RouterCallBack { void onResult(Context context, String flag, Object... objects); void onError(); }
/** * <copyright> * </copyright> * * $Id$ */ package edu.tsinghua.lumaqq.ecore.proxy; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; /** * <!-- begin-user-doc --> * The <b>Package</b> for the model. * It contains accessors for the meta objects to represent * <ul> * <li>each class,</li> * <li>each feature of each class,</li> * <li>each enum,</li> * <li>and each data type</li> * </ul> * <!-- end-user-doc --> * @see edu.tsinghua.lumaqq.ecore.proxy.ProxyFactory * @model kind="package" * @generated */ public interface ProxyPackage extends EPackage { /** * The package name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ String eNAME = "proxy"; /** * The package namespace URI. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ String eNS_URI = "http://lumaqq.tsinghua.edu/ecore/edu/tsinghua/lumaqq/ecore/proxy"; /** * The package namespace name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ String eNS_PREFIX = "proxy"; /** * The singleton instance of the package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ ProxyPackage eINSTANCE = edu.tsinghua.lumaqq.ecore.proxy.impl.ProxyPackageImpl.init(); /** * The meta object id for the '{@link edu.tsinghua.lumaqq.ecore.proxy.impl.HttpProxyImpl <em>Http Proxy</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see edu.tsinghua.lumaqq.ecore.proxy.impl.HttpProxyImpl * @see edu.tsinghua.lumaqq.ecore.proxy.impl.ProxyPackageImpl#getHttpProxy() * @generated */ int HTTP_PROXY = 0; /** * The feature id for the '<em><b>Password</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int HTTP_PROXY__PASSWORD = 0; /** * The feature id for the '<em><b>Port</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int HTTP_PROXY__PORT = 1; /** * The feature id for the '<em><b>Server</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int HTTP_PROXY__SERVER = 2; /** * The feature id for the '<em><b>Username</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int HTTP_PROXY__USERNAME = 3; /** * The number of structural features of the '<em>Http Proxy</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int HTTP_PROXY_FEATURE_COUNT = 4; /** * The meta object id for the '{@link edu.tsinghua.lumaqq.ecore.proxy.impl.ProxiesImpl <em>Proxies</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see edu.tsinghua.lumaqq.ecore.proxy.impl.ProxiesImpl * @see edu.tsinghua.lumaqq.ecore.proxy.impl.ProxyPackageImpl#getProxies() * @generated */ int PROXIES = 1; /** * The feature id for the '<em><b>Socks5 Proxy</b></em>' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int PROXIES__SOCKS5_PROXY = 0; /** * The feature id for the '<em><b>Http Proxy</b></em>' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int PROXIES__HTTP_PROXY = 1; /** * The number of structural features of the '<em>Proxies</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int PROXIES_FEATURE_COUNT = 2; /** * The meta object id for the '{@link edu.tsinghua.lumaqq.ecore.proxy.impl.Socks5ProxyImpl <em>Socks5 Proxy</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see edu.tsinghua.lumaqq.ecore.proxy.impl.Socks5ProxyImpl * @see edu.tsinghua.lumaqq.ecore.proxy.impl.ProxyPackageImpl#getSocks5Proxy() * @generated */ int SOCKS5_PROXY = 2; /** * The feature id for the '<em><b>Password</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int SOCKS5_PROXY__PASSWORD = 0; /** * The feature id for the '<em><b>Port</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int SOCKS5_PROXY__PORT = 1; /** * The feature id for the '<em><b>Server</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int SOCKS5_PROXY__SERVER = 2; /** * The feature id for the '<em><b>Username</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int SOCKS5_PROXY__USERNAME = 3; /** * The number of structural features of the '<em>Socks5 Proxy</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int SOCKS5_PROXY_FEATURE_COUNT = 4; /** * Returns the meta object for class '{@link edu.tsinghua.lumaqq.ecore.proxy.HttpProxy <em>Http Proxy</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Http Proxy</em>'. * @see edu.tsinghua.lumaqq.ecore.proxy.HttpProxy * @generated */ EClass getHttpProxy(); /** * Returns the meta object for the attribute '{@link edu.tsinghua.lumaqq.ecore.proxy.HttpProxy#getPassword <em>Password</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Password</em>'. * @see edu.tsinghua.lumaqq.ecore.proxy.HttpProxy#getPassword() * @see #getHttpProxy() * @generated */ EAttribute getHttpProxy_Password(); /** * Returns the meta object for the attribute '{@link edu.tsinghua.lumaqq.ecore.proxy.HttpProxy#getPort <em>Port</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Port</em>'. * @see edu.tsinghua.lumaqq.ecore.proxy.HttpProxy#getPort() * @see #getHttpProxy() * @generated */ EAttribute getHttpProxy_Port(); /** * Returns the meta object for the attribute '{@link edu.tsinghua.lumaqq.ecore.proxy.HttpProxy#getServer <em>Server</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Server</em>'. * @see edu.tsinghua.lumaqq.ecore.proxy.HttpProxy#getServer() * @see #getHttpProxy() * @generated */ EAttribute getHttpProxy_Server(); /** * Returns the meta object for the attribute '{@link edu.tsinghua.lumaqq.ecore.proxy.HttpProxy#getUsername <em>Username</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Username</em>'. * @see edu.tsinghua.lumaqq.ecore.proxy.HttpProxy#getUsername() * @see #getHttpProxy() * @generated */ EAttribute getHttpProxy_Username(); /** * Returns the meta object for class '{@link edu.tsinghua.lumaqq.ecore.proxy.Proxies <em>Proxies</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Proxies</em>'. * @see edu.tsinghua.lumaqq.ecore.proxy.Proxies * @generated */ EClass getProxies(); /** * Returns the meta object for the containment reference list '{@link edu.tsinghua.lumaqq.ecore.proxy.Proxies#getSocks5Proxy <em>Socks5 Proxy</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the containment reference list '<em>Socks5 Proxy</em>'. * @see edu.tsinghua.lumaqq.ecore.proxy.Proxies#getSocks5Proxy() * @see #getProxies() * @generated */ EReference getProxies_Socks5Proxy(); /** * Returns the meta object for the containment reference list '{@link edu.tsinghua.lumaqq.ecore.proxy.Proxies#getHttpProxy <em>Http Proxy</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the containment reference list '<em>Http Proxy</em>'. * @see edu.tsinghua.lumaqq.ecore.proxy.Proxies#getHttpProxy() * @see #getProxies() * @generated */ EReference getProxies_HttpProxy(); /** * Returns the meta object for class '{@link edu.tsinghua.lumaqq.ecore.proxy.Socks5Proxy <em>Socks5 Proxy</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Socks5 Proxy</em>'. * @see edu.tsinghua.lumaqq.ecore.proxy.Socks5Proxy * @generated */ EClass getSocks5Proxy(); /** * Returns the meta object for the attribute '{@link edu.tsinghua.lumaqq.ecore.proxy.Socks5Proxy#getPassword <em>Password</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Password</em>'. * @see edu.tsinghua.lumaqq.ecore.proxy.Socks5Proxy#getPassword() * @see #getSocks5Proxy() * @generated */ EAttribute getSocks5Proxy_Password(); /** * Returns the meta object for the attribute '{@link edu.tsinghua.lumaqq.ecore.proxy.Socks5Proxy#getPort <em>Port</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Port</em>'. * @see edu.tsinghua.lumaqq.ecore.proxy.Socks5Proxy#getPort() * @see #getSocks5Proxy() * @generated */ EAttribute getSocks5Proxy_Port(); /** * Returns the meta object for the attribute '{@link edu.tsinghua.lumaqq.ecore.proxy.Socks5Proxy#getServer <em>Server</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Server</em>'. * @see edu.tsinghua.lumaqq.ecore.proxy.Socks5Proxy#getServer() * @see #getSocks5Proxy() * @generated */ EAttribute getSocks5Proxy_Server(); /** * Returns the meta object for the attribute '{@link edu.tsinghua.lumaqq.ecore.proxy.Socks5Proxy#getUsername <em>Username</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Username</em>'. * @see edu.tsinghua.lumaqq.ecore.proxy.Socks5Proxy#getUsername() * @see #getSocks5Proxy() * @generated */ EAttribute getSocks5Proxy_Username(); /** * Returns the factory that creates the instances of the model. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the factory that creates the instances of the model. * @generated */ ProxyFactory getProxyFactory(); /** * <!-- begin-user-doc --> * Defines literals for the meta objects that represent * <ul> * <li>each class,</li> * <li>each feature of each class,</li> * <li>each enum,</li> * <li>and each data type</li> * </ul> * <!-- end-user-doc --> * @generated */ interface Literals { /** * The meta object literal for the '{@link edu.tsinghua.lumaqq.ecore.proxy.impl.HttpProxyImpl <em>Http Proxy</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see edu.tsinghua.lumaqq.ecore.proxy.impl.HttpProxyImpl * @see edu.tsinghua.lumaqq.ecore.proxy.impl.ProxyPackageImpl#getHttpProxy() * @generated */ EClass HTTP_PROXY = eINSTANCE.getHttpProxy(); /** * The meta object literal for the '<em><b>Password</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute HTTP_PROXY__PASSWORD = eINSTANCE.getHttpProxy_Password(); /** * The meta object literal for the '<em><b>Port</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute HTTP_PROXY__PORT = eINSTANCE.getHttpProxy_Port(); /** * The meta object literal for the '<em><b>Server</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute HTTP_PROXY__SERVER = eINSTANCE.getHttpProxy_Server(); /** * The meta object literal for the '<em><b>Username</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute HTTP_PROXY__USERNAME = eINSTANCE.getHttpProxy_Username(); /** * The meta object literal for the '{@link edu.tsinghua.lumaqq.ecore.proxy.impl.ProxiesImpl <em>Proxies</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see edu.tsinghua.lumaqq.ecore.proxy.impl.ProxiesImpl * @see edu.tsinghua.lumaqq.ecore.proxy.impl.ProxyPackageImpl#getProxies() * @generated */ EClass PROXIES = eINSTANCE.getProxies(); /** * The meta object literal for the '<em><b>Socks5 Proxy</b></em>' containment reference list feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference PROXIES__SOCKS5_PROXY = eINSTANCE.getProxies_Socks5Proxy(); /** * The meta object literal for the '<em><b>Http Proxy</b></em>' containment reference list feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference PROXIES__HTTP_PROXY = eINSTANCE.getProxies_HttpProxy(); /** * The meta object literal for the '{@link edu.tsinghua.lumaqq.ecore.proxy.impl.Socks5ProxyImpl <em>Socks5 Proxy</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see edu.tsinghua.lumaqq.ecore.proxy.impl.Socks5ProxyImpl * @see edu.tsinghua.lumaqq.ecore.proxy.impl.ProxyPackageImpl#getSocks5Proxy() * @generated */ EClass SOCKS5_PROXY = eINSTANCE.getSocks5Proxy(); /** * The meta object literal for the '<em><b>Password</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute SOCKS5_PROXY__PASSWORD = eINSTANCE.getSocks5Proxy_Password(); /** * The meta object literal for the '<em><b>Port</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute SOCKS5_PROXY__PORT = eINSTANCE.getSocks5Proxy_Port(); /** * The meta object literal for the '<em><b>Server</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute SOCKS5_PROXY__SERVER = eINSTANCE.getSocks5Proxy_Server(); /** * The meta object literal for the '<em><b>Username</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute SOCKS5_PROXY__USERNAME = eINSTANCE.getSocks5Proxy_Username(); } } //ProxyPackage
package com.javakc.ssm.modules.copyright.dao; import com.javakc.ssm.base.dao.BaseDao; import com.javakc.ssm.modules.copyright.entity.CopyrightEntity; /** * @InterfaceName CopyrightDao * @Description TODO * @Author Administrator * @Date 2020/3/21 12:00 * @Version 1.0 **/ public interface CopyrightDao extends BaseDao<CopyrightEntity> { }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class p5 { public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(System.in); System.out.println("What is the first number?"); while (!scanner.hasNextInt()){ scanner.next(); System.out.println("confirm your input, It is only valid number"); } long first = scanner.nextLong(); System.out.println("What is the second number?"); while (!scanner.hasNextInt()){ scanner.next(); System.out.println("confirm your input, It is only valid number"); } long second = scanner.nextLong(); System.out.println(first + " + " + second + " = " + Math.addExact(first, second)); System.out.println(first + " - " + second + " = " + Math.subtractExact(first,second)); System.out.println(first + " * " + second + " = " + Math.multiplyExact(first, second)); System.out.println(first + " / " + second + " = " + Math.floorDiv(first, second)); } }
package com.kenji47.volley_work.instagram_model; /** * Created by kenji1947 on 28.07.2015. */ public class Image { public Image() { } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getWidth() { return width; } public void setWidth(String width) { this.width = width; } public String getHeight() { return height; } public void setHeight(String height) { this.height = height; } private String url; private String width; private String height; }
class Solution { public List<String> removeSubfolders(String[] folder) { /* /a /a/b /a/b/c /b /b/c /b/d string start with "/a/" can be ignored. **/ List<String> res = new ArrayList<>(); if (folder == null || folder.length == 0) return res; Arrays.sort(folder); for (String s : folder) { if (res.isEmpty() || !s.startsWith(res.get(res.size() - 1) + "/")) { res.add(s); } } return res; } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.commerceservices.order.strategies.impl; import de.hybris.platform.commerceservices.order.EntryMergeFilter; import de.hybris.platform.commerceservices.order.strategies.EntryMergeStrategy; import de.hybris.platform.commerceservices.service.data.CommerceCartParameter; import de.hybris.platform.core.model.order.AbstractOrderEntryModel; import de.hybris.platform.servicelayer.util.ServicesUtil; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Objects; import javax.annotation.Nonnull; /** * Default implementation of {@link EntryMergeStrategy}. * <p> * Any module can register a filter of type {@link EntryMergeFilter}. The filter can return {@code FALSE} * to deny merging particular entry with given {@link CommerceCartParameter}. * </p> * <p> * Also it is possible to change order of preference for input entries. * </p> * * @see de.hybris.platform.commerceservices.order.impl.DefaultCommerceAddToCartStrategy */ public class DefaultEntryMergeStrategy implements EntryMergeStrategy { private List<EntryMergeFilter> entryMergeFilters = Collections.emptyList(); private Comparator<AbstractOrderEntryModel> entryModelComparator = (entry1, entry2) -> 0; @Override public AbstractOrderEntryModel getEntryToMerge( final List<AbstractOrderEntryModel> entries, @Nonnull final AbstractOrderEntryModel newEntry) { ServicesUtil.validateParameterNotNullStandardMessage("newEntry", newEntry); if (entries == null) { return null; } return entries.stream() .filter(Objects::nonNull) .filter(e -> !newEntry.equals(e)) .filter(entry -> canMerge(entry, newEntry).booleanValue()) .sorted(getEntryModelComparator()) .findFirst() .orElse(null); } /** * This method determines whether given entry can be merged with the given entry creation candidate. * * @param mergeCandidate entry that is supposed to be merge acceptor * @param newEntry entry to find merge target for * @return {@link Boolean#FALSE} to disable merge of {@code newEntry} to {@code mergeCandidate} */ protected Boolean canMerge( @Nonnull final AbstractOrderEntryModel mergeCandidate, @Nonnull final AbstractOrderEntryModel newEntry) { return getEntryMergeFilters().stream() .map(filter -> filter.apply(mergeCandidate, newEntry)) .filter(Boolean.FALSE::equals) .findAny() .orElse(Boolean.TRUE); } protected List<EntryMergeFilter> getEntryMergeFilters() { return entryMergeFilters; } /** * Filters to reject entities that can not be merged. * <p> * The filters are applied in their natural order, * so it worth to put the filters that are fast and likely return {@link Boolean#FALSE} * on top of the list. * It will speed up the filtration. * </p> * * @see de.hybris.platform.spring.config.ListMergeDirective * * @param items new list of filters */ public void setEntryMergeFilters(final List<EntryMergeFilter> items) { entryMergeFilters = items; } protected Comparator<AbstractOrderEntryModel> getEntryModelComparator() { return entryModelComparator; } /** * The comparator can be overridden to change order of preference for entries. * {@link this#getEntryToMerge(List, CommerceCartParameter)} returns first suitable entry of the resulting list. * <p> * The default implementation does not change order of entries. * </p> * * @param entryModelComparator new {@code AbstractOrderEntryModel} comparator */ public void setEntryModelComparator(final Comparator<AbstractOrderEntryModel> entryModelComparator) { this.entryModelComparator = entryModelComparator; } }
package com.rc.utils; import com.rc.app.Launcher; import java.io.IOException; public class ShellUtil { public static String ICON_PATH = Launcher.appFilesBasePath + "/ic_launcher.png"; public static void executeShell(String shellCommand) throws IOException { String[] cmd = {"/bin/sh", "-c", shellCommand}; Runtime.getRuntime().exec(cmd); } }
package com.aws.demo.permids; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.LambdaLogger; import com.amazonaws.services.lambda.runtime.RequestStreamHandler; import com.aws.demo.permids.services.dynamodb.DynamoDBServiceImpl; import com.aws.demo.permids.util.InputParserService; import com.aws.demo.permids.util.InputParserServiceImpl; import com.aws.demo.permids.util.WithErrorService; import com.aws.demo.permids.util.WithErrorServiceImpl; import org.json.simple.JSONObject; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; public class ResetPermIdHandler implements RequestStreamHandler { public static final String INIT_DATA = "initData"; @Override public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException { long begin = System.currentTimeMillis(); LambdaLogger lambdaLogger = context.getLogger(); lambdaLogger.log("ResetPermIdHandler handleRequest begin"); WithErrorService withErrorService = new WithErrorServiceImpl(); InputParserService inputParserService = new InputParserServiceImpl(); JSONObject json = (JSONObject) inputParserService.parse(inputStream, withErrorService); applyResetPermId(json, context, withErrorService); buildOutputStream(outputStream, withErrorService); lambdaLogger.log("ResetPermIdHandler handleRequest end duration " + (System.currentTimeMillis() - begin)); } /** * apply id ot ids as required * * @param json * @param withErrorService */ private void applyResetPermId(JSONObject json, Context context, WithErrorService withErrorService) { DynamoDBServiceImpl permIDService = new DynamoDBServiceImpl(); permIDService.init(json, context); } /** * build response with id or ids * * @param outputStream * @param withErrorService * @throws IOException */ private void buildOutputStream(OutputStream outputStream, WithErrorService withErrorService) throws IOException { JSONObject headerJson = new JSONObject(); JSONObject responseBody = new JSONObject(); JSONObject responseJson = new JSONObject(); responseJson.put("statusCode", 200); responseJson.put("headers", headerJson); responseJson.put("body", responseBody.toString()); OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8"); writer.write(responseJson.toString()); writer.close(); } }
package com.vic.common.base.form; import lombok.Data; import javax.validation.constraints.Max; import javax.validation.constraints.Min; /** * @ProjectName: spring-cloud-examples * @Package: com.github.manage.common.form * @Description: 查询表单 * @Author: Vayne.Luo * @date 2019/01/29 */ @Data public class SearchForm extends BaseForm { private static final long serialVersionUID = -9218053938242059294L; /** 当前页数*/ @Min(value = 1) private int currentPage; /** 每页条数*/ @Max(value = 100) private int pageSize;; }
package admin; import java.awt.Color; import java.awt.Toolkit; import java.awt.event.WindowEvent; /* * 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. */ /** * * @author anoop */ public class University extends javax.swing.JFrame { /** * Creates new form University */ public University() { initComponents(); setTitle("University"); getContentPane().setBackground(Color.pink); } public void close (){ WindowEvent winClosingEvent = new WindowEvent(this,WindowEvent.WINDOW_CLOSING); Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winClosingEvent); } /** * 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(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N jLabel1.setText("STUDENT INFORMATION"); jButton1.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N jButton1.setText("SMVDU"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N jButton2.setText("NIT SRINAGAR"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N jButton3.setText("IIT JAMMU"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jLabel2.setFont(new java.awt.Font("Dialog", 2, 18)); // NOI18N jLabel2.setForeground(new java.awt.Color(0, 102, 102)); jLabel2.setText("Select Your College"); jLabel3.setIcon(new javax.swing.ImageIcon("/home/anoop/Downloads/1.png")); // NOI18N jLabel4.setIcon(new javax.swing.ImageIcon("/home/anoop/Downloads/1.png")); // NOI18N jLabel5.setIcon(new javax.swing.ImageIcon("/home/anoop/Downloads/1.png")); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(178, 178, 178) .addComponent(jLabel1)) .addGroup(layout.createSequentialGroup() .addGap(165, 165, 165) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(34, 34, 34) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addContainerGap(170, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(26, 26, 26) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)) .addGap(28, 28, 28) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addGap(27, 27, 27) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(123, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed close (); branch b = new branch(); b.setVisible(true); }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed close (); branch c = new branch(); c.setVisible(true); }//GEN-LAST:event_jButton2ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed close (); branch d = new branch(); d.setVisible(true); }//GEN-LAST:event_jButton3ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(University.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(University.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(University.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(University.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new University().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; // End of variables declaration//GEN-END:variables }
package com.tencent.mm.plugin.shake.d.a; import com.tencent.mm.protocal.c.bhp; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; class a$2 implements Runnable { final /* synthetic */ a mYA; final /* synthetic */ boolean mYB = false; final /* synthetic */ boolean mYC; a$2(a aVar, boolean z) { this.mYA = aVar; this.mYC = z; } public final void run() { if (this.mYB) { a.a(this.mYA, null, -1, this.mYC); } else if (!this.mYA.mYp) { x.w("MicroMsg.MusicFingerPrintRecorder", "tryCallBack netscen not return."); } else if (this.mYA.bDp != null) { x.w("MicroMsg.MusicFingerPrintRecorder", "tryCallBack device not ready!"); } else if (this.mYA.mYq != null) { a aVar = this.mYA; bhp bvf = this.mYA.mYq.bvf(); e eVar = this.mYA.mYq; long VF = bi.VF(); if (eVar.mYG > 0 && eVar.mYG < VF) { VF = eVar.mYG; } a.a(aVar, bvf, VF, this.mYC); } else { a.a(this.mYA, null, -1, this.mYC); } } }
public interface Swimmable { public void swim(String s); }
package com.youthchina.dao.qingyang; import com.youthchina.domain.qingyang.Hr; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Component; import java.util.List; @Mapper @Component public interface HrMapper { Integer insertHr(Hr hr); Integer updateHr(Hr hr); Integer deleteHr(Integer id); Integer deleteHrByComId(Integer id); Hr selectHrById(Integer id); List<Hr> selectHrByIdList(List<Integer> ids); }
package com.tencent.mm.plugin.appbrand.game.b; import com.tencent.magicbrush.a.b.a; import com.tencent.mm.compatible.util.k; import com.tencent.mm.plugin.appbrand.game.e.d; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.x; class c$1 implements a { c$1() { } public final void loadLibrary(String str) { try { x.i("MicroMsg.MBLoadDelegateRegistery", "loadLibrary libName:%s", new Object[]{str}); k.b(str, c.class.getClassLoader()); } catch (Throwable e) { x.printErrStackTrace("MicroMsg.MBLoadDelegateRegistery", e, "hy: link %s error!!", new Object[]{str}); d.cw(ad.getContext()); } } }
/** * */ package continuum.cucumber.OSUtility; import java.io.IOException; import java.io.InputStream; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; /** * @author sneha.chemburkar * */ public class RemoteSSHConnection { public static Channel createSSHConnection(String host,int port, String userName, String password) { // String host = "10.2.42.148"; // String user = "junovm"; // String password = "junovm@123"; // String command1 ="ls -l"; Session session=null; Channel channel=null; try{ JSch jsch = new JSch(); session=jsch.getSession(userName, host, port); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); System.out.println("Remote machine Connected"); channel = session.openChannel("exec"); channel.setInputStream(null); ((ChannelExec)channel).setErrStream(System.err); } catch (JSchException e) { // TODO Auto-generated catch block e.printStackTrace();} return channel; } public static void executeCommand(Channel channel,String command) { ((ChannelExec)channel).setCommand(command); // Channel channel; // try { // channel = session.openChannel("exec"); // // ((ChannelExec)channel).setCommand(command); // channel.setInputStream(null); // ((ChannelExec)channel).setErrStream(System.err); ((ChannelExec)channel).setCommand(command); try { channel.connect(); } catch (JSchException e) { // TODO Auto-generated catch block e.printStackTrace(); } // InputStream in=channel.getInputStream(); // // byte[] tmp=new byte[1024]; // while(true){ // while(in.available()>0){ // int i=in.read(tmp, 0, 1024); // if(i<0)break; // System.out.print(new String(tmp, 0, i)); // } // } System.out.println(channel.getExitStatus()); channel.disconnect(); } public static void closeSSHConnection(Channel channel) { if(channel.isClosed()){ System.out.println("exit-status: "+channel.getExitStatus()); } try{Thread.sleep(1000);}catch(Exception ee){ System.out.println("Execetion "+ee.getMessage()); } channel.disconnect(); try { channel.getSession().disconnect(); } catch (JSchException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Connection closed"); } // public static void executeCommandOnWindowsMachine(String machine, String username, String password,String command) { // try { // String executeCmd = "cmd /c net use \\\\" + machine + "\\IPC$ /U:" + username + " " + password; // Process runtimeProcess = Runtime.getRuntime().exec(executeCmd); // System.out.println("Execution output"+runtimeProcess.getOutputStream().); // int cmdStatus = runtimeProcess.waitFor(); // System.out.println("Execution status"+cmdStatus); // } catch (IOException | InterruptedException ex) { // System.out.println("Error to connect to windows machine: "+ ex); // } // } public static void executeCommandOnWindows(String machine, String username, String password, String executeCmd ){ System.out.println("Execute command: " + executeCmd); try { Process runtimeProcess = Runtime.getRuntime().exec(executeCmd); InputStream in=runtimeProcess.getInputStream(); byte[] tmp=new byte[1024]; while(true){ while(in.available()>0){ int i=in.read(tmp, 0, 1024); if(i<0)break; System.out.print(new String(tmp, 0, i)); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // public static void main(String []args) // { // String osType="Windows"; // if(osType.equalsIgnoreCase("Linux")) // { // Session sh= createSSHConnection("10.2.42.148",22,"junovm","junovm@123"); // //executeCommand(sh,"sudo visudo"); // executeCommand(sh,"service cassandra status"); // } // else if(osType.equalsIgnoreCase("Windows")) // { // //Session sh= createSSHConnection("10.2.14.207",22,"mahesh.mahajan","MAhi1234@"); // executeCommandOnWindows("10.2.14.207","mahesh.mahajan","MAhi1234@","cmd.exe /c dir"); // } // } }
package com.ht.test; import com.ht.entity.User; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * @company 宏图 * @User Kodak * @create 2019-03-19 -10:07 */ public class CaseTest { public static void main(String[] args) { // 获取连接池配置 JedisPoolConfig config=new JedisPoolConfig(); // 设置连接池最大链接数 config.setMaxTotal(50); // 设置连接池最大空闲数 config.setMaxIdle(10); //获得连接池 JedisPool jedisPool=new JedisPool(config,"127.0.0.1",6379); //获取核心对象 Jedis jedis=null; try { // 通过连接池连接redis缓存数据库 jedis=jedisPool.getResource(); // 创建一个user对象 User u=new User(1,20,"zhangsan","2270301642@qq.com"); // 创建map并将user对象放进map中 Map map=new HashMap(); map.put("id",u.getId()+""); map.put("name",u.getName()); map.put("age",u.getAge()+""); map.put("email",u.getEmail()); //将map封装进redis jedis.hmset("usermap",map); Map resultmap=jedis.hgetAll("usermap"); System.out.println("查询返回的数据是:"+resultmap); }catch (Exception e){ e.printStackTrace(); }finally { // 关闭redis连接 if(jedis!=null){ jedis.close(); System.out.println("redis连接已关闭"); } //关闭连接池 if(jedisPool!=null){ jedisPool.close(); System.out.println("连接池已关闭"); } } } }
package rs.jug.rx.qconsf2014.netflix.gateway; import java.util.Random; import rx.Observable; public class VideoServiceGateway { Random random = new Random(); public Observable<Rating> rating(String video) { addLatency(); return Observable.just(new Rating()); } public Observable<VideoMetadata> metadata(String video) { addLatency(); return Observable.just(new VideoMetadata()); } private void addLatency(){ int latency = random.nextInt(5000); try { Thread.sleep(latency); } catch (InterruptedException e) { // Stop adding latency } } }
package com.prokarma.reference.architecture.app; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import com.prokarma.reference.architecture.R; import com.prokarma.reference.architecture.di.Injection; import javax.inject.Inject; import androidx.navigation.Navigation; public class MainActivity extends AppCompatActivity { // creating reference to access the object @Inject NavigationManager navigationManager; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // accessing all dagger objects Injection.create().getAppComponent().inject(MainActivity.this); navigationManager.setNavController(Navigation.findNavController(this, R.id.my_nav_host_fragment)); } }
package com.projet3.library_webservice.library_webservice_consumer.DAO; import java.sql.SQLException; import java.util.List; import com.projet3.library_webservice.library_webservice_model.beans.Author; public interface AuthorDAO { public Author getAuthorByID(int id) throws SQLException; public List<Author> getAuthorList() throws SQLException; public void createAuthor(Author author) throws SQLException; public void updateAuthor(Author author) throws SQLException; public void deleteAuthor(Author author) throws SQLException; }
package skorban.loremipsum; public class Paragraph extends Generator { }
package day14; public class test2 { public static void main(String[] args) { //demo2(); demo3(); } private static void demo3() { String regex = "\\W"; System.out.println("12".matches(regex)); System.out.println("a".matches(regex)); System.out.println("_".matches(regex)); System.out.println("&".matches(regex)); } private static void demo2() { String regex = "[^abc]"; System.out.println("a".matches(regex)); System.out.println("b".matches(regex)); System.out.println("c".matches(regex)); System.out.println("d".matches(regex)); System.out.println("1".matches(regex)); System.out.println("%".matches(regex)); } static void demo1() { extracted(); } private static void extracted() { String regex = "[abc]"; System.out.println("a".matches(regex)); System.out.println("b".matches(regex)); System.out.println("c".matches(regex)); System.out.println("d".matches(regex)); System.out.println("1".matches(regex)); System.out.println("%".matches(regex)); } }
package com.aktway.services.profile.api.response; import org.springframework.stereotype.Component; import java.util.List; @Component public class MyPrivatePostData { private String postName; private List<String> tagList; private String postId; private String postedDate; private String postPicture; public String getPostName() { return postName; } public void setPostName(String postName) { this.postName = postName; } public List<String> getTagList() { return tagList; } public void setTagList(List<String> tagList) { this.tagList = tagList; } public String getPostId() { return postId; } public void setPostId(String postId) { this.postId = postId; } public String getPostedDate() { return postedDate; } public void setPostedDate(String postedDate) { this.postedDate = postedDate; } public String getPostPicture() { return postPicture; } public void setPostPicture(String postPicture) { this.postPicture = postPicture; } }
package pages; import org.openqa.selenium.By; import static com.codeborne.selenide.Selenide.*; public class BasePage { // click the link from the list of tasks public void clickLinkOver(String text){ $(By.xpath("//h2[text()='" + text + "']/..")).click(); } // click any link public void clickLink(String marker){ $(By.xpath(marker)).click(); } // switch window public void switchWindow(int num){ switchTo().window(num); } // switch frame public void switchFrame(int num){ switchTo().frame(num); } }
package com.ibanity.apis.client.http.handler; import com.ibanity.apis.client.exceptions.IbanityClientException; import com.ibanity.apis.client.exceptions.IbanityServerException; import com.ibanity.apis.client.models.IbanityError; import org.apache.http.HttpResponse; import org.apache.http.ProtocolVersion; import org.apache.http.client.entity.EntityBuilder; import org.apache.http.message.BasicStatusLine; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.io.IOException; import java.util.List; import static com.google.common.collect.Lists.newArrayList; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class IbanityResponseHandlerTest { private IbanityResponseHandler ibanityResponseHandler = new IbanityResponseHandler(); @Mock private HttpResponse httpResponse; @Test void handleResponse() throws IOException { //language=JSON String expected = validPayload(); when(httpResponse.getEntity()).thenReturn(EntityBuilder.create().setText(expected).build()); when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(dummyProtocolVersion(), 200, "")); String actual = ibanityResponseHandler.handleResponse(httpResponse); assertThat(actual).isEqualTo(expected); } @Test void handleResponse_whenServerError_thenThrowIbanityServerSideException() { //language=JSON String expected = errorPayload(); when(httpResponse.getEntity()).thenReturn(EntityBuilder.create().setText(expected).build()); when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(dummyProtocolVersion(), 500, "")); IbanityServerException actual = assertThrows(IbanityServerException.class, () -> ibanityResponseHandler.handleResponse(httpResponse)); assertThat(actual).isEqualToComparingFieldByFieldRecursively(new IbanityServerException(createExpectedErrors(), 500)); } @Test void handleResponse_whenResourceNotFound_thenThrowIbanityClientSideException() { //language=JSON String expected = errorPayload(); when(httpResponse.getEntity()).thenReturn(EntityBuilder.create().setText(expected).build()); when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(dummyProtocolVersion(), 404, "")); IbanityClientException actual = assertThrows(IbanityClientException.class, () -> ibanityResponseHandler.handleResponse(httpResponse)); assertThat(actual).isEqualToComparingFieldByFieldRecursively(new IbanityServerException(createExpectedErrors(), 404)); } private List<IbanityError> createExpectedErrors() { return newArrayList(IbanityError.builder() .code("invalidCredentials") .detail("Your credentials are invalid.") .build()); } private String validPayload() { return "{\"message\": \"hello world\"}"; } private String errorPayload() { return "{\n" + " \"errors\": [\n" + " {\n" + " \"code\": \"invalidCredentials\",\n" + " \"detail\": \"Your credentials are invalid.\"\n" + " }\n" + " ]\n" + "}"; } private ProtocolVersion dummyProtocolVersion() { return new ProtocolVersion("", 0, 0); } }
package gof.decorator; import java.math.BigDecimal; public abstract class Pizza { protected String description = null; public String getDescription() { return description; } public abstract BigDecimal cost(); }
class Break { public static void main(String args[]) { boolean x=true; bl1: { bl2: { bl3: { System.out.println("Block 3"); if(x) break bl2; } System.out.println("Block 2"); } System.out.println("Block 1"); } System.out.println("Out of all blocks"); } }
package com.example.imdb.repository.orm; import java.util.List; import java.util.Optional; import java.util.stream.Stream; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.example.imdb.entity.Movie; import com.example.imdb.repository.MovieRepository; /** * * @author Binnur Kurt <binnur.kurt@gmail.com> * */ @Repository public class JpaMovieRepository implements MovieRepository { @PersistenceContext private EntityManager em; @Override public Optional<Movie> findOneById(Integer id) { return Optional.ofNullable(em.find(Movie.class, id)); } @Override public List<Movie> findAll(int pageNo, int pageSize) { return em.createNamedQuery("Movie.findAll", Movie.class).setFirstResult(pageNo * pageSize) .setMaxResults(pageSize).getResultList(); } @Override @Transactional public Optional<Movie> save(Movie movie) { em.persist(movie); return Optional.of(movie); } @Override @Transactional public Optional<Movie> update(Movie movie) { Integer id = movie.getMovieId(); Optional<Movie> optionalOfMovie = this.findOneById(id); optionalOfMovie.ifPresent(managed -> { managed.setTitle(movie.getTitle()); managed.setYear(movie.getYear()); }); return optionalOfMovie; } @Override @Transactional public Optional<Movie> removeById(Integer id) { Optional<Movie> movie = this.findOneById(id); movie.ifPresent(managed -> { em.remove(managed); }); return movie; } @Override @Transactional public Optional<Movie> remove(Movie movie) { return this.removeById(movie.getMovieId()); } @Override public Stream<Movie> findAllByYearBetween(int from, int to) { return em.createNamedQuery("Movie.findAllByYearBetween", Movie.class).setParameter("from", from) .setParameter("to", to).getResultList().stream(); } @Override public Optional<Movie> findOneByImdb(String imdb) { // TODO Auto-generated method stub return null; } }
package Module2_OOP.ExtraTasks.Lesson4.E_ticket; import java.util.Objects; import java.util.Scanner; public class E_Ticket { // Composition public static Ticket[] tickets = new Ticket[54]; public static int count = 0; public static Order[] orders = new Order[10]; public static User[] users = new User[100]; public static User activeUser = new User(null, null, null, null, null); public static TrainSchedule[] trainSchedule = new TrainSchedule[25]; public static Train[] trains = new Train[10]; public static void main(String[] args) { initBase(); while (true) { login(); } } private static void login() { Scanner scanner = new Scanner(System.in); System.out.print("Login: "); String loginName = scanner.nextLine(); System.out.print("Password: "); String password = scanner.nextLine(); boolean notLoginUser = true; for (User loginUser : users) { if (loginUser != null) { if (loginUser.getFirstName().equals(loginName) && loginUser.getPassword().equals(password)) { notLoginUser = false; System.out.println("\nWelcome to E-Ticket " + loginUser.getFirstName() + " " + loginUser.getSecondName()); activeUser = loginUser; activeUserCommands(); } } } if (notLoginUser) { System.out.println("Incorrect login (0-Exit)"); } } private static void activeUserCommands() { while (true) { showMAinMenu(); Scanner scanner = new Scanner(System.in); int choiceActiveUser = scanner.nextInt(); switch (choiceActiveUser) { case 1: System.out.println("--Order Ticket--"); orderTicket(); break; case 2: System.out.println("--Show Train schedule--"); showTrainSchedules(); break; case 3: System.out.println("--Ordered Tickets-- "); showOrderedTickets(); break; case 4: break; case 5: break; case 0: return; default: System.out.println("Incorrect number"); break; } } } private static void showOrderedTickets() { System.out.println("----------------------------------------"); for (int i = 0; i < count; i++) { if (Objects.equals(activeUser, orders[i].getUser())) { System.out.println("TicketId: " + orders[i].getOrderId() + " | " + "From: " + orders[i].getTicket().getTrainSchedule().getFromStation() + " | " + "To: " + orders[i].getTicket().getTrainSchedule().getToStation() + " | " + "Class: " + orders[i].getTicket().getClassCategory() + " | " + "Price: " + orders[i].getTicket().getPrice()); } } System.out.println("----------------------------------------\n"); } private static void orderTicket() { Scanner scanner = new Scanner(System.in); System.out.print("From: "); String fromStation = scanner.nextLine(); System.out.print("To: "); String toStation = scanner.nextLine(); System.out.print("Category: "); int category = scanner.nextInt(); boolean trainScheduleFound = false; for (Ticket orderTicket : tickets) { if (orderTicket != null && orderTicket.getTrainSchedule().getFromStation().equals(fromStation) && orderTicket.getTrainSchedule().getToStation().equals(toStation) && orderTicket.getClassCategory() == category) { trainScheduleFound = true; System.out.println(orderTicket.getTicketNumber() + " " + orderTicket.getTrainSchedule().getFromStation() + " " + orderTicket.getTrainSchedule().getToStation() + " " + orderTicket.getClassCategory() + " " + orderTicket.getPrice()); System.out.println("Do you order the ticket Yes-1 or No-2"); scanner = new Scanner(System.in); int choice = scanner.nextInt(); if (choice == 1) { orders[count] = new Order(count, activeUser, orderTicket); count++; System.out.println("You ordered succesfully!!\n"); break; } } } if (!trainScheduleFound) { System.out.println("\nSuch TrainSchedule is not exist!\n"); } } private static void showTrainSchedules() { Scanner scanner = new Scanner(System.in); System.out.print("From: "); String from = scanner.nextLine(); System.out.println("----------------------------------------"); for (TrainSchedule schedule : trainSchedule) { if (schedule != null) { if (schedule.getFromStation().contains(from)) { System.out.println(schedule.getTrain().getNumberId() + " " + schedule.getFromStation() + " " + schedule.getToStation()); } } } System.out.println("----------------------------------------\n"); } private static void showMAinMenu() { System.out.println("Main menu: "); System.out.println("----------------------------------------"); System.out.println("1.Order ticket\n" + "2.Show Train Schedules\n" + "3.Show my Ordered Tickets\n" + "0.Exit"); System.out.println("----------------------------------------"); } private static void initBase() { trains[0] = new Train("123@123", 500); trains[1] = new Train("123@124", 635); trains[2] = new Train("123@125", 540); trains[3] = new Train("123@126", 100); trains[4] = new Train("123@127", 50); trains[5] = new Train("123@128", 120); trains[6] = new Train("123@129", 400); trainSchedule[0] = new TrainSchedule(trains[0], "TashkentSouth", "Buxara"); trainSchedule[1] = new TrainSchedule(trains[0], "TashkentNorth", "Buxara"); trainSchedule[2] = new TrainSchedule(trains[1], "Tashkent", "Nukus"); trainSchedule[3] = new TrainSchedule(trains[1], "Tashkent", "Andijan"); trainSchedule[4] = new TrainSchedule(trains[2], "Tashkent", "Kokan"); trainSchedule[5] = new TrainSchedule(trains[2], "Kokan", "Fergana"); trainSchedule[6] = new TrainSchedule(trains[3], "Andijan", "Tashkent"); trainSchedule[7] = new TrainSchedule(trains[3], "Nukus", "Tashkent"); trainSchedule[8] = new TrainSchedule(trains[4], "Fergana", "TashkentSouth"); trainSchedule[9] = new TrainSchedule(trains[4], "Buxara", "TashkentSouth"); trainSchedule[10] = new TrainSchedule(trains[5], "Buxara", "TashkentNorth"); trainSchedule[11] = new TrainSchedule(trains[5], "Fergana", "TashkentNorth"); trainSchedule[12] = new TrainSchedule(trains[6], "Fergana", "Kokan"); trainSchedule[13] = new TrainSchedule(trains[6], "Fergana", "Andijan"); trainSchedule[14] = new TrainSchedule(trains[4], "Fergana", "Namangan"); trainSchedule[15] = new TrainSchedule(trains[4], "Namangan", "Kokan"); trainSchedule[16] = new TrainSchedule(trains[5], "Kokan", "Pap"); trainSchedule[17] = new TrainSchedule(trains[5], "Samarkand", "Nukus"); users[0] = new User("Lochinbek", "Xojiyev", "Khojiyev@gmail.com", "asd123", null); users[1] = new User("Shohruh", "Sindarov", "Sindarov@gmail.com", "asd123", null); users[2] = new User("Sodiq", "Bo'riyev", "Boriyev@gmail.com", "asd123", null); users[3] = new User("Mamur", "Karimov", "Karimov@gmail.com", "asd123", null); users[4] = new User("Shokir", "Ahtamov", "Ahtamov@gmail.com", "asd123", null); tickets[0] = new Ticket("000", trainSchedule[0], 1, 250000); tickets[1] = new Ticket("010", trainSchedule[0], 2, 200000); tickets[2] = new Ticket("100", trainSchedule[0], 3, 150000); tickets[3] = new Ticket("000", trainSchedule[1], 1, 250000); tickets[4] = new Ticket("010", trainSchedule[1], 2, 200000); tickets[5] = new Ticket("100", trainSchedule[1], 3, 150000); tickets[6] = new Ticket("000", trainSchedule[2], 1, 250000); tickets[7] = new Ticket("001", trainSchedule[2], 2, 200000); tickets[8] = new Ticket("100", trainSchedule[2], 3, 150000); tickets[9] = new Ticket("000", trainSchedule[3], 1, 250000); tickets[10] = new Ticket("010", trainSchedule[3], 2, 200000); tickets[11] = new Ticket("100", trainSchedule[3], 3, 150000); tickets[12] = new Ticket("000", trainSchedule[4], 1, 250000); tickets[13] = new Ticket("010", trainSchedule[4], 2, 200000); tickets[14] = new Ticket("100", trainSchedule[4], 3, 150000); tickets[15] = new Ticket("000", trainSchedule[5], 1, 250000); tickets[16] = new Ticket("001", trainSchedule[5], 2, 200000); tickets[17] = new Ticket("100", trainSchedule[5], 3, 150000); tickets[18] = new Ticket("000", trainSchedule[6], 1, 250000); tickets[19] = new Ticket("001", trainSchedule[6], 2, 200000); tickets[20] = new Ticket("100", trainSchedule[6], 3, 150000); tickets[21] = new Ticket("000", trainSchedule[7], 1, 250000); tickets[22] = new Ticket("001", trainSchedule[7], 2, 200000); tickets[23] = new Ticket("100", trainSchedule[7], 3, 150000); tickets[24] = new Ticket("000", trainSchedule[8], 1, 250000); tickets[25] = new Ticket("001", trainSchedule[8], 2, 200000); tickets[26] = new Ticket("100", trainSchedule[8], 3, 150000); tickets[27] = new Ticket("000", trainSchedule[9], 1, 250000); tickets[28] = new Ticket("001", trainSchedule[9], 2, 200000); tickets[29] = new Ticket("100", trainSchedule[9], 3, 150000); tickets[30] = new Ticket("000", trainSchedule[10], 1, 250000); tickets[31] = new Ticket("001", trainSchedule[10], 2, 200000); tickets[32] = new Ticket("100", trainSchedule[10], 3, 150000); tickets[33] = new Ticket("000", trainSchedule[11], 1, 250000); tickets[34] = new Ticket("001", trainSchedule[11], 2, 200000); tickets[35] = new Ticket("100", trainSchedule[11], 3, 150000); tickets[36] = new Ticket("000", trainSchedule[12], 1, 250000); tickets[37] = new Ticket("001", trainSchedule[12], 2, 200000); tickets[38] = new Ticket("100", trainSchedule[12], 3, 150000); tickets[39] = new Ticket("000", trainSchedule[13], 1, 250000); tickets[40] = new Ticket("001", trainSchedule[13], 2, 200000); tickets[41] = new Ticket("100", trainSchedule[13], 3, 150000); tickets[42] = new Ticket("000", trainSchedule[14], 1, 250000); tickets[43] = new Ticket("001", trainSchedule[14], 2, 200000); tickets[44] = new Ticket("100", trainSchedule[14], 3, 150000); tickets[45] = new Ticket("000", trainSchedule[15], 1, 250000); tickets[46] = new Ticket("001", trainSchedule[15], 2, 200000); tickets[47] = new Ticket("100", trainSchedule[15], 3, 150000); tickets[48] = new Ticket("000", trainSchedule[16], 1, 250000); tickets[49] = new Ticket("001", trainSchedule[16], 2, 200000); tickets[50] = new Ticket("100", trainSchedule[16], 3, 150000); tickets[51] = new Ticket("000", trainSchedule[17], 1, 250000); tickets[52] = new Ticket("001", trainSchedule[17], 2, 200000); tickets[53] = new Ticket("100", trainSchedule[17], 3, 150000); } }
package com.originalandtest.tx.downloaddemo; import android.Manifest; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Process; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.app.NotificationCompat; import android.util.Log; import android.view.View; import android.widget.Toast; import com.originalandtest.tx.downloaddemo.download.DownladManager; import com.originalandtest.tx.downloaddemo.download.MediaUitl; import java.io.File; import kr.co.namee.permissiongen.PermissionFail; import kr.co.namee.permissiongen.PermissionGen; import kr.co.namee.permissiongen.PermissionSuccess; public class MainActivity extends AppCompatActivity { private String path = "http://imtt.dd.qq.com/16891/756EE19C6AAB03B58BBE742DFAD138C1.apk?fsname=com.tencent.movieticket_7.5.1_77.apk&csr=1bbd"; private NotificationManager notificationManager; private NotificationCompat.Builder mBuilder; private final static int mId = 0x01; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initPermission(); findViewById(R.id.downLoad).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { download(); } }); notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Log.e("taxi", "onCreate pid=" + Process.myPid()); } private void initPermission() { PermissionGen.with(this).addRequestCode(100).permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE) .request(); } @PermissionSuccess(requestCode = 100) public void onPRSuc() { } @PermissionFail(requestCode = 100) public void onPRFail() { Toast.makeText(this, "fail", Toast.LENGTH_SHORT).show(); } private void download() { mBuilder = new NotificationCompat.Builder(this); mBuilder.setSmallIcon(R.mipmap.ic_launcher); mBuilder.setContentTitle("下载中"); final UpdateThread updateThread = new UpdateThread(); updateThread.start(); DownladManager.getInstance(this).downloadVideo(path, MediaUitl.TYPE_DLOAD, new DownladManager.VideoCacheManagerDownLoadListener() { @Override public void onDownLoadSucceed(String filePath) { Log.e("taxi", "Activity下载成功"); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, "suc", Toast.LENGTH_SHORT).show(); //TODO 自动调用apk mBuilder.setContentText("下载完成"); mBuilder.setProgress(0, 0, true); notificationManager.notify(mId, mBuilder.build()); } }); //直接安装应用。 installApk(filePath); } @Override public void onDownLoading(int progress) { //TODO 通知栏显示进度 // sendNotification(progress); // notificationManager.notify(mId, mBuilder.build()); updateThread.update(progress); } @Override public void onDownLoadFailure() { Log.d("taxi", "下载失败"); } }); } private void installApk(String filePath) { Log.d("taxi", "install path="+filePath); Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive"); startActivity(intent); } private void sendNotification(int progress) { if (mBuilder == null) { return; } //每500ms执行一次 mBuilder.setProgress(100, progress, false); mBuilder.setContentText("当前进度:" + progress + "%"); notificationManager.notify(mId, mBuilder.build()); } class UpdateThread extends Thread { UpdateThread() { isRunning = true; } private int progress; private boolean isRunning = false; void update(int progress) { this.progress = progress; } @Override public void run() { while (isRunning) { loop(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } void loop() { //发消息改变 if (progress < 100) { mBuilder.setProgress(100, progress, false); mBuilder.setContentText("当前进度:" + progress + "%"); notificationManager.notify(mId, mBuilder.build()); } else if (progress == 100) { mBuilder.setProgress(100, progress, false); mBuilder.setContentText("当前进度:" + progress + "%"); Log.e("taxi", "progress =100,停止线程-----------"); isRunning = false; } } } }
package com.java.michael.chesstutor; import com.java.michael.chesstutor.Piece; /* public class Pieces { private Piece[] Pieces = new Piece[12]; Pieces(int row, int column) { Pieces[0] = new Piece(row, column,"Pawn", "Black", false, false, 1); Pieces[1] = new Piece(row, column,"Knight", "Black", false, false, 3); Pieces[2] = new Piece(row, column,"Bishop", "Black", false, false, 3); Pieces[3] = new Piece(row, column,"Bishop", "Black", false, false, 5); Pieces[4] = new Piece(row, column,"Queen", "Black", false, false, 9); Pieces[5] = new Piece(row, column,"King", "Black", false, false, 2000); Pieces[6] = new Piece(row, column,"Pawn", "White", false, false, 1); Pieces[7] = new Piece(row, column,"Knight", "White", false, false, 3); Pieces[8] = new Piece(row, column,"Bishop", "White", false, false, 3); Pieces[9] = new Piece(row, column,"Rook", "White", false, false, 5); Pieces[10] = new Piece(row, column,"Queen", "White", false, false, 9); Pieces[11] = new Piece(row, column,"King", "White", false, false, 2000); Pieces[12] = new Pieace("Cell", "None", false, false,0); } } */
package cl.model; import java.util.ArrayList; import javax.ejb.LocalBean; import javax.ejb.Singleton; /** * Session Bean implementation class Servicio */ @Singleton @LocalBean public class Servicio implements ServicioLocal { private ArrayList<Cliente> lista= new ArrayList(); /** * Default constructor. */ public Servicio() { lista.add(new Cliente( "juan","perez","111111-1")); lista.add(new Cliente( "Diego","perez","2222222-2")); // TODO Auto-generated constructor stub } @Override public void addCliente(Cliente cli) { lista.add(cli); // TODO Auto-generated method stub } @Override public Cliente buscarCliente(String rut) { for (Cliente cliente:lista){ if (cliente.getRut().equals(rut)) return cliente; } return null; } // TODO Auto-generated method stub @Override public String elminar(String rut) { // TODO Auto-generated method stub Cliente cli = buscarCliente(rut); if (cli ==null) { return "cliente no encontrado"; } else{ lista.remove(cli); return "cliente eliminado"; } } @Override public void actualizar(Cliente cli) { Cliente cliente = buscarCliente(cli.getRut()); lista.remove(cliente); lista.add(cli); } @Override public ArrayList<Cliente> getClientes() { // TODO Auto-generated method stub return lista; } }
package frame; import java.awt.Frame; import java.awt.Image; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class MyFrame extends Frame { Image image = GameUtil.getImage("images/add_fav.png"); public void launchFrame() { setSize(Constants.WIDTH, Constants.HEIGHT); setLocation(100, 100); setVisible(true); new PaintThread().start(); // 启动重画线程 addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } /** * * 定义一个重画类 * @Company 杭州木瓜科技有限公司 * @className: MyFrame.java * @author Patrick Shen jingtian@amugua.com * @date 2017年9月4日 下午11:36:17 */ class PaintThread extends Thread { @Override public void run() { while (true) { repaint(); try { Thread.sleep(40); } catch (InterruptedException e) { e.printStackTrace(); } } } } public static void main(String[] args) { MyFrame gf = new MyFrame(); gf.launchFrame(); } }
package driverClass; import io.github.bonigarcia.wdm.WebDriverManager; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; public class DriverClass { public static WebDriver driver; @BeforeTest public void initialize() { if (null == driver) { WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); } } @AfterTest public static void destoryDriver() { driver.quit(); } }
package com.fleet.mybatis.plus.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.fleet.mybatis.plus.entity.User; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.List; import java.util.Map; @Mapper public interface UserDao extends BaseMapper<User> { @Select("list") List<User> list(Page<User> page, @Param("map") Map<String, Object> map); }
package com.podarbetweenus.Adapter; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.ColorDrawable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.podarbetweenus.BetweenUsConstant.Constant; import com.podarbetweenus.Entity.LoginDetails; import com.podarbetweenus.Entity.TeacherAttendaceResult; import com.podarbetweenus.R; import com.podarbetweenus.Services.DataFetchService; import com.podarbetweenus.Utility.AppController; import org.json.JSONObject; import org.w3c.dom.Text; import java.util.ArrayList; /** * Created by Gayatri on 2/3/2016. */ public class ShowAttendanceAdapter extends BaseAdapter { LayoutInflater layoutInflater; Context context; DataFetchService dft; LoginDetails login_details; ProgressDialog progressDialog; String clt_id,msd_id,board_name,school_name,usl_id,teacher_name,version_name,month_id,atn_valid,academic_yearId,hideReason; String ShowAttendanceReasonMethod_name = "ViewStudAttendDetails"; public ArrayList<TeacherAttendaceResult> teacherAttendaceResult = new ArrayList<TeacherAttendaceResult>(); //Attendence adapter Constructor public ShowAttendanceAdapter(Context context, ArrayList<TeacherAttendaceResult> teacherAttendaceResult,String academic_yearId,String clt_id){ this.context = context; this.teacherAttendaceResult = teacherAttendaceResult; this.layoutInflater = layoutInflater.from(this.context); this.academic_yearId = academic_yearId; this.clt_id = clt_id; layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE); dft = new DataFetchService(context); login_details = new LoginDetails(); progressDialog = Constant.getProgressDialog(context); } @Override public int getCount() { return teacherAttendaceResult.size(); } @Override public Object getItem(int position) { return teacherAttendaceResult.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder = null; View showLeaveStatus = convertView; if (showLeaveStatus == null) { holder = new ViewHolder(); showLeaveStatus = layoutInflater.inflate(R.layout.show_attendance_list_item, null); holder.tv_student_name = (TextView) showLeaveStatus.findViewById(R.id.tv_student_name); holder.tv_roll_no_value = (TextView) showLeaveStatus.findViewById(R.id.tv_roll_no_value); holder.tv_attendance_Presentvalue = (TextView) showLeaveStatus.findViewById(R.id.tv_attendance_Presentvalue); holder.tv_attendance_value = (TextView) showLeaveStatus.findViewById(R.id.tv_attendance_value); holder.ll_main = (LinearLayout) showLeaveStatus.findViewById(R.id.ll_main); holder.ll_roll_no = (LinearLayout) showLeaveStatus.findViewById(R.id.ll_roll_no); holder.ll_attendance = (LinearLayout) showLeaveStatus.findViewById(R.id.ll_attendance); holder.ll_attendance_present = (LinearLayout)showLeaveStatus.findViewById(R.id.ll_attendance_present); } else { holder = (ViewHolder) showLeaveStatus.getTag(); } showLeaveStatus.setTag(holder); // If even position then set this color or else other color if(position % 2 == 0){ holder.ll_main.setBackgroundColor(Color.parseColor("#617b81")); holder.ll_attendance.setBackgroundResource(R.color.attendance_listview_even_row); holder.ll_roll_no.setBackgroundResource(R.color.attendance_listview_even_row); holder.tv_student_name.setBackgroundResource(R.color.attendance_listview_even_row); holder.ll_attendance_present.setBackgroundResource(R.color.attendance_listview_even_row); } else{ holder.ll_main.setBackgroundColor(Color.parseColor("#617b81")); holder.ll_attendance.setBackgroundResource(R.color.attendance_listview_odd_row); holder.ll_roll_no.setBackgroundResource(R.color.attendance_listview_odd_row); holder.tv_student_name.setBackgroundResource(R.color.attendance_listview_odd_row); holder.ll_attendance_present.setBackgroundResource(R.color.attendance_listview_odd_row); } // holder.tv_attendance_value.setPaintFlags(holder.tv_attendance_value.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); holder.tv_roll_no_value.setText(teacherAttendaceResult.get(position).Roll_No); holder.tv_student_name.setText(teacherAttendaceResult.get(position).student_Name); if(teacherAttendaceResult.get(position).total.equalsIgnoreCase("0")){ holder.tv_attendance_value.setText(""); } else{ holder.tv_attendance_value.setText(teacherAttendaceResult.get(position).total); } if(teacherAttendaceResult.get(position).totalp.equalsIgnoreCase("0")){ holder.tv_attendance_Presentvalue.setText(""); } else { holder.tv_attendance_Presentvalue.setText(teacherAttendaceResult.get(position).totalp); } // atn_valid = teacherAttendaceResult.get(position).atn_valid.toString(); month_id = teacherAttendaceResult.get(position).month.toString(); final ViewHolder finalHolder = holder; holder.ll_attendance.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { hideReason = "0"; if(!(teacherAttendaceResult.get(position).total.equalsIgnoreCase(""))) { msd_id = teacherAttendaceResult.get(position).msd_id; Log.e("ATTENDACE MSD", msd_id); atn_valid = "0"; //View Attendance with reason callWebserviceToViewAttendance(msd_id, clt_id, month_id,atn_valid,academic_yearId); } } }); holder.ll_attendance_present.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { hideReason = "1"; if(!(teacherAttendaceResult.get(position).totalp.equalsIgnoreCase(""))) { msd_id = teacherAttendaceResult.get(position).msd_id; Log.e("ATTENDACE MSD", msd_id); atn_valid = "1"; //View Attendance with reason callWebserviceToViewAttendance(msd_id, clt_id, month_id,atn_valid,academic_yearId); } } }); return showLeaveStatus; } private void callWebserviceToViewAttendance(String msd_id,String clt_id,String month_id,String atn_valid,String academic_yearId) { if(dft.isInternetOn()==true) { if (!progressDialog.isShowing()) { progressDialog.show(); } } else{ progressDialog.dismiss(); } dft.getTeacherAttendanceListReason(msd_id, clt_id, month_id,atn_valid,academic_yearId, ShowAttendanceReasonMethod_name, Request.Method.POST, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { if (progressDialog.isShowing()) { progressDialog.dismiss(); } try { login_details = (LoginDetails) dft.GetResponseObject(response, LoginDetails.class); if (login_details.Status.equalsIgnoreCase("1")) { try { if (hideReason.equalsIgnoreCase("0")) { final Dialog alertDialog = new Dialog(context); // final AlertDialog alertDialog = builder.create(); // LayoutInflater inflater = context.getLayoutInflater(); LayoutInflater inflater = LayoutInflater.from(context); alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); alertDialog.getWindow().setBackgroundDrawable( new ColorDrawable(Color.TRANSPARENT)); View convertView = inflater.inflate(R.layout.absent_history, null); alertDialog.setContentView(convertView); //Image View ImageView img_close; final ListView list_absent_history = (ListView) convertView.findViewById(R.id.list_absent_history); img_close = (ImageView) convertView.findViewById(R.id.img_close); TeacherViewAttendanceAdapter teacher_attendnaceAdapter = new TeacherViewAttendanceAdapter(context, login_details.ViewStudAttendRes,hideReason); list_absent_history.setAdapter(teacher_attendnaceAdapter); alertDialog.show(); img_close.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); } }); } else if(hideReason.equalsIgnoreCase("1")){ final Dialog alertDialog = new Dialog(context); // final AlertDialog alertDialog = builder.create(); // LayoutInflater inflater = context.getLayoutInflater(); LayoutInflater inflater = LayoutInflater.from(context); alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); alertDialog.getWindow().setBackgroundDrawable( new ColorDrawable(Color.TRANSPARENT)); View convertView = inflater.inflate(R.layout.present_history, null); alertDialog.setContentView(convertView); //Image View ImageView img_close; final ListView list_present_history = (ListView) convertView.findViewById(R.id.list_present_history); img_close = (ImageView) convertView.findViewById(R.id.img_close); TeacherViewAttendanceAdapter teacher_attendnaceAdapter = new TeacherViewAttendanceAdapter(context, login_details.ViewStudAttendRes,hideReason); list_present_history.setAdapter(teacher_attendnaceAdapter); alertDialog.show(); img_close.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); } }); } } catch (Exception e) { e.printStackTrace(); } } else { } } catch (Exception e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //Show error or whatever... Log.d("LoginActivity", "ERROR.._---" + error.getCause()); } }); } public static class ViewHolder { TextView tv_roll_no_value,tv_student_name,tv_attendance_value,tv_attendance_Presentvalue; LinearLayout ll_roll_no,ll_main,ll_attendance,ll_attendance_present; } }
package com.hackaton.compgenblockdocs.controller; import com.hackaton.compgenblockdocs.model.OrderServicesModel; import com.hackaton.compgenblockdocs.service.OrderServicesService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/v1/order-services") public class OrderServiceController { @Autowired private OrderServicesService service; @PostMapping @ResponseStatus(HttpStatus.CREATED) public OrderServicesModel createUser(@RequestBody OrderServicesModel orderService){ return service.createOrderService(orderService); } }
package studio.baka.originiumcraft.block; import net.minecraft.block.Block; import net.minecraft.item.ItemBlock; import studio.baka.originiumcraft.OriginiumCraft; import studio.baka.originiumcraft.item.OCItems; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import studio.baka.originiumcraft.util.OCCreativeTabs; import studio.baka.originiumcraft.util.IHasModel; import studio.baka.originiumcraft.util.ReferenceConsts; import javax.annotation.Nonnull; import java.util.Random; public class BlockOriginiumOre extends Block implements IHasModel { public BlockOriginiumOre(){ super(Material.IRON); setTranslationKey("originium_ore"); setRegistryName(ReferenceConsts.MODID,"originium_ore"); setCreativeTab(OCCreativeTabs.ArknightsDecorations); OCBlocks.BLOCKS.add(this); OCItems.ITEMS.add(new ItemBlock(this).setRegistryName("originium_ore")); this.setSoundType(SoundType.STONE); this.setHardness(5.0f); this.setResistance(15.0f); this.setHarvestLevel("pickaxe", 2); } /* Register models for the block which derived from this or just a instance of this. */ @Override public void registerModels() { OriginiumCraft.proxy.registerItemRenderer(Item.getItemFromBlock(this),0,"inventory"); } /* Drops {@see cn.alaricxu.arknights.item.Originium} when harvested. */ @Nonnull @Override public Item getItemDropped(IBlockState state, Random rand, int fortune) { return OCItems.ORIGINIUM; } /* Only drops one {@see cn.alaricxu.arknights.item.Originium} per ore. */ @Override public int quantityDropped(Random random) { return 1; } @Override public int quantityDroppedWithBonus(int fortune, Random random) { if (fortune > 0) { int bonusFactor = Math.max(random.nextInt(fortune + 2) - 1, 0); return this.quantityDropped(random) * (bonusFactor + 1); } else { return this.quantityDropped(random); } } /* Drops an amount of xp after having been harvested. */ @Override public int getExpDrop(IBlockState state, IBlockAccess world, BlockPos pos, int fortune) { Random random = world instanceof World ? ((World) world).rand : new Random(); return 3+random.nextInt(4); } @Override public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) { return new ItemStack(this); } }
package com.tencent.mm.modelappbrand; public abstract class x implements k { public abstract void Z(String str, String str2); public final String getName() { return "OnDataPush"; } }
/*package general_classes; import model.repository.UserRepository; import model.repository.UserRepositoryImpl; import view.EventView; import java.io.IOException; import java.util.Scanner; public class MainView { UserRepository userRepository2 = UserRepositoryImpl.getInstance(); public MainView() throws Exception { } public static void main(String[] args) throws Exception { MainView welcomeHit = new MainView(); welcomeHit.Run(); } public void Run() throws Exception { Scanner scanner = new Scanner(System.in); while (true) { System.out.println("Welcome!"); System.out.println("1. Sign in"); System.out.println("2. Sign up"); System.out.println("3. change password"); System.out.println("Q. Exit"); String selectedOption = scanner.nextLine(); switch (selectedOption) { case "1": userRepository2.showall(); System.out.print("Write your Email: "); String email = scanner.nextLine(); System.out.print("Write your password: "); String password = scanner.nextLine(); boolean check = userRepository2.validateuser(email, password); if (check == true) { System.out.println("yay! welcome"); System.out.println(Session.getInstance().isadmin()); event(); } else { System.out.println("Entered wrong credentials"); break; } case "2": userRepository2.showall(); System.out.print("Write your Name: "); String namenew = scanner.nextLine(); System.out.print("Write your Email: "); String emailnew = scanner.nextLine(); System.out.print("Write your password (leangh of password needs to be 8 or more): "); String passwordnew = scanner.nextLine(); System.out.println("Write your type of job by number"); System.out.println("1.campign manger,2.city headquarter manager,3.member of party,4.volunteer,5.technical support,6.telephone receptionist"); String typeofjob = scanner.nextLine(); System.out.println("Write your Telephone"); String telephone = scanner.nextLine(); // userRepository2.Enteruser(namenew, emailnew, passwordnew, typeofjob, telephone); System.out.println("new user added!!"); break; case "3": System.out.print("Write your Email: "); String emailforget = scanner.nextLine(); System.out.print("Write your new password: "); String passwordforget = scanner.nextLine(); boolean check1 = userRepository2.changepassword(emailforget, passwordforget); if (check1 == true) { userRepository2.showall(); } else { System.out.println("try again for now bye bye.."); break; } case "Q": case "q": default: System.out.println("Goodbye"); System.exit(0); } } } public static void event() throws IOException, ClassNotFoundException { EventView welcomeHit = new EventView(); welcomeHit.Eventscliimpl(); } } */
package 手撕; /** * @Author: Mr.M * @Date: 2019-04-15 14:40 * @Description: **/ import java.util.LinkedHashMap; import java.util.Map; public class LRU<K, V> extends LinkedHashMap<K, V> { private int cacheSize; public LRU(int cacheSize) { super(16, 0.75f, true); this.cacheSize = cacheSize; } @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { // System.out.println(eldest.getKey() + "=" + eldest.getValue()); return size() > cacheSize; } @Override public V get(Object key) { if (super.get(key) == null) { // return (V) (new Integer(-1)); return (V) (Integer.valueOf(-1)); } return super.get(key); } public static void main(String[] args) { LRU<Integer, Integer> cache = new LRU<>(2); cache.put(1, 1); cache.put(2, 2); // cache.get(1); // 返回 1 System.out.println(cache.get(1)); // System.out.println(cache.get(2)); cache.put(3, 3); // 该操作会使得密钥 2 作废 // cache.get(2); // 返回 -1 (未找到) System.out.println(cache.get(2)); cache.put(4, 4); // 该操作会使得密钥 1 作废 // cache.get(1); // 返回 -1 (未找到) System.out.println(cache.get(1)); // cache.get(3); // 返回 3 System.out.println(cache.get(3)); // cache.get(4); // 返回 4 System.out.println(cache.get(4)); } }
package developer.skylight.com.retrofitdemo.adapter; import android.content.Context; import android.graphics.Bitmap; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import java.util.ArrayList; import developer.skylight.com.retrofitdemo.R; import developer.skylight.com.retrofitdemo.interfaces.OnItemClick; import developer.skylight.com.retrofitdemo.model.PersonDetails; /** * Created by Akash Wangalwar on 17-01-2017. */ public class PersonListAdapter extends RecyclerView.Adapter<PersonListAdapter.PersonViewHolder> { private Context context; private ArrayList<PersonDetails> list; private final LayoutInflater inflator; private final ImageLoader mImageLoader; private final DisplayImageOptions options; private OnItemClick onitemClick; public PersonListAdapter(Context context, ArrayList<PersonDetails> list, OnItemClick onitemClick) { this.context = context; this.list = list; this.onitemClick = onitemClick; inflator = LayoutInflater.from(context); mImageLoader = ImageLoader.getInstance(); options = new DisplayImageOptions.Builder() .showImageOnFail(R.mipmap.ic_launcher) .cacheInMemory(true) .cacheOnDisk(true) .showImageOnLoading(R.mipmap.ic_launcher) .showImageForEmptyUri(R.mipmap.ic_launcher) .bitmapConfig(Bitmap.Config.RGB_565) .build(); } @Override public PersonViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = inflator.inflate(R.layout.list_row_item, parent, false); return new PersonViewHolder(view); } @Override public void onBindViewHolder(PersonViewHolder holder, int position) { final PersonDetails item = list.get(position); holder.mName.setText(item.getPeople_name()); if (item.getPeople_image() != null && !item.getPeople_image().isEmpty()) { mImageLoader.displayImage(item.getPeople_image(), holder.mPhoto, options); } else { holder.mPhoto.setImageResource(R.mipmap.ic_launcher); } holder.mPhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onitemClick.onClick(item,(ImageView)view); } }); } @Override public int getItemCount() { return list.size(); } public class PersonViewHolder extends RecyclerView.ViewHolder { private ImageView mPhoto; private TextView mName; public PersonViewHolder(View itemView) { super(itemView); mPhoto = (ImageView) itemView.findViewById(R.id.profile_image_id); mName = (TextView) itemView.findViewById(R.id.profile_name_id); } } }
package pe.gob.trabajo.repository; import pe.gob.trabajo.domain.Bancos; import org.springframework.stereotype.Repository; import org.springframework.data.jpa.repository.*; import java.util.List; /** * Spring Data JPA repository for the Bancos entity. */ @SuppressWarnings("unused") @Repository public interface BancosRepository extends JpaRepository<Bancos, Long> { @Query("select bancos from Bancos bancos where bancos.nFlgactivo = true") List<Bancos> findAll_Activos(); }
package com.rc.portal.util; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Properties; /** * Created by ws on 2015/4/9. */ public class PropertiesUtil { public static Properties readPropertiesFile( String propertiesFileName ) { return readPropertiesFile( propertiesFileName, "UTF-8" ); } public static Properties readPropertiesFile( String propertiesFileName, String charset ) { if( StringUtil.isNull( propertiesFileName ) ) { return null; } if( StringUtil.isNull( charset ) ) { charset = "utf-8"; } String filePath = PropertiesUtil.class.getResource("/").getPath().replaceAll("file:/", "") + propertiesFileName; Properties properties = new Properties(); InputStreamReader inputStream = null; try { inputStream = new InputStreamReader(new FileInputStream(filePath), charset ); properties.load(inputStream); } catch (Exception e) { e.printStackTrace(); } finally{ if(inputStream != null){ try { inputStream.close(); } catch (IOException e) { //e.printStackTrace(); } } } return properties; } public static String getPropertyValue(String propertiesFileName, String propertyName) { if (StringUtil.isNull(propertiesFileName) || StringUtil.isNull(propertyName)) { return ""; } String value = ""; try { value = (String) readPropertiesFile(propertiesFileName).get(propertyName); } catch (Exception e) { e.printStackTrace(); } return value; } public static String getPropertyValue( Properties properties, String propertyName) { if ( null == properties || StringUtil.isNull(propertyName) ) { return ""; } String value = ""; try { value = (String) properties.get(propertyName); } catch (Exception e) { e.printStackTrace(); } return value; } }
package com.tencent.mm.ipcinvoker.wx_extension; import com.tencent.mm.ipcinvoker.h.a.a; import com.tencent.mm.sdk.platformtools.x; final class e$b implements a { static final a dnj = new e$b(); private e$b() { } public final void a(int i, String str, String str2, Object... objArr) { switch (i) { case 2: x.v(str, str2, objArr); return; case 3: x.d(str, str2, objArr); return; case 4: x.i(str, str2, objArr); return; case 5: x.w(str, str2, objArr); return; case 6: x.e(str, str2, objArr); return; case 7: x.e(str, str2, objArr); return; default: return; } } }
package fr.lteconsulting; public interface Expression { double getValeur() throws CalculImpossibleException; String getDescription(); }
package com.ls.Test.packages.p4; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.concurrent.CopyOnWriteArrayList; import com.ls.Test.packages.p3.Student; class RThread implements Runnable{ @Override public void run() { // TODO Auto-generated method stub for (int i = 0; i < 20; i++) { System.out.println(Thread.currentThread().getName()+"听歌"); } } } public class Test12 { public static void main(String[] args) throws InterruptedException{ CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList(); for (int i = 0; i < 100; i++) { new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub list.add(Thread.currentThread().getName()); } },"线程1").start(); } Thread.sleep(5000); for (String string : list) { System.out.println(string); } System.out.println(list.size()); } }
package jpa.project.advide.exception; public class CUsernameSigninFailedException extends RuntimeException{ public CUsernameSigninFailedException(String msg,Throwable t){ super(msg,t); } public CUsernameSigninFailedException(String msg){ super(msg); } public CUsernameSigninFailedException(){ super(); } }
package bomberman; import java.awt.Rectangle; public class Bomb extends Sprite { public static int BOMB_SIZE=1; public static int FLAME_LEG=2; private final int BOARD_WIDTH = 390; private final int EXPLODE_RANGE = 10; public final int unitSize = PanelSwap.unitSize; static final int B_STEP = PanelSwap.B_STEP; Rectangle flameBound; Rectangle flameX; Rectangle flameY; int count = 0; int explodeTime=40; int explodeDuration = 5; boolean flameVisible = false; Flame flame; public class Flame extends Sprite{ int top = FLAME_LEG*unitSize; int bottom = FLAME_LEG*unitSize; int right = FLAME_LEG*unitSize; int left = FLAME_LEG*unitSize; public Flame(int x, int y){ super(x, y); initFlame(); for(int i=x/unitSize-1;i>=0&&i>=x/unitSize-FLAME_LEG;i--){ if(!Block.freePos(i*unitSize, y)&&!Block.freePos(i*unitSize, y+1)&&!Block.freePos(i*unitSize-1, y-1)){ left= x-(i+1)*unitSize; break; } } for(int i=x/unitSize+1;i<=PanelSwap.B_WIDTH&&i<=x/unitSize+FLAME_LEG;i++){ if(!Block.freePos(i*unitSize, y)&&!Block.freePos(i*unitSize, y+1)&&!Block.freePos(i*unitSize-1, y-1)){ right= (i-1)*unitSize-x; break; } } for(int i=y/unitSize-1;i>=0&&i>=y/unitSize-FLAME_LEG;i--){ if(!Block.freePos(x, i*unitSize)&&!Block.freePos(x+1, i*unitSize)&&!Block.freePos(x-1, i*unitSize)){ bottom= y-(i+1)*unitSize; break; } } for(int i=y/unitSize+1;i<=PanelSwap.B_HEIGHT&&i<=y/unitSize+FLAME_LEG;i++){ if(!Block.freePos(x, i*unitSize)&&!Block.freePos(x+1, i*unitSize)&&!Block.freePos(x-1, i*unitSize)){ top= (i-1)*unitSize-y; break; } } flameBound = new Rectangle((x-left)*B_STEP/unitSize, (y-bottom)*B_STEP/unitSize, (left+right+unitSize)*B_STEP/unitSize, (bottom+top+unitSize)*B_STEP/unitSize); flameX = new Rectangle((x-left)*B_STEP/unitSize, y*B_STEP/unitSize, (left+right+unitSize)*B_STEP/unitSize, B_STEP); flameY = new Rectangle(x*B_STEP/unitSize, (y-bottom)*B_STEP/unitSize, B_STEP, (bottom+top+unitSize)*B_STEP/unitSize); } public void initFlame(){ loadImage("flame.png"); } //public Rectangle getBounds() { // return new Rectangle(x, y, width, height); //} public boolean reach(int x, int y){ Rectangle target = new Rectangle(x*B_STEP/unitSize, y*B_STEP/unitSize, B_STEP, B_STEP); if(target.intersects(flameX)||target.intersects(flameY))return true; return false; } } //private final i public Bomb(int x, int y) { super(x, y); initBomb(); } private void initBomb() { loadImage("bomb.jpg"); } public void move(){ count+=1; if(count>explodeTime){ flameVisible=true; flame = new Flame(x, y); //setVisible(false); } if(count>explodeTime+explodeDuration){ flameVisible=false; setVisible(false); } } }
package MyCollections; import org.junit.Assert; import org.junit.Test; public class TestUnit2 { public static int sum(int a,int b){ return a+b; } @Test public void testSum(){ Assert.assertEquals(sum(1,2),6); } @Test public void test2(){ Assert.assertEquals(sum(1,2),3); } }
package com.b12.offer.config; import com.b12.offer.entity.Offer; public class ContentFilter { @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof Offer)) { return false; } Offer offer = (Offer) obj; return offer.getOfferId() > 0; } }
package lesson25; public class TestClass <T, K, L> { public T doSomething1(T t){ System.out.println("1"); //logic1 return t; } public K doSomething2(K k){ System.out.println("2"); //logic2 return k; } public L doSomething3(L l){ System.out.println("3"); //logic3 return l; } }
package com.beiyelin.messageportal.controller; /** * @Description: * @Author: newmann * @Date: Created in 22:58 2018-01-27 */ public class LogMessageController { }
package com.tencent.mm.plugin.appbrand.jsapi.video.danmu; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint.FontMetrics; import android.text.Layout; import android.text.Layout.Alignment; import android.text.SpannableString; import android.text.StaticLayout; import android.text.TextPaint; public final class a implements d { private static int gbJ; private static int gbK; private int Jg; private int Jq; private StaticLayout duh; private SpannableString gbL; private int gbM; private int gbN; private int gbO = -1; private int gbP; private int gbQ; private float gbR; private Context mContext; private int vD = -1; public a(Context context, SpannableString spannableString, int i, int i2) { this.mContext = context; this.gbL = spannableString; this.gbP = b.y(this.mContext, b.gbS); this.vD = i; this.gbR = 3.0f; this.gbQ = i2; TextPaint textPaint = new TextPaint(); textPaint.setAntiAlias(true); textPaint.setColor(this.vD); textPaint.setTextSize((float) this.gbP); FontMetrics fontMetrics = textPaint.getFontMetrics(); this.Jq = ((int) Math.ceil((double) (fontMetrics.descent - fontMetrics.top))) + 2; this.duh = new StaticLayout(this.gbL, textPaint, ((int) Layout.getDesiredWidth(this.gbL, 0, this.gbL.length(), textPaint)) + 1, Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); this.Jg = this.duh.getWidth(); } public final void b(Canvas canvas, boolean z) { int width = canvas.getWidth(); int height = canvas.getHeight(); if (!(width == gbJ && height == gbK)) { gbJ = width; gbK = height; } canvas.save(); canvas.translate((float) this.gbM, (float) this.gbN); this.duh.draw(canvas); canvas.restore(); if (!z) { this.gbM = (int) (((float) this.gbM) - (((float) b.akf()) * this.gbR)); } } public final void bN(int i, int i2) { this.gbM = i; this.gbN = i2; } public final float akc() { return this.gbR; } public final boolean akd() { return this.gbM < 0 && Math.abs(this.gbM) > this.Jg; } public final int getWidth() { return this.Jg; } public final int getCurrX() { return this.gbM; } public final int ake() { return this.gbQ; } public final boolean kX(int i) { if (i >= this.gbQ && i - this.gbQ <= b.gbT) { return true; } return false; } public final boolean kY(int i) { return i - this.gbQ > b.gbT; } public final boolean a(d dVar) { if (dVar.getWidth() + dVar.getCurrX() > gbJ) { return true; } if (this.gbO < 0) { this.gbO = b.y(this.mContext, 20); } if (dVar.akc() >= this.gbR) { if (dVar.akc() != this.gbR || ((float) (gbJ - (dVar.getCurrX() + dVar.getWidth()))) >= ((float) this.gbO)) { return false; } return true; } else if (((double) (((((float) (dVar.getCurrX() + dVar.getWidth())) / (dVar.akc() * ((float) b.akf()))) * this.gbR) * ((float) b.akf()))) <= ((double) gbJ) - (((double) this.gbO) * 1.5d)) { return false; } else { return true; } } }
package com.yinghai.a24divine_user.module.setting.person; import com.example.fansonlib.base.BaseModel; import com.example.fansonlib.http.HttpResponseCallback; import com.example.fansonlib.http.HttpUtils; import com.example.fansonlib.utils.SharePreferenceHelper; import com.yinghai.a24divine_user.bean.NoDataBean; import com.yinghai.a24divine_user.bean.PersonInfoBean; import com.yinghai.a24divine_user.constant.ConHttp; import com.yinghai.a24divine_user.constant.ConResultCode; import com.yinghai.a24divine_user.constant.ConstantPreference; import com.yinghai.a24divine_user.utils.ValidateAPITokenUtil; import java.util.HashMap; import java.util.Map; /** * @author Created by:fanson * Created Time: 2017/11/21 15:47 * Describe:修改个人信息M层 */ public class EditPersonModel extends BaseModel implements ContractEditPerson.IModel { private IEditCallback mCallback; private ILogoutCallback mLogoutCallback; @Override public void editPerson(String name, String birthday, int constellationId, boolean sex, String photoUrl, IEditCallback callback) { mCallback = callback; String time = String.valueOf(System.currentTimeMillis()); Map<String, Object> maps = new HashMap<>(7); maps.put("userId", SharePreferenceHelper.getInt(ConstantPreference.I_USER_ID, 0)); maps.put("nick", name); maps.put("birthday", birthday); maps.put("sex", sex); maps.put("constellation", constellationId); maps.put("apiSendTime", time); maps.put("apiToken", ValidateAPITokenUtil.ctreatTokenStringByTimeString(time)); HttpUtils.getHttpUtils().post(ConHttp.EDIT_PERSON, maps, new HttpResponseCallback<PersonInfoBean>() { @Override public void onSuccess(PersonInfoBean bean) { if (mCallback == null) { return; } switch (bean.getCode()) { case ConResultCode.SUCCESS: mCallback.onEditPersonSuccess(bean.getData()); SharePreferenceHelper.putString(ConstantPreference.S_USER_BIRTHDAY, bean.getData().getTfUser().getUBirthday()); SharePreferenceHelper.putString(ConstantPreference.S_USER_PHOTO, bean.getData().getTfUser().getUImgUrl()); SharePreferenceHelper.putString(ConstantPreference.S_USER_NAME, bean.getData().getTfUser().getUNick()); SharePreferenceHelper.putInt(ConstantPreference.I_USER_CONSTELLATION, bean.getData().getTfUser().getUConstellation()); SharePreferenceHelper.putBoolean(ConstantPreference.B_USER_SEX, bean.getData().getTfUser().isUSex()); SharePreferenceHelper.apply(); break; default: mCallback.handlerResultCode(bean.getCode()); break; } } @Override public void onFailure(String errorMsg) { if (mCallback != null) { mCallback.onEditPersonFailure(errorMsg); } } }); } @Override public void onLogout(ILogoutCallback callback) { mLogoutCallback = callback; String time = String.valueOf(System.currentTimeMillis()); Map<String, Object> maps = new HashMap<>(3); maps.put("userId", SharePreferenceHelper.getInt(ConstantPreference.I_USER_ID, 0)); maps.put("apiSendTime", time); maps.put("apiToken", ValidateAPITokenUtil.ctreatTokenStringByTimeString(time)); HttpUtils.getHttpUtils().post(ConHttp.LOGOUT, maps, new HttpResponseCallback<NoDataBean>() { @Override public void onSuccess(NoDataBean bean) { if (mLogoutCallback == null) { return; } switch (bean.getCode()) { case ConResultCode.SUCCESS: SharePreferenceHelper.clear(); mLogoutCallback.onLogoutSuccess(); break; default: mLogoutCallback.handlerResultCode(bean.getCode()); break; } } @Override public void onFailure(String errorMsg) { if (mLogoutCallback != null) { mLogoutCallback.onLogoutFailure(errorMsg); } } }); } @Override public void onDestroy() { super.onDestroy(); mCallback = null; mLogoutCallback = null; } }
package com.github.dsessn.filter; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.web.context.ContextLoader; import org.springframework.web.filter.GenericFilterBean; import com.github.dsessn.wrapper.RedisHttpServletRequestWrapper; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import java.io.IOException; /** * Redis Session 拦截器。 * * @author Linpn */ public class RedisSessionClusterFilter extends GenericFilterBean { private static RedisTemplate<String, Object> cache; private String redisTemplate; // RedisTemplate 的 bean id private String filterSuffix; // 要过滤的扩展名 @Override protected void initFilterBean() throws ServletException { try { //创建redisTemplate客户端 if (cache == null) { cache = ContextLoader.getCurrentWebApplicationContext().getBean(redisTemplate, RedisTemplate.class); } } catch (Exception e) { throw new ServletException("创建RedisTemplate出错", e); } } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest _request = (HttpServletRequest) request; String url = _request.getRequestURI(); if (filterSuffix != null && !filterSuffix.equals("") && !url.matches(filterSuffix)) { chain.doFilter(new RedisHttpServletRequestWrapper(_request, cache), response); } else { chain.doFilter(request, response); } } /** * RedisTemplate 的 bean id */ public void setRedisTemplate(String redisTemplate) { this.redisTemplate = redisTemplate; } /** * 要过滤的扩展名 */ public void setFilterSuffix(String filterSuffix) { this.filterSuffix = filterSuffix; this.filterSuffix = this.filterSuffix.replaceAll("\\s+", ""); this.filterSuffix = this.filterSuffix.replaceAll("\\.", "\\\\."); this.filterSuffix = this.filterSuffix.replaceAll("\\*", ".*"); this.filterSuffix = this.filterSuffix.replaceAll(",", "\\$|") + "$"; } }
package entities.controller; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; 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.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import entities.model.Admin; import entities.model.Produit; import entities.service.IProduitService; @Controller @RequestMapping("/produit") public class ProduitController { @Autowired private IProduitService produitService; public void setProduitService(IProduitService produitService) { this.produitService = produitService; } /** * définition et mapping accueil */ @RequestMapping(value = "/accueil", method = RequestMethod.GET) public String accueil(ModelMap model) { model.addAttribute("nomApp", "APPLICATION DE GESTION DES PRODUITS"); model.addAttribute("salutation", "Avec SPRING MVC"); return "accueil"; } /** * Afficher liste produit */ @RequestMapping(value = "/listeProduit", method = RequestMethod.GET) public String afficherProduit(ModelMap model) { List<Produit> listeProduit = produitService.getAllProduit(); model.addAttribute("produitListe", listeProduit); return "afficherListeProduit"; } /** * update d'produit */ /** * Ajout d'produit */ // Methode pour afficher le formulaire d'ajout et lui attribuer le modele @RequestMapping(value = "/affichFormAjout", method = RequestMethod.GET) public ModelAndView affichFormAjout() { return new ModelAndView("ajouterProduit", "produitForm", new Produit()); } // Methode pour soummettre le formulaire d'ajout et lui attribuer le modele @RequestMapping(value = "/soumettreFormAjout", method = RequestMethod.POST) public String soumettreFormAjout(Model model, @Valid @ModelAttribute("produitForm") Produit produit,BindingResult resultatValidation ) { if(resultatValidation.hasErrors()){ return "ajouterProduit"; } if(produit.getIdProduit()==0){ // appel de la methode ajouter du service produitService.addProduit(produit); } // else{ // /** // * appel de la méthode update du service // */ // produitService.updateProduit(produit); // } // rafraichissement de la liste List<Produit> listeProduit = produitService.getAllProduit(); model.addAttribute("produitListe", listeProduit); return "afficherListeProduit"; } /** * suppression produit */ @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET) public String deleteProduit(Model model, @PathVariable("id") long id) { Produit produit = produitService.getProduitById(id); produitService.deleteProduit(produit); /** * rafraichissement de la liste et affichage d'un message d'alerte */ List<Produit> listeProduit = produitService.getAllProduit(); model.addAttribute("produitListe", listeProduit); model.addAttribute("css", "success"); model.addAttribute("msg", "Produit is deleted!"); return "afficherListeProduit"; } }
package com.example.kaymo.resolveai; import com.orm.SugarRecord; import com.orm.dsl.Column; import com.orm.dsl.Table; @Table(name = "reclamacoes") public class Reclamacao extends SugarRecord { @Column(name = "categoria") private String categoria; @Column(name = "descricao") private String descricao; @Column(name = "curtir") int curtir; @Column(name = "naoCurtir") int naoCurtir; @Column(name = "resolvido") boolean resolvido; @Column(name = "arquivados") boolean arquivados; public boolean isArquivado() { return arquivados; } public void setArquivado(boolean arquivado) { this.arquivados = arquivado; } public Reclamacao() { } public String getUsuario() { return usuario; } public void setUsuario(String usuario) { this.usuario = usuario; } @Column(name = "usuario") String usuario; public boolean isResolvido() { return resolvido; } public void setResolvido(boolean resolvido) { this.resolvido = resolvido; } public Reclamacao(String categoria, String descricao, int curtir, int naocurtir, String usuario, boolean resolvido, boolean arquivado) { this.categoria = categoria; this.descricao = descricao; this.curtir = curtir; this.naoCurtir = naocurtir; this.usuario = usuario; this.resolvido = resolvido; this.arquivados = arquivado; } public String getCategoria() { return categoria; } public String getDescricao() { return descricao; } public int getCurtir() { return curtir; } public void setCurtir(int qtdCurtir) { this.curtir = qtdCurtir; } public int getNaoCurtir() { return naoCurtir; } public void setNaoCurtir(int qtdNaoCurtir) { this.naoCurtir = qtdNaoCurtir; } }
package cop.swing.controls.tabviewer; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Insets; import java.awt.Rectangle; import javax.swing.Icon; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.plaf.basic.BasicTabbedPaneUI; /** * TODO we have to use delegation of BasicTabbedPaneUI instead of inheritance * @author Oleg Cherednik * @since 09.11.2012 */ public final class TabViewerUI<K, T extends TabPage> extends BasicTabbedPaneUI implements JTabbedPaneUIDelegate { private final TabViewer<K, T> tabViewer; private final TabTitle tabTitle = new TabTitle(); private int hTextAlign = CENTER; // CENTER, LEFT, RIGHT, LEADING private int hIconPos = LEFT; // LEFT, RIGHT, LEADING public TabViewerUI(TabViewer<K, T> tabViewer) { super(); this.tabViewer = tabViewer; } public void setHorizontalTextAlignment(int hTextAlign) { switch (hTextAlign) { case CENTER: case LEFT: case RIGHT: case LEADING: this.hTextAlign = hTextAlign; break; default: this.hTextAlign = CENTER; break; } } public void setHorizontalIconPosition(int hIconPos) { switch (hIconPos) { case LEFT: case RIGHT: case LEADING: this.hIconPos = hIconPos; break; default: this.hIconPos = SwingConstants.LEFT; break; } } private boolean isTabEnable(int index) { return tabPane.isEnabled() && tabPane.isEnabledAt(index); } // ========== BasicTabbedPaneUI ========== @Override protected Icon getIconForTab(int tabIndex) { return tabViewer.getTabIcon(tabViewer.getKey(tabIndex)); } @Override protected int calculateMaxTabWidth(int tabPlacement) { String maxWidthName = ""; String maxWidthStatus = ""; int maxIconWidth = 0; for (int i = 0, tabCount = tabPane.getTabCount(); i < tabCount; i++) { T tab = tabViewer.getTab(i); Icon icon = tabPane.getIconAt(i); String name = tab.getName(); String status = tab.getStatus(); name = name != null ? name : ""; status = status != null ? status : ""; maxWidthName = name.length() > maxWidthName.length() ? name : maxWidthName; maxWidthStatus = status.length() > maxWidthStatus.length() ? status : maxWidthStatus; maxIconWidth = Math.max(maxIconWidth, icon != null ? icon.getIconWidth() : 0); } FontMetrics metrics = getFontMetrics(); int res = metrics.stringWidth(TabViewer.DIRTY_MARKER); res += tabInsets.left + tabInsets.right + metrics.stringWidth(maxWidthName); if (maxWidthStatus.length() != 0) res += metrics.stringWidth(maxWidthStatus) + textIconGap; if (maxIconWidth != 0) res += maxIconWidth + textIconGap; return res; } @Override protected int calculateTabWidth(int tabPlacement, int tabIndex, FontMetrics metrics) { Insets insets = getTabInsets(tabPlacement, tabIndex); int width = insets.left + insets.right + 3; Icon icon = getIconForTab(tabIndex); K key = tabViewer.getKey(tabIndex); T tab = tabViewer.<T>getTab(key); tabTitle.update(tabViewer.getTab(tabIndex)); width += tab.isDirty() ? metrics.stringWidth(TabViewer.DIRTY_MARKER) : 0; width += icon != null ? icon.getIconWidth() + textIconGap : 0; width += metrics.stringWidth(tabTitle.toString()); return width; } @Override protected void layoutLabel(int tabPlacement, FontMetrics metrics, int tabIndex, String title, Icon icon, Rectangle tabRect, Rectangle iconRect, Rectangle textRect, boolean isSelected) { super.layoutLabel(tabPlacement, metrics, tabIndex, title, icon, tabRect, iconRect, textRect, isSelected); boolean leftToRight = tabPane.getComponentOrientation().isLeftToRight(); int hIconPos = this.hIconPos == LEADING ? leftToRight ? LEFT : RIGHT : this.hIconPos; int hTextAlign = (icon != null && this.hTextAlign == CENTER) || this.hTextAlign == LEADING ? leftToRight ? LEFT : RIGHT : this.hTextAlign; iconRect.width = icon != null ? icon.getIconWidth() + textIconGap : 0; iconRect.x = hIconPos == LEFT ? tabRect.x + tabInsets.left + (iconRect.width != 0 ? textIconGap : 0) : tabRect.x + tabRect.width - (iconRect.width != 0 ? 0 : tabInsets.right) - iconRect.width; if (hTextAlign == LEFT) { textRect.x = hIconPos == LEFT ? iconRect.x + iconRect.width : tabRect.x + tabInsets.left; textRect.width = Math.min(textRect.width, hIconPos == LEFT ? iconRect.x - (iconRect.width != 0 ? textIconGap : 0) : tabRect.x + tabRect.width - tabInsets.right); } else if (hTextAlign == RIGHT) { textRect.width = Math.min(textRect.width, tabRect.width - tabInsets.left - iconRect.x - (iconRect.width != 0 ? textIconGap : 0)); if (hIconPos == LEFT) textRect.x = Math.max(iconRect.x + (iconRect.width != 0 ? textIconGap : 0), tabRect.x + tabRect.width - tabInsets.left - textRect.width); else if (hIconPos == RIGHT) textRect.x = Math.max(tabRect.x + tabInsets.left, iconRect.x - (iconRect.width != 0 ? textIconGap : 0) - textRect.width); } } @Override protected void paintText(Graphics g, int tab_placement, Font font, FontMetrics metrics, int tabIndex, String title, Rectangle textRect, boolean isSelected) { int x = textRect.x + 1; int y = textRect.y + metrics.getAscent() + 1; g.setFont(font); if (isTabEnable(tabIndex)) { tabTitle.update(tabViewer.getTab(tabIndex)); g.setColor(UIManager.getColor(isSelected ? "FullQuote.Foreground" : "TabbedPane.foreground")); g.drawString(tabTitle.name + tabTitle.separator, x, y); x += metrics.stringWidth(tabTitle.name + tabTitle.separator); if (tabTitle.status != null) { g.setColor(Color.blue); g.drawString(tabTitle.status, x, y); } } else { g.setColor(UIManager.getColor("TosTabbedPane.disabledForeground")); g.drawString(title, x, y); } } }
package AdbUtilPkg; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.Timer; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.DateAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.data.time.Millisecond; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.ui.RectangleInsets; public class AdbUtil_Graph extends JPanel { /** * */ private final int MAX_CATEGORY_NUM = 3; private static final int NOTICE_CNT = 3; public static ChartPanel thisPanel; private static final long serialVersionUID = 1L; private DataGenerator genTimer; private List<TimeSeries> tCategory = new ArrayList<TimeSeries>(); private static List<String> feedDataListAxisCPU = new ArrayList<String>(); private static int maxAge; private static XYPlot plot; private static RectangleInsets rectInset; private static XYItemRenderer renderer; private static BasicStroke stroke; private static Dimension dChartDimension; private static List<String> mNoticeCpu = new ArrayList<String>(); public AdbUtil_Graph(int max, List<String> obj) { AdbUtil_Definition layout = AdbUtil_Main_Layout.getDefinitionInstance(); int i = 0; maxAge = max; String tempStr = ""; for (i = 0; i < MAX_CATEGORY_NUM; i++) { this.tCategory.add(i, new TimeSeries(tempStr+obj.get(i).toString().trim(), Millisecond.class)); this.tCategory.get(i).setMaximumItemAge(maxAge); } tempStr = "notice"; for (i = MAX_CATEGORY_NUM; i < MAX_CATEGORY_NUM+NOTICE_CNT; i++) { this.tCategory.add(i, new TimeSeries(tempStr+(i-MAX_CATEGORY_NUM), Millisecond.class)); this.tCategory.get(i).setMaximumItemAge(maxAge); } TimeSeriesCollection dataset = new TimeSeriesCollection(); for (i = 0; i < MAX_CATEGORY_NUM+NOTICE_CNT; i++) { dataset.addSeries(this.tCategory.get(i)); } DateAxis domain = new DateAxis("Time"); NumberAxis range = new NumberAxis("CPU %"); domain.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 12)); range.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 12)); domain.setLabelFont(new Font("SansSerif", Font.PLAIN, 14)); range.setLabelFont(new Font("SansSerif", Font.PLAIN, 14)); range.setRange(0, 100); renderer = new XYLineAndShapeRenderer(true, false); for (i = 0; i < MAX_CATEGORY_NUM; i++) { renderer.setSeriesPaint(i, layout.GRAPH_COLOR[i]); } for (i = MAX_CATEGORY_NUM; i < MAX_CATEGORY_NUM+NOTICE_CNT; i++) { renderer.setSeriesPaint(i, layout.GRAPH_COLOR_IMPORTANT[i-MAX_CATEGORY_NUM]); } stroke = new BasicStroke(2f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL); renderer.setBaseStroke(stroke); for (i = 0; i < MAX_CATEGORY_NUM+NOTICE_CNT; i++) { renderer.setSeriesStroke(i, stroke); } plot = new XYPlot(dataset, domain, range, renderer); plot.setBackgroundPaint(Color.black); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); rectInset = new RectangleInsets(5.0, 5.0, 5.0, 5.0); plot.setAxisOffset(rectInset); //domain.setAutoRange(true); domain.setLowerMargin(5.0); domain.setUpperMargin(5.0); //domain.setTickLabelsVisible(true); domain.setFixedAutoRange(120000); domain.setTickMarksVisible(false); range.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); String title = "android system CPU %"; Font titleFont = new Font("SansSerif", Font.BOLD, 15); boolean createLegend = false; JFreeChart chart = new JFreeChart(title, titleFont, plot, createLegend); chart.setBackgroundPaint(Color.white); dChartDimension = new Dimension(layout.CHART_WIDTH, layout.CHART_HEIGHT); ChartPanel chartPanel = new ChartPanel(chart); thisPanel = chartPanel; setSubPanelBounds(); add(chartPanel); } private void addObservation(int i, double y) { this.tCategory.get(i).add(new Millisecond(), y); } class DataGenerator extends Timer implements ActionListener { /** * */ private static final long serialVersionUID = 1L; DataGenerator(int interval) { super(interval, null); addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { int i = 0; if (feedDataListAxisCPU.size() > 0) { for (i = 0; i < MAX_CATEGORY_NUM; i++) { String temp = feedDataListAxisCPU.get(i).toString().trim(); double dTemp = Double.parseDouble(temp); addObservation(i, dTemp); } if (mNoticeCpu != null && mNoticeCpu.size() > 0) { for (i = MAX_CATEGORY_NUM; i < MAX_CATEGORY_NUM+mNoticeCpu.size(); i++) { String temp = mNoticeCpu.get(i-MAX_CATEGORY_NUM); double dTemp = Double.parseDouble(temp); addObservation(i, dTemp); } } else { addObservation(MAX_CATEGORY_NUM, 0.00); addObservation(MAX_CATEGORY_NUM+1, 0.00); addObservation(MAX_CATEGORY_NUM+2, 0.00); } } } } public static void setSubPanelBounds() { thisPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); thisPanel.setLocation(0, 0); thisPanel.setPreferredSize(dChartDimension); } public static void setFeedData(List<String> cpu, List<String> notice) { feedDataListAxisCPU = cpu; mNoticeCpu = notice; } public void drawStart(AdbUtil_Graph comp) { if (genTimer != null && genTimer.isRunning()) { plot.setRenderer(renderer); genTimer.restart(); } else { AdbUtil_Definition layout = AdbUtil_Main_Layout.getDefinitionInstance(); thisPanel.setBounds(0, 0, layout.CHART_WIDTH, layout.CHART_HEIGHT); this.repaint(); genTimer = comp.new DataGenerator(500); genTimer.start(); } } public void drawStop() { if (genTimer != null && genTimer.isRunning()){ genTimer.stop(); } } public void drawDestroy() { drawStop(); thisPanel.removeAll(); this.removeAll(); } public static ChartPanel getChartPanel() { return thisPanel; } }