text
stringlengths
10
2.72M
package PizzaTruck; public class Pizza { public boolean Pepperoni; public boolean isFamilySize; public boolean getPepperoni() { return Pepperoni; } }
package net.praqma.jenkins.plugin.drmemory; import java.io.IOException; import java.io.PrintStream; import java.util.logging.Logger; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import hudson.Extension; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.Result; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Builder; import java.io.File; public class DrMemoryBuilder extends Builder { private static final Logger logger = Logger.getLogger(DrMemoryBuilder.class.getName()); private String executable; private String arguments; private String logPath; private boolean treatFailed; private String finalLogPath; @DataBoundConstructor public DrMemoryBuilder(String executable, String arguments, String logPath, boolean treatFailed) { this.executable = executable; this.arguments = arguments; this.logPath = logPath; this.treatFailed = treatFailed; } @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException { PrintStream out = listener.getLogger(); /* Add the action */ DrMemoryBuildAction dba = DrMemoryBuildAction.getActionForBuild(build); dba.addBuilder(this); String version = Jenkins.getInstance().getPlugin("drmemory-plugin").getWrapper().getVersion(); out.println("Dr Memory Plugin version " + version); try { finalLogPath = logPath + (logPath.endsWith(File.separator) ? "" : File.separator); finalLogPath += build.getNumber(); build.getWorkspace().act(new DrMemoryRemoteBuilder(executable, arguments, finalLogPath, listener)); return true; } catch (IOException e) { if (isTreatFailed()) { out.println("Dr. Memory command line program returned with error code. Continuing anyway."); out.println("The message was:"); out.println(e.getMessage()); build.setResult(Result.UNSTABLE); return true; } else { out.println("Unable to execute Dr. Memory: " + e.getMessage()); return false; } } } public String getExecutable() { return executable; } public String getArguments() { return arguments; } public String getLogPath() { return logPath; } public String getFinalLogPath() { return finalLogPath; } /** * @return the treatFailed */ public boolean isTreatFailed() { return treatFailed; } /** * @param treatFailed the treatFailed to set */ public void setTreatFailed(boolean treatFailed) { this.treatFailed = treatFailed; } @Extension public static class DescriptorImpl extends BuildStepDescriptor<Builder> { @Override public DrMemoryBuilder newInstance(StaplerRequest req, JSONObject data) { DrMemoryBuilder instance = req.bindJSON(DrMemoryBuilder.class, data); save(); return instance; } @Override public boolean isApplicable(Class<? extends AbstractProject> jobType) { return true; } @Override public String getDisplayName() { return "Execute with Dr. Memory"; } } }
package com.SearchHouse.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.SearchHouse.dao.HouseStatusDao; import com.SearchHouse.pojo.HouseStatus; import com.SearchHouse.service.HouseStatusService; @Service public class HouseStatusServiceImpl implements HouseStatusService { @Autowired HouseStatusDao housestatusdao; public HouseStatusDao getHousestatusdao() { return housestatusdao; } public void setHousestatusdao(HouseStatusDao housestatusdao) { this.housestatusdao = housestatusdao; } @Override public void addHouseStatus(HouseStatus housestatus) { // TODO Auto-generated method stub housestatusdao.addHouseStatus(housestatus); } @Override public void deleteHouseStatus(int houseStatusId) { // TODO Auto-generated method stub housestatusdao.deleteHouseStatus(houseStatusId); } @Override public void updateHouseStatus(HouseStatus housestatus) { // TODO Auto-generated method stub housestatusdao.updateHouseStatus(housestatus); } @Override public HouseStatus getHouseStatusById(int houseStatusId) { // TODO Auto-generated method stub return housestatusdao.getHouseStatusById(houseStatusId); } @Override public List<HouseStatus> queryAllHouseStatus() { // TODO Auto-generated method stub return housestatusdao.queryAllHouseStatus(); } }
package com.needii.dashboard.service; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.needii.dashboard.dao.OrderDetailDao; import com.needii.dashboard.model.OrderDetail; import com.needii.dashboard.model.search.BalanceDueSearchCriteria; import com.needii.dashboard.utils.Option; @Transactional @Service("orderDeailService") public class OrderDetailServiceImpl implements OrderDetailService { @Autowired private OrderDetailDao dao; @Override public List<OrderDetail> findAll(Option option) { return dao.findAll(option); } @Override public List<OrderDetail> findByOrderId(long orderId) { return dao.findByOrderId(orderId); } @Override public List<OrderDetail> findBySupplierIdAndOrderId(long supplierId, long orderid) { return null; } @Override public List<OrderDetail> findBySupplierId(long supplierId) { return null; } @Override public List<OrderDetail> findBySupplierId(long supplierId, int limit, int offset) { return null; } @Override public Long count(Option option) { return dao.count(option); } @Override public OrderDetail findOne(long id) { return dao.findOne(id); } @Override public void create(OrderDetail model) { dao.create(model); } @Override public void update(OrderDetail model) { dao.update(model); } @Override public void delete(OrderDetail model) { dao.delete(model); } @Override public List<OrderDetail> findAll(int offset, int limit) { // TODO Auto-generated method stub return dao.findAll(offset, limit); } @Override public List<OrderDetail> findAll(Date from, Date to) { // TODO Auto-generated method stub return dao.findAll(from, to); } @Override public List<OrderDetail> findByPaymentMethodIds(BalanceDueSearchCriteria searchCriteria) { // TODO Auto-generated method stub return dao.findByPaymentMethodIds(searchCriteria); } @Override public long countByPaymentMethodIds(BalanceDueSearchCriteria searchCriteria) { // TODO Auto-generated method stub return dao.countByPaymentMethodIds(searchCriteria); } }
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.unicore.samlidp.ws; import java.util.Map; import pl.edu.icm.unity.saml.idp.SamlIdpProperties; import pl.edu.icm.unity.saml.idp.ws.SAMLAssertionQueryImpl; import pl.edu.icm.unity.saml.idp.ws.SamlSoapEndpoint; import pl.edu.icm.unity.saml.metadata.cfg.MetaDownloadManager; import pl.edu.icm.unity.saml.metadata.cfg.RemoteMetaManager; import pl.edu.icm.unity.saml.slo.SAMLLogoutProcessorFactory; import pl.edu.icm.unity.server.api.PKIManagement; import pl.edu.icm.unity.server.api.PreferencesManagement; import pl.edu.icm.unity.server.api.internal.IdPEngine; import pl.edu.icm.unity.server.api.internal.NetworkServer; import pl.edu.icm.unity.server.api.internal.SessionManagement; import pl.edu.icm.unity.server.authn.AuthenticationProcessor; import pl.edu.icm.unity.server.registries.AttributeSyntaxFactoriesRegistry; import pl.edu.icm.unity.server.utils.ExecutorsService; import pl.edu.icm.unity.server.utils.UnityMessageSource; import pl.edu.icm.unity.server.utils.UnityServerConfiguration; import eu.unicore.samly2.webservice.SAMLAuthnInterface; import eu.unicore.samly2.webservice.SAMLQueryInterface; /** * Endpoint exposing SAML SOAP binding. This version extends the {@link SamlSoapEndpoint} * by exposing a modified implementation of the {@link SAMLAuthnInterface}. The * {@link SAMLETDAuthnImpl} is used, which also returns a bootstrap ETD assertion. * * @author K. Benedyczak */ public class SamlUnicoreSoapEndpoint extends SamlSoapEndpoint { public SamlUnicoreSoapEndpoint(UnityMessageSource msg, NetworkServer server, String servletPath, String metadataServletPath, IdPEngine idpEngine, PreferencesManagement preferencesMan, PKIManagement pkiManagement, ExecutorsService executorsService, SessionManagement sessionMan, Map<String, RemoteMetaManager> remoteMetadataManagers, MetaDownloadManager downloadManager, UnityServerConfiguration mainConfig, SAMLLogoutProcessorFactory logoutProcessorFactory, AuthenticationProcessor authnProcessor, AttributeSyntaxFactoriesRegistry attributeSyntaxFactoriesRegistry) { super(msg, server, servletPath, metadataServletPath, idpEngine, preferencesMan, pkiManagement, executorsService, sessionMan, remoteMetadataManagers, downloadManager, mainConfig, logoutProcessorFactory, authnProcessor, attributeSyntaxFactoriesRegistry); } @Override protected void configureServices() { String endpointURL = getServletUrl(servletPath); SamlIdpProperties virtualConf = (SamlIdpProperties) myMetadataManager.getVirtualConfiguration(); SAMLAssertionQueryImpl assertionQueryImpl = new SAMLAssertionQueryImpl(virtualConf, endpointURL, idpEngine, preferencesMan, attributeSyntaxFactoriesRegistry); addWebservice(SAMLQueryInterface.class, assertionQueryImpl); SAMLETDAuthnImpl authnImpl = new SAMLETDAuthnImpl(virtualConf, endpointURL, idpEngine, preferencesMan, attributeSyntaxFactoriesRegistry); addWebservice(SAMLAuthnInterface.class, authnImpl); } }
package com.worldchip.bbp.ect.receiver; import com.worldchip.bbp.ect.service.ScanService; import com.worldchip.bbp.ect.service.TimeTontrolService; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class DetectionAlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); Log.d("Wing", "action: " + action); if (action != null) { if (action.equals("com.worldchip.bbp.ect.service.TimeTontrolService")) { Log.d("Wing", "com.worldchip.bbp.ect.service.TimeTontrolService"); Intent i = new Intent(context, TimeTontrolService.class); context.startService(i); } else if(action.equals("com.worldchip.bbp.ect.service.ScanService")) { Log.d("Wing", "com.worldchip.bbp.ect.service.ScanService"); Intent i = new Intent(context, ScanService.class); context.startService(i); } } } }
/* * 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 Ficheros4; /** * * @author mati */ import java.util.*; //import java.io.*; public class AlumnoMain { public static void main(String[] args) { ArrayList<Alumno> listadato=new ArrayList<Alumno>(); //Alumno prueba=new Alumno(); //prueba.ponerDato(listadato); //prueba.llenarArchivo(listadato); if(listadato.pasarALista()!= null){ listadato.pasarALista(); for(int i=0;prueba.) System.out.println(""); } } }
package messageQueue; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import utils.RabbitMQUtil; import java.io.IOException; import java.util.Arrays; import java.util.concurrent.TimeoutException; /** * 广播模式: fanout —— 所有消费者都可以获得所有消息 */ public class RabbitMQFanoutProducer { public final static String EXCHANGE_NAME = "FANOUT"; public static void main(String[] args) throws IOException, TimeoutException { //检查服务器是否开启 RabbitMQUtil.checkServer(); //创建连接工厂 ConnectionFactory connectionFactory = new ConnectionFactory(); //设置工厂连接 connectionFactory.setHost("localhost"); //创建连接 Connection connection = connectionFactory.newConnection(); //为工厂创建通道 Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "fanout"); for (int i = 0; i < 100; i++) { String testMsg = "fanout message: " + i ; //发送消息到消息队列 channel.basicPublish(EXCHANGE_NAME, "", null, testMsg.getBytes("UTF-8")); System.out.println("发送消息: " + testMsg); } //关闭通道 channel.close(); //关闭连接 connection.close(); } }
package ec.edu.upse.util; public class Context { private final static Context instance = new Context(); private Integer idUsuarioLogeado; public static Context getInstance() { return instance; } public Integer getIdUsuarioLogeado() { return idUsuarioLogeado; } public void setIdUsuarioLogeado(Integer idUsuarioLogeado) { this.idUsuarioLogeado = idUsuarioLogeado; } }
package com.zhicai.byteera.activity.community.dynamic.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.nostra13.universalimageloader.core.ImageLoader; import com.zhicai.byteera.R; import com.zhicai.byteera.commonutil.ViewHolder; import java.util.ArrayList; import java.util.List; /** Created by lieeber on 15/8/26. */ public class SubjectActivityAdapter extends BaseAdapter { private Context mContext; private List mList; public SubjectActivityAdapter(Context mContext) { this.mContext = mContext; this.mList = new ArrayList(); } public void setData(List mList) { this.mList = mList; } @Override public int getCount() { return mList.size(); } @Override public Object getItem(int position) { return mList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(mContext).inflate(R.layout.subject_item, null); } TextView title = ViewHolder.get(convertView,R.id.title); TextView subTitle = ViewHolder.get(convertView,R.id.sub_title); ImageView ivDetail = ViewHolder.get(convertView, R.id.iv_detail); String url = "http://cdn.duitang.com/uploads/item/201301/30/20130130185116_wCzRA.thumb.600_0.jpeg"; ImageLoader.getInstance().displayImage(url,ivDetail); return convertView; } }
package com.example.myapplication; import android.app.FragmentManager; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; import android.widget.Toast; public class Frammenti extends AppCompatActivity { public String numero; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fragment); Bundle extras = getIntent().getExtras(); if(extras != null){ numero = extras.getString("numero"); } Bundle bundle = new Bundle(); bundle.putString("numero", numero); FragPreferiti frag = new FragPreferiti(); frag.setArguments(bundle); impostaPager(); } public String getNumero(){ return numero; } private void impostaPager(){ final ViewPager viewPager = findViewById(R.id.pager); final PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager()); viewPager.setAdapter(pagerAdapter); TabLayout tabLayout = findViewById(R.id.tab_layout); for (int i = 0; i < pagerAdapter.getCount(); i++) tabLayout.addTab(tabLayout.newTab().setText(pagerAdapter.getItemTabNameResourceId(i))); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } }
package entities; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor public class CoffeeOrderItem { private int id; private int coffeeTypeId; private int orderId; private int quantity; }
package application; import java.io.File; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.scene.Node; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.Stage; public class EditInfo { public static Company company = null; // The name of the current logo. This is used to add the logo name to the // Company object. public static String companyLogo = null; // This allows the logo on the page to be changed dynamically. All instances // have access to the same object, removing duplicates. public static Image logo = null; // This string is used to delete the old logo when a new logo is assigned public static String previousLogo = null; public VBox getPage(Stage stage) { VBox vbox = new VBox(); vbox.setPadding(new Insets(20, 20, 20, 20)); GridPane grid = new GridPane(); grid.setPadding(new Insets(20, 20, 20, 20)); grid.setVgap(12); grid.setHgap(10); vbox.getChildren().add(grid); grid.getColumnConstraints().add(new ColumnConstraints(150)); Label nameLabel = new Label("Enter Company Name:"); GridPane.setConstraints(nameLabel, 0, 0); TextField companyName = new TextField(); companyName.setPromptText("Name"); companyName.setPrefWidth(200); companyName.setMaxWidth(200); GridPane.setConstraints(companyName, 1, 0); Label emailLabel = new Label("Enter Company Email:"); GridPane.setConstraints(emailLabel, 0, 1); TextField companyEmail = new TextField(); companyEmail.setPromptText("company.email@email.com"); companyEmail.setPrefWidth(200); companyEmail.setMaxWidth(200); GridPane.setConstraints(companyEmail, 1, 1); Label phoneLabel = new Label("Enter Company Phone:"); GridPane.setConstraints(phoneLabel, 0, 2); TextField companyPhone = new TextField(); companyPhone.setPromptText("#"); companyPhone.setPrefWidth(200); companyPhone.setMaxWidth(200); GridPane.setConstraints(companyPhone, 1, 2); Label faxLabel = new Label("Enter Company Fax:"); GridPane.setConstraints(faxLabel, 0, 3); TextField companyFax = new TextField(); companyFax.setPromptText("#"); companyFax.setPrefWidth(200); companyFax.setMaxWidth(200); GridPane.setConstraints(companyFax, 1, 3); Label logoLabel = new Label("Attach Company Logo:"); GridPane.setConstraints(logoLabel, 0, 4); // Choose Directory for Logo FileChooser fileChooser = new FileChooser(); fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Image Files", "*.png"), new FileChooser.ExtensionFilter("Image Files", "*.jpg"), new FileChooser.ExtensionFilter("Image Files", "*.PNG"), new FileChooser.ExtensionFilter("Image Files", "*.jpeg")); HBox logoSelect = new HBox(10); GridPane.setConstraints(logoSelect, 1, 4); Label fileDir = new Label(); Button setDir = new Button("Select Image"); setDir.setOnAction(e -> { File selectedFile = fileChooser.showOpenDialog(stage); try { // Get the selected file directory String dir = selectedFile.getAbsolutePath(); fileDir.setText(dir); // Remove the last image view so the images don't overlap try { ObservableList<Node> childrens = grid.getChildren(); for (Node node : childrens) { if (node instanceof ImageView) { grid.getChildren().remove(node); break; } } } catch (Exception e1) { e1.printStackTrace(); } // Add the image to the grid logo = new Image("file:////" + dir); ImageView imgView = new ImageView(logo); // set the current image to previousLogo and then reassign current image previousLogo = companyLogo; companyLogo = selectedFile.getName(); // Resize the image if it is too big imgView.setPreserveRatio(true); if (logo.getHeight() > 128) imgView.setFitHeight(150); GridPane.setConstraints(imgView, 0, 14); grid.getChildren().add(imgView); } catch (Exception e1) { e1.printStackTrace(); } }); logoSelect.getChildren().addAll(fileDir, setDir); Label street = new Label("Street Address:"); GridPane.setConstraints(street, 0, 7); TextField companyStreet = new TextField(); companyStreet.setPromptText("Street"); companyStreet.setPrefWidth(200); companyStreet.setMaxWidth(200); GridPane.setConstraints(companyStreet, 1, 7); Label city = new Label("City:"); GridPane.setConstraints(city, 0, 8); TextField companyCity = new TextField(); companyCity.setPromptText("City"); companyCity.setPrefWidth(200); companyCity.setMaxWidth(200); GridPane.setConstraints(companyCity, 1, 8); Label state = new Label("State:"); GridPane.setConstraints(state, 0, 9); TextField companyState = new TextField(); companyState.setPromptText("State"); companyState.setPrefWidth(200); companyState.setMaxWidth(200); GridPane.setConstraints(companyState, 1, 9); Label zip = new Label("Zip Code:"); GridPane.setConstraints(zip, 0, 10); TextField companyZip = new TextField(); companyZip.setPromptText("Zip"); companyZip.setPrefWidth(200); companyZip.setMaxWidth(200); GridPane.setConstraints(companyZip, 1, 10); Label slogan = new Label("Enter Company Slogan:"); GridPane.setConstraints(slogan, 0, 13); TextField companySlogan = new TextField(); companySlogan.setPromptText("Slogan"); companySlogan.setPrefWidth(350); companySlogan.setMaxWidth(350); GridPane.setConstraints(companySlogan, 1, 13); Button save = new Button("Save"); save.setPrefWidth(60); save.setOnAction(e -> { // Create company object company = new Company(companyName.getText(), companyEmail.getText(), companyPhone.getText(), companyFax.getText(), companyLogo, companyStreet.getText(), companyCity.getText(), companyState.getText(), companyZip.getText(), companySlogan.getText()); // Make sure all fields are filled in. Alert alert = new Alert(AlertType.NONE); if (company.getName().equals("")) { alert.setContentText("Enter Company Name."); alert.setAlertType(AlertType.ERROR); alert.show(); } else if (company.getEmail().equals("")) { alert.setContentText("Enter Company Email."); alert.setAlertType(AlertType.ERROR); alert.show(); } else if (company.getPhone().equals("")) { alert.setContentText("Enter Company Phone."); alert.setAlertType(AlertType.ERROR); alert.show(); } else if (company.getFax().equals("")) { alert.setContentText("Enter Company Fax."); alert.setAlertType(AlertType.ERROR); alert.show(); } else if (company.getLogo() == null) { alert.setContentText("Attach Company Logo."); alert.setAlertType(AlertType.ERROR); alert.show(); } else if (company.getStreet().equals("")) { alert.setContentText("Enter Company Street."); alert.setAlertType(AlertType.ERROR); alert.show(); } else if (company.getCity().equals("")) { alert.setContentText("Enter Company City."); alert.setAlertType(AlertType.ERROR); alert.show(); } else if (company.getState().equals("")) { alert.setContentText("Enter Company State."); alert.setAlertType(AlertType.ERROR); alert.show(); } else if (company.getZip().equals("")) { alert.setContentText("Enter Company Zip Code."); alert.setAlertType(AlertType.ERROR); alert.show(); } else if (company.getSlogan().equals("")) { alert.setContentText("Enter Company Slogan."); alert.setAlertType(AlertType.ERROR); alert.show(); } // If all fields are filled in else { ManageData manage = new ManageData(); manage.upload(company); alert.setAlertType(AlertType.INFORMATION); alert.setContentText("Information Saved"); alert.show(); } }); GridPane.setConstraints(save, 0, 16); grid.getChildren().addAll(nameLabel, companyName, emailLabel, companyEmail, phoneLabel, companyPhone, faxLabel, companyFax, logoLabel, logoSelect, street, companyStreet, city, companyCity, state, companyState, zip, companyZip, slogan, companySlogan, save); grid.getStyleClass().add("border"); // Load previous data try { companyName.setText(company.getName()); companyEmail.setText(company.getEmail()); companyPhone.setText(company.getPhone()); companyFax.setText(company.getFax()); companyStreet.setText(company.getStreet()); companyCity.setText(company.getCity()); companyState.setText(company.getState()); companyZip.setText(company.getZip()); companySlogan.setText(company.getSlogan()); // Logo ImageView imgView = new ImageView(logo); imgView.setPreserveRatio(true); if (logo.getHeight() > 128) imgView.setFitHeight(150); GridPane.setConstraints(imgView, 0, 14); grid.getChildren().add(imgView); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return vbox; } }
package slimeknights.tconstruct.library.client.crosshair; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.lwjgl.opengl.GL11; import javax.annotation.Nonnull; @SideOnly(Side.CLIENT) public final class CrosshairRenderEvents { public static final CrosshairRenderEvents INSTANCE = new CrosshairRenderEvents(); private static final Minecraft mc = Minecraft.getMinecraft(); private CrosshairRenderEvents() {} @SubscribeEvent public void onCrosshairRender(RenderGameOverlayEvent event) { if(event.getType() != RenderGameOverlayEvent.ElementType.CROSSHAIRS) { return; } EntityPlayer entityPlayer = mc.player; ItemStack itemStack = getItemstack(entityPlayer); if(itemStack.isEmpty()) { return; } ICustomCrosshairUser customCrosshairUser = (ICustomCrosshairUser) itemStack.getItem(); ICrosshair crosshair = customCrosshairUser.getCrosshair(itemStack, entityPlayer); if(crosshair == ICrosshair.DEFAULT) { return; } float width = event.getResolution().getScaledWidth(); float height = event.getResolution().getScaledHeight(); crosshair.render(customCrosshairUser.getCrosshairState(itemStack, entityPlayer), width, height, event.getPartialTicks()); event.setCanceled(true); // restore gui texture for following draw calls mc.getTextureManager().bindTexture(Gui.ICONS); // damage cooldown indicator if(mc.gameSettings.attackIndicator == 1) { int resW = event.getResolution().getScaledWidth(); int resH = event.getResolution().getScaledHeight(); GlStateManager.enableBlend(); GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.ONE_MINUS_DST_COLOR, GlStateManager.DestFactor.ONE_MINUS_SRC_COLOR, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO); GlStateManager.enableAlpha(); float f = mc.player.getCooledAttackStrength(0.0F); if(f < 1.0F) { int i = resH / 2 - 7 + 16; int j = resW / 2 - 7; int k = (int) (f * 17.0F); mc.ingameGUI.drawTexturedModalRect(j, i, 36, 94, 16, 4); mc.ingameGUI.drawTexturedModalRect(j, i, 52, 94, k, 4); } } OpenGlHelper.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0); GlStateManager.disableBlend(); } @Nonnull private ItemStack getItemstack(EntityPlayer entityPlayer) { ItemStack itemStack = ItemStack.EMPTY; if(entityPlayer.isHandActive() && isValidItem(entityPlayer.getActiveItemStack())) { itemStack = entityPlayer.getActiveItemStack(); } if(itemStack.isEmpty() && isValidItem(entityPlayer.getHeldItemMainhand())) { itemStack = entityPlayer.getHeldItemMainhand(); } if(itemStack.isEmpty() && isValidItem(entityPlayer.getHeldItemOffhand())) { itemStack = entityPlayer.getHeldItemOffhand(); } return itemStack; } private boolean isValidItem(ItemStack itemStack) { return itemStack.getItem() instanceof ICustomCrosshairUser; } }
package xtrus.user.apps.test.comp.restful; import junit.framework.TestCase; import org.apache.commons.io.IOUtils; import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider; import org.apache.http.HttpEntity; import xtrus.user.apps.comp.restful.CustomerService; import com.esum.framework.http.HttpClientTemplate; import com.esum.framework.http.HttpResponse; import com.esum.framework.http.entity.ByteArrayDataEntity; public class JaxRsServerTest extends TestCase { public void testRESTfulServer() throws Exception { startServer(); Thread.sleep(100*1000); } public void testWS() throws Exception { startServer(); HttpClientTemplate httpClient = new HttpClientTemplate(); //GET HttpResponse response = httpClient.invokeGet("http://localhost:9000/customers/123"); System.out.println(response.getStatusString()); System.out.println(new String(response.getData())); // //PUT // byte[] data = IOUtils.toByteArray(getClass().getResourceAsStream("/rs/update_customer.xml")); // HttpEntity entity = new ByteArrayDataEntity(data, "text/xml; charset=ISO-8859-1"); // response = httpClient.invokePut("http://localhost:9000/customerservice/customers", entity); // System.out.println(response.getStatusString()); // System.out.println(new String(response.getData())); // // POST byte[] data = IOUtils.toByteArray(getClass().getResourceAsStream("/rs/add_customer.xml")); HttpEntity entity = new ByteArrayDataEntity(data, "application/xml; charset=ISO-8859-1"); response = httpClient.invokePost("http://localhost:9000/customers", entity); // response = httpClient.invokePost("http://localhost:9080/rest/TEST_REST_IF/customerservice/customers", entity); System.out.println(response.getStatusString()); System.out.println(new String(response.getData())); // Read all customers // response = httpClient.invokeGet("http://localhost:9000/customerservice/customers"); // System.out.println(response.getStatusString()); // System.out.println(new String(response.getData())); Thread.sleep(100 * 1000); } private void startServer() { // create service JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean(); sf.setResourceClasses(CustomerService.class); sf.setResourceProvider(CustomerService.class, new SingletonResourceProvider(new CustomerService())); sf.setAddress("http://localhost:9000/"); sf.create(); System.out.println("RESTful Server Started."); } }
package com.example.hyunyoungpark.myfavoriterestaurant; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class FirstPageActivity extends AppCompatActivity { public Button startButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } public void init() { startButton = (Button) findViewById(R.id.startButton); startButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent firstButton = new Intent(FirstPageActivity.this, MainActivity.class); startActivity(firstButton); } }); } }
/* * Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.jet.beam; import org.apache.beam.runners.core.construction.PTransformTranslation; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.runners.TransformHierarchy; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.View; import org.apache.beam.sdk.values.PValue; import org.apache.beam.sdk.values.TupleTag; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Map; class PrintFullGraphVisitor extends Pipeline.PipelineVisitor.Defaults { private final StringBuilder sb = new StringBuilder(); private int depth; @Override public CompositeBehavior enterCompositeTransform(TransformHierarchy.Node node) { printNode(node, " COMPOSITE"); depth++; return super.enterCompositeTransform(node); } @Override public void leaveCompositeTransform(TransformHierarchy.Node node) { --depth; sb.append("\n").append(genTabs(2 * depth)).append(depth).append(" -- END OF COMPOSITE"); super.leaveCompositeTransform(node); } @Override public void visitPrimitiveTransform(TransformHierarchy.Node node) { printNode(node, " PRIMITIVE"); } private void printNode(TransformHierarchy.Node node, String prefix) { String indent = genTabs(2 * depth); sb.append("\n\n").append(indent).append(depth).append(prefix).append(" Node: ").append(node.getFullName()) .append("@").append(Integer.toHexString(System.identityHashCode(node))); PTransform<?, ?> transform = node.getTransform(); sb.append("\n\t").append(indent).append("Transform: ").append(transform); String urn = transform != null ? PTransformTranslation.urnForTransformOrNull(transform) : null; sb.append("\n\t").append(indent).append("URN: ").append(urn); Map<TupleTag<?>, PValue> additionalInputs = Utils.getAdditionalInputs(node); if (additionalInputs != null && !additionalInputs.isEmpty()) { sb.append("\n\t\tSide inputs: "); PrintGraphVisitor.printTags(additionalInputs.keySet(), indent, sb); } sb.append("\n\t").append(indent).append("Inputs: "); Collection<PValue> mainInputs = Utils.getMainInputs(getPipeline(), node); PrintGraphVisitor.printValues(mainInputs, indent, sb); sb.append("\n\t").append(indent).append("Outputs: "); PrintGraphVisitor.printValues(node.getOutputs().values(), indent, sb); if (transform instanceof View.CreatePCollectionView) { sb.append("\n\t\tSide outputs:"); PrintGraphVisitor.printTags(Collections.singleton(Utils.getTupleTagId(((View.CreatePCollectionView) transform).getView())), "\t", sb); } } String print() { return sb.toString(); } private static String genTabs(int n) { char[] charArray = new char[n]; Arrays.fill(charArray, ' '); return new String(charArray); } }
package com.mytech.tkpost.entities; import java.io.Serializable; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.JoinColumns; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; @Entity public class User implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) Long id; String firstName; String secondeName; String email; String password; @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.MERGE) @JoinTable( name="role_user", joinColumns= @JoinColumn(name="id_user"), inverseJoinColumns = @JoinColumn(name="id_role") ) Set<UserRole> roles = new HashSet<UserRole>(); @ManyToMany(mappedBy = "users") Set<Post> posts = new HashSet<Post>(); public User() { } public User(String firstName, String secondeName, String email, String password) { super(); this.firstName = firstName; this.secondeName = secondeName; this.email = email; this.password= password; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getSecondeName() { return secondeName; } public void setSecondeName(String secondeName) { this.secondeName = secondeName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Set<Post> getPosts() { return posts; } // public void setPost(Post post) { // this.posts.add(post); // } // public Set<UserRole> getRoles() { return roles; } public void setRoles(UserRole role) { this.roles.add(role); } }
package com.fsck.k9.mail; import java.security.Principal; /** * This exception is thrown when, during an SSL handshake, a client certificate * is requested and user didn't provide one * * @author Konrad Gadzinowski * */ public class ClientCertificateRequiredException extends RuntimeException { public static final long serialVersionUID = -1; public ClientCertificateRequiredException(Exception e) { super("Client certificate wasn't set - it's required to authenticate", e); } }
package bean; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name="TEAM") public class Team { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="TEAM_ID") private Long id; @Column(name="TEAM_NAME") private String name; // @ManyToMany // private List<Match> matches= new ArrayList<Match>(); // // public List<Match> getMatches() { // return matches; // } // public void setMatches(List<Match> matches) { // this.matches = matches; // } // public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package web; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class sample1JDBC { public static void main(String[] args) { //DBに接続する際に使うやつ Connection conn = null; //SQL実行結果を格納するやつ ResultSet rs = null; //SQLを実行するときに使うやつ Statement st = null; try { //MYSQLのJDBCドライバを使うよって定義 Class.forName("com.mysql.jdbc.Driver"); //DBに接続する際に必要な情報を変数に格納 String url = "jdbc:mysql://localhost/ec"; String id = "root"; String pass = "password"; //DBに実際に接続する。 conn = DriverManager.getConnection(url, id, pass); // 接続に失敗した場合SQLExcelptionを投げる st = conn.createStatement(); //SQL文の実行を行っています。 //実行を結果をrsに代入している rs = st.executeQuery("SELECT * FROM product WHERE cat_id=1"); ResultSet result = statement.executeQuery(); } catch (ClassNotFoundException ex) { System.out.println("エラーが起きました。"); ex.printStackTrace(); } catch (SQLException ex) { System.out.println("データベースに接続失敗しました。"); ex.printStackTrace(); } finally { //下記行でDBの接続を解除している。 try { if (rs != null) rs.close(); if (st != null) st.close(); if (conn != null) conn.close(); } catch (Exception ex) { } } } }
package LinkedList; class Node{ int val; Node next; public Node(int val){ this.val = val; this.next = null; } } public class LinkedListPractice { Node head; public void insertNode(int val, int pos){ Node newNode = new Node(val); if(head == null){ head = newNode; return; } if(pos == 0){ newNode.next = head; head = newNode; } else { int currPos = 1; Node current = head; while(currPos < pos-1 && current.next!=null){ currPos++; current = current.next; } if(current.next == null){ current.next = newNode; } else{ Node temp = current.next; current.next = newNode; newNode.next = temp; } } } public boolean findNode(int val){ Node current = head; while(current.next!=null&&current.val!=val){ current = current.next; } if(current.val == val) return true; else return false; } public boolean deleteNode(int val){ Node current = head; Node prev = null; while(current.next!=null&&current.val!=val){ prev = current; current = current.next; } if(current.next == null){ prev.next = current.next; return true; } else{ prev.next = current.next; return true; } } public void reverseList(){ Node prev = null; Node current = head; while(current!=null){ Node temp = current.next; current.next = prev; prev = current; current =temp; } head = prev; } public void printList(){ Node current = head; while(current!=null){ System.out.println(current.val + " "); current = current.next; } } public static void main(String[] args) { // TODO Auto-generated method stub LinkedListPractice llp = new LinkedListPractice(); llp.insertNode(4, 1); llp.insertNode(3, 0); llp.insertNode(5, 2); llp.insertNode(6, 1); llp.printList(); System.out.println(); System.out.println(); llp.reverseList(); llp.printList(); System.out.println(); llp.reverseList(); llp.printList(); System.out.println(); System.out.println(llp.findNode(3)); System.out.println(llp.findNode(4)); System.out.println(llp.findNode(5)); System.out.println(llp.findNode(6)); System.out.println(llp.findNode(7)); llp.deleteNode(4); llp.printList(); System.out.println(); llp.deleteNode(6); llp.printList(); System.out.println(); llp.deleteNode(5); llp.printList(); } }
package com.pibs.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.sql.DataSource; //import org.springframework.dao.DataAccessException; //import org.springframework.jdbc.core.JdbcTemplate; //import org.springframework.jdbc.core.ResultSetExtractor; //import org.springframework.jdbc.core.RowMapper; import org.apache.log4j.Logger; import com.pibs.config.ServerContext; //import com.pibs.config.SpringContext; import com.pibs.constant.ActionConstant; import com.pibs.constant.MapConstant; import com.pibs.constant.MiscConstant; import com.pibs.dao.BuildingDao; import com.pibs.model.Building; import com.pibs.model.User; import com.pibs.util.PIBSUtils; public class BuildingDaoImpl implements BuildingDao { private final static Logger logger = Logger.getLogger(BuildingDaoImpl.class); //sample code only for this datasource //not used anymore private DataSource dataSource; public DataSource getDataSource() { return dataSource; } public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } @Override public Map<String, Object> save(HashMap<String, Object> dataMap) throws Exception{ PIBSUtils.writeLogInfo(logger, MiscConstant.LOGGING_MESSSAGE_SAVE); //DBCP JNDI Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; Map<String, Object> returnMap = new HashMap<String, Object>(); boolean status = false; Building model = (Building) dataMap.get(MapConstant.CLASS_DATA); User user = (User) dataMap.get(MapConstant.USER_SESSION_DATA); if (user!=null) { model.setCreatedBy((int) user.getId()); } model.setCreatedOn(new Timestamp(new java.util.Date().getTime())); StringBuffer qry = new StringBuffer("insert into pibs.file_building ("); qry.append("description "); qry.append(",nooffloor "); qry.append(",remarks "); qry.append(",createdby "); qry.append(",createdon "); qry.append(",version "); qry.append(",active "); qry.append(" ) "); qry.append(" values "); qry.append(" ( "); qry.append(" ? "); qry.append(" ,? "); qry.append(" ,? "); qry.append(" ,? "); qry.append(" ,? "); qry.append(" ,1 "); qry.append(" ,true "); qry.append(" ) "); StringBuffer qryLog = new StringBuffer("insert into pibs.file_building ("); qryLog.append("description "); qryLog.append(",nooffloor "); qryLog.append(",remarks "); qryLog.append(",createdby "); qryLog.append(",createdon "); qryLog.append(",version "); qryLog.append(",active "); qryLog.append(" ) "); qryLog.append(" values "); qryLog.append(" ( "); qryLog.append(model.getDescription()); qryLog.append(" ,"+model.getNoOfFloor()); qryLog.append(" ,"+model.getRemarks()); qryLog.append(" ,"+model.getCreatedBy()); qryLog.append(" ,"+model.getCreatedOn()); qryLog.append(" ,1 "); qryLog.append(" ,true "); qryLog.append(" ) "); PIBSUtils.writeLogDebug(logger, "SQL: "+qryLog.toString()); try { conn = ServerContext.getJDBCHandle(); conn.setAutoCommit(false); pstmt = conn.prepareStatement(qry.toString()); pstmt.setString(1, model.getDescription()); pstmt.setInt(2, model.getNoOfFloor()); pstmt.setString(3, model.getRemarks()); pstmt.setInt(4, model.getCreatedBy()); pstmt.setTimestamp(5, model.getCreatedOn()); int statusInt = pstmt.executeUpdate(); if (statusInt == 1) { conn.commit(); status = true; } } catch (Exception e) { conn.rollback(); e.printStackTrace(); } finally { PIBSUtils.closeObjects(rs); PIBSUtils.closeObjects(pstmt); PIBSUtils.closeObjects(conn); } returnMap.put(MapConstant.TRANSACTION_STATUS, status); // Map<String, Object> returnMap = new HashMap<String, Object>(); // // //temp codes // java.util.Date date= new java.util.Date(); // model.setCreatedBy(1); // model.setCreatedOn(new Timestamp(date.getTime())); // model.setVersion(1); // model.setActive(true); // // boolean status = false; // // try { // String qry = "insert into pibs.file_building (description,nooffloor,remarks," // + "createdby,createdon,version,active) values (?,?,?,?,?,?,?)"; // // int resultInt = SpringContext.getJDBCHandle().update(qry, model.getDescription(),model.getNoOfFloor(), model.getRemarks(), // model.getCreatedBy(),model.getCreatedOn(),model.getVersion(),model.isActive()); // // // if (resultInt==1) { // status = true; // System.out.println("Inserted into Building table successfully.."); // } // // returnMap.put(MapConstant.TRANSACTION_STATUS, status); // } catch (Exception e) { // System.out.println(e.getMessage()); // returnMap.put(MapConstant.TRANSACTION_STATUS, status); // } finally { // // } return returnMap; } @Override public Map<String, Object> update(HashMap<String, Object> dataMap) throws Exception{ // TODO Auto-generated method stub PIBSUtils.writeLogInfo(logger, MiscConstant.LOGGING_MESSSAGE_UPDATE); //DBCP JNDI Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; Map<String, Object> returnMap = new HashMap<String, Object>(); boolean status = false; Building model = (Building) dataMap.get(MapConstant.CLASS_DATA); User user = (User) dataMap.get(MapConstant.USER_SESSION_DATA); if (user!=null) { model.setModifiedBy((int) user.getId()); } model.setModifiedOn(new Timestamp(new java.util.Date().getTime())); StringBuffer qry = new StringBuffer("update pibs.file_building set "); qry.append(" description=? "); qry.append(" ,nooffloor=? "); qry.append(" ,remarks=? "); qry.append(" ,modifiedby=? "); qry.append(" ,modifiedon=? "); qry.append(" ,version=(version+1) "); qry.append(" where "); qry.append(" id = ? "); StringBuffer qryLog = new StringBuffer("update pibs.file_building set "); qryLog.append(" description="+model.getDescription()); qryLog.append(" ,nooffloor="+model.getNoOfFloor()); qryLog.append(" ,remarks="+model.getRemarks()); qryLog.append(" ,modifiedby="+model.getModifiedBy()); qryLog.append(" ,modifiedon="+model.getModifiedOn()); qryLog.append(" ,version=(version+1) "); qryLog.append(" where "); qryLog.append(" id = "+model.getId()); PIBSUtils.writeLogDebug(logger, "SQL: "+qryLog.toString()); try { conn = ServerContext.getJDBCHandle(); conn.setAutoCommit(false); pstmt = conn.prepareStatement(qry.toString()); pstmt.setString(1, model.getDescription()); pstmt.setInt(2, model.getNoOfFloor()); pstmt.setString(3, model.getRemarks()); pstmt.setInt(4, model.getModifiedBy()); pstmt.setTimestamp(5, model.getModifiedOn()); pstmt.setLong(6, model.getId()); int statusInt = pstmt.executeUpdate(); if (statusInt == 1) { conn.commit(); status = true; } } catch (Exception e) { conn.rollback(); e.printStackTrace(); } finally { PIBSUtils.closeObjects(rs); PIBSUtils.closeObjects(pstmt); PIBSUtils.closeObjects(conn); } returnMap.put(MapConstant.TRANSACTION_STATUS, status); // //temp codes // java.util.Date date= new java.util.Date(); // model.setModifiedBy(1); // model.setModifiedOn(new Timestamp(date.getTime())); // // boolean status = false; // // try { // String qry = "update pibs.file_building set description=?,nooffloor=?,remarks=?," // + "modifiedby=?,modifiedon=?,version=(version+1) where id = ?"; // // JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); // //// jdbcTemplate.update(qry, new Object[] { model.getDescription(),model.getNoOfFloor(), model.getRemarks(), //// model.getModifiedBy(),model.getModifiedOn(),model.getId()}); // // int resultInt = jdbcTemplate.update(qry, model.getDescription(),model.getNoOfFloor(), model.getRemarks(), // model.getModifiedBy(),model.getModifiedOn(),model.getId()); // // if (resultInt == 1) { // status = true; // System.out.println("Updated Building (id: " +model.getId()+") successfully.."); // } // // returnMap.put(MapConstant.TRANSACTION_STATUS, status); // } catch (Exception e) { // System.out.println(e.getMessage()); // returnMap.put(MapConstant.TRANSACTION_STATUS, status); // } finally { // // } return returnMap; } @Override public Map<String, Object> delete(HashMap<String, Object> dataMap) throws Exception{ // TODO Auto-generated method stub PIBSUtils.writeLogInfo(logger, MiscConstant.LOGGING_MESSSAGE_DELETE); //DBCP JNDI Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; Map<String, Object> returnMap = new HashMap<String, Object>(); boolean status = false; Building model = (Building) dataMap.get(MapConstant.CLASS_DATA); User user = (User) dataMap.get(MapConstant.USER_SESSION_DATA); if (user!=null) { model.setModifiedBy((int) user.getId()); } model.setModifiedOn(new Timestamp(new java.util.Date().getTime())); StringBuffer qry = new StringBuffer("update pibs.file_building set "); qry.append(" active=false "); qry.append(" ,modifiedby=? "); qry.append(" ,modifiedon=? "); qry.append(" ,version=(version+1) "); qry.append(" where "); qry.append(" id = ? "); StringBuffer qryLog = new StringBuffer("update pibs.file_building set "); qryLog.append(" active=false "); qryLog.append(" ,modifiedby="+model.getModifiedBy()); qryLog.append(" ,modifiedon="+model.getModifiedOn()); qryLog.append(" ,version=(version+1) "); qryLog.append(" where "); qryLog.append(" id = "+model.getId()); PIBSUtils.writeLogDebug(logger, "SQL: "+qryLog.toString()); try { conn = ServerContext.getJDBCHandle(); conn.setAutoCommit(false); pstmt = conn.prepareStatement(qry.toString()); pstmt.setInt(1, model.getModifiedBy()); pstmt.setTimestamp(2, model.getModifiedOn()); pstmt.setLong(3, model.getId()); int statusInt = pstmt.executeUpdate(); if (statusInt == 1) { conn.commit(); status = true; } } catch (Exception e) { conn.rollback(); e.printStackTrace(); } finally { PIBSUtils.closeObjects(rs); PIBSUtils.closeObjects(pstmt); PIBSUtils.closeObjects(conn); } returnMap.put(MapConstant.TRANSACTION_STATUS, status); // Map<String, Object> returnMap = new HashMap<String, Object>(); // // //temp codes // java.util.Date date= new java.util.Date(); // model.setModifiedBy(1); // model.setModifiedOn(new Timestamp(date.getTime())); // // boolean status = false; // // try { // String qry = "update pibs.file_building set active=false,modifiedby=?,modifiedon=?,version=(version+1) where id = ?"; // // JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); // // int resultInt = jdbcTemplate.update(qry, model.getModifiedBy(),model.getModifiedOn(),model.getId()); // // if (resultInt == 1) { // status = true; // System.out.println("Deleted Building (id: " +model.getId()+") successfully.."); // } // // returnMap.put(MapConstant.TRANSACTION_STATUS, status); // } catch (Exception e) { // System.out.println(e.getMessage()); // returnMap.put(MapConstant.TRANSACTION_STATUS, status); // } finally { // // } return returnMap; } @Override public Map<String, Object> search(HashMap<String, Object> criteriaMap) throws Exception{ PIBSUtils.writeLogInfo(logger, MiscConstant.LOGGING_MESSSAGE_SEARCH); Map<String, Object> returnMap = null; //Connection using JNDI DBCP //get the pagination and offset int offset = (int) criteriaMap.get(MapConstant.PAGINATION_OFFSET); int limit = (int) criteriaMap.get(MapConstant.PAGINATION_LIMIT); // //get the category String category = (String) criteriaMap.get(MapConstant.ACTION); String criteria = (String) criteriaMap.get(MapConstant.SEARCH_CRITERIA); Connection conn = null; ResultSet rs = null;; PreparedStatement pstmt = null; List<Building> rsList = new ArrayList<Building>(); try { conn = ServerContext.getJDBCHandle(); StringBuffer sql = null; if (category.equals(ActionConstant.SEARCHALL)) { sql = new StringBuffer("select id,description,nooffloor,remarks,createdby,createdon,modifiedby,modifiedon,version,active "); sql.append(" from pibs.file_building "); sql.append(" where active = true "); sql.append(" order by description "); sql.append(" limit ? "); sql.append(" offset ?"); } else { sql = new StringBuffer("select id,description,nooffloor,remarks,createdby,createdon,modifiedby,modifiedon,version,active "); sql.append(" from pibs.file_building "); sql.append(" where "); sql.append(" (description ilike '%"+criteria+"%' or remarks ilike '%"+criteria+"%')" ); sql.append(" and active = true "); sql.append(" order by description "); sql.append(" limit ? "); sql.append(" offset ?"); } PIBSUtils.writeLogDebug(logger, "SQL: "+sql.toString()); pstmt = conn.prepareStatement(sql.toString()); pstmt.setInt(1, limit); pstmt.setInt(2, offset); rs = pstmt.executeQuery(); while(rs.next()) { Building model=new Building(); model.setId(rs.getInt(1)); model.setDescription(rs.getString(2)); model.setNoOfFloor(rs.getInt(3)); model.setRemarks(rs.getString(4)); rsList.add(model); } } catch (SQLException e) { throw e; } finally { PIBSUtils.closeObjects(rs); PIBSUtils.closeObjects(pstmt); PIBSUtils.closeObjects(conn); } //get the total of records int totalNoOfRecords = 0; StringBuffer sqlCount = null; try { conn = ServerContext.getJDBCHandle(); if (category.equals(ActionConstant.SEARCHALL)) { sqlCount = new StringBuffer("select count(*) from pibs.file_building where active = true"); }else { sqlCount = new StringBuffer("select count(*) from pibs.file_building where (description ilike '%"+criteria+"%' or remarks ilike '%"+criteria+"%') and active = true"); } PIBSUtils.writeLogDebug(logger, "SQL: "+sqlCount.toString()); pstmt = conn.prepareStatement(sqlCount.toString()); rs = pstmt.executeQuery(); if (rs.next()) { totalNoOfRecords = rs.getInt(1); } } catch (SQLException e) { throw e; } finally { PIBSUtils.closeObjects(rs); PIBSUtils.closeObjects(pstmt); PIBSUtils.closeObjects(conn); } if (rsList!=null && !rsList.isEmpty()) { returnMap = new HashMap<String, Object>(); returnMap.put(MapConstant.CLASS_LIST, rsList); returnMap.put(MapConstant.PAGINATION_TOTALRECORDS, totalNoOfRecords); } // //Using Spring JDBC // //get the pagination and offset // int offset = (int) criteriaMap.get(MapConstant.PAGINATION_OFFSET); // int limit = (int) criteriaMap.get(MapConstant.PAGINATION_LIMIT); // // //get the category // String category = (String) criteriaMap.get(MapConstant.ACTION); // String criteria = (String) criteriaMap.get(MapConstant.SEARCH_CRITERIA); // // String qry = null; // if (category.equals(ActionConstant.SEARCHALL)) { // qry = "select id,description,nooffloor,remarks,createdby,createdon,modifiedby," // + " modifiedon,version,active from pibs.file_building where active = true order by id limit " +limit+" offset "+offset; // } else { // qry = "select id,description,nooffloor,remarks,createdby,createdon,modifiedby," // + " modifiedon,version,active from pibs.file_building where (description ilike '%"+criteria+"%' or remarks ilike '%"+criteria+"%') and active = true order by id limit " +limit+" offset "+offset; // } // // JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); // // //List<Map<String,Object>> rsList = jdbcTemplate.queryForList(qry); // // List<Building> rsList = jdbcTemplate.query(qry, new RowMapper<Building>() { // public Building mapRow(ResultSet rs, int rowNumber) throws SQLException{ // Building b=new Building(); // b.setId(rs.getInt(1)); // b.setDescription(rs.getString(2)); // b.setNoOfFloor(rs.getInt(3)); // b.setRemarks(rs.getString(4)); // return b; // } // }); // // //get the total of records // int totalNoOfRecords = 0; // if (category.equals(ActionConstant.SEARCHALL)) { // totalNoOfRecords = jdbcTemplate.queryForInt("select count(*) from pibs.file_building where active = true"); // }else { // totalNoOfRecords = jdbcTemplate.queryForInt("select count(*) from pibs.file_building where (description ilike '%"+criteria+"%' or remarks ilike '%"+criteria+"%') and active = true"); // } // Map<String, Object> returnMap = null; // // if (rsList!=null && !rsList.isEmpty()) { // returnMap = new HashMap<String, Object>(); // returnMap.put(MapConstant.CLASS_LIST, rsList); // returnMap.put(MapConstant.PAGINATION_TOTALRECORDS, totalNoOfRecords); // } return returnMap; } @Override public Map<String, Object> getDataById(HashMap<String, Object> criteriaMap) throws Exception { // TODO Auto-generated method stub PIBSUtils.writeLogInfo(logger, MiscConstant.LOGGING_MESSSAGE_GETDATA_BY_ID); //get the model criteria Building model = (Building) criteriaMap.get(MapConstant.CLASS_DATA); //Connection using JNDI DBCP Connection conn = null; ResultSet rs = null;; PreparedStatement pstmt = null; Map<String, Object> returnMap = null; try { conn = ServerContext.getJDBCHandle(); StringBuffer sql = new StringBuffer(); sql.append("select id,description,nooffloor,remarks,createdby,createdon,modifiedby,modifiedon,version,active "); sql.append("from pibs.file_building "); sql.append("where id = ?"); StringBuffer sqlLog = new StringBuffer(); sqlLog.append("select id,description,nooffloor,remarks,createdby,createdon,modifiedby,modifiedon,version,active "); sqlLog.append("from pibs.file_building "); sqlLog.append("where id = "+ model.getId()); PIBSUtils.writeLogDebug(logger, "SQL: "+sqlLog.toString()); pstmt = conn.prepareStatement(sql.toString()); pstmt.setInt(1, model.getId()); rs = pstmt.executeQuery(); while(rs.next()) { model.setId(rs.getInt(1)); model.setDescription(rs.getString(2)); model.setNoOfFloor(rs.getInt(3)); model.setRemarks(rs.getString(4)); } } catch (SQLException e) { throw e; } finally { PIBSUtils.closeObjects(rs); PIBSUtils.closeObjects(pstmt); PIBSUtils.closeObjects(conn); } if (model!=null) { returnMap = new HashMap<String, Object>(); returnMap.put(MapConstant.CLASS_DATA, model); } // //Using Spring JDBC // //get the model criteria // Building model = (Building) criteriaMap.get(MapConstant.CLASS_DATA); // // StringBuffer qry = new StringBuffer(); // qry.append("select id,description,nooffloor,remarks,createdby,createdon,modifiedby,modifiedon,version,active "); // qry.append("from pibs.file_building "); // qry.append("where id = "); // qry.append(model.getId()); // // // JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); // // Building modelData = jdbcTemplate.query(qry.toString(), new ResultSetExtractor<Building>() { // public Building extractData(ResultSet rs) throws SQLException, DataAccessException { // Building b = new Building(); // if(rs.next()) { // b.setId(rs.getInt(1)); // b.setDescription(rs.getString(2)); // b.setNoOfFloor(rs.getInt(3)); // b.setRemarks(rs.getString(4)); // } // return b; // } // }); // Map<String, Object> returnMap = null; // // if (modelData!=null) { // returnMap = new HashMap<String, Object>(); // returnMap.put(MapConstant.CLASS_DATA, modelData); // } return returnMap; } @Override public Map<String, Object> getActiveData() throws Exception { // TODO Auto-generated method stub PIBSUtils.writeLogInfo(logger, MiscConstant.LOGGING_MESSSAGE_GET_ACTIVE_DATA); //Connection using JNDI DBCP Connection conn = null; ResultSet rs = null;; PreparedStatement pstmt = null; Map<String, Object> returnMap = null; List<Building> rsList = new ArrayList<Building>(); try { conn = ServerContext.getJDBCHandle(); StringBuffer sql = new StringBuffer(); sql.append("select id,description,nooffloor,remarks,createdby,createdon,modifiedby,modifiedon,version,active "); sql.append("from pibs.file_building "); sql.append("where active = true "); sql.append("order by description"); StringBuffer sqlLog = new StringBuffer(); sqlLog.append("select id,description,nooffloor,remarks,createdby,createdon,modifiedby,modifiedon,version,active "); sqlLog.append("from pibs.file_building "); sqlLog.append("where active = true "); sqlLog.append("order by description"); PIBSUtils.writeLogDebug(logger, "SQL: "+sqlLog.toString()); pstmt = conn.prepareStatement(sql.toString()); rs = pstmt.executeQuery(); while(rs.next()) { //get the model criteria Building model = new Building(); model.setId(rs.getInt(1)); model.setDescription(rs.getString(2)); model.setNoOfFloor(rs.getInt(3)); model.setRemarks(rs.getString(4)); rsList.add(model); } } catch (SQLException e) { throw e; } finally { PIBSUtils.closeObjects(rs); PIBSUtils.closeObjects(pstmt); PIBSUtils.closeObjects(conn); } if (rsList!=null && !rsList.isEmpty()) { returnMap = new HashMap<String, Object>(); returnMap.put(MapConstant.CLASS_LIST, rsList); } return returnMap; } @Override public Map<String, Object> getInActiveData(HashMap<String, Object> criteriaMap) throws Exception { // TODO Auto-generated method stub PIBSUtils.writeLogInfo(logger, MiscConstant.LOGGING_MESSSAGE_GET_INACTIVE_DATA); //get the pagination and offset int offset = (int) criteriaMap.get(MapConstant.PAGINATION_OFFSET); int limit = (int) criteriaMap.get(MapConstant.PAGINATION_LIMIT); //Connection using JNDI DBCP Connection conn = null; ResultSet rs = null;; PreparedStatement pstmt = null; Map<String, Object> returnMap = null; List<Building> rsList = new ArrayList<>(); try { conn = ServerContext.getJDBCHandle(); StringBuffer sql = new StringBuffer(); sql.append("select id,description,nooffloor,remarks,createdby,createdon,modifiedby,modifiedon,version,active "); sql.append(" from pibs.file_building "); sql.append(" where active = false "); sql.append(" order by description "); sql.append(" limit ? "); sql.append(" offset ? "); PIBSUtils.writeLogDebug(logger, "SQL: "+sql.toString()); pstmt = conn.prepareStatement(sql.toString()); pstmt.setInt(1, limit); pstmt.setInt(2, offset); rs = pstmt.executeQuery(); while(rs.next()) { //get the model criteria Building model = new Building(); model.setId(rs.getInt(1)); model.setDescription(rs.getString(2)); model.setNoOfFloor(rs.getInt(3)); model.setRemarks(rs.getString(4)); rsList.add(model); } } catch (SQLException e) { throw e; } finally { PIBSUtils.closeObjects(rs); PIBSUtils.closeObjects(pstmt); PIBSUtils.closeObjects(conn); } //get the total of records int totalNoOfRecords = 0; StringBuffer sqlCount = null; try { conn = ServerContext.getJDBCHandle(); sqlCount = new StringBuffer("select count(*) from pibs.file_building where active = false"); PIBSUtils.writeLogDebug(logger, "SQL: "+sqlCount.toString()); pstmt = conn.prepareStatement(sqlCount.toString()); rs = pstmt.executeQuery(); if (rs.next()) { totalNoOfRecords = rs.getInt(1); } } catch (SQLException e) { throw e; } finally { PIBSUtils.closeObjects(rs); PIBSUtils.closeObjects(pstmt); PIBSUtils.closeObjects(conn); } if (rsList!=null && !rsList.isEmpty()) { returnMap = new HashMap<String, Object>(); returnMap.put(MapConstant.CLASS_LIST, rsList); returnMap.put(MapConstant.PAGINATION_TOTALRECORDS, totalNoOfRecords); } return returnMap; } @Override public Map<String, Object> restore(HashMap<String, Object> dataMap) throws Exception{ // TODO Auto-generated method stub PIBSUtils.writeLogInfo(logger, MiscConstant.LOGGING_MESSSAGE_RESTORE); //DBCP JNDI Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; Map<String, Object> returnMap = new HashMap<String, Object>(); boolean status = false; Building model = (Building) dataMap.get(MapConstant.CLASS_DATA); User user = (User) dataMap.get(MapConstant.USER_SESSION_DATA); if (user!=null) { model.setModifiedBy((int) user.getId()); } model.setModifiedOn(new Timestamp(new java.util.Date().getTime())); StringBuffer qry = new StringBuffer("update pibs.file_building set "); qry.append(" active=true "); qry.append(" ,modifiedby=? "); qry.append(" ,modifiedon=? "); qry.append(" ,version=(version+1) "); qry.append(" where "); qry.append(" id = ? "); PIBSUtils.writeLogDebug(logger, "SQL: "+qry.toString()); try { conn = ServerContext.getJDBCHandle(); conn.setAutoCommit(false); pstmt = conn.prepareStatement(qry.toString()); pstmt.setInt(1, model.getModifiedBy()); pstmt.setTimestamp(2, model.getModifiedOn()); pstmt.setLong(3, model.getId()); int statusInt = pstmt.executeUpdate(); if (statusInt == 1) { conn.commit(); System.out.println("Room Category record (id: " +model.getId()+") restored successfully.."); status = true; } } catch (Exception e) { conn.rollback(); e.printStackTrace(); } finally { PIBSUtils.closeObjects(rs); PIBSUtils.closeObjects(pstmt); PIBSUtils.closeObjects(conn); } returnMap.put(MapConstant.TRANSACTION_STATUS, status); return returnMap; } }
package webuters.com.geet_uttarakhand20aprilpro.adapter; import android.app.Activity; import android.content.Intent; import android.support.v4.app.Fragment; 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.LinearLayout; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.util.List; import webuters.com.geet_uttarakhand20aprilpro.R; import webuters.com.geet_uttarakhand20aprilpro.activity.NewAlbumSongsActivity; import webuters.com.geet_uttarakhand20aprilpro.pojo.AlbumPOJO; /** * Created by sunil on 05-05-2017. */ public class AlbumRecyclerAdapter extends RecyclerView.Adapter<AlbumRecyclerAdapter.ViewHolder> { private List<AlbumPOJO> items; Activity activity; Fragment fragment; public AlbumRecyclerAdapter(Activity activity, Fragment fragment, List<AlbumPOJO> items) { this.items = items; this.activity = activity; this.fragment = fragment; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.inflate_album_adapter, parent, false); return new ViewHolder(v); } @Override public void onBindViewHolder(final ViewHolder holder, final int position) { Picasso.with(activity) .load(items.get(position).getAlbumCover()) .into(holder.iv_album); holder.tv_album.setText(items.get(position).getAlbumName()); holder.ll_album.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Intent i = new Intent(activity, AlbumeSongs.class); Intent i = new Intent(activity, NewAlbumSongsActivity.class); i.putExtra("Album_id", items.get(position).getId()); i.putExtra("SongImage123", items.get(position).getAlbumCover()); i.putExtra("album_name", items.get(position).getAlbumName()); activity.startActivity(i); } }); holder.itemView.setTag(items.get(position)); } private final String TAG = getClass().getSimpleName(); @Override public int getItemCount() { return items.size(); } public static class ViewHolder extends RecyclerView.ViewHolder { public ImageView iv_album; public TextView tv_album; public LinearLayout ll_album; public ViewHolder(View itemView) { super(itemView); ll_album = (LinearLayout) itemView.findViewById(R.id.ll_album); tv_album = (TextView) itemView.findViewById(R.id.tv_album); iv_album = (ImageView) itemView.findViewById(R.id.iv_album); } } }
package parameters; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.io.Writer; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; /** * Created by daniel on 18/11/14. */ public class TransferCollections { List<Transfer> transfers; RequestedTransfer requestedTransfer; int maxFreq; int maxTime; int maxA0; int maxA1; public TransferCollections(int maxFreq){ transfers=new LinkedList<Transfer>(); this.maxFreq=maxFreq; maxTime=-1; maxA0=-1; maxA1=-1; } public RequestedTransfer getRequestedTransfer() { return requestedTransfer; } public void setRequestedTransfer(RequestedTransfer requestedTransfer) { this.requestedTransfer = requestedTransfer; requestedTransfer.computeRectanglesSet(maxFreq); } public List<Transfer> getTransfers() { return transfers; } public int getMaxFreq() { return maxFreq; } public int getMaxTime() { return maxTime; } public int getMaxA0() { return maxA0; } public int getMaxA1() { return maxA1; } public void add_transfer(Transfer transfer){ transfer.computeRectanglesSets(maxFreq); transfers.add(transfer); if (transfer.getTime_completion()>maxTime){ maxTime=transfer.getTime_completion(); } if (transfer.getA0().size()>maxA0){ maxA0=transfer.getA0().size(); } if (transfer.getA1().size()>maxA1){ maxA1=transfer.getA1().size(); } } public void formatData(FileOutputStream file){ LinkedHashSet<Rectangle> A0s, A1s; A0s=new LinkedHashSet<Rectangle>(); A1s=new LinkedHashSet<Rectangle>(); PrintStream printStream = new PrintStream(file); printStream.print("nA="+requestedTransfer.getA().size()+";\n"); printStream.print("nA0="+maxA0+";\n"); printStream.print("nA1="+maxA1+";\n"); printStream.print("nS="+maxFreq+";\n"); printStream.print("nT="+maxTime+";\n"); printStream.print("nR="+transfers.size()+";\n"); printStream.print("mA=["); A0s.clear(); A0s.addAll(requestedTransfer.getA()); for(Rectangle rectangle:A0s){ printStream.print("["); for(int freq=0; freq<maxFreq; freq++){ if (freq!=0){ printStream.print(", "); } if (rectangle.frequencyBelongsToRectangle(freq)){ printStream.print("1"); } else { printStream.print("0"); } } printStream.print("]\n"); } printStream.print("];\n"); printStream.print("mA0=["); for(Transfer transfer: transfers){ A0s.clear(); A0s.addAll(transfer.getA0()); printStream.print("["); for(Rectangle rectangle:A0s){ System.out.println("freq size: " + rectangle.getFrequencySlices().size() + " t0=" + rectangle.getT_start() + " t1=" + rectangle.getT_end()); printStream.print("["); for(int freq=0; freq<maxFreq; freq++){ if (freq!=0){ printStream.print(", "); } if (rectangle.frequencyBelongsToRectangle(freq)){ printStream.print("1"); } else { printStream.print("0"); } } printStream.print("]\n"); } for(int extraRectangle=A0s.size();extraRectangle<maxA0;extraRectangle++){ printStream.print("["); for(int freq=0; freq<maxFreq; freq++){ if (freq!=0){ printStream.print(", "); } printStream.print("0"); } printStream.print("]\n"); } printStream.print("]\n"); System.out.println(" ------------- "); } printStream.print("];\n"); printStream.print("mA1=["); for(Transfer transfer: transfers){ A1s.clear(); A1s.addAll(transfer.getA1()); printStream.print("["); for(Rectangle rectangle:A1s){ System.out.println("freq size: "+rectangle.getFrequencySlices().size()+" t0="+rectangle.getT_start()+" t1="+rectangle.getT_end()); printStream.print("["); for(int freq=0; freq<maxFreq; freq++){ if (freq!=0){ printStream.print(", "); } if (rectangle.frequencyBelongsToRectangle(freq)){ printStream.print("1"); } else { printStream.print("0"); } } printStream.print("]\n"); } for(int extraRectangle=A1s.size();extraRectangle<maxA1;extraRectangle++){ printStream.print("["); for(int freq=0; freq<maxFreq; freq++){ if (freq!=0){ printStream.print(", "); } printStream.print("0"); } printStream.print("]\n"); } System.out.println("---------------------------"); printStream.print("]\n"); } printStream.print("];\n"); printStream.print("beta_ra0a1=["); for(Transfer transfer: transfers){ A0s.clear(); A0s.addAll(transfer.getA0()); A1s.clear(); A1s.addAll(transfer.getA1()); printStream.print("["); for(Rectangle rectangleA0:A0s){ printStream.print("["); boolean first=true; for(Rectangle rectangleA1:A1s){ if(first) { first=false; }else { printStream.print(", "); } if (transfer.computeFeasibility(rectangleA0, rectangleA1)){ printStream.print(1); } else { printStream.print(0); } } for(int extraRectangleA1=A1s.size(); extraRectangleA1<maxA1; extraRectangleA1++){ printStream.print(", 0"); } printStream.print("]\n"); } for(int extraRectangleA0=A0s.size(); extraRectangleA0<maxA0; extraRectangleA0++){ boolean first=true; printStream.print("["); for(int extraRectangleA1=0; extraRectangleA1<maxA1; extraRectangleA1++){ if(first) { first=false; }else { printStream.print(", "); } printStream.print("0"); } printStream.print("]"); } printStream.print("]\n"); } printStream.print("];\n"); printStream.print("gamma_at=["); A0s.clear(); A0s.addAll(requestedTransfer.getA()); for(Rectangle rectangle:A0s) { boolean first=true; printStream.print("["); for(int t=0; t<maxTime; t++){ if(first) { first=false; }else { printStream.print(", "); } if (rectangle.getT_start()<=t && t<rectangle.getT_end()){ printStream.print("1"); } else { printStream.print("0"); } } printStream.print("]"); } printStream.print("];\n"); printStream.print("gamma_a0t=["); for(Transfer transfer: transfers){ A0s.clear(); A0s.addAll(transfer.getA0()); printStream.print("["); for(Rectangle rectangle:A0s) { boolean first=true; printStream.print("["); for(int t=0; t<maxTime; t++){ if(first) { first=false; }else { printStream.print(", "); } if (rectangle.getT_start()<=t && t<rectangle.getT_end()){ printStream.print("1"); } else { printStream.print("0"); } } printStream.print("]"); } for(int extraRectangleA0=A0s.size(); extraRectangleA0<maxA0; extraRectangleA0++){ boolean first=true; printStream.print("["); for(int t=0; t<maxTime; t++){ if(first) { first=false; }else { printStream.print(", "); } printStream.print("0"); } printStream.print("]"); } printStream.print("]\n"); } printStream.print("];\n"); printStream.print("gamma_a1t=["); for(Transfer transfer: transfers){ A1s.clear(); A1s.addAll(transfer.getA1()); printStream.print("["); for(Rectangle rectangle:A1s) { boolean first=true; printStream.print("["); for(int t=0; t<maxTime; t++){ if(first) { first=false; }else { printStream.print(", "); } if (rectangle.getT_start()<=t && t<rectangle.getT_end()){ printStream.print("1"); } else { printStream.print("0"); } } printStream.print("]"); } for(int extraRectangleA1=A1s.size(); extraRectangleA1<maxA1; extraRectangleA1++){ boolean first=true; printStream.print("["); for(int t=0; t<maxTime; t++){ if(first) { first=false; }else { printStream.print(", "); } printStream.print("0"); } printStream.print("]"); } printStream.print("]\n"); } printStream.print("];\n"); printStream.print("omega_ar=["); for(Transfer transfer: transfers) { A0s.clear(); A0s.addAll(transfer.getA0()); printStream.print("["); boolean first = true; boolean found = false; for (Rectangle rectangle : A0s) { if (first) { first = false; } else { printStream.print(", "); } if (transfer.rectangleConformantAllocation(rectangle)) { printStream.print("1"); found = true; } else { printStream.print("0"); } } for (int extraRectangleA0 = A0s.size(); extraRectangleA0 < maxA0; extraRectangleA0++) { printStream.print(", 0"); } printStream.print("]"); } printStream.print("];"); printStream.close(); } public void printTransferCollectionsParameters(Writer writer) throws IOException { LinkedHashSet<Rectangle> A0s, A1s; A0s=new LinkedHashSet<Rectangle>(); A1s=new LinkedHashSet<Rectangle>(); writer.write("mA=["); A0s.clear(); A0s.addAll(requestedTransfer.getA()); for(Rectangle rectangle:A0s){ writer.write("["); for(int freq=0; freq<maxFreq; freq++){ if (freq!=0){ writer.write(", "); } if (rectangle.frequencyBelongsToRectangle(freq)){ writer.write("1"); } else { writer.write("0"); } } writer.write("]\n"); } writer.write("];\n"); writer.write("mA0=["); for(Transfer transfer: transfers){ A0s.clear(); A0s.addAll(transfer.getA0()); writer.write("["); for(Rectangle rectangle:A0s){ writer.write("["); for(int freq=0; freq<maxFreq; freq++){ if (freq!=0){ writer.write(", "); } if (rectangle.frequencyBelongsToRectangle(freq)){ writer.write("1"); } else { writer.write("0"); } } writer.write("]\n"); } for(int extraRectangle=A0s.size();extraRectangle<maxA0;extraRectangle++){ writer.write("["); for(int freq=0; freq<maxFreq; freq++){ if (freq!=0){ writer.write(", "); } writer.write("0"); } writer.write("]\n"); } writer.write("]\n"); } writer.write("];\n"); writer.write("mA1=["); for(Transfer transfer: transfers){ A1s.clear(); A1s.addAll(transfer.getA1()); writer.write("["); for(Rectangle rectangle:A1s){ writer.write("["); for(int freq=0; freq<maxFreq; freq++){ if (freq!=0){ writer.write(", "); } if (rectangle.frequencyBelongsToRectangle(freq)){ writer.write("1"); } else { writer.write("0"); } } writer.write("]\n"); } for(int extraRectangle=A1s.size();extraRectangle<maxA1;extraRectangle++){ writer.write("["); for(int freq=0; freq<maxFreq; freq++){ if (freq!=0){ writer.write(", "); } writer.write("0"); } writer.write("]\n"); } writer.write("]\n"); } writer.write("];\n"); writer.write("beta_ra0a1=["); for(Transfer transfer: transfers){ A0s.clear(); A0s.addAll(transfer.getA0()); A1s.clear(); A1s.addAll(transfer.getA1()); writer.write("["); for(Rectangle rectangleA0:A0s){ writer.write("["); boolean first=true; for(Rectangle rectangleA1:A1s){ if(first) { first=false; }else { writer.write(", "); } if (transfer.computeFeasibility(rectangleA0, rectangleA1)){ writer.write("1"); } else { writer.write("0"); } } for(int extraRectangleA1=A1s.size(); extraRectangleA1<maxA1; extraRectangleA1++){ writer.write(", 0"); } writer.write("]\n"); } for(int extraRectangleA0=A0s.size(); extraRectangleA0<maxA0; extraRectangleA0++){ boolean first=true; writer.write("["); for(int extraRectangleA1=0; extraRectangleA1<maxA1; extraRectangleA1++){ if(first) { first=false; }else { writer.write(", "); } writer.write("0"); } writer.write("]"); } writer.write("]\n"); } writer.write("];\n"); writer.write("gamma_at=["); A0s.clear(); A0s.addAll(requestedTransfer.getA()); for(Rectangle rectangle:A0s) { boolean first=true; writer.write("["); for(int t=0; t<maxTime; t++){ if(first) { first=false; }else { writer.write(", "); } if (rectangle.getT_start()<=t && t<rectangle.getT_end()){ writer.write("1"); } else { writer.write("0"); } } writer.write("]"); } writer.write("];\n"); writer.write("gamma_a0t=["); for(Transfer transfer: transfers){ A0s.clear(); A0s.addAll(transfer.getA0()); writer.write("["); for(Rectangle rectangle:A0s) { boolean first=true; writer.write("["); for(int t=0; t<maxTime; t++){ if(first) { first=false; }else { writer.write(", "); } if (rectangle.getT_start()<=t && t<rectangle.getT_end()){ writer.write("1"); } else { writer.write("0"); } } writer.write("]"); } for(int extraRectangleA0=A0s.size(); extraRectangleA0<maxA0; extraRectangleA0++){ boolean first=true; writer.write("["); for(int t=0; t<maxTime; t++){ if(first) { first=false; }else { writer.write(", "); } writer.write("0"); } writer.write("]"); } writer.write("]\n"); } writer.write("];\n"); writer.write("gamma_a1t=["); for(Transfer transfer: transfers){ A1s.clear(); A1s.addAll(transfer.getA1()); writer.write("["); for(Rectangle rectangle:A1s) { boolean first=true; writer.write("["); for(int t=0; t<maxTime; t++){ if(first) { first=false; }else { writer.write(", "); } if (rectangle.getT_start()<=t && t<rectangle.getT_end()){ writer.write("1"); } else { writer.write("0"); } } writer.write("]"); } for(int extraRectangleA1=A1s.size(); extraRectangleA1<maxA1; extraRectangleA1++){ boolean first=true; writer.write("["); for(int t=0; t<maxTime; t++){ if(first) { first=false; }else { writer.write(", "); } writer.write("0"); } writer.write("]"); } writer.write("]\n"); } writer.write("];\n"); writer.write("omega_ar=["); for(Transfer transfer: transfers) { A0s.clear(); A0s.addAll(transfer.getA0()); writer.write("["); boolean first = true; boolean found = false; for (Rectangle rectangle : A0s) { if (first) { first = false; } else { writer.write(", "); } if (transfer.rectangleConformantAllocation(rectangle)) { writer.write("1"); found = true; } else { writer.write("0"); } } for (int extraRectangleA0 = A0s.size(); extraRectangleA0 < maxA0; extraRectangleA0++) { writer.write(", 0"); } writer.write("]"); } writer.write("];"); } }
package DataStructures.trees; /** * Created by senthil on 25/9/16. */ public class IdenticalTrees { private boolean identicalTrees(TreeNode root1, TreeNode root2) { if (root1 == null && root2 == null) return true; else if (root1 != null && root2 != null){ return ((root1.val == root2.val) && identicalTrees(root1.left, root2.left) && identicalTrees(root1.right, root2.right)); } else return false; } public static void main(String a[]) { IdenticalTrees it = new IdenticalTrees(); TreeNode root1 = new TreeNode(4, new TreeNode(2, new TreeNode(1, null, null), new TreeNode(3, null, null)), new TreeNode(5, null, null)); TreeNode root2 = new TreeNode(4, new TreeNode(2, new TreeNode(1, null, null), new TreeNode(3, null, null)), new TreeNode(5, new TreeNode(8, null, null), null)); System.out.println(it.identicalTrees(root1, root2)); } }
package io.dcbn.backend.inferenceEngine; import com.google.common.collect.Lists; import de.fraunhofer.iosb.iad.maritime.datamodel.Vessel; import io.dcbn.backend.core.VesselCache; import io.dcbn.backend.datamodel.Outcome; import io.dcbn.backend.evidence_formula.model.EvidenceFormula; import io.dcbn.backend.evidence_formula.repository.EvidenceFormulaRepository; import io.dcbn.backend.evidence_formula.services.EvidenceFormulaEvaluator; import io.dcbn.backend.graph.*; import io.dcbn.backend.graph.repositories.GraphRepository; import io.dcbn.backend.inference.Algorithm; import io.dcbn.backend.inference.InferenceManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import java.util.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; public class InferenceManagerTest { private static final int NUM_TIME_SLICES = 5; private static final Position ZERO_POSITION = new Position(0.0, 0.0); private InferenceManager inferenceManager; private Graph graph; private Node smuggling; private Node nullSpeed; private Node inTrajectoryArea; private Node isInReportedArea; @BeforeEach public void setUp() { smuggling = new Node("smuggling", null, null, "", null, StateType.BOOLEAN, ZERO_POSITION); nullSpeed = new Node("nullSpeed", null, null, "", "nullSpeed", StateType.BOOLEAN, ZERO_POSITION); inTrajectoryArea = new Node("inTrajectoryArea", null, null, "", "inTrajectory", StateType.BOOLEAN, ZERO_POSITION); isInReportedArea = new Node("isInReportedArea", null, null, "", "inArea", StateType.BOOLEAN, ZERO_POSITION); List<Node> smugglingParentsList = Lists.reverse(Arrays.asList(isInReportedArea, inTrajectoryArea, nullSpeed)); double[][] probabilities = {{0.8, 0.2}, {0.6, 0.4}, {0.4, 0.6}, {0.4, 0.6}, {0.2, 0.8}, {0.2, 0.8}, {0.001, 0.999}, {0.001, 0.999}}; NodeDependency smuggling0Dep = new NodeDependency(smugglingParentsList, new ArrayList<>(), probabilities); NodeDependency smugglingTDep = new NodeDependency(smugglingParentsList, new ArrayList<>(), probabilities); smuggling.setTimeZeroDependency(smuggling0Dep); smuggling.setTimeTDependency(smugglingTDep); NodeDependency nS0Dep = new NodeDependency(new ArrayList<>(), new ArrayList<>(), new double[][]{{0.7, 0.3}}); NodeDependency nSTDep = new NodeDependency(new ArrayList<>(), new ArrayList<>(), new double[][]{{0.7, 0.3}}); nullSpeed.setTimeZeroDependency(nS0Dep); nullSpeed.setTimeTDependency(nSTDep); NodeDependency iTA0Dep = new NodeDependency(new ArrayList<>(), new ArrayList<>(), new double[][]{{0.8, 0.2}}); NodeDependency iTATDep = new NodeDependency(new ArrayList<>(), new ArrayList<>(), new double[][]{{0.8, 0.2}}); inTrajectoryArea.setTimeZeroDependency(iTA0Dep); inTrajectoryArea.setTimeTDependency(iTATDep); NodeDependency iIRA0Dep = new NodeDependency(new ArrayList<>(), new ArrayList<>(), new double[][]{{0.8, 0.2}}); NodeDependency iIRATDep = new NodeDependency(new ArrayList<>(), new ArrayList<>(), new double[][]{{0.8, 0.2}}); isInReportedArea.setTimeZeroDependency(iIRA0Dep); isInReportedArea.setTimeTDependency(iIRATDep); graph = new Graph(0, "testGraph", NUM_TIME_SLICES, Arrays.asList(smuggling, nullSpeed, inTrajectoryArea, isInReportedArea)); Vessel[] vessels = new Vessel[NUM_TIME_SLICES]; for (int i = 0; i < vessels.length; ++i) { vessels[i] = new Vessel("test", 0); vessels[i].setSpeed(i < 2 ? 0.0 : 3.0); vessels[i].setLongitude(1.0 * i); } VesselCache mockCache = mock(VesselCache.class); when(mockCache.getVesselsByUuid(anyString())) .thenReturn(vessels); GraphRepository mockRepository = mock(GraphRepository.class); when(mockRepository.findAll()) .thenReturn(Collections.singletonList(graph)); EvidenceFormulaEvaluator mockEvaluator = mock(EvidenceFormulaEvaluator.class); ArgumentCaptor<EvidenceFormula> evidenceFormulaCaptor = ArgumentCaptor .forClass(EvidenceFormula.class); ArgumentCaptor<Vessel> vesselCaptor = ArgumentCaptor.forClass(Vessel.class); Set<String> correlatedAois = new HashSet<>(); Set<Vessel> correlatedVessels = new HashSet<>(); when(mockEvaluator .evaluate(anyInt(), vesselCaptor.capture(), evidenceFormulaCaptor.capture())) .then(invocation -> { EvidenceFormula formula = evidenceFormulaCaptor.getValue(); Vessel vessel = vesselCaptor.getValue(); switch (formula.getName()) { case "nullSpeed": return vessel.getSpeed() <= 2; case "inArea": correlatedAois.add("AREA"); return vessel.getLongitude() <= 4 && vessel.getLongitude() >= 2; default: return false; } }); doAnswer(invocation -> { correlatedAois.clear(); correlatedVessels.clear(); return null; }).when(mockEvaluator).reset(); when(mockEvaluator.getCorrelatedAois()).thenReturn(correlatedAois); when(mockEvaluator.getCorrelatedVessels()).thenReturn(correlatedVessels); EvidenceFormulaRepository mockFormulaRepository = mock(EvidenceFormulaRepository.class); ArgumentCaptor<String> nameCaptor = ArgumentCaptor.forClass(String.class); when(mockFormulaRepository.findByName(nameCaptor.capture())).then(invocation -> Optional.of((new EvidenceFormula(nameCaptor.getValue(), null)))); when(mockFormulaRepository.existsByName(anyString())).thenReturn(true); inferenceManager = new InferenceManager(mockCache, mockRepository, mockFormulaRepository, mockEvaluator); } @Test @DisplayName("InferenceManager produces correct output graph.") void testInferenceManagerCorrectResult() { List<Outcome> outcomes = inferenceManager.calculateInference("test"); assertEquals(1, outcomes.size()); Outcome outcome = outcomes.get(0); double[][][] expectedValues = new double[][][]{ {{0.4, 0.6}, {0.4, 0.6}, {0.001, 0.999}, {0.001, 0.999}, {0.001, 0.999}}, {{1.0, 0.0}, {1.0, 0.0}, {0.0, 1.0}, {0.0, 1.0}, {0.0, 1.0}}, {{0.0, 1.0}, {0.0, 1.0}, {0.0, 1.0}, {0.0, 1.0}, {0.0, 1.0}}, {{0.0, 1.0}, {0.0, 1.0}, {1.0, 0.0}, {1.0, 0.0}, {1.0, 0.0}}, }; Graph graph = outcome.getCorrelatedNetwork(); for (int nodeIndex = 0; nodeIndex < expectedValues.length; nodeIndex++) { Node node = graph.getNodes().get(nodeIndex); assertTrue(node.isValueNode()); ValueNode valueNode = (ValueNode) node; for (int timeSlice = 0; timeSlice < NUM_TIME_SLICES; timeSlice++) { assertArrayEquals(expectedValues[nodeIndex][timeSlice], valueNode.getValue()[timeSlice], 1e-2); } } } @Test @DisplayName("InferenceManager set correlated vessels and areas of interest.") void testCorrelatedVesselsAndAreasCorrect() { List<Outcome> outcomes = inferenceManager.calculateInference("test"); Outcome outcome = outcomes.get(0); Set<String> correlatedAois = outcome.getCorrelatedAOIs(); assertEquals(1, correlatedAois.size()); assertTrue(correlatedAois.contains("AREA")); Set<Vessel> correlatedVessels = outcome.getCorrelatedVessels(); assertEquals(1, correlatedVessels.size()); Vessel vessel = correlatedVessels.iterator().next(); assertEquals("test", vessel.getUuid()); } @Test void testVirtualEvidence() { List<Node> newNodes = new ArrayList<>(); smuggling.setEvidenceFormulaName(null); nullSpeed.setEvidenceFormulaName(null); inTrajectoryArea.setEvidenceFormulaName(null); isInReportedArea.setEvidenceFormulaName(null); newNodes.add(smuggling); newNodes.add(nullSpeed); ValueNode newInTrajectoryArea = new ValueNode(inTrajectoryArea, new double[][]{{0.6, 0.4}}); newNodes.add(newInTrajectoryArea); newNodes.add(isInReportedArea); graph = new Graph(0, "testGraph", NUM_TIME_SLICES, newNodes); AmidstGraphAdapter adapter = new AmidstGraphAdapter(graph); Graph result = inferenceManager.calculateInference(adapter, null, Algorithm.IMPORTANCE_SAMPLING); result.getNodes().forEach(node -> { double[][] correctValues; switch (node.getName()) { case "smuggling": correctValues = new double[][]{{0.54, 0.46}, {0.54, 0.46}, {0.54, 0.46}, {0.54, 0.46}, {0.54, 0.46}}; break; case "nullSpeed": correctValues = new double[][]{{0.7, 0.3}, {0.7, 0.3}, {0.7, 0.3}, {0.7, 0.3}, {0.7, 0.3}}; break; case "inTrajectoryArea": correctValues = new double[][]{{0.85, 0.15}, {0.85, 0.15}, {0.85, 0.15}, {0.85, 0.15}, {0.85, 0.15}}; break; case "isInReportedArea": correctValues = new double[][]{{0.8, 0.2}, {0.8, 0.2}, {0.8, 0.2}, {0.8, 0.2}, {0.8, 0.2}}; break; default: throw new IllegalStateException("Unexpected value: " + node.getName()); } for(int i = 0; i < ((ValueNode) node).getValue().length; i++) { for( int j = 0; j < ((ValueNode) node).getValue()[i].length; j++) { assertEquals(correctValues[i][j], ((ValueNode) node).getValue()[i][j], 2e-2); } } }); } }
package com.kodilla.good.patterns.flights; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; public final class FlightsRepository { private Map<String , List<String>> dataBase; public FlightsRepository(Map<String, List<String>> dataBase) { this.dataBase = dataBase; } public boolean isFlightAvailable(FlightRequest flightRequest){ List<String> request = flightRequest.getAirports(); for(int i = 1; i < request.size(); i++){ if(!getFlightsFromCity(request.get(i - 1)).contains(request.get(i))){ return false; } } return true; } public List<String> getFlightsFromCity(String city){ if(dataBase.containsKey(city)){ return dataBase.get(city); } return new ArrayList<>(); } public List<String> getFlightsToCity(String city){ List<String> cities = new ArrayList<>(); for(Map.Entry<String, List<String>> entry : dataBase.entrySet()){ if(entry.getValue().contains(city)){ cities.add(entry.getKey()); } } return cities; } }
package com.openfarmanager.android.model.exeptions; /** * @author Vlad Namashko */ public class FileIsNotDirectoryException extends RuntimeException { public FileIsNotDirectoryException(String detailMessage) { super(detailMessage); } }
package com.codingchili.instance.model.movement; import com.codingchili.instance.context.GameContext; /** * A movement behaviour may be applied to 1..n creatures and is active * for a finite amount of time. Only one behaviour may be used at a time. * <p> * A behaviour may be cancelled by a player or a script, can be used * to move a player to a desired location (point and click) or have * players follow a creature or the reverse. It can even be used to * have NPC's flee from eachother or a player character. */ public interface MovementBehaviour { /** * @param game the game context the check is being run on. * @return true if the behaviour is still active. */ boolean active(GameContext game); /** * Performs an update on the behaviour, this will not be called * for each tick but rather a few times per second. * * @param game the game context. */ void update(GameContext game); /** * Called once when the behaviour is applied. * * @param game the game context. * @return fluent. */ default MovementBehaviour activate(GameContext game) { return this; } }
package backend; // Hit class used for the synteny computations enum SyHitType {Pseudo,Mrk,Bes}; public class SyHit { int mPos1; int mPos2; int mIdx; // index of the hit in the database table int mI; // index of the hit in the sorted list int mCtgIdx1; int mPctID; int mCloneIdx1 = 0; RF mRF = null; int mScore = 0; int mPos1_alt = 0; HitType mBT = HitType.NonGene; SyHitType mType; // parameters used during dynamic programming int mDPScore; // DP score of longest chain terminating here int mPrevI; // predecessor in longest chain int mNDots; // number of hits in longest chain // indicates that the hit has been returned in a chain in the current // iteration of the dynamic programming boolean mDPUsed = false; // indicates that the hit has been put into a block and should not // be used in any future DP iterations boolean mDPUsedFinal = false; public SyHit(int pos1, int pos2, int idx, SyHitType type, int pctid, int bt) { mPos1 = pos1; mPos2 = pos2; mIdx = idx; mType = type; mPctID = pctid; if (bt == 2) { mBT = HitType.GeneGene; } else if (bt == 1) { mBT = HitType.GeneNonGene; } } }
package plugins.fmp.capillarytrack; import java.awt.Color; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.ArrayList; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import javax.swing.SwingConstants; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import icy.gui.util.GuiUtil; import plugins.fmp.fmpSequence.SequencePlus; import plugins.fmp.fmpTools.ComboBoxColorRenderer; import plugins.fmp.fmpTools.EnumImageOp; import plugins.fmp.fmpTools.EnumThresholdType; public class DetectTab_Colors extends JPanel implements ActionListener, ChangeListener { private static final long serialVersionUID = 6652216082377109572L; private JComboBox<Color> colorPickCombo = new JComboBox<Color>(); private ComboBoxColorRenderer colorPickComboRenderer = new ComboBoxColorRenderer(colorPickCombo); private String textPickAPixel = "Pick a pixel"; private JButton pickColorButton = new JButton (textPickAPixel); private JButton deleteColorButton = new JButton ("Delete color"); private JRadioButton rbL1 = new JRadioButton ("L1"); private JRadioButton rbL2 = new JRadioButton ("L2"); public JSpinner distanceSpinner = new JSpinner (new SpinnerNumberModel(10, 0, 800, 5)); private JRadioButton rbRGB = new JRadioButton ("RGB"); private JRadioButton rbHSV = new JRadioButton ("HSV"); private JRadioButton rbH1H2H3 = new JRadioButton ("H1H2H3"); private JLabel distanceLabel = new JLabel("Distance "); private JLabel colorspaceLabel = new JLabel("Color space ", SwingConstants.RIGHT); private JButton detectColorButton = new JButton("Detect limits"); private JCheckBox detectAllColorsCheckBox = new JCheckBox ("all", true); // private JButton openFiltersButton = new JButton("Load..."); // private JButton saveFiltersButton = new JButton("Save..."); public JSpinner thresholdSpinner = new JSpinner(new SpinnerNumberModel(70, 0, 255, 5)); // private boolean thresholdOverlayON = false; public int colorthreshold = 20; public EnumImageOp colortransformop = EnumImageOp.NONE; public int colordistanceType = 0; public ArrayList <Color> colorarray = new ArrayList <Color>(); public EnumThresholdType thresholdtype = EnumThresholdType.COLORARRAY; private Capillarytrack parent0; private DetectPane parent; public void init(GridLayout capLayout, Capillarytrack parent0, DetectPane parent) { setLayout(capLayout); this.parent0 = parent0; this.parent = parent; colorPickCombo.setRenderer(colorPickComboRenderer); add( GuiUtil.besidesPanel(pickColorButton, colorPickCombo, deleteColorButton)); distanceLabel.setHorizontalAlignment(SwingConstants.RIGHT); ButtonGroup bgd = new ButtonGroup(); bgd.add(rbL1); bgd.add(rbL2); add( GuiUtil.besidesPanel(distanceLabel, rbL1, rbL2, distanceSpinner)); ButtonGroup bgcs = new ButtonGroup(); bgcs.add(rbRGB); bgcs.add(rbHSV); bgcs.add(rbH1H2H3); add( GuiUtil.besidesPanel(colorspaceLabel, rbRGB, rbHSV, rbH1H2H3)); add(GuiUtil.besidesPanel(detectColorButton, detectAllColorsCheckBox)); rbL1.setSelected(true); rbRGB.setSelected(true); rbL1.setSelected(true); rbRGB.setSelected(true); colortransformop = EnumImageOp.NONE; defineListeners(); } private void defineListeners() { deleteColorButton.addActionListener(new ActionListener () { @Override public void actionPerformed( final ActionEvent e ) { if (colorPickCombo.getItemCount() > 0 && colorPickCombo.getSelectedIndex() >= 0) colorPickCombo.removeItemAt(colorPickCombo.getSelectedIndex()); colorsUpdateThresholdOverlayParameters(); } } ); pickColorButton.addActionListener(new ActionListener () { @Override public void actionPerformed( final ActionEvent e ) { pickColor(); } } ); rbRGB.addActionListener(new ActionListener () { @Override public void actionPerformed( final ActionEvent e ) { colortransformop = EnumImageOp.NONE; colorsUpdateThresholdOverlayParameters(); } } ); rbHSV.addActionListener(new ActionListener () { @Override public void actionPerformed( final ActionEvent e ) { colortransformop = EnumImageOp.RGB_TO_HSV; colorsUpdateThresholdOverlayParameters(); } } ); rbH1H2H3.addActionListener(new ActionListener () { @Override public void actionPerformed( final ActionEvent e ) { colortransformop = EnumImageOp.RGB_TO_H1H2H3; colorsUpdateThresholdOverlayParameters(); } } ); rbL1.addActionListener(new ActionListener () { @Override public void actionPerformed( final ActionEvent e ) { colorsUpdateThresholdOverlayParameters(); } } ); rbL2.addActionListener(new ActionListener () { @Override public void actionPerformed( final ActionEvent e ) { colorsUpdateThresholdOverlayParameters(); } } ); class ItemChangeListener implements ItemListener{ @Override public void itemStateChanged(ItemEvent event) { if (event.getStateChange() == ItemEvent.SELECTED) { updateThresholdOverlayParameters(); } } } colorPickCombo.addItemListener(new ItemChangeListener()); distanceSpinner.addChangeListener(this); thresholdSpinner.addChangeListener(this); } private void updateThresholdOverlayParameters() { if (parent0.vSequence == null) return; boolean activateThreshold = true; switch (parent.tabsPane.getSelectedIndex()) { case 0: // simple filter & single threshold parent.simpletransformop = (EnumImageOp) parent.transformsComboBox.getSelectedItem(); parent.simplethreshold = Integer.parseInt(thresholdSpinner.getValue().toString()); thresholdtype = EnumThresholdType.SINGLE; break; case 1: // color array colorthreshold = Integer.parseInt(distanceSpinner.getValue().toString()); thresholdtype = EnumThresholdType.COLORARRAY; colorarray.clear(); for (int i=0; i<colorPickCombo.getItemCount(); i++) { colorarray.add(colorPickCombo.getItemAt(i)); } colordistanceType = 1; if (rbL2.isSelected()) colordistanceType = 2; break; default: activateThreshold = false; break; } colorsActivateSequenceThresholdOverlay(activateThreshold); } public void colorsUpdateThresholdOverlayParameters() { boolean activateThreshold = true; switch (parent.tabsPane.getSelectedIndex()) { case 0: // simple filter & single threshold parent.simpletransformop = (EnumImageOp) parent.transformsComboBox.getSelectedItem(); parent.simplethreshold = Integer.parseInt(thresholdSpinner.getValue().toString()); thresholdtype = EnumThresholdType.SINGLE; break; case 1: // color array colorthreshold = Integer.parseInt(distanceSpinner.getValue().toString()); thresholdtype = EnumThresholdType.COLORARRAY; colorarray.clear(); for (int i=0; i<colorPickCombo.getItemCount(); i++) { colorarray.add(colorPickCombo.getItemAt(i)); } colordistanceType = 1; if (rbL2.isSelected()) colordistanceType = 2; break; default: activateThreshold = false; break; } colorsActivateSequenceThresholdOverlay(activateThreshold); } private void colorsActivateSequenceThresholdOverlay(boolean activate) { if (parent0.kymographArrayList.size() == 0) return; for (SequencePlus kSeq: parent0.kymographArrayList) { kSeq.setThresholdOverlay(activate); if (activate) { if (thresholdtype == EnumThresholdType.SINGLE) kSeq.setThresholdOverlayParametersSingle(parent.simpletransformop, parent.simplethreshold); else kSeq.setThresholdOverlayParametersColors( colortransformop, colorarray, colordistanceType, colorthreshold); } } // thresholdOverlayON = activate; } public void enableItems(boolean enabled) { } @Override public void actionPerformed(ActionEvent e) { // Object o = e.getSource(); // if ( o == transformForLevelsComboBox) { // firePropertyChange("KYMO_DISPLAYFILTERED", false, true); // } } @Override public void stateChanged(ChangeEvent arg0) { if (( arg0.getSource() == thresholdSpinner) || (arg0.getSource() == distanceSpinner)) colorsUpdateThresholdOverlayParameters(); } private void pickColor() { boolean bActiveTrapOverlay = false; if (pickColorButton.getText().contains("*") || pickColorButton.getText().contains(":")) { pickColorButton.setBackground(Color.LIGHT_GRAY); pickColorButton.setText(textPickAPixel); bActiveTrapOverlay = false; } else { pickColorButton.setText("*"+textPickAPixel+"*"); pickColorButton.setBackground(Color.DARK_GRAY); bActiveTrapOverlay = true; } // System.out.println("activate mouse trap =" + bActiveTrapOverlay); for (SequencePlus kSeq: parent0.kymographArrayList) kSeq.setMouseTrapOverlay(bActiveTrapOverlay, pickColorButton, colorPickCombo); } }
/** */ package Metamodell.model.metamodell.impl; import Metamodell.model.metamodell.Alarm; import Metamodell.model.metamodell.MetamodellPackage; import Metamodell.model.metamodell.Task; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.EObjectImpl; import org.eclipse.emf.ecore.util.EDataTypeUniqueEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Task</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link Metamodell.model.metamodell.impl.TaskImpl#getTask_alarm <em>Task alarm</em>}</li> * <li>{@link Metamodell.model.metamodell.impl.TaskImpl#getTask_priority <em>Task priority</em>}</li> * </ul> * </p> * * @generated */ public class TaskImpl extends EObjectImpl implements Task { /** * The cached value of the '{@link #getTask_alarm() <em>Task alarm</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTask_alarm() * @generated * @ordered */ protected Alarm task_alarm; /** * The cached value of the '{@link #getTask_priority() <em>Task priority</em>}' attribute list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTask_priority() * @generated * @ordered */ protected EList task_priority; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected TaskImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected EClass eStaticClass() { return MetamodellPackage.Literals.TASK; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Alarm getTask_alarm() { return task_alarm; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetTask_alarm(Alarm newTask_alarm, NotificationChain msgs) { Alarm oldTask_alarm = task_alarm; task_alarm = newTask_alarm; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MetamodellPackage.TASK__TASK_ALARM, oldTask_alarm, newTask_alarm); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setTask_alarm(Alarm newTask_alarm) { if (newTask_alarm != task_alarm) { NotificationChain msgs = null; if (task_alarm != null) msgs = ((InternalEObject)task_alarm).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - MetamodellPackage.TASK__TASK_ALARM, null, msgs); if (newTask_alarm != null) msgs = ((InternalEObject)newTask_alarm).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - MetamodellPackage.TASK__TASK_ALARM, null, msgs); msgs = basicSetTask_alarm(newTask_alarm, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MetamodellPackage.TASK__TASK_ALARM, newTask_alarm, newTask_alarm)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList getTask_priority() { if (task_priority == null) { task_priority = new EDataTypeUniqueEList(Integer.class, this, MetamodellPackage.TASK__TASK_PRIORITY); } return task_priority; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case MetamodellPackage.TASK__TASK_ALARM: return basicSetTask_alarm(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case MetamodellPackage.TASK__TASK_ALARM: return getTask_alarm(); case MetamodellPackage.TASK__TASK_PRIORITY: return getTask_priority(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void eSet(int featureID, Object newValue) { switch (featureID) { case MetamodellPackage.TASK__TASK_ALARM: setTask_alarm((Alarm)newValue); return; case MetamodellPackage.TASK__TASK_PRIORITY: getTask_priority().clear(); getTask_priority().addAll((Collection)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void eUnset(int featureID) { switch (featureID) { case MetamodellPackage.TASK__TASK_ALARM: setTask_alarm((Alarm)null); return; case MetamodellPackage.TASK__TASK_PRIORITY: getTask_priority().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean eIsSet(int featureID) { switch (featureID) { case MetamodellPackage.TASK__TASK_ALARM: return task_alarm != null; case MetamodellPackage.TASK__TASK_PRIORITY: return task_priority != null && !task_priority.isEmpty(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (task_priority: "); result.append(task_priority); result.append(')'); return result.toString(); } } //TaskImpl
package src.usuarios; public class Usuario { private String nombre; private int puntuacion; private int partidasGanadas; private int partidasPerdidas; private int id; public Usuario(int id,String nombre,int puntuacion,int partidasGanadas,int partidasPerdidas){ this.id=id; this.nombre=nombre; this.puntuacion=puntuacion; this.partidasGanadas=partidasGanadas; this.partidasPerdidas=partidasPerdidas; } public void setNombre(String nombre){ this.nombre=nombre; } public void setPuntuacion(int puntuacion){ this.puntuacion=puntuacion; } public void setPartidasGanadas(int partidasGanadas){ this.partidasGanadas=partidasGanadas; } public void setPartidasPerdidas(int partidasPerdidas){ this.partidasPerdidas=partidasPerdidas; } public String getNombre(){ return nombre; } public int getPuntuacion(){ return puntuacion; } public int getPartidasGanadas(){ return partidasGanadas; } public int getPartidasPerdidas(){ return partidasPerdidas; } public int getId(){ return id; } public String getInformacion(){ return "Id: "+id+". Nombre: "+nombre+". Puntuacion: "+puntuacion+". Partidas Ganadas: "+partidasGanadas+". Partidas Perdidas: "+partidasPerdidas; } }
package com.it18zhang.java; import com.it18zhang.java.PackageDemo; public class PackageDemo2 { public static void main(String[] args) { System.out.println("Hello World 2 !"); PackageDemo.sayHello("Hello"); } public static void sayHi(String msg) { System.out.println(msg); } }
package sty.studyproxy; import org.junit.Test; public class AriCalculatorProxyTest { @Test public void testProxy(){ AriCalculator target = new AriCalculatorImpl(); Object obj = new AriCalculatorProxy(target).getProxy(); AriCalculator proxy = (AriCalculator) obj; int add = proxy.add(1, 2); System.out.println(add); } }
package com.sda.TicketSystem.controller; import com.sda.TicketSystem.model.SubscriptionDTO; import com.sda.TicketSystem.service.PriceService; import com.sda.TicketSystem.service.SecurityService; import com.sda.TicketSystem.service.SubscriptionService; import com.sda.TicketSystem.service.UserService; import com.sda.TicketSystem.validator.UserValidator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import java.util.List; @Controller @RequestMapping(value = "/private") public class SubscriptionController { private UserService userService; private PriceService priceService; private SubscriptionService subscriptionService; private SecurityService securityService; private UserValidator userValidator; @Autowired public SubscriptionController(UserService userService, PriceService priceService, SubscriptionService subscriptionService, SecurityService securityService, UserValidator userValidator) { this.userService = userService; this.priceService = priceService; this.subscriptionService = subscriptionService; this.securityService = securityService; this.userValidator = userValidator; } @GetMapping("/subscriptions") public String getAllSubscriptions(Model model) { List<SubscriptionDTO> subscriptionDTOList = subscriptionService.getAll(); if (subscriptionDTOList.isEmpty()) { model.addAttribute("subscriptions_message", "Empty Subscritpions list !!!"); model.addAttribute("subscriptionsList", null); } else { model.addAttribute("subscriptionsList", subscriptionDTOList); } return "subscriptions"; } }
package edu.upenn.cis455.crawler; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.StringReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.Socket; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; import java.util.TreeMap; import javax.net.ssl.HttpsURLConnection; import edu.upenn.cis455.crawler.info.RobotsTxtInfo; import edu.upenn.cis455.crawler.info.URLInfo; public class HTTPClient { private Map<String, RobotsTxtInfo> rulesMap; private int maxFileSize; private InetAddress monitorHost; private DatagramSocket ds; // Result codes for HEAD request public final static String NOT_MODIFIED = "not_modified"; public final static String REDIRECT = "redirect"; public final static String ERROR = "error"; public final static String UNDESIRED = "undesired"; public HTTPClient(int maxFileSize, String monitorHost) { this.rulesMap = new HashMap<String, RobotsTxtInfo>(); this.maxFileSize = maxFileSize; /* The first two commands need to be run only once */ try { this.monitorHost = InetAddress.getByName(monitorHost); this.ds = new DatagramSocket(); } catch (Exception e) { e.printStackTrace(); } } public String getFileHTTP(URLInfo info) { try { Socket s = new Socket(info.getHostName(), info.getPortNo()); InputStream in = s.getInputStream(); OutputStream out = s.getOutputStream(); // Write the request through out out.write(("GET " + info.normalize() + " HTTP/1.1\r\n").getBytes()); out.write(("Host: " + info.getHostName() + "\r\n").getBytes()); out.write(("User-Agent: cis455crawler\r\n").getBytes()); out.write(("Connection: close\r\n\r\n").getBytes()); out.flush(); // sendUDP(info); // Read initial line bytes to a string buffer StringBuffer buf = new StringBuffer(10000); int currByte; while (true) { try { buf.append((char) (currByte = in.read())); if (currByte == '\n') { // If \n, find CRLF break; } } catch (SocketTimeoutException e) { // Timeout while looking for CRLF s.close(); return null; } } // Parsing the request from socket String currLine = buf.toString(); // Obtain the status code String status = currLine.substring(9, 12); if (status.startsWith("4") || status.startsWith("5")) { s.close(); return null; } // Then read all header bytes buf = new StringBuffer(10000); // reset buf while (true) { try { buf.append((char) (currByte = in.read())); if (currByte == '\n') { // If \n if ((currByte = in.read()) == '\r') { // Then if \r -> so we find \n\r in \r\n\r\n buf.append((char) currByte); buf.append((char) in.read()); break; } else { buf.append((char) currByte); // Not \r, write it in and continue } } } catch (SocketTimeoutException e) { // Timeout while looking for CRLF s.close(); return null; } } // Reset br to new buf BufferedReader br = new BufferedReader(new StringReader(buf.toString())); // Setting buf to null such that gc can collect the memory buf = null; // Put all headers into a map. // This String is for multi-line header value TreeMap<String, String> headers = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER); String prevField = ""; while (!(currLine = br.readLine()).equals("")) { // While not reading a CRLF if (currLine.contains(":")) { // Normal line String fieldName = currLine.substring(0, currLine.indexOf(':')); prevField = fieldName; String fieldValue; // To prevent out-of-index if (currLine.indexOf(':') != currLine.length()-1) { fieldValue = currLine.substring(currLine.indexOf(':')+1).trim(); } else { fieldValue = ""; } headers.put(fieldName, fieldValue); } else if (!prevField.equals("") && (currLine.charAt(0) == ' ' || currLine.charAt(0) == '\t')) { // A multi-line field value String fieldValue = headers.get(prevField); fieldValue += currLine; headers.put(prevField, fieldValue); } } if (status.startsWith("3")) { if (headers.containsKey("location")) { String newTargetStr = headers.get("location"); try { newTargetStr = URLDecoder.decode(newTargetStr, StandardCharsets.UTF_8.name()); } catch (Exception e) { // Do nothing } URLInfo newTarget = new URLInfo(newTargetStr); s.close(); if (newTarget.getProtocol().equals("https")) { return getFileHTTPS(newTarget); } else { return getFileHTTP(newTarget); } } else { s.close(); return null; } } // Obtain body if (headers.containsKey("Content-Length")) { int numOfBytesInBody = Integer.parseInt(headers.get("Content-Length")); if (numOfBytesInBody > maxFileSize) { s.close(); return null; } InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8); StringBuilder sb = new StringBuilder(); while (numOfBytesInBody > 0) { sb.append((char) reader.read()); numOfBytesInBody--; } s.close(); return sb.toString(); } else { int numOfBytesRead = 0; InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8); StringBuilder sb = new StringBuilder(); while (numOfBytesRead <= maxFileSize) { char currChar = (char) reader.read(); if (currChar == -1) { break; } sb.append(currChar); numOfBytesRead++; } if ((int) reader.read() != -1) { s.close(); return null; } s.close(); return sb.toString(); } } catch (Exception e) { e.printStackTrace(); return null; } } public String getFileHTTPS(URLInfo info) { try { URL url = new URL(info.normalize()); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.addRequestProperty("Connection", "close"); conn.setRequestProperty("User-Agent", "cis455crawler"); conn.connect(); sendUDP(info); int responseCode = conn.getResponseCode(); // if 4xx or 5xx, null if (responseCode >= 400) { return null; } else if (responseCode >= 300) { if (conn.getHeaderField("location") != null) { String newTargetStr = conn.getHeaderField("location"); try { newTargetStr = URLDecoder.decode(newTargetStr, StandardCharsets.UTF_8.name()); } catch (Exception e) { // Do nothing } URLInfo newTarget = new URLInfo(newTargetStr); if (newTarget.getProtocol().equals("https")) { return getFileHTTPS(newTarget); } else { return getFileHTTP(newTarget); } } else { return null; } } // Obtain body if (responseCode == 200 && conn.getContentLength() != -1) { int numOfBytesInBody = conn.getContentLength(); if (numOfBytesInBody > maxFileSize) { return null; } InputStreamReader reader = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8); StringBuilder sb = new StringBuilder(); while (numOfBytesInBody > 0) { char nextChar = (char) reader.read(); if (nextChar != -1) { sb.append(nextChar); } numOfBytesInBody--; } return sb.toString(); } else { int numOfBytesRead = 0; InputStreamReader reader = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8); StringBuilder sb = new StringBuilder(); while (numOfBytesRead <= maxFileSize) { char currChar = (char) reader.read(); if (currChar == -1) { break; } sb.append(currChar); numOfBytesRead++; } if ((int) reader.read() != -1) { return null; } return sb.toString(); } } catch (Exception e) { e.printStackTrace(); return null; } } public String sendHeadHTTP(URLInfo info, Date lastModified) { try { Socket s = new Socket(info.getHostName(), info.getPortNo()); InputStream in = s.getInputStream(); OutputStream out = s.getOutputStream(); // Write the request through out out.write(("HEAD " + info.normalize() + " HTTP/1.1\r\n").getBytes()); out.write(("Host: " + info.getHostName() + "\r\n").getBytes()); out.write(("User-Agent: cis455crawler\r\n").getBytes()); if (lastModified != null) { SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z"); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); out.write(("If-Modified-Since: " + dateFormat.format(lastModified) + "\r\n").getBytes()); } out.write(("Connection: close\r\n\r\n").getBytes()); out.flush(); sendUDP(info); // Read initial line bytes to a string buffer StringBuffer buf = new StringBuffer(10000); int currByte; while (true) { try { buf.append((char) (currByte = in.read())); if (currByte == '\n') { // If \n, find CRLF break; } } catch (SocketTimeoutException e) { // Timeout while looking for CRLF s.close(); return ERROR; } } // Parsing the request from socket String currLine = buf.toString(); // Obtain the status code String status = currLine.substring(9, 12); if (status.startsWith("4") || status.startsWith("5")) { s.close(); return ERROR; } if (status.equals("304")) { s.close(); return NOT_MODIFIED; } // Then read all header bytes buf = new StringBuffer(10000); // reset buf while (true) { try { buf.append((char) (currByte = in.read())); if (currByte == '\n') { // If \n if ((currByte = in.read()) == '\r') { // Then if \r -> so we find \n\r in \r\n\r\n buf.append((char) currByte); buf.append((char) in.read()); break; } else { buf.append((char) currByte); // Not \r, write it in and continue } } } catch (SocketTimeoutException e) { // Timeout while looking for CRLF s.close(); return ERROR; } } // Reset br to new buf BufferedReader br = new BufferedReader(new StringReader(buf.toString())); // Setting buf to null such that gc can collect the memory buf = null; // Put all headers into a map. // This String is for multi-line header value TreeMap<String, String> headers = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER); String prevField = ""; while (!(currLine = br.readLine()).equals("")) { // While not reading a CRLF if (currLine.contains(":")) { // Normal line String fieldName = currLine.substring(0, currLine.indexOf(':')); prevField = fieldName; String fieldValue; // To prevent out-of-index if (currLine.indexOf(':') != currLine.length()-1) { fieldValue = currLine.substring(currLine.indexOf(':')+1).trim(); } else { fieldValue = ""; } headers.put(fieldName, fieldValue); } else if (!prevField.equals("") && (currLine.charAt(0) == ' ' || currLine.charAt(0) == '\t')) { // A multi-line field value String fieldValue = headers.get(prevField); fieldValue += currLine; headers.put(prevField, fieldValue); } } if (status.startsWith("3")) { if (headers.containsKey("location")) { String newTargetStr = headers.get("location"); if (newTargetStr.contains(",")) { // Multiple choices, choose first newTargetStr = newTargetStr.split(",")[0].trim(); } // Could be encoded, so try decode try { newTargetStr = URLDecoder.decode(newTargetStr, StandardCharsets.UTF_8.name()); } catch (Exception e) { // Do nothing } URLInfo newTarget = new URLInfo(newTargetStr); // Add newTarget to taskQueue if it has desired URL form if (newTarget.isDesired()) { XPathCrawler.taskQueue.add(newTarget); } s.close(); return REDIRECT; } else { s.close(); return ERROR; } } if (status.startsWith("2")) { if (headers.containsKey("content-length")) { int targetFileSize = Integer.parseInt(headers.get("content-length").trim()); if (targetFileSize > maxFileSize) { s.close(); return UNDESIRED; } } if (headers.containsKey("content-type")) { String mimeType = headers.get("content-type").trim(); if (mimeType.contains("text/html")) { s.close(); return mimeType; } else { s.close(); return UNDESIRED; } } s.close(); return UNDESIRED; } else { s.close(); return UNDESIRED; } } catch (Exception e) { e.printStackTrace(); return ERROR; } } public String sendHeadHTTPS(URLInfo info, Date lastModified) { try { URL url = new URL(info.normalize()); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); conn.addRequestProperty("Connection", "close"); conn.setRequestProperty("User-Agent", "cis455crawler"); if (lastModified != null) { SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z"); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); conn.addRequestProperty("If-Modified-Since", dateFormat.format(lastModified)); } conn.connect(); sendUDP(info); int responseCode = conn.getResponseCode(); // if 4xx or 5xx, null if (responseCode >= 400) { return ERROR; } else if (responseCode == 304) { return NOT_MODIFIED; } else if (responseCode >= 300) { if (conn.getHeaderField("location") != null) { String newTargetStr = conn.getHeaderField("location"); try { newTargetStr = URLDecoder.decode(newTargetStr, StandardCharsets.UTF_8.name()); } catch (Exception e) { // Do nothing } URLInfo newTarget = new URLInfo(newTargetStr); // Add newTarget to taskQueue if it has desired URL form if (newTarget.isDesired()) { XPathCrawler.taskQueue.add(newTarget); } return REDIRECT; } else { return ERROR; } } // Obtain body if (responseCode >= 200) { if (conn.getContentLength() != -1) { int targetFileSize = conn.getContentLength(); if (targetFileSize > maxFileSize) { return UNDESIRED; } } if (conn.getContentType() != null) { String mimeType = conn.getContentType(); if (mimeType.contains("text/html")) { return mimeType; } else { return UNDESIRED; } } return UNDESIRED; } else { return UNDESIRED; } } catch (Exception e) { e.printStackTrace(); return ERROR; } } public void parseRobotsTxt(URLInfo linkInfo, String body) { RobotsTxtInfo robotInfo = new RobotsTxtInfo(); try (BufferedReader br = new BufferedReader(new StringReader(body));) { String currLine; while ((currLine = br.readLine()) != null) { if (currLine.contains(":")) { String[] rulePair = currLine.split(":"); if (rulePair[0].equalsIgnoreCase("User-agent")) { if (rulePair[1].trim().equalsIgnoreCase("cis455crawler")) { robotInfo.setSpecific(); robotInfo.reset(); currLine = br.readLine(); while (currLine != null && !currLine.equals("")) { rulePair = currLine.split(":"); if (rulePair[0].equalsIgnoreCase("Disallow")) { robotInfo.addDisallowedLink(rulePair[1].trim()); } else if (rulePair[0].equalsIgnoreCase("Crawl-Delay")) { robotInfo.addCrawlDelay(Integer.parseInt(rulePair[1].trim()) * 1000); } currLine = br.readLine(); } } else if (rulePair[1].trim().equalsIgnoreCase("*") && !robotInfo.isSpecific()) { currLine = br.readLine(); while (currLine != null && !currLine.equals("")) { rulePair = currLine.split(":"); if (rulePair[0].equalsIgnoreCase("Disallow")) { robotInfo.addDisallowedLink(rulePair[1].trim()); } else if (rulePair[0].equalsIgnoreCase("Crawl-Delay")) { robotInfo.addCrawlDelay(Integer.parseInt(rulePair[1].trim()) * 1000); } currLine = br.readLine(); } } } } } } catch (Exception e) { e.printStackTrace(); } rulesMap.put(linkInfo.getHostName() + ":" + linkInfo.getPortNo(), robotInfo); } public Map<String, RobotsTxtInfo> getRulesMap() { return this.rulesMap; } private void sendUDP(URLInfo task) { /* The commands below need to be run for every single URL */ byte[] data = ("haohua;" + task.normalize()).getBytes(); DatagramPacket packet = new DatagramPacket(data, data.length, this.monitorHost, 10455); try { this.ds.send(packet); } catch (IOException e) { e.printStackTrace(); } } }
package Model.DAO; import Model.GamingGroup; import Model.PlaySession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.rowset.SqlRowSet; import org.springframework.stereotype.Component; import javax.sql.DataSource; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; @Component public class JDBCPlaySessionDAO implements PlaySessionDAO { private JdbcTemplate jdbcTemplate; @Autowired public JDBCPlaySessionDAO(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } @Override public void startNewPlaySession(PlaySession session, GamingGroup group) { String newSqlRow = "INSERT INTO play_session (session_name, session_date, session_location, has_prize, group_id) " + "VALUES (?,?,?,?,?);"; jdbcTemplate.update(newSqlRow, session.getSessionName(), session.getSessionDate(), session.getSessionLocation(), session.isHasPrize(), group.getGroupId()); if (session.isHasPrize()) { String newPrizeEntry = "INSERT INTO play_session (prize, money_prize) Values (?,?);"; jdbcTemplate.update(newPrizeEntry, session.getPrize(), session.getMoneyPrize()); } } @Override public List<PlaySession> getPlaySessionsByGroup(GamingGroup group) { String sqlGetGroupSessions = "SELECT * FROM play_session WHERE group_id = ?;"; SqlRowSet sessions = jdbcTemplate.queryForRowSet(sqlGetGroupSessions, group.getGroupId()); List<PlaySession> groupSessions = new ArrayList<>(); PlaySession thisSession; // initialize as null while (sessions.next()) { thisSession = new PlaySession(); thisSession.setSessionId(sessions.getInt("session_id")); thisSession.setSessionName(sessions.getString("session_name")); thisSession.setSessionDate(sessions.getDate("session_date").toLocalDate()); thisSession.setSessionLocation(sessions.getString("session_location")); thisSession.setHasPrize(sessions.getBoolean("has_prize")); thisSession.setPrize(sessions.getString("prize")); thisSession.setMoneyPrize(sessions.getBigDecimal("money_prize")); thisSession.setGroupId(sessions.getInt("group_id")); groupSessions.add(thisSession); } return groupSessions; } @Override public List<PlaySession> getPlaySessionsByLocation(String sessionLocation) { String sqlGetLocationSessions = "SELECT * FROM play_session WHERE session_location LIKE '%'?'%';"; SqlRowSet sessions = jdbcTemplate.queryForRowSet(sqlGetLocationSessions, sessionLocation); List<PlaySession> locationSessions = new ArrayList<>(); PlaySession thisSession; // initialize as null while (sessions.next()) { thisSession = new PlaySession(); thisSession.setSessionId(sessions.getInt("session_id")); thisSession.setSessionName(sessions.getString("session_name")); thisSession.setSessionDate(sessions.getDate("session_date").toLocalDate()); thisSession.setSessionLocation(sessions.getString("session_location")); thisSession.setHasPrize(sessions.getBoolean("has_prize")); thisSession.setPrize(sessions.getString("prize")); thisSession.setMoneyPrize(sessions.getBigDecimal("money_prize")); thisSession.setGroupId(sessions.getInt("group_id")); locationSessions.add(thisSession); } return locationSessions; } @Override public List<PlaySession> getPlaySessionsByDate(LocalDate date) { String sqlGetSessionsByDate = "SELECT * FROM play_session WHERE session_date = ?;"; SqlRowSet sessions = jdbcTemplate.queryForRowSet(sqlGetSessionsByDate, date); List<PlaySession> dateSessions = new ArrayList<>(); PlaySession thisSession; // initialize as null while (sessions.next()) { thisSession = new PlaySession(); thisSession.setSessionId(sessions.getInt("session_id")); thisSession.setSessionName(sessions.getString("session_name")); thisSession.setSessionDate(sessions.getDate("session_date").toLocalDate()); thisSession.setSessionLocation(sessions.getString("session_location")); thisSession.setHasPrize(sessions.getBoolean("has_prize")); thisSession.setPrize(sessions.getString("prize")); thisSession.setMoneyPrize(sessions.getBigDecimal("money_prize")); thisSession.setGroupId(sessions.getInt("group_id")); dateSessions.add(thisSession); } return dateSessions; } @Override public void updatePlaySession(PlaySession session) { jdbcTemplate.update("BEGIN TRANSACTION; UPDATE play_session SET session_name = ?, session_date = ?, " + "session_location = ?, has_prize = ?, prize = ?, money_prize = ?, group_id = ? WHERE session_id = ?;" + "COMMIT;", session.getSessionName(), session.getSessionDate(), session.getSessionLocation(), session.isHasPrize(), session.getPrize(), session.getMoneyPrize(), session.getGroupId(), session.getSessionId()); } // Move this to JDBCGameSessionDAO to be able to delete data from tables @Override public void deletePlaySession(PlaySession session) { jdbcTemplate.update("DELETE * FROM game_session WHERE session_id = ?; " + "DELETE * FROM play_session WHERE session_id = ?;", session.getSessionId(), session.getSessionId()); } }
package ru.job4j.srp; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; /** * This class add employee to list, stores data about all employees. * @author Aliaksandr Kuzura (vorota-24@bk.ru) * @version $Id$ * @since 0.1 */ public class MemStore implements Store { /** * Create list of employees. */ private final List<Employee> employees = new ArrayList<>(); /** * This method adds to list an employee. * @param em */ public void add(Employee em) { this.employees.add(em); } /** * this method returns list 0f employees. * @param filter functional interface. * @return */ @Override public List<Employee> findBy(Predicate<Employee> filter) { return employees.stream().filter(filter).collect(Collectors.toList()); } }
package negocio.apresentacao; import negocio.basica.Departamento; import negocio.basica.Funcionario; import negocio.controlador.ControladorDepartamento; public class ApresentacaoDepartamento { public static void main(String[] args) { ControladorDepartamento compDept = new ControladorDepartamento(); Departamento dept = new Departamento(); Funcionario funcionarios = new Funcionario(); funcionarios.setId(1); dept.setId(1); dept.setNome("Finanšas"); dept.setDescricao("Departamendo de Finanšas"); dept.setFuncionarios(null); compDept.alterar(dept); } }
import java.util.Random; /** * Class implementing a bank account. * <p> * Complete and document this class as part of Lab 8. * * @see <a href="https://cs125.cs.illinois.edu/lab/8/">Lab 8 Description</a> */ public class BankAccount { /** * The possible types of a bank account. */ public enum BankAccountType { /** * The. */ CHECKINGS, /** * The. */ SAVINGS, /** * The. */ STUDENT, /** * The. */ WORKPLACE } /** The the account numeber. * */ private int accountNumber; /** The type of the bank. * */ private BankAccountType accountType; /** * The amount of money in the account. */ private double accountBalance; /** * the name of the owner of the account. */ private String ownerName; /** * The interest rate of the account. */ private double interestRate; /** * The interest earned by this account. */ private double interestEarned; /** * create a new account. * @param name the name of the owner * @param accountCategory the type of the account */ public BankAccount(final String name, final BankAccountType accountCategory) { /* * Implement this function */ ownerName = name; accountType = accountCategory; System.out.println("A new account is created."); } /** * Set the account number. * @param number the number typed in */ public void setAccountNumebr(final int number) { accountNumber = number; } /** * Get the account Number. * @return return the account Number */ public int getAccountNumber() { return accountNumber; } /** * Set the type of the account. * *@param accountCategory the type of the account */ public void setAccountType(final BankAccountType accountCategory) { accountType = accountCategory; } /** * Get the type of the account. * @return the type of the account */ public BankAccountType getAccountType() { return accountType; } /** * Set the account balance. * @param balance the balance of the account */ public void setAccountBalance(final double balance) { accountBalance = balance; } /** * Get the current balance of the account. * @return the current balance of the account */ public double getAccountBalance() { return accountBalance; } /** * Reset the owner of the account. * @param owner the new owner of the account */ public void setOwnerName(final String owner) { ownerName = owner; } /** * Get the current owner's name. * @return the current owner's name */ public String getOwnerName() { return ownerName; } /** * Set the interest rate of the account. * @param rate the interest rate of the account. */ public void setInterestAccount(final double rate) { interestRate = rate; } /** * Get the current interest rate of the account. * @return the current interest rate of the account */ public double getInterestRate() { return interestRate; } /** * Set the current interest earned. * @param interest the current interest earned */ public void setInterestEarned(final double interest) { interestEarned = interest; } /** * Get the current interest earned. * @return the current interest earned */ public double getInterstEarned() { return interestEarned; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * Tela.java * * Created on 03/03/2011, 18:28:20 */ package Controler; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.IOException; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import java.util.logging.Level; import java.util.logging.Logger; import com.google.gson.Gson; import Auxiliar.Consts; import Auxiliar.Posicao; import LoloModel.Bau; import LoloModel.BichinhoVaiVemHorizontal; import LoloModel.Coracao; import LoloModel.Elemento; import LoloModel.Fases; import LoloModel.Lolo; import LoloModel.Porta; /** * * @author junio */ public class Tela extends javax.swing.JFrame implements MouseListener, KeyListener { /** * */ private static final long serialVersionUID = 1L; private Lolo lLolo; private BichinhoVaiVemHorizontal bBichinhoH; private Coracao coracao; private Bau bau; private Porta porta; private ArrayList<Elemento> e; private ControleDeJogo cj = new ControleDeJogo(); /** * Creates new form tabuleiro */ public Tela(int fase) { initComponents(); this.addMouseListener(this); /*mouse*/ this.addKeyListener(this); /*teclado*/ /*Cria a janela do tamanho do tabuleiro + insets (bordas) da janela*/ this.setSize(Consts.RES*Consts.CELL_SIDE + getInsets().left + getInsets().right, Consts.RES*Consts.CELL_SIDE + getInsets().top + getInsets().bottom); e = new ArrayList<Elemento>(80); lLolo = new Lolo(this); coracao = new Coracao(); bBichinhoH = new BichinhoVaiVemHorizontal(); bau = new Bau(this); porta = new Porta(); this.addElemento(lLolo); try { Fases fases = new Fases(this, bBichinhoH, coracao, lLolo, bau, porta); fases.start(fase); } catch (Exception e1) { } } public Porta getPorta() { return porta; } public void setPorta(Porta porta) { this.porta = porta; } public Bau getBau() { return bau; } public void setBau(Bau bau) { this.bau = bau; } public void addElemento(Elemento umElemento){ e.add(umElemento); } public void removeElemento(Elemento umElemento){ e.remove(umElemento); } public void paint(Graphics gOld) { Graphics g = getBufferStrategy().getDrawGraphics(); /*Criamos um contexto gráfico*/ Graphics g2 = g.create(getInsets().right,getInsets().top,getWidth() - getInsets().left,getHeight() - getInsets().bottom); /*Desenha cenário*/ for (int i = 0; i < Consts.RES; i++) { for (int j = 0; j < Consts.RES; j++) { try { Image newImage = Toolkit.getDefaultToolkit().getImage(new java.io.File(".").getCanonicalPath() + Consts.PATH + "bricks.png"); g2.drawImage(newImage, j*Consts.CELL_SIDE, i*Consts.CELL_SIDE, Consts.CELL_SIDE, Consts.CELL_SIDE, null); } catch (IOException ex) { Logger.getLogger(Tela.class.getName()).log(Level.SEVERE, null, ex); } } } this.cj.desenhaTudo(e, g2); this.cj.processaTudo(e); g.dispose(); g2.dispose(); if (!getBufferStrategy().contentsLost()) { getBufferStrategy().show(); } } public void go() { TimerTask task = new TimerTask() { public void run() { repaint(); } }; Timer timer = new Timer(); timer.schedule(task, 0, Consts.DELAY); } public void restart(){ this.dispose(); TelaController control = new TelaController(); control.run(); } public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_UP) { move(); lLolo.moveUp(); } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { move(); lLolo.moveDown(); } else if (e.getKeyCode() == KeyEvent.VK_LEFT) { move(); lLolo.moveLeft(); } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) { move(); lLolo.moveRight(); } else if (e.getKeyCode() == KeyEvent.VK_X) { lLolo.lançaFogoHorizontal(lLolo); } else if (e.getKeyCode() == KeyEvent.VK_C) { lLolo.lançaFogoVertical(lLolo); } if(!cj.ehPosicaoValida(this.e, lLolo.getPosicao())) lLolo.voltaAUltimaPosicao(); this.setTitle("-> Cell: " + (lLolo.getPosicao().getColuna()) + ", " + (lLolo.getPosicao().getLinha())); // repaint(); /*invoca o paint imediatamente, sem aguardar o refresh*/ } private void move() { saveLoloPosition(this); bau.Touch(this); coracao.Touch(this); porta.Touch(this); } private void saveLoloPosition(Tela tela) { TelaController savePos = new TelaController(); savePos.saveLoloPos(this); } public void mousePressed(MouseEvent e) { // int x = e.getX(); // int y = e.getY(); // // this.setTitle("X: "+ x + ", Y: " + y + // " -> Cell: " + (y/Consts.CELL_SIDE) + ", " + (x/Consts.CELL_SIDE)); // // this.lLolo.getPosicao().setPosicao(y/Consts.CELL_SIDE, x/Consts.CELL_SIDE); // repaint(); } /** * 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() { setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("POO2015-1 - Adventures of lolo"); setAutoRequestFocus(false); setPreferredSize(new java.awt.Dimension(500, 500)); setResizable(false); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 500, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 500, Short.MAX_VALUE) ); getAccessibleContext().setAccessibleName("POO2015-1 - Adventures of lolo"); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables // End of variables declaration//GEN-END:variables public void mouseMoved(MouseEvent e) { } public void mouseClicked(MouseEvent a) { if(a.getButton() == 3){ Elemento element = getElementoByPosition(a.getX()/Consts.CELL_SIDE, a.getY()/Consts.CELL_SIDE); if(element == null){ System.out.println("Não existe elemento aqui"); }else{ TelaController controller = new TelaController(); Elemento elemento = controller.returnObject(); if(elemento == null) System.out.println("Elemento não pode ser inserido"); else{ elemento.setPosicao(element.getPosicao().getLinha(), element.getPosicao().getColuna()); this.addElemento(elemento); e.remove(element); } } } } public Elemento getElementoByPosition(int coluna, int linha){ for (Elemento elements : e) { if((elements.getPosicao().getColuna() == coluna ) && (elements.getPosicao().getLinha() == linha )){ return elements; } } return null; } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseDragged(MouseEvent e) { } public void keyTyped(KeyEvent e) { } public void keyReleased(KeyEvent e) { } public void setLoloPosition(Posicao posicao){ this.lLolo.setPosicao(posicao.getLinha(), posicao.getColuna()); } public Lolo getlLolo() { return lLolo; } public BichinhoVaiVemHorizontal getbBichinhoH() { return bBichinhoH; } }
package application; import java.io.Serializable; /** * A class to define and create a pizza. * <p> * The size, the amount of cheese, amount of pineapple, greenpepper and ham is recorded. * It includes the default constructor, a toString method, an equals method, an accessor getCost and a clone method * * @author Anne Liu 20069271 */ public class Pizza implements Comparable<Pizza>, Serializable { private static final long serialVersionUID =1L ; //cannot find the number private String Size; private String Cheese; private String Pineapple; private String Greenpepper; private String Ham; /** * Full parameter constructor. * @param yr The year when the data was collected. * @param numKids The number of Trick or Treaters! * @param temps The air temperatures in degrees Centigrade in an array of int of any size. * @param weather The weather condition: "clear", "snow" or "rain". * @throws IllegalHalloweenException If arguments are not legal. */ public Pizza (String size, String cheese, String pineapple, String greenpepper, String ham) throws IllegalPizza { if ((size == null)|| (cheese==null)|| (pineapple==null)||(greenpepper==null)||(ham==null)) throw new IllegalPizza ("something is null"); if ((size.equalsIgnoreCase("small")) ||(size.equalsIgnoreCase("medium")) ||(size.equalsIgnoreCase("large"))) { this.Size = size; } else throw new IllegalPizza ("Illegal size"); if ((cheese.equalsIgnoreCase("single")) || (cheese.equalsIgnoreCase("double")) || (cheese.equalsIgnoreCase("triple"))) { this.Cheese = cheese; } else throw new IllegalPizza ("Illegal amount of cheese"); if ((ham.equalsIgnoreCase("none")) || (ham.equalsIgnoreCase("single"))) { this.Ham = ham; } else throw new IllegalPizza ("Illegal amount of ham"); if ((pineapple.equalsIgnoreCase("none")) || (pineapple.equalsIgnoreCase("single") && ham.equalsIgnoreCase("single"))) { this.Pineapple = pineapple; } else throw new IllegalPizza ("Illegal amount of pineapple"); if ((greenpepper.equalsIgnoreCase("none")) || (greenpepper.equalsIgnoreCase("single") && ham.equalsIgnoreCase("single"))) { this.Greenpepper = greenpepper; } else throw new IllegalPizza ("Illegal amount of greenpepper"); } //second constructor public Pizza () { //sets conditions for small single cheese and ham this.Size= "small"; this.Cheese= "single"; this.Ham= "single"; this.Greenpepper="none"; this.Pineapple="none"; } @Override public String toString() { /* medium pizza, double cheese. Cost: $10.50 each. small pizza, single cheese, pineapple, green pepper, ham. Cost: $11.50 each. large pizza, triple cheese, pineapple, ham. Cost: $17.00 each. */ String s; s= Size.toLowerCase()+ " pizza, "+ Cheese.toLowerCase() + " cheese"; if(Pineapple.equalsIgnoreCase("single")) s=s+ ", pineapple"; if(Greenpepper.equalsIgnoreCase("single")) s=s+ ", green pepper"; if(Ham.equalsIgnoreCase("single")) s=s+ ", ham"; s+=". Cost: $" + String.format("%1$,.2f", this.getCost()) +" each."; return s; } public boolean equals(Object otherObject) { if (otherObject instanceof Pizza) { Pizza otherP= (Pizza)otherObject; if (this.Size.equalsIgnoreCase(otherP.Size) && this.Cheese.equalsIgnoreCase(otherP.Cheese) && this.Pineapple.equalsIgnoreCase(otherP.Pineapple)&& this.Greenpepper.equalsIgnoreCase(otherP.Greenpepper)&& this.Ham.equalsIgnoreCase(otherP.Ham)) return true; } return false; } public double getCost () { double cost; int toppings; if (Size.equalsIgnoreCase("small")) cost= 7.00; else if (Size.equalsIgnoreCase("medium")) cost= 9.00; else cost= 11.00; if(Cheese.equalsIgnoreCase("single")) toppings=0; else if (Cheese.equalsIgnoreCase("double")) toppings= 1; else toppings=2; if(Ham.equalsIgnoreCase("single")) { toppings++; if (Pineapple.equalsIgnoreCase("single")) toppings++; if (Greenpepper.equalsIgnoreCase("single")) toppings++; } cost+=toppings* 1.5; return cost; } public Pizza clone() { Pizza pCopy= null; try { pCopy= new Pizza(Size, Cheese,Pineapple,Greenpepper,Ham); } catch(IllegalPizza e) { return null; } return pCopy; } @Override public int compareTo(Pizza arg0) { // TODO Auto-generated method stub return 0; } }
package Functions; public class Student { String firstName; String lastName; int adminNum; int grade; char section; student(String firstName, String lastName, int adminNum, int grade, char section) { this.firstName = firstName; this.lastName = lastName; this.adminNum = adminNum; this.grade = grade; this.section = section; } void display() { System.out.println("First Name \t Last Name \t Admin No \t Grade \t Section"); System.out.println(firstName + "\t" + lastName + "\t" + adminNum + "\t" + grade + "\t" + section); } public static void main() { student s1 = new student("Parth", "Sharma", 5265, 10, 'D'); student s2 = new student("Vasu", "Aggarwal", 6278, 10, 'D'); student s3 = new student("Vedant", "Bagadia", 5259, 10, 'E'); student s4 = new student("Kabir", "Oberoi", 3524, 10, 'F'); s1.display(); s2.display(); s3.display(); s4.display(); } }
package patterns.creational.simpleFactory; /** * @author:lanmengxi@viomi.com.cn * @createtime : * @description * @since version 初始于版本 */ public class Rectangle implements Shape { @Override public void draw() { System.out.println("draw a rectangle"); } }
package rss.printlnstuidios.com.myapplication; import android.app.AlertDialog; import android.content.Intent; import android.graphics.Color; import android.media.Image; import android.net.Uri; import android.os.Bundle; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.ShareActionProvider; import android.text.Html; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.squareup.picasso.Picasso; /** * Created by Justin Hill on 12/29/2014. * * Activity used for viewing a specific post and sharing it, saving it, and viewing it in a web browser. */ public class ViewPostActivity extends ActionBarActivity implements View.OnClickListener { //Elements of the Activity UI Button button; ImageView image; TextView imageText; TextView postText; String[] post; String postString = ""; //The URL of the post. Used for opening it and shairing it. String postURL = "The Website"; //if the post it starred boolean saved = false; LinearLayout layout; boolean addButton = false; //used for shareing the post private android.support.v7.widget.ShareActionProvider mShareActionProvider; /** * Sets each of the elements on the Activity to the elements of the post and establishes the * necessary listeners and intents. */ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.view_post); //references to Activity components button = (Button) findViewById(R.id.button); image = (ImageView) findViewById(R.id.top_image); imageText = (TextView) findViewById(R.id.imageViewText); postText = (TextView) findViewById(R.id.postText); layout = (LinearLayout) findViewById(R.id.relative_layout); //Sets of listener for open in browser button button.setOnClickListener(this); post = this.getIntent().getStringArrayExtra("Post"); // Get the text and image url data for the post // See if there in an image that goes along with the post if (post[2]!=null&&!post[2].equals("")) { try { Picasso.with(this).load(post[2]).placeholder(R.drawable.ic_launcher).into(image); } catch (Exception e) { e.printStackTrace(); image.setImageResource(R.drawable.ic_launcher); } } else { // If there is no image then use a default image image.setImageResource(R.drawable.ic_launcher); } Log.d("Text",post[6]); imageText.setText(post[0]); postURL = post[4]; String text = post[6]; postString = post[6]; saved = post[7].equals("star"); try { while (text.contains("<img") || text.contains("< img")) { //only runs if there is an image in the text addButton = true; layout.removeView(button); //write the text before the image if (text.contains("<img")) { postText.setText(Html.fromHtml(text.substring(0, text.indexOf("<img")))); text = text.substring(text.indexOf("<img")); } else if (text.contains("< img")) { postText.setText(Html.fromHtml(text.substring(0, text.indexOf("< img")))); text = text.substring(text.indexOf("< img")); } //draw the image String imageUrl = text.substring(text.indexOf("src=\"") + 5); imageUrl = imageUrl.substring(0, imageUrl.indexOf("\"")); int lastId = postText.getId(); ImageView imageView = new ImageView(this); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); imageView.setLayoutParams(params); //load the image try { Picasso.with(this).load(imageUrl).placeholder(R.drawable.ic_launcher).into(imageView); } catch (Exception e) { e.printStackTrace(); imageView.setImageResource(R.drawable.ic_launcher); } //add the image layout.addView(imageView); lastId = imageView.getId(); //set up a new textView text = text.substring(text.indexOf(">") +1); LinearLayout.LayoutParams textParams = new LinearLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT); postText = new TextView(this); postText.setLayoutParams(textParams); postText.setTextColor(Color.BLACK); layout.addView(postText); } }catch(Exception e) { } if(text.length()>0) { postText.setText(Html.fromHtml(text)); } if(addButton) { layout.addView(button); } } /** * Sets up the menu on the Action bar for sharing and starring the post */ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_post, menu); MenuItem item = menu.findItem(R.id.menu_item_share); mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item); Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_SUBJECT, imageText.getText()); String post = ""+Html.fromHtml(postString)+"\n\n"+"Read More At " + postURL; i.putExtra(Intent.EXTRA_TEXT, post); mShareActionProvider.setShareIntent(i); if(saved) { menu.findItem(R.id.star_post).setIcon(R.drawable.btn_star_on_normal_holo_light);} return true; } /** * Called if one of the items is selected from the options menu */ @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } else if(id == R.id.menu_item_share) //This is handled by the share intent that was set up earlier {} else if(id == R.id.star_post) { //Toggle the star from blue to gray if(saved) item.setIcon(R.drawable.btn_rating_star_off_disabled_holo_dark); else item.setIcon(R.drawable.btn_star_on_normal_holo_light); //Record that the post has been starred saved=!saved; MainActivity.starPost(); } return super.onOptionsItemSelected(item); } /** * Open the post in a web browser if the user click open in browser */ @Override public void onClick(View v) { try{ Intent openBrowser = new Intent(Intent.ACTION_VIEW, Uri.parse(post[4])); startActivity(openBrowser); } catch (Exception e) { //Display an error if something goes wrong AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Couldn't Open URL").setMessage("Sorry but I couldn't open this post in a web browser. The URL may be invalid or you man not have an internet connection.").setPositiveButton("OK", null).show(); } } }
package application; public abstract class Shape { public boolean visibility; public abstract void setVisibility(boolean arg); }
/* * HDF5AlleleDepth */ package net.maizegenetics.dna.snp.depth; import ch.systemsx.cisd.hdf5.IHDF5Reader; import net.maizegenetics.taxa.TaxaList; import net.maizegenetics.taxa.TaxaListBuilder; import net.maizegenetics.util.Tassel5HDF5Constants; import java.util.LinkedHashMap; import java.util.Map; /** * * @author Terry Casstevens */ public class HDF5AlleleDepth extends AbstractAlleleDepth { private static int MAX_CACHE_SIZE = 1 << 16; private static final int HDF5_BLOCK = 1 << 16; private final Map<Long, byte[][]> myDepthCache = new LinkedHashMap<Long, byte[][]>((3 * MAX_CACHE_SIZE) / 2) { @Override protected boolean removeEldestEntry(Map.Entry eldest) { return size() > MAX_CACHE_SIZE; } }; private final IHDF5Reader myReader; private final int myNumSites; private final TaxaList myTaxa; HDF5AlleleDepth(IHDF5Reader reader) { super(6,reader.getIntAttribute(Tassel5HDF5Constants.GENOTYPES_MODULE, Tassel5HDF5Constants.GENOTYPES_NUM_TAXA), reader.getIntAttribute(Tassel5HDF5Constants.POSITION_ATTRIBUTES_PATH, Tassel5HDF5Constants.POSITION_NUM_SITES) ); myReader = reader; myNumSites = reader.getIntAttribute(Tassel5HDF5Constants.POSITION_ATTRIBUTES_PATH, Tassel5HDF5Constants.POSITION_NUM_SITES); myTaxa =new TaxaListBuilder().buildFromHDF5(reader); } private static long getCacheKey(int taxon, int site) { return ((long) taxon << 33) + (site / HDF5_BLOCK); } public byte[] depthForAllelesBytes(int taxon, int site) { long key = getCacheKey(taxon, site); byte[][] data = myDepthCache.get(key); if (data == null) { data = cacheDepthBlock(taxon, site, key); } byte[] result = new byte[6]; for (int i = 0; i < 6; i++) { result[i] = data[i][site % MAX_CACHE_SIZE]; } return result; } public byte[][] depthForAllelesBytes(int taxon) { byte[][] result = new byte[6][myNumSites]; for (int site = 0; site < myNumSites; site++) { long key = getCacheKey(taxon, site); byte[][] data = myDepthCache.get(key); if (data == null) { data = cacheDepthBlock(taxon, site, key); } for (int i = 0; i < 6; i++) { result[i][site] = data[i][site % MAX_CACHE_SIZE]; } } return result; } private byte[][] cacheDepthBlock(int taxon, int site, long key) { int start = (site / MAX_CACHE_SIZE) * MAX_CACHE_SIZE; int realSiteCache = (myNumSites - start < MAX_CACHE_SIZE) ? myNumSites - start : MAX_CACHE_SIZE; byte[][] data = myReader.readByteMatrixBlockWithOffset(Tassel5HDF5Constants.getGenotypesDepthPath(myTaxa.taxaName(taxon)), 6, realSiteCache, 0, start); if (data == null) { return null; } myDepthCache.put(key, data); return data; } @Override public int[] depthForAlleles(int taxon, int site) { return AlleleDepthUtil.depthByteToInt(depthForAllelesBytes(taxon,site)); //throw new UnsupportedOperationException("Not supported yet."); } @Override public int depthForAllele(int taxon, int site, int allele) { return AlleleDepthUtil.depthByteToInt(depthForAlleleByte(taxon, site, allele)); } @Override public byte depthForAlleleByte(int taxon, int site, int allele) { long key = getCacheKey(taxon, site); byte[][] data = myDepthCache.get(key); if (data == null) { data = cacheDepthBlock(taxon, site, key); } return data[allele][site % MAX_CACHE_SIZE]; } }
package com.zc.base.sys.modules.login; import com.zc.base.bla.common.util.DateUtil; import com.zc.base.common.constant.SdConstant; import com.zc.base.sys.modules.login.entity.LoginInfo; import com.zc.base.sys.modules.login.repository.LoginInfoDao; import com.zc.base.sys.modules.user.entity.Reply; import com.zc.base.sys.modules.user.service.UserService; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.apache.shiro.web.filter.authc.FormAuthenticationFilter; import org.apache.shiro.web.util.WebUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.*; public class CaptchaFormAuthentication extends FormAuthenticationFilter { public static final ThreadLocal<LoginInfo> LOGININFO = new ThreadLocal(); private static Logger logger = LoggerFactory.getLogger(CaptchaFormAuthentication.class); private LoginInfoDao loginInfoDao; private String captchaParam = "captcha"; private String proxParam = "proxFlag"; private Boolean enableUserLock; private Integer failLockCount; private Integer userLockTime; protected String reLoginUrl; public void persistLoginInfo(LoginInfo loginInfo) { if (loginInfo != null) { Long infoId = loginInfo.getLoginInfoId(); if (infoId == null) { this.loginInfoDao.addLoginInfo(loginInfo); } else { this.loginInfoDao.updateLoginInfo(loginInfo); } } } protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) { UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token; String host = usernamePasswordToken.getHost(); String username = usernamePasswordToken.getUsername(); if ("com.zc.base.sys.modules.login.CaptchaTimeoutException".equals(e.getClass().getName())) { logger.info(getLoginFaildInfo(host, username, "captcha timeout!")); } else if ("com.zc.base.sys.modules.login.CaptchaIncorrectException".equals(e.getClass().getName())) { logger.info(getLoginFaildInfo(host, username, "captcha incorrect!")); } else if ("org.apache.shiro.authc.UnknownAccountException".equals(e.getClass().getName())) { logger.info(getLoginFaildInfo(host, username, "user doesn't exsits!")); } else if ("org.apache.shiro.authc.IncorrectCredentialsException".equals(e.getClass().getName())) { logger.info(getLoginFaildInfo(host, username, "username or password Incorrect!")); if (this.enableUserLock.booleanValue()) { long now = System.currentTimeMillis(); LoginInfo loginInfo = (LoginInfo) LOGININFO.get(); Integer errorCount = loginInfo.getErrorCount(); errorCount = Integer.valueOf(errorCount.intValue() + 1); loginInfo.setErrorCount(errorCount); loginInfo.setLstErrLoginTime(new Date(now)); if (errorCount.intValue() >= this.failLockCount.intValue()) { loginInfo.setLocked(Integer.valueOf(1)); loginInfo.setLockTime(new Date(now)); loginInfo.setLockLostEffTime(new Date(now + this.userLockTime.intValue() * SdConstant.THOUSAND.intValue())); } persistLoginInfo(loginInfo); } } else if ("org.apache.shiro.authc.LockedAccountException".equals(e.getClass().getName())) { logger.info(getLoginFaildInfo(host, username, "user locked!")); } else if ("com.zc.base.sys.modules.login.MaxOnlineCountException".equals(e.getClass().getName())) { logger.info(getLoginFaildInfo(host, username, "exceed max online count!")); } else if ("com.zc.base.sys.modules.login.PasswordExpiredException".equals(e.getClass().getName())) { logger.info(getLoginFaildInfo(host, username, "Password is expired!")); } else { logger.info(getLoginFaildInfo(host, username, e.getMessage()), e); } return super.onLoginFailure(token, e, request, response); } protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; createNewSession(req, resp); UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token; if (this.enableUserLock.booleanValue()) { LoginInfo loginInfo = (LoginInfo) LOGININFO.get(); loginInfo.setErrorCount(Integer.valueOf(0)); loginInfo.setLstErrLoginTime(null); loginInfo.setLockTime(null); loginInfo.setLockLostEffTime(null); if (loginInfo.getFstSucLoginTime() == null) { loginInfo.setFstSucLoginTime(new Date()); } persistLoginInfo(loginInfo); } UserService.ENTER_COUNT.addAndGet(1); String userAccount = usernamePasswordToken.getUsername(); String ipAdd = usernamePasswordToken.getHost(); String loginDate = DateUtil.getYYYYMMDDHHMMSSFromDate(new Date()); HttpSession session = req.getSession(); UserService.MAP.put(userAccount, session); Reply reply = new Reply(userAccount, ipAdd, loginDate); session.setAttribute("reply_Info", reply); session.setAttribute("current_user", userAccount); logger.info(userAccount + " successfully login !" + "|request host:" + ipAdd); return super.onLoginSuccess(token, subject, request, response); } protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception { WebUtils.issueRedirect(request, response, getSuccessUrl()); } protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) { String username = getUsername(request); String password = getPassword(request); String captcha = getCaptcha(request); boolean rememberMe = isRememberMe(request); String host = getHost(request); return new CaptchaUsernamePasswordToken(username, password, rememberMe, host, captcha); } protected String getProxFlag(ServletRequest request) { return WebUtils.getCleanParam(request, getProxParam()); } public String getProxParam() { return this.proxParam; } private static String getLoginFaildInfo(String host, String username, String message) { return username + " login failed ! |request host:" + host + "|msg:" + (message == null ? "" : message); } private static void createNewSession(HttpServletRequest request, HttpServletResponse response) { HttpSession oldSession = request.getSession(); Map<String, Object> oldSessionAttrMap = new HashMap(); Enumeration attributeNames = oldSession.getAttributeNames(); while (attributeNames.hasMoreElements()) { String key = (String) attributeNames.nextElement(); Object value = oldSession.getAttribute(key); oldSessionAttrMap.put(key, value); } oldSession.invalidate(); HttpSession newSession = request.getSession(); Set<String> keys = oldSessionAttrMap.keySet(); for (String key : keys) { newSession.setAttribute(key, oldSessionAttrMap.get(key)); } Cookie cookie = new Cookie("JSESSIONID", newSession.getId()); cookie.setSecure(false); cookie.setPath(request.getContextPath()); response.addCookie(cookie); } protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { if (isLoginRequest(request, response)) { if (isLoginSubmission(request, response)) { if (logger.isTraceEnabled()) { logger.trace("Login submission detected. Attempting to execute login."); } return executeLogin(request, response); } if (logger.isTraceEnabled()) { logger.trace("Login page view."); } return true; } if (logger.isTraceEnabled()) { logger.trace("Attempting to access a path which requires authentication. Forwarding to the Authentication url [" + getLoginUrl() + "]"); } WebUtils.issueRedirect(request, response, getReLoginUrl()); return false; } public String getCaptchaParam() { return this.captchaParam; } protected String getPassword(ServletRequest request) { return request.getParameter(getPasswordParam()); } protected String getCaptcha(ServletRequest request) { return WebUtils.getCleanParam(request, getCaptchaParam()); } public Boolean getEnableUserLock() { return this.enableUserLock; } public void setEnableUserLock(Boolean enableUserLock) { this.enableUserLock = enableUserLock; } public LoginInfoDao getLoginInfoDao() { return this.loginInfoDao; } public void setLoginInfoDao(LoginInfoDao loginInfoDao) { this.loginInfoDao = loginInfoDao; } public Integer getFailLockCount() { return this.failLockCount; } public void setFailLockCount(Integer failLockCount) { this.failLockCount = failLockCount; } public Integer getUserLockTime() { return this.userLockTime; } public void setUserLockTime(Integer userLockTime) { this.userLockTime = userLockTime; } public String getReLoginUrl() { return this.reLoginUrl; } public void setReLoginUrl(String reLoginUrl) { this.reLoginUrl = reLoginUrl; } }
package net.edzard.kinetic; /** * A regular polygon. * Regular polygons are defined using a radius and a number of sides. * @author Ed */ public class RegularPolygon extends Shape { /** Protected default Ctor keeps GWT happy */ protected RegularPolygon() {} /** * Retrieve this regular polygon's radius. * @return The radius */ public final native double getRadius() /*-{ return this.getRadius(); }-*/; /** * Assign a radius. * @param radius The new radius value */ public final native void setRadius(double radius) /*-{ this.setRadius(radius); }-*/; /** * Retrieve the number of sides for this regular polygon shape. * @return The number of sides */ public final native int getSides() /*-{ return this.getSides(); }-*/; /** * Assigns a number of sides. * @param sides A new number of sides. */ public final native void setSides(int sides) /*-{ this.setSides(sides); }-*/; /** * Animate a linear transition of this regular polygon shape. * @param target Another regular polygon shape - defines the characteristics that the current regular polygon shape will have at the end of the animation * @param duration The time it will take for the animation to complete, in seconds * @return An object for controlling the transition. */ public final Transition transitionTo(RegularPolygon target, double duration) { return transitionTo(target, duration, null, null); } /** * Animate a transition of this regular polygon shape. * @param target Another regular polygon shape - defines the characteristics that the current regular polygon shape will have at the end of the animation * @param duration The time it will take for the animation to complete, in seconds * @param ease An easing function that defines how the transition will take place * @param callback A function that will be called at the end of the animation * @return An object for controlling the transition. */ public final Transition transitionTo(RegularPolygon target, double duration, EasingFunction ease, Runnable callback) { StringBuffer sb = new StringBuffer(); if (this.getRadius() != target.getRadius()) sb.append("radius:").append(target.getRadius()).append(","); if (this.getSides() != target.getSides()) sb.append("sides:").append(target.getSides()).append(","); return transitionToShape(target, sb, duration, ease, callback); } }
package com.kirer.voice.util; /** * Created by xinwb on 2016/12/16. */ public interface OnVoiceToWordListener { void onBegin(); void onSucceed(String result); void onFailed(String errorMsg); void onEnd(); }
package utilidades; import java.util.Comparator; import produto.Produto; /** * Classe comparadora de Produto. * * @author Aluno de período anterior * @author Mariane Carvalho */ public class ComparatorProduto implements Comparator<Produto> { /** * Compara dois produtos através do nome. * * @param p1 Primeiro produto. * @param p2 Segundo produto. * @return Inteiro que representa se o primeiro produto é lexicograficamente maior(>0), menor(<0) ou igual(0) ao segundo produto. */ @Override public int compare(Produto p1, Produto p2) { String nome1 = p1.getNome(); String nome2 = p2.getNome(); return nome1.compareTo(nome2); } } //Seu Olavo - Pastel de frango - Pastel de forno de frango - R$2,00 | Seu Olavo - Suco - Suco de maracuja (copo) - R$1,50 | Seu Olavo - X-burguer - Hamburguer de carne com queijo e calabresa - R$4,50 | Seu Olavo - X-burguer + refrigerante - X-burguer com refri (lata) - R$6,00 | Seu Olavo - X-burguer + suco - X-burguer com suco de maracuja - R$4,80 //Seu Olavo - Pastel de frango - Pastel de forno de frango - R$2,00 | Seu Olavo - Suco - Suco de maracuja (copo) - R$1,50 | Seu Olavo - X-burguer + refrigerante - X-burguer com refri (lata) - R$6,00 | Seu Olavo - X-burguer + suco - X-burguer com suco de maracuja - R$4,80 | Seu Olavo - X-burguer - Hamburguer de carne com queijo e calabresa - R$4,50
import java.util.ArrayList; import java.util.Scanner; import java.util.Random; import java.util.Arrays; import java.util.Stack; import java.awt.Point; import algos.ShortestPath; import Graph.BFSandDijkstra; import Graph.PRM; import utils.Results; public class Program { public static void main(String[] args) { Scanner in = new Scanner( System.in ); System.out.print("Input Largest Power Of 10: "); int max_n = in.nextInt(), n_tests = 100; Random random = new Random(); for ( int pow = 1; pow <= max_n; ++pow ) { for ( int k = 1; k < 10; ++k ) { int n_samples = ( int ) Math.pow( 10, pow ) * k; System.out.println( "Beginning Experiment Of Size: " + n_samples + "\n" ); ArrayList<Point> samples = new ArrayList<Point>(); for ( int i = 0; i < n_samples; ++i) { samples.add( new Point( random.nextInt( 100 ), random.nextInt( 100 ) ) ); } PRM prm = new PRM( samples, n_samples ); ArrayList< ArrayList<Integer> > adj_list = prm.get_adjList(); ArrayList<Point> nodes = prm.get_nodes(); Stack<Integer> s = new Stack< Integer >(); double ave_time = 0; for ( int j = 0; j < n_tests; ++j ) { double start = System.nanoTime(); s = ShortestPath.a_star( nodes, adj_list ); ave_time += ( System.nanoTime() - start ) / n_tests; } while ( !s.empty() ) { System.out.print(s.pop() + " "); } System.out.println("\n"); System.out.println( "Average Time For Size " + n_samples + ": " + ave_time + "\n" ); System.out.println( "Appending Results To Data File" ); Results.write( n_samples, ave_time, "AAA_ASS.csv", "time" ); System.out.println( "\n#################### Input Of Size " + n_samples + " DONE!!! ####################\n" ); } } System.out.println( "\n#################### All Inputs DONE!!! ####################\n" ); in.close(); } }
/* Jennifer Lennick * 0627839 * Program: Fibonacci Program * User will enter a number an the program will * print the series up until the user entered value. * */ import java.util.Scanner; import java.util.concurrent.TimeUnit; public class main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner reader = new Scanner(System.in); int userInput = 0; int fibSeries = 0; long startTime = System.nanoTime(); long endTime = System.nanoTime(); long timeElapsed = endTime- startTime; // Welcome the user System.out.println("Welcome to the Fibonacci Sequence Program"); //acquire userInput System.out.println("Please Enter a number less than 50 =>"); userInput = reader.nextInt(); reader.close(); System.out.println("UserInput=>" + userInput); //loops start at 0 for(int i = 0; i < userInput;i++ ) { fibSeries = fiboSeriesRec(i); System.out.print(fibSeries+" "); } System.out.println("\n\nElapsed time in nanoseconds is: " + timeElapsed); } // fiboSeriesRec a recursive function that calls itself public static int fiboSeriesRec(int x){ if (x == 0) return 0; else if (x == 1) return 1; else return (fiboSeriesRec(x - 1) + fiboSeriesRec(x - 2)); } //fiboSeriesIte: iterative function that uses a for loop public static int fiboSeriesIte(int x){ int fib1 = 0; for (int i = 0; i < x; i++) { } } }
package com.stk123.model.mass; import cn.hutool.core.collection.CollUtil; import com.stk123.common.CommonUtils; import com.stk123.common.util.ImageUtils; import com.stk123.common.util.ListUtils; import com.stk123.model.core.Bar; import com.stk123.model.core.Stock; import com.stk123.util.ServiceUtils; import lombok.Data; import lombok.SneakyThrows; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.reflections.ReflectionUtils; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @Data public class Mass { public static List<MassStrategy> getStrategies(){ List<MassStrategy> strategies = new ArrayList<>(); MassStrategy ms = null; ms = MassStrategy.build("000408", "20210326", 50, 2.8, "ST藏格[SZ000408]-20210326.png") .addMassFunction(1, bar -> bar.getMA(5, Bar.EnumValue.C)); strategies.add(ms); ms = MassStrategy.build("002538", "20200703", 80, 7, "司尔特[SZ002538]-20200703.png") .addMassFunction(1, bar -> bar.getMA(5, Bar.EnumValue.C)) .addMassFunction(3, Bar::getVolume); strategies.add(ms); ms = MassStrategy.build("002524", "20210412", 30, 5, "光正眼科[SZ002524]-20210412.png") .addMassFunction(1, Bar::getClose) .addMassFunction(1, Bar::getVolume, 15) .setCountOfMinDistance(5); strategies.add(ms); ms = MassStrategy.build("002524", "20210407", 20, 5, "光正眼科[SZ002524]-20210412.png") .addMassFunction(1, Bar::getClose).addMassFunction(1, Bar::getVolume); strategies.add(ms); ms = MassStrategy.build("000516", "20200703", 100, 6, "国际医学[SZ000516]-20200703.png") .addMassFunction(1, Bar::getClose).setCountOfMinDistance(5); strategies.add(ms); ms = MassStrategy.build("000516", "20200702", 50, 4.5, "国际医学[SZ000516]-20200703.png") .addMassFunction(1, Bar::getClose).addMassFunction(2, bar -> bar.getMA(60, Bar.EnumValue.C)-bar.getClose()) .addMassFunction(1, Bar::getClose, 8); strategies.add(ms); ms = MassStrategy.build("600859", "20200430", 100, 5, "王府井[SH600859]-20200430.png") .addMassFunction(1, Bar::getClose); strategies.add(ms); ms = MassStrategy.build("600958", "20200630", 100, 5, "东方证券[SH600958]-20200630.png") .addMassFunction(1, Bar::getClose).addMassFunction(1, Bar::getVolume); strategies.add(ms); ms = MassStrategy.build("600958", "20200630", 13, 1, "东方证券[SH600958]-20200630.png") .addMassFunction(1, Bar::getChange).addMassFunction(1, Bar::getVolume); strategies.add(ms); ms = MassStrategy.build("002177", "20210323", 80, 7, "御银股份[SZ002177]-20210319.png") .addMassFunction(1, Bar::getClose) .addMassFunction(1, Bar::getVolume) .addMassFunction(1, bar -> bar.getMA(120, Bar.EnumValue.C)); strategies.add(ms); ms = MassStrategy.build("002762", "20210317", 40, 5, "金发拉比[SZ002762]-20210317.png") .addMassFunction(1, Bar::getClose).addMassFunction(1, Bar::getClose, 20) .addMassFunction(1, Bar::getVolume); //.addMassFunction(1, bar -> bar.getMA(60, Bar.EnumValue.C)); strategies.add(ms); ms = MassStrategy.build("002735", "20210322", 40, 4.5, "王子新材[SZ002735]-20210322.png") .addMassFunction(1, Bar::getClose) .addMassFunction(1, Bar::getVolume); strategies.add(ms); // ms = MassStrategy.build("002172", "20210115", 60, 6, "澳洋健康[SZ002172]-20210115.png") // .addMassFunction(1, Bar::getClose) // .addMassFunction(1, Bar::getVolume); // strategies.add(ms); ms = MassStrategy.build("000807", "20210203", 30, 4.5, "云铝股份[SZ000807]-20210203.png") .addMassFunction(1, Bar::getClose) .addMassFunction(1, Bar::getVolume); strategies.add(ms); ms = MassStrategy.build("000807", "20201102", 40, 6, "云铝股份[SZ000807]-20201102.png") .addMassFunction(1, Bar::getClose) .addMassFunction(1, Bar::getVolume); strategies.add(ms); ms = MassStrategy.build("000807", "20200630", 80, 7, "云铝股份[SZ000807]-20200630.png") .addMassFunction(2, Bar::getClose) .addMassFunction(1, Bar::getVolume); strategies.add(ms); ms = MassStrategy.build("002813", "20210331", 35, 4.5, "路畅科技[SZ002813]-20210331.png") .addMassFunction(1, Bar::getClose) .addMassFunction(1, Bar::getVolume); strategies.add(ms); ms = MassStrategy.build("688068", "20210318", 40, 6, "热景生物[SH688068]-20210318.png") .addMassFunction(1, Bar::getClose).addMassFunction(1, Bar::getVolume); strategies.add(ms); ms = MassStrategy.build("002348", "20210331", 60, 7, "高乐股份[SZ002348]-20210331.png") .addMassFunction(1, Bar::getClose).addMassFunction(1, Bar::getVolume); strategies.add(ms); ms = MassStrategy.build("300253", "20200622", 15, 2.5, "卫宁健康[SZ300253]-20200622.png") .addMassFunction(1, Bar::getClose).addMassFunction(1, Bar::getHigh) .addMassFunction(1, Bar::getLow).addMassFunction(1, Bar::getOpen); strategies.add(ms); ms = MassStrategy.build("300278", "20200805", 50, 5, "华昌达[SZ300278]-20200805.png") .addMassFunction(1, Bar::getClose).addMassFunction(1, Bar::getVolume); strategies.add(ms); ms = MassStrategy.build("300283", "20200814", 50, 50, "温州宏丰[SZ300283]-20200814.png") .addMassFunction(1, Bar::getClose).addMassFunction(1, Bar::getVolume) .addMassFunction(1, bar -> bar.getMA(120, Bar.EnumValue.C)-bar.getClose()); //strategies.add(ms); ms = MassStrategy.build("300312", "20210219", 25, 3, "邦讯技术[SZ300312]-20210219.png") .addMassFunction(1, Bar::getClose).addMassFunction(1, Bar::getVolume); strategies.add(ms); ms = MassStrategy.build("300313", "20200812", 100, 6, "天山生物[SZ300313]-20200812.png") .addMassFunction(1, Bar::getClose).addMassFunction(1, Bar::getClose, 25) .addMassFunction(1, bar -> bar.getMA(120, Bar.EnumValue.C)-bar.getClose()); strategies.add(ms); return strategies; } @SneakyThrows public static MassResult execute(List<Stock> stocks){ /*Set<Field> fieldSet = ReflectionUtils.getFields(Mass.class, field -> StringUtils.startsWith(field.getName(), "a")); List<MassStrategy> strategies = new ArrayList<>(); for(Field field : fieldSet){ strategies.add((MassStrategy) field.get(null)); }*/ return Mass.execute(stocks, Mass.getStrategies().toArray(new MassStrategy[0])); } public static MassResult execute(List<Stock> stocks, MassStrategy... massStrategies){ MassResult massResult = new MassResult(); for(MassStrategy strategy : massStrategies){ List<MassStockDistance> minDistances = strategy.getMinDistances(stocks); List<MassStockDistance> listStocks = minDistances.stream().filter(massStockDistance -> massStockDistance.getDistance() <= strategy.getTargetDistance()).collect(Collectors.toList()); List<List<String>> subTable = new ArrayList<>(); for(MassStockDistance massStockDistance : listStocks){ List<String> row = ListUtils.createList(massStockDistance.getStock().getNameAndCodeWithLink()+"<br/>distance:" + massStockDistance.getDistance(), massStockDistance.getStock().getDayBarImage(), massStockDistance.getStock().getWeekBarImage()); subTable.add(row); } String table = CommonUtils.createHtmlTable(null, subTable); String imageStr = ImageUtils.getImageStr(ServiceUtils.getResourceFileAsBytes("similar_stock_image/" + strategy.getTemplateStockImage())); String imageHtml = CommonUtils.getImgBase64(imageStr, 450, 300); List<String> row = ListUtils.createList(strategy.getTemplateStock().getNameAndCodeWithLink() +"-"+strategy.getTemplateStockStartDate()+"<br/>"+ imageHtml, "", table); massResult.getDatas().add(row); massResult.count(listStocks.size()); } return massResult; } public static void main(String[] args) throws Exception { Set<Field> fieldSet = ReflectionUtils.getFields(Mass.class, field -> StringUtils.startsWith(field.getName(), "a")); System.out.println(fieldSet.size()); fieldSet.forEach(field -> { try { System.out.println(field.get(null)); } catch (IllegalAccessException e) { e.printStackTrace(); } }); } }
package net.voldrich.graal.async.api; import lombok.extern.slf4j.Slf4j; import reactor.core.publisher.Mono; import java.time.Duration; import java.util.HashMap; import java.util.Map; @Slf4j public class MockedHttpClient { private final Map<String, ScriptMockedHttpResponse> urlToResponseMap = new HashMap<>(); public void addResponse(String url, ScriptMockedHttpResponse response) { this.urlToResponseMap.put(url, response); } public Mono<ScriptMockedHttpResponse> get(String url) { ScriptMockedHttpResponse response = urlToResponseMap.get(url); if (response == null) { throw new RuntimeException("404 NOT FOUND"); } return Mono.delay(Duration.ofMillis(response.responseTimeoutMs)) .thenReturn(response) .doOnSubscribe(subscription -> log.trace("Request {} started", url)) .doOnSuccess(result -> log.trace("Request {} finished", url)); } }
package br.com.renan.model; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; import br.com.renan.model.db.DBUtil; public class DbCarDao implements CarDao { private DataSource dataSource; public DbCarDao() { this.dataSource = DBUtil.getDataSource(); } @Override public List<Car> getAll() { List<Car> cars = new ArrayList<Car>(); try { Connection conn = dataSource.getConnection(); PreparedStatement ps = conn.prepareStatement("select * from carro"); ResultSet rs = ps.executeQuery(); while (rs.next()) { Car car = new Car(); car.setId(rs.getInt(1)); car.setBrand(rs.getString("marca")); car.setModel(rs.getString("modelo")); car.setWebsite(rs.getString("website")); cars.add(car); } } catch (SQLException e) { throw new RuntimeException(e); } return cars; } @Override public Car getById(int id) { Connection conn; Car car = new Car(); try { conn = dataSource.getConnection(); PreparedStatement ps = conn .prepareStatement("select * from carro where id = ?"); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); if (rs.next()) { car.setId(rs.getInt(1)); car.setBrand(rs.getString("marca")); car.setModel(rs.getString("modelo")); car.setWebsite(rs.getString("website")); } } catch (SQLException e) { throw new RuntimeException(e); } return car; } @Override public boolean add(Car c) { Connection conn; try { conn = dataSource.getConnection(); PreparedStatement ps = conn .prepareStatement("insert into carro(marca,modelo,website) values(?,?,?)"); ps.setString(1, c.getBrand()); ps.setString(2, c.getModel()); ps.setString(3, c.getWebsite()); ps.execute(); } catch (SQLException e) { throw new RuntimeException(e); } return true; } @Override public boolean update(Car c) { Connection conn; try { conn = dataSource.getConnection(); PreparedStatement ps = conn .prepareStatement("update carro set marca = ?, modelo = ?, website = ? where id = ?"); ps.setString(1, c.getBrand()); ps.setString(2, c.getModel()); ps.setString(3, c.getWebsite()); ps.setInt(4, c.getId()); return ps.executeUpdate() > 0; } catch (SQLException e) { throw new RuntimeException(e); } } @Override public boolean delete(Car c) { Connection conn; try { conn = dataSource.getConnection(); PreparedStatement ps = conn .prepareStatement("delete from carro where id = ?"); ps.setInt(1, c.getId()); return ps.executeUpdate() > 0; } catch (SQLException e) { throw new RuntimeException(e); } } }
package controllers; import User.User; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import com.google.inject.persist.Transactional; import ninja.Context; import ninja.jpa.UnitOfWork; import ninja.session.Session; import javax.persistence.EntityManager; import javax.persistence.NonUniqueResultException; import javax.persistence.Query; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import User.Game; /** * Created by harduNel on 2015-01-16. */ public class AuthenticationControler { @Inject Provider<EntityManager> entityManagerProvider; List<String> someList = new ArrayList<String>(); int tel = 0; @Inject CryptWithMD5 cr; public boolean LoginTheUser(String Username, String Password) { boolean test = false; someList.add("Hardu*Nel"); if (Password != null) { Password = cr.cryptWithMD5(Password); } if ((Username!=null) && (Password!=null)) { for (String item : someList) { if (item.toString().compareTo(Username + "*" + Password)==0) { test = true; } List<User> us = new LinkedList<User>(); us = getIndex(); String UserNameS; String PasswordS; for (User u : us){ UserNameS = u.getUsername(); PasswordS = u.getPassword(); if (((Username.compareTo(UserNameS)==0)&&(Password.compareTo(PasswordS)==0))){ test = true; } } } } return test; } public boolean RegisterTheUser(String Username, String Password) { // Context Con; // Session Ses; // Ses = Con.getSession(); if (Password != null) { Password = cr.cryptWithMD5(Password); } boolean test = true; someList.add("Hardu*Nel"); if ((Username != null) && (Password != null)) { for (String item : someList) {//TU if (item.toString().compareTo(Username + "*" + Password)==0) { System.out.println("Bestaan Klaar"); test = false; } } } if (test == true) { User u = new User(); u.setPassword(Password); u.setUsername(Username); postIndex(u); someList.add(Username +"*"+ Password); System.out.println("Added"); } return test; } @UnitOfWork public List<User> getIndex() { EntityManager entityManager = entityManagerProvider.get(); Query q = entityManager.createQuery("SELECT x FROM User x"); if(q!=null) { List<User> guestbookEntries = (List<User>) q.getResultList(); return guestbookEntries; } return null; } @Transactional public void postIndex(User use) { //logger.info("In postRoute"); EntityManager entityManager = entityManagerProvider.get(); entityManager.persist(use); // return Results.redirect(router.getReverseRoute(ApplicationController.class, "getIndex")); } @Transactional public void postIndexGame(Game use) { //logger.info("In postRoute"); EntityManager entityManager = entityManagerProvider.get(); entityManager.persist(use); // return Results.redirect(router.getReverseRoute(ApplicationController.class, "getIndex")); } }
package com.openfarmanager.android.fragments; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.openfarmanager.android.R; import com.openfarmanager.android.utils.ParcelableWrapper; import java.io.Serializable; public abstract class EditViewDialog extends BaseDialog { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setStyle(DialogFragment.STYLE_NO_TITLE, R.style.Action_Dialog); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { getDialog().setTitle(getSafeString(R.string.app_name)); final View view = inflater.inflate(getLayout(), container, false); restoreSettings(view); view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dismiss(); } }); view.findViewById(R.id.ok).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View button) { if (getListener() != null) { saveSettings(view); dismiss(); handleAction(view); } } }); return view; } protected EditDialogListener getListener() { //noinspection unchecked return ((ParcelableWrapper<EditDialogListener>) getArguments().getParcelable("listener")).value; } protected abstract void restoreSettings(View view); protected abstract void saveSettings(View view); protected abstract int getLayout(); protected abstract void handleAction(final View view); public static interface EditDialogListener extends Serializable { public void doSearch(String pattern, boolean caseSensitive, boolean wholeWords, boolean regularExpression); public void doReplace(String pattern, String replaceTo, boolean caseSensitive, boolean wholeWords, boolean regularExpression); public void goTo(int position, int unit); } }
package com.xeland.project; public final class ClassTh { public static ClassTh createDevText(final String string) { return new ClassTh(string); } public ClassTh(final String devString) { } public static ClassTh createEAD(final String englishString, final String dutchString) { return new ClassTh(""); } }
package se.acorntechnology.volvopak; import android.app.Activity; import android.os.Bundle; import android.os.PowerManager; import android.text.Html; import android.text.Spanned; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import java.util.ArrayList; import java.util.Random; import java.util.Set; public class MainActivity extends Activity { private Random mRand = new Random(); private final String CHARADER = "Charader!"; private final String[] STRINGS = { CHARADER, CHARADER, "Tumme mäster", "Sjung", "Rimma", "Rimma", "Regel", "Saga", "Saga", "Ämne", "Ämne", }; ArrayList<String> mAssignments = new ArrayList<>(); private TextView mCounterTextView; private String mCounterText = "ingen än"; private Thread mThread; private String mCharadeText = "ingen än"; private Button mCharadeButton; public String get() { if (mAssignments.size() <= 0){ for (int i = 0; i < STRINGS.length;i++){ mAssignments.add(STRINGS[i]); } } int n = mRand.nextInt(mAssignments.size()); String assignment = mAssignments.get(n); mAssignments.remove(n); if (assignment.equals(CHARADER)){ mCharadeText = getCharade(); } else { mCharadeText = ""; } return assignment; } private final String[] CHARADES = { "Spela fotboll", "Basket", "Hockey", "giraff äter löv", "lejon", "katt leker med garn", "elefant rädd för en mus", "ko", "mus", "gorilla", "häst", "kanin", "apa", "hund", "fisk", "haj", "ambulance", "Sparka tegelstenar", "Solglasögon", "Mygga", "Sax", "Klippa gräss", "Klippa häcken", "Stjärna", "Rymdskepp", "Träd", "Flygplan", "Svans", "Basketboll", "Toalett", "Telefon", "Burk", "Trumma", "Spela gitarr", "Spela triangel", "Sköldpadda", "vingar", "Docka", "Fågel", "Spindel", "Barn", "Gris", "Krita", "Ärm", "Kanin", "Kamera", "Sten", "Kyckling", "Robot", "Dryck", "Ballong", "Känguru", "Tandborste", "Dörr", "Alligator", "Dansa", "Hoppa", "Mygga", "Polis", "Nypa", "Sova", "Sova som Pippi", "Titta på teve", "Arg mamma", "Åka skidor", "Ramla från cyckeln", "Cykla", "Åka skridskor", "Simma", "Leka med iPad", "Såga ner träd", "Häst", "Spela Matts' Hockey Spel", "Spela video spel", "Dansa runt julgran", "Bebis", "Groda", "T-Rex", "Äta en sur äpple", "Tända ljus", "Brandbil", "Brandmän", "Darth Vader", "Yoda", "Hulk", "Boxning", "Går med hunden", "Duscha", "Bada", "Vattna blommorna", "Måla", "Demonstrant", "Programmerar appar", "Astronaut", "Präst", "Spela pianot", "Paddla kanot", "Trumpet", "Fiol", "Skateboard", "Anka", "Mata ankarna", "Pirater", "Grilla", "Fiska", "Morfar", "Mormor", "Kalle spelar fotboll", "Hund", "Flygande orm", "Leopard", "Flygande ekorre", "Indominous Rex" }; public String getCharade() { int n = mRand.nextInt(CHARADES.length); return CHARADES[n]; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); mCounterTextView = (TextView) findViewById(R.id.whatToDo); final Button counterButton = (Button) findViewById(R.id.counterButton); mCharadeButton = (Button)findViewById(R.id.charadeButton); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); mRand.setSeed(System.nanoTime()); counterButton.setOnClickListener((view) -> { mCounterText = get(); mCounterTextView.setText(Html.fromHtml(mCounterText)); }); mCharadeButton.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { mCharadeText = getCharade(); return false; } }); mCharadeButton.setOnClickListener((view) -> { mCounterText = mCharadeText;//getCharade(); mCounterTextView.setText(Html.fromHtml(mCounterText)); mThread = new Thread() { @Override public void run() { for (int i = 10; (mCharadeText.length() > 0) && (this == mThread) && (i > 0); i--) { final int cnt = i; runOnUiThread(new Runnable() { @Override public void run() { mCounterTextView.setText(Html.fromHtml(mCounterText + " " + Integer.toString(cnt))); } }); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } runOnUiThread(new Runnable() { @Override public void run() { if ((mCharadeText.length() > 0)) { mCounterTextView.setText(""); } } }); } }; mThread.start(); }); } @Override protected void onResume(){ super.onResume(); } }
package hiring.service; import com.google.gson.Gson; import hiring.converter.Convert; import hiring.daointerface.DaoException; import hiring.daointerface.EmployerDaoImpl; import hiring.database.DataBaseException; import hiring.dto.DTO; import hiring.dto.ErrorDto; import hiring.dto.RegisterEmployerDtoRequest; import hiring.model.Demand; abstract public class EmployerService extends UserService { private static EmployerDaoImpl employerDao = new EmployerDaoImpl(); public static String registerEmployer(String requestJsonString) { ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); RegisterEmployerDtoRequest registerEmployerDtoRequest = gson.fromJson(requestJsonString, RegisterEmployerDtoRequest.class); if (registerEmployerDtoRequest.getFirstName() == null || registerEmployerDtoRequest.getFirstName().equals("")) { errorDto.setError("Wrong first name"); return gson.toJson(errorDto); } if (registerEmployerDtoRequest.getLastName().equals("") || registerEmployerDtoRequest.getLastName() == null) { errorDto.setError("Wrong last name"); return gson.toJson(errorDto); } if (registerEmployerDtoRequest.getPatronymic() == null) registerEmployerDtoRequest.setPatronymic("-"); if (registerEmployerDtoRequest.getEmail() == null || registerEmployerDtoRequest.getEmail().equals("") || !registerEmployerDtoRequest.getEmail().contains("@")) { errorDto.setError("Wrong email"); return gson.toJson(errorDto); } if (registerEmployerDtoRequest.getLogin() == null || registerEmployerDtoRequest.getLogin().equals("")) { errorDto.setError("Wrong login"); return gson.toJson(errorDto); } if (registerEmployerDtoRequest.getPassword().length() < 8 || registerEmployerDtoRequest.getPassword().equals("")) { errorDto.setError("The password must contain more 8 characters"); return gson.toJson(errorDto); } if (registerEmployerDtoRequest.getAddress() == null || registerEmployerDtoRequest.getAddress().equals("")) { errorDto.setError("Wrong address"); return gson.toJson(errorDto); } if (registerEmployerDtoRequest.getCompany() == null || registerEmployerDtoRequest.getCompany().equals("")) { errorDto.setError("Wrong company"); return gson.toJson(errorDto); } try { return employerDao.insert(Convert.from(registerEmployerDtoRequest)).toString(); } catch (DataBaseException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } } public static String changeFirstName(String requestJsonString) { ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); DTO dto = gson.fromJson(requestJsonString, DTO.class); if (dto.getToken() == null) { errorDto.setError("Token is null"); return gson.toJson(errorDto); } if (dto.getFirstName() == null || dto.getFirstName().equals("")) { errorDto.setError("Wrong first name"); return gson.toJson(errorDto); } try { employerDao.changeFirstName(dto.getToken(), dto.getFirstName()); } catch (DataBaseException | DaoException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } return ""; } public static String changeLastName(String requestJsonString) { //С этого начать ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); DTO dto; try { dto = gson.fromJson(requestJsonString, DTO.class);//Может быть исключение, обработать! }catch (Exception e){ errorDto.setError("Request dto error"); return gson.toJson(errorDto); } if (dto.getToken() == null) { errorDto.setError("Token is null"); return gson.toJson(errorDto); } if (dto.getLastName() == null || dto.getLastName().equals("")) { errorDto.setError("Wrong last name"); return gson.toJson(errorDto); } try { employerDao.changeLastName(dto.getToken(), dto.getLastName()); } catch (DataBaseException | DaoException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } return ""; } public static String changePatronymic(String requestJsonString) { ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); DTO dto; try { dto = gson.fromJson(requestJsonString, DTO.class);//Может быть исключение, обработать! }catch (Exception e){ errorDto.setError("Request dto error"); return gson.toJson(errorDto); } if (dto.getToken() == null) { errorDto.setError("Token is null"); return gson.toJson(errorDto); } if (dto.getPatronymic() == null || dto.getPatronymic().equals("")) { errorDto.setError("Wrong patronymic"); return gson.toJson(errorDto); } try { employerDao.changePatronymic(dto.getToken(), dto.getPatronymic()); } catch (DataBaseException | DaoException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } return ""; } public static String changeCompany(String requestJsonString) { ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); DTO dto; try { dto = gson.fromJson(requestJsonString, DTO.class);//Может быть исключение, обработать! }catch (Exception e){ errorDto.setError("Request dto error"); return gson.toJson(errorDto); } if (dto.getToken() == null) { errorDto.setError("Token is null"); return gson.toJson(errorDto); } if (dto.getCompany() == null || dto.getCompany().equals("")) { errorDto.setError("Wrong company"); return gson.toJson(errorDto); } try { employerDao.changeCompany(dto.getToken(), dto.getCompany()); } catch (DataBaseException | DaoException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } return ""; } public static String changeAddress(String requestJsonString) { ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); DTO dto; try { dto = gson.fromJson(requestJsonString, DTO.class);//Может быть исключение, обработать! }catch (Exception e){ errorDto.setError("Request dto error"); return gson.toJson(errorDto); } if (dto.getToken() == null) { errorDto.setError("Token is null"); return gson.toJson(errorDto); } if (dto.getAddress() == null || dto.getAddress().equals("")) { errorDto.setError("Wrong address"); return gson.toJson(errorDto); } try { employerDao.changeAddress(dto.getToken(), dto.getAddress()); } catch (DataBaseException | DaoException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } return ""; } public static String addVacany(String requestJsonString) { ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); DTO dto; try { dto = gson.fromJson(requestJsonString, DTO.class);//Может быть исключение, обработать! }catch (Exception e){ errorDto.setError("Request dto error"); return gson.toJson(errorDto); } if (dto.getToken() == null) { errorDto.setError("Token is null"); return gson.toJson(errorDto); } if (dto.getVacancy() == null) { errorDto.setError("Vacancy is null"); return gson.toJson(errorDto); } if (dto.getVacancy().getPosition() == null || dto.getVacancy().getPosition().equals("")) { errorDto.setError("Wrong vacancy position"); return gson.toJson(errorDto); } if (dto.getVacancy().getSalary() == null) { errorDto.setError("Vacancy salary is null"); return gson.toJson(errorDto); } int i = 1; for (Demand demand : dto.getVacancy().getDemands()) { if (demand.getName() == null || demand.getName().equals("")) { errorDto.setError(String.format("Vacancy demand %d wrong name", i)); return gson.toJson(errorDto); } if (demand.getLvl() < 1 || demand.getLvl() > 5) { errorDto.setError(String.format("Vacancy demand %d wrong lvl", i)); return gson.toJson(errorDto); } i++; } try { employerDao.insert(dto.getToken(), dto.getVacancy()); } catch (DataBaseException | DaoException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } return ""; } public static String changeVacancyPosition(String requestJsonString) { ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); DTO dto; try { dto = gson.fromJson(requestJsonString, DTO.class);//Может быть исключение, обработать! }catch (Exception e){ errorDto.setError("Request dto error"); return gson.toJson(errorDto); } if (dto.getToken() == null) { errorDto.setError("Token is null"); return gson.toJson(errorDto); } if (dto.getNumberVacancy() == null) { errorDto.setError("Vacancy number is null"); return gson.toJson(errorDto); } if (dto.getPosition() == null || dto.getPosition().equals("")) { errorDto.setError("Wrong vacancy position"); return gson.toJson(errorDto); } try { employerDao.changeVacancyPosition(dto.getToken(), dto.getNumberVacancy(), dto.getPosition()); } catch (DataBaseException | DaoException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } return ""; } public static String changeVacancySalary(String requestJsonString) { ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); DTO dto; try { dto = gson.fromJson(requestJsonString, DTO.class);//Может быть исключение, обработать! }catch (Exception e){ errorDto.setError("Request dto error"); return gson.toJson(errorDto); } if (dto.getToken() == null) { errorDto.setError("Token is null"); return gson.toJson(errorDto); } if (dto.getNumberVacancy() == null) { errorDto.setError("Vacancy number is null"); return gson.toJson(errorDto); } if (dto.getSalary() == null) { errorDto.setError("Vacancy salary is null"); return gson.toJson(errorDto); } try { employerDao.changeVacancySalary(dto.getToken(), dto.getNumberVacancy(), dto.getSalary()); } catch (DataBaseException | DaoException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } return ""; } public static String addVacancyDemands(String requestJsonString) { ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); DTO dto; try { dto = gson.fromJson(requestJsonString, DTO.class);//Может быть исключение, обработать! }catch (Exception e){ errorDto.setError("Request dto error"); return gson.toJson(errorDto); } if (dto.getToken() == null) { errorDto.setError("Token is null"); return gson.toJson(errorDto); } if (dto.getNumberVacancy() == null) { errorDto.setError("Vacancy number is null"); return gson.toJson(errorDto); } int i = 1; for (Demand demand : dto.getDemands()) { if (demand.getName() == null || demand.getName().equals("")) { errorDto.setError(String.format("Vacancy demand %d wrong name", i)); return gson.toJson(errorDto); } if (demand.getLvl() < 1 || demand.getLvl() > 5) { errorDto.setError(String.format("Vacancy demand %d wrong lvl", i)); return gson.toJson(errorDto); } i++; } try { employerDao.addVacancyDemands(dto.getToken(), dto.getNumberVacancy(), dto.getDemands()); } catch (DataBaseException | DaoException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } return ""; } public static String deleteVacancyDemand(String requestJsonString) { ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); DTO dto; try { dto = gson.fromJson(requestJsonString, DTO.class);//Может быть исключение, обработать! }catch (Exception e){ errorDto.setError("Request dto error"); return gson.toJson(errorDto); } if (dto.getToken() == null) { errorDto.setError("Token is null"); return gson.toJson(errorDto); } if (dto.getNumberVacancy() == null) { errorDto.setError("Vacancy number is null"); return gson.toJson(errorDto); } if (dto.getNumberDemand() == null) { errorDto.setError("Vacancy number demand is null"); return gson.toJson(errorDto); } try { employerDao.deleteVacancyDemand(dto.getToken(), dto.getNumberVacancy(), dto.getNumberDemand()); } catch (DataBaseException | DaoException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } return ""; } public static String changeVacancyDemandName(String requestJsonString) { ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); DTO dto; try { dto = gson.fromJson(requestJsonString, DTO.class);//Может быть исключение, обработать! }catch (Exception e){ errorDto.setError("Request dto error"); return gson.toJson(errorDto); } if (dto.getToken() == null) { errorDto.setError("Token is null"); return gson.toJson(errorDto); } if (dto.getNumberVacancy() == null) { errorDto.setError("Vacancy number is null"); return gson.toJson(errorDto); } if (dto.getNumberDemand() == null) { errorDto.setError("Vacancy number demand is null"); return gson.toJson(errorDto); } if (dto.getName() == null || dto.getName().equals("")) { errorDto.setError("Wrong demand name"); return gson.toJson(errorDto); } try { employerDao.changeVacancyDemandName(dto.getToken(), dto.getNumberVacancy(), dto.getNumberDemand(), dto.getName()); } catch (DataBaseException | DaoException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } return ""; } public static String changeVacancyDemandLvl(String requestJsonString) { ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); DTO dto; try { dto = gson.fromJson(requestJsonString, DTO.class);//Может быть исключение, обработать! }catch (Exception e){ errorDto.setError("Request dto error"); return gson.toJson(errorDto); } if (dto.getToken() == null) { errorDto.setError("Token is null"); return gson.toJson(errorDto); } if (dto.getNumberVacancy() == null) { errorDto.setError("Vacancy number is null"); return gson.toJson(errorDto); } if (dto.getNumberDemand() == null) { errorDto.setError("Vacancy number demand is null"); return gson.toJson(errorDto); } if (dto.getLvl() == null || dto.getLvl() < 1 || dto.getLvl() > 5) { errorDto.setError("Wrong lvl demand"); return gson.toJson(errorDto); } try { employerDao.changeVacancyDemandLvl(dto.getToken(), dto.getNumberVacancy(), dto.getNumberDemand(), dto.getLvl()); } catch (DataBaseException | DaoException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } return ""; } public static String changeVacancyDemandNecessarily(String requestJsonString) { ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); DTO dto; try { dto = gson.fromJson(requestJsonString, DTO.class);//Может быть исключение, обработать! }catch (Exception e){ errorDto.setError("Request dto error"); return gson.toJson(errorDto); } if (dto.getToken() == null) { errorDto.setError("Token is null"); return gson.toJson(errorDto); } if (dto.getNumberVacancy() == null) { errorDto.setError("Vacancy number is null"); return gson.toJson(errorDto); } if (dto.getNumberDemand() == null) { errorDto.setError("Vacancy number demand is null"); return gson.toJson(errorDto); } try { employerDao.changeVacancyDemandNecessarily(dto.getToken(), dto.getNumberVacancy(), dto.getNumberDemand(), dto.isNecessarily()); } catch (DataBaseException | DaoException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } return ""; } public static String getVacancies(String requestJsonString) { ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); DTO dto; try { dto = gson.fromJson(requestJsonString, DTO.class);//Может быть исключение, обработать! }catch (Exception e){ errorDto.setError("Request dto error"); return gson.toJson(errorDto); } if (dto.getToken() == null) { errorDto.setError("Token is null"); return gson.toJson(errorDto); } try { return gson.toJson(employerDao.getVacancies(dto.getToken())); } catch (DataBaseException | DaoException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } } public static String getVacanciesWithActive(String requestJsonString) { ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); DTO dto; try { dto = gson.fromJson(requestJsonString, DTO.class);//Может быть исключение, обработать! }catch (Exception e){ errorDto.setError("Request dto error"); return gson.toJson(errorDto); } if (dto.getToken() == null) { errorDto.setError("Token is null"); return gson.toJson(errorDto); } try { return gson.toJson(employerDao.getVacanciesWithActive(dto.getToken(), dto.isActive())); } catch (DataBaseException | DaoException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } } public static String setActiveVacancy(String requestJsonString) { ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); DTO dto; try { dto = gson.fromJson(requestJsonString, DTO.class);//Может быть исключение, обработать! }catch (Exception e){ errorDto.setError("Request dto error"); return gson.toJson(errorDto); } if (dto.getToken() == null) { errorDto.setError("Token is null"); return gson.toJson(errorDto); } if (dto.getNumberVacancy() == null) { errorDto.setError("Vacancy number is null"); return gson.toJson(errorDto); } try { employerDao.setActiveVacancy(dto.getToken(), dto.getNumberVacancy(), dto.isActive()); } catch (DataBaseException | DaoException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } return ""; } public static String deleteVacancy(String requestJsonString) { ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); DTO dto; try { dto = gson.fromJson(requestJsonString, DTO.class);//Может быть исключение, обработать! }catch (Exception e){ errorDto.setError("Request dto error"); return gson.toJson(errorDto); } if (dto.getToken() == null) { errorDto.setError("Token is null"); return gson.toJson(errorDto); } if (dto.getNumberVacancy() == null) { errorDto.setError("Vacancy number is null"); return gson.toJson(errorDto); } try { employerDao.deleteVacancy(dto.getToken(), dto.getNumberVacancy()); } catch (DataBaseException | DaoException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } return ""; } public static String getEmployeesHaveAllSkillsDemandedLvl(String requestJsonString) { ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); DTO dto; try { dto = gson.fromJson(requestJsonString, DTO.class);//Может быть исключение, обработать! }catch (Exception e){ errorDto.setError("Request dto error"); return gson.toJson(errorDto); } if (dto.getToken() == null) { errorDto.setError("Token is null"); return gson.toJson(errorDto); } if (dto.getNumberVacancy() == null) { errorDto.setError("Vacancy number is null"); return gson.toJson(errorDto); } try { employerDao.getEmployeesHaveAllSkillsDemandedLvl(dto.getToken(), dto.getNumberVacancy()); } catch (DataBaseException | DaoException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } return ""; } public static String getEmployeesHaveAllNecessarySkillsDemandedLvl(String requestJsonString) { ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); DTO dto; try { dto = gson.fromJson(requestJsonString, DTO.class);//Может быть исключение, обработать! }catch (Exception e){ errorDto.setError("Request dto error"); return gson.toJson(errorDto); } if (dto.getToken() == null) { errorDto.setError("Token is null"); return gson.toJson(errorDto); } if (dto.getNumberVacancy() == null) { errorDto.setError("Vacancy number is null"); return gson.toJson(errorDto); } try { employerDao.getEmployeesHaveAllNecessarySkillsDemandedLvl(dto.getToken(), dto.getNumberVacancy()); } catch (DataBaseException | DaoException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } return ""; } public static String getEmployeesHaveAllSkills(String requestJsonString) { ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); DTO dto; try { dto = gson.fromJson(requestJsonString, DTO.class);//Может быть исключение, обработать! }catch (Exception e){ errorDto.setError("Request dto error"); return gson.toJson(errorDto); } if (dto.getToken() == null) { errorDto.setError("Token is null"); return gson.toJson(errorDto); } if (dto.getNumberVacancy() == null) { errorDto.setError("Vacancy number is null"); return gson.toJson(errorDto); } try { employerDao.getEmployeesHaveAllSkills(dto.getToken(), dto.getNumberVacancy()); } catch (DataBaseException | DaoException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } return ""; } public static String getEmployeesWithOneSuitableSkillDemandedLvl(String requestJsonString) { ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); DTO dto; try { dto = gson.fromJson(requestJsonString, DTO.class);//Может быть исключение, обработать! }catch (Exception e){ errorDto.setError("Request dto error"); return gson.toJson(errorDto); } if (dto.getToken() == null) { errorDto.setError("Token is null"); return gson.toJson(errorDto); } if (dto.getNumberVacancy() == null) { errorDto.setError("Vacancy number is null"); return gson.toJson(errorDto); } try { employerDao.getEmployeesWithOneSuitableSkillDemandedLvl(dto.getToken(), dto.getNumberVacancy()); } catch (DataBaseException | DaoException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } return ""; } public static String recruit(String requestJsonString) { ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); DTO dto; try { dto = gson.fromJson(requestJsonString, DTO.class);//Может быть исключение, обработать! }catch (Exception e){ errorDto.setError("Request dto error"); return gson.toJson(errorDto); } if (dto.getToken() == null) { errorDto.setError("Token is null"); return gson.toJson(errorDto); } if (dto.getNumberVacancy() == null) { errorDto.setError("Vacancy number is null"); return gson.toJson(errorDto); } if (dto.getLogin().equals("") || dto.getLogin() == null) { errorDto.setError("Wrong login format"); return gson.toJson(errorDto); } try { employerDao.recruit(dto.getToken(), dto.getNumberVacancy(),dto.getLogin()); } catch (DataBaseException | DaoException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } return ""; } public static String getEmployer(String requestJsonString){ ErrorDto errorDto = new ErrorDto(); Gson gson = new Gson(); DTO dto; try { dto = gson.fromJson(requestJsonString, DTO.class);//Может быть исключение, обработать! }catch (Exception e){ errorDto.setError("Request dto error"); return gson.toJson(errorDto); } if (dto.getToken() == null) { errorDto.setError("Token is null"); return gson.toJson(errorDto); } try { return gson.toJson(employerDao.getEmployer(dto.getToken())); } catch (DataBaseException | DaoException e) { errorDto.setError(e.getMessage()); return gson.toJson(errorDto); } } }
public class CheckConsonants { public static void main(String[] args) { String s = "This Is1to $% check Consonents"; CheckCharacterType(s); } private static void CheckCharacterType(String s) { int consonants= 0; int vowels=0; int digit=0; int spaces=0; int specialChar=0; for(int i=0;i<s.length();i++) { s = s.toLowerCase(); char ch = s.charAt(i); if(ch =='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u') { vowels++; } else if (( ch >= 'a' && ch <='z') || (ch >= 'A' && ch <='Z')) { consonants++; } else if(ch >='0' && ch <='9') { digit++; } else if (ch == ' ') { spaces++; }else specialChar++; } System.out.println("Number of Characters in the String "+s+"are::" +s.length()); System.out.println("Number of vowels::"+vowels); System.out.println("Number of consonants::"+consonants); System.out.println("Number of digit::"+digit); System.out.println("Number of spaces::"+spaces); System.out.println("Number of specialChar::"+specialChar); } }
package com.example.demo.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import lombok.Data; import java.io.Serializable; import java.math.BigDecimal; import java.time.LocalDateTime; /** * RentDetail * * @author ZhangJP * @date 2020/10/26 */ @Data public class RentDetail implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Integer id; @TableField("dept_id") private String deptId; @TableField("dept_name") private String deptName; @TableField("team_id") private String teamId; @TableField("team_name") private String teamName; @TableField("year") private Integer year; @TableField("month") private Integer month; @TableField("rent") private BigDecimal rent; @TableField("create_time") private LocalDateTime createTime; }
package com.example.cameraplay; import android.Manifest; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.location.Location; import android.os.Bundle; import android.os.Looper; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.RadioGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.fragment.app.FragmentActivity; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationCallback; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationResult; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; private GoogleMap mMap; //private final LatLng Cebanc = new LatLng(43.304953, -2.016847); private final LatLng Cebanc = new LatLng(4, 15); private TextView mTxtLongitud; private TextView mTxtLatitud; private Button mbtnMyPosition; //Para conseguir la ubicación actualizada: private FusedLocationProviderClient mFusedLocationClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.maps_layout); mbtnMyPosition = findViewById(R.id.btnMyPosition); mTxtLongitud = findViewById(R.id.textLongitud); mTxtLatitud = findViewById(R.id.textLatitud); mFusedLocationClient = LocationServices.getFusedLocationProviderClient(MapsActivity.this); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // Add a marker in Sydney and move the camera RadioGroup rgViews = findViewById(R.id.rg_views); mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(Cebanc, 15)); //mMap.moveCamera(CameraUpdateFactory.newLatLng(Cebanc)); mMap.addMarker(new MarkerOptions() .position(Cebanc) .title("Cebanc") .snippet("San Sebastián") .icon(BitmapDescriptorFactory .fromResource(android.R.drawable.ic_menu_compass)) .anchor(0.5f, 0.5f)); rgViews.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if(checkedId == R.id.rb_normal){ mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); }else if(checkedId == R.id.rb_satellite){ mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE); }else if(checkedId == R.id.rb_terrain){ mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN); } } }); mbtnMyPosition.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Tenemos que avisar al usuario y que nos de permiso para ubicarle checkLocationPermission(); } }); } public boolean checkLocationPermission() { //La primera vez, entrara por los dos ifs: if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Show an explanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. new AlertDialog.Builder(this) .setTitle("Permiso de ubicación") .setMessage("Das permiso para localizar tu posición") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //Prompt the user once explanation has been shown ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); } }) .create() .show(); } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); } return false; } else { //Ya nos habia concedido el permiso getLocalizacion(); return true; } } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_LOCATION: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the // location-related task you need to do. if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { //Request location updates: //locationManager.requestLocationUpdates(provider, 400, 1, this); getLocalizacion(); } } else { // permission denied, boo! Disable the // functionality that depends on this permission. } return; } } } private LocationCallback mLocationCallback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult) { Location mLastLocation = locationResult.getLastLocation(); Log.e("MapsActivity","getCurrLoc: Lat:"+mLastLocation.getLatitude()+ " Long: "+mLastLocation.getLongitude()); // Add a marker in myLocation and move the camera marcarUbicacion(new LatLng(mLastLocation.getLatitude() , mLastLocation.getLongitude() )); } }; private void requestNewLocationData(){ LocationRequest mLocationRequest = new LocationRequest(); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); mLocationRequest.setInterval(0); mLocationRequest.setFastestInterval(0); mLocationRequest.setNumUpdates(1); mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this); mFusedLocationClient.requestLocationUpdates( mLocationRequest, mLocationCallback, Looper.myLooper() ); } private void getLocalizacion() { mFusedLocationClient.getLastLocation().addOnCompleteListener( new OnCompleteListener<Location>() { @Override public void onComplete(@NonNull Task<Location> task) { Location location = task.getResult(); if (location == null) { requestNewLocationData(); } else { Log.e("MapsActivity","getCurrLoc: Lat:"+location.getLatitude()+ " Long: " + location.getLongitude()); mTxtLongitud.setText("" + location.getLongitude()); mTxtLatitud.setText("" + location.getLatitude()); // Add a marker in myLocation and move the camera marcarUbicacion(new LatLng(location.getLatitude() , location.getLongitude() )); } } } ); } private void marcarUbicacion(LatLng myLocation) { mMap.addMarker(new MarkerOptions() .position(myLocation) .title("Mi posición") .icon(BitmapDescriptorFactory .fromResource(android.R.drawable.ic_menu_compass)) .anchor(0.5f, 0.5f)); //mMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation )); //zoom to position with level 15 CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(myLocation , 15); mMap.animateCamera(cameraUpdate); } } //http://wptrafficanalyzer.in/blog/google-map-android-api-v2-switching-between-normal-view-satellite-view-and-terrain-view/
package com; import model.Customer; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.parser.Parser; import com.google.gson.JsonObject; import com.google.gson.JsonParser; //For REST Service import javax.ws.rs.*; import javax.ws.rs.core.MediaType; //For JSON import com.google.gson.*; //For XML import org.jsoup.*; import org.jsoup.parser.*; import org.jsoup.nodes.Document; @Path("/Customers") public class CustomerService { Customer customerObj = new Customer(); @GET @Path("/") @Produces(MediaType.TEXT_HTML) public String readCustomer() { return customerObj.readCustomer(); } @POST @Path("/") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_PLAIN) public String insertCustomer( @FormParam("customer_name") String customer_name, @FormParam("email") String email, @FormParam("phone_number") String phone_number, @FormParam("country") String country) { String output = customerObj.insertCustomer(customer_name, email, phone_number, country ); return output; } @PUT @Path("/") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.TEXT_PLAIN) public String updateCustomer(String customerData) { //Convert the input string to a JSON object JsonObject customerObject = new JsonParser().parse(customerData).getAsJsonObject(); //Read the values from the JSON object String customer_id = customerObject.get("customer_id").getAsString(); String customer_name = customerObject.get("customer_name").getAsString(); String email = customerObject.get("email").getAsString(); String phone_number = customerObject.get("phone_number").getAsString(); String country = customerObject.get("country").getAsString(); String output = customerObj.updateCustomer(customer_id, customer_name, email, phone_number, country); return output; } @DELETE @Path("/") @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.TEXT_PLAIN) public String deleteCustomer(String customerData) { //Convert the input string to an XML document Document doc = Jsoup.parse(customerData, "", Parser.xmlParser()); //Read the value from the element <Researcher_ID> String customer_id = doc.select("customer_id").text(); String output = customerObj.deleteCustomer(customer_id); return output; } }
package com.imooc.aop.demo6; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; /** * @Author: Asher Huang * @Date: 2019-10-21 * @Description: com.imooc.aop.demo4 * @Version:1.0 */ public class MyAroundAdvice implements MethodInterceptor { public Object invoke(MethodInvocation methodInvocation) throws Throwable { System.out.println("环绕前增强...."); Object object= methodInvocation.proceed(); System.out.println("环绕后增强...."); return object; } }
public class circle extends shape { protected double radius; public circle(double radius) { this.radius = radius; } public double getRadius() { return radius; } public void setRadius(double radius) { this.radius = radius; } @Override public double area() { return Math.PI*Math.pow(radius, 2); } @Override public double volume() { return (4/3)*Math.PI*Math.pow(radius, 3); } @Override public double pC() { return 2* Math.PI*radius; } public String toString() { return "radius : " + radius + "\n"+ "circumfernce : "+ pC() + " volume : " + volume() +"\n"+ " area : "+ area(); } }
package com.nfschina.aiot.adapter; import java.util.ArrayList; import java.util.List; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; /** * 自定义的viewpager适配器,主要是适配fragment list * @author wujian * */ public class MyViewPagerAdapter extends FragmentStatePagerAdapter { private List<Fragment> fragments = new ArrayList<Fragment>(); public MyViewPagerAdapter(FragmentManager fm) { super(fm); } public MyViewPagerAdapter(FragmentManager fragmentManager, List<Fragment> fragments) { super(fragmentManager); this.fragments = fragments; } /* * 返回当前位置的数据 */ @Override public Fragment getItem(int position) { return fragments.get(position); } /* * 获取列表中数据个数 */ @Override public int getCount() { return fragments.size(); } }
/** * Author: Dustin Mao */ package com.mfg; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class InterviewApplication { public static void main(String[] args) { System.out.println("Before SpringApplication.run"); SpringApplication.run(InterviewApplication.class, args); System.out.println("After SpringApplication.run"); } }
package org.dreamer.expression.calc; import java.util.ArrayList; import java.util.HashMap; import java.text.ParseException; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.ParsePosition; /** * Class that detects token type from token value. */ public class TypedTokenParser { // Internal state of the parser. private enum ParserState { EMPTY, OPEN_BRACKET, CLOSE_BRACKET, OPERATOR, VALUE, FUNC }; public TypedTokenParser() { // Define all known tokens like operators and constants. _operatorsAndConstants = new HashMap<String, TypedToken.Type>(); _operatorsAndConstants.put("(", TypedToken.Type.OPEN_BRACKET); _operatorsAndConstants.put(")", TypedToken.Type.CLOSE_BRACKET); _operatorsAndConstants.put("+", TypedToken.Type.OP_ADD); _operatorsAndConstants.put("-", TypedToken.Type.OP_SUB); _operatorsAndConstants.put("*", TypedToken.Type.OP_MUL); _operatorsAndConstants.put("/", TypedToken.Type.OP_DIV); _operatorsAndConstants.put("E", TypedToken.Type.CONST); _operatorsAndConstants.put("PI", TypedToken.Type.CONST); // Starting with empty state. _lastState = ParserState.EMPTY; } public ArrayList<TypedToken> parse(Iterable<Token> tokens) throws ParserException { ArrayList<TypedToken> result = new ArrayList<TypedToken>(); // Process all tokens. for (Token token : tokens) result.add(parseToken(token)); // Check our state at the end. finishParsing(); return result; } private TypedToken parseToken(Token token) throws ParserException { final TypedToken.Type type = parseTokenType(token); final TypedToken result = new TypedToken(token, type); // Check expression syntax. promoteParserState(result); return result; } public TypedToken.Type parseTokenType(Token token) throws ParserException { final String tokenValue = token.getValue(); if (_operatorsAndConstants.containsKey(tokenValue)) return _operatorsAndConstants.get(tokenValue); if (checkOnlyLiterals(tokenValue)) return TypedToken.Type.FUNC; // It can be only a number, so check that. try { if (null == parseNumber(tokenValue)) throw ExceptionsHelper.parseNumberError(token); } catch (ParseException e) { throw ExceptionsHelper.parseNumberError(token); } return TypedToken.Type.VALUE; } private static Number parseNumber(String input) throws ParseException { DecimalFormat df = new DecimalFormat(); DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setDecimalSeparator('.'); df.setDecimalFormatSymbols(symbols); ParsePosition parsePosition = new ParsePosition(0); final Number result = df.parse(input, parsePosition); if (parsePosition.getIndex() != input.length()) { throw new ParseException("Invalid input", parsePosition.getIndex()); } return result; } private static boolean checkOnlyLiterals(String token) { for (int i = 0; i < token.length(); ++i) if (!Character.isLetter(token.charAt(i))) return false; return true; } // Here we check the order of tokens. private void promoteParserState(TypedToken token) throws ParserException { ParserState newState = ParserState.EMPTY; switch (token.getType()) { case OPEN_BRACKET: newState = ParserState.OPEN_BRACKET; break; case CLOSE_BRACKET: newState = ParserState.CLOSE_BRACKET; break; case CONST: case VALUE: newState = ParserState.VALUE; break; case OP_ADD: case OP_SUB: case OP_MUL: case OP_DIV: newState = ParserState.OPERATOR; break; case FUNC: newState = ParserState.FUNC; break; } if (newState == ParserState.EMPTY) throw ExceptionsHelper.invalidToken(token); switch (_lastState) { case EMPTY: case OPERATOR: // First token right after start or after operator should be // '(', number/constant or function name. if (newState != ParserState.OPEN_BRACKET && newState != ParserState.VALUE && newState != ParserState.FUNC) throw ExceptionsHelper.invalidSyntax(_lastState.toString(), newState.toString(), token); break; case OPEN_BRACKET: // After '(' there should be a number, one more '(' or function name. if (newState != ParserState.VALUE && newState != ParserState.OPEN_BRACKET && newState != ParserState.FUNC) throw ExceptionsHelper.invalidSyntax(_lastState.toString(), newState.toString(), token); break; case CLOSE_BRACKET: case VALUE: // After number or constant there should be operator or ')'. if (newState != ParserState.OPERATOR && newState != ParserState.CLOSE_BRACKET) throw ExceptionsHelper.invalidSyntax(_lastState.toString(), newState.toString(), token); break; case FUNC: // And only '(' should follow after function name. if (newState != ParserState.OPEN_BRACKET) throw ExceptionsHelper.invalidSyntax(_lastState.toString(), newState.toString(), token); break; } _lastState = newState; } private void finishParsing() throws ParserException { // Check that expression ends with ')' or number/constant. switch (_lastState) { case CLOSE_BRACKET: case VALUE: _lastState = ParserState.EMPTY; return; } throw ExceptionsHelper.invalidSyntaxAtEnd(_lastState.toString()); } private HashMap<String, TypedToken.Type> _operatorsAndConstants; private ParserState _lastState; }
/*----------------------------------------------------------------------------- CS 211 01/20/2015 Kathryn Brusewitz Class: Item Super Class: Object Implements: None Item holds an items name and price. Includes a bulk price. Public Interface ------------------------------------------------------------ Item(String, double) Initializing Constructor: name, price Item(String, double, int, double) Initializing Constructor: name, price, bulkQuanity, bulkPrice boolean equals(Object) Test this with other class object for equality String toString() RETurns "String" description of this item double priceFor(int) RETurns the price for a given quantity of item Private Methods ------------------------------------------------------------- non-static String name Name of this item non-static double price Regular price of this item non-static double bulkPrice Price per bulk quantity non-static int bulkQuantity Quantity that qualifies for bulk price ------------------------------------------------------------------------------*/ public class Item { public Item(String name, double price) { if (price < 0.0) throw new IllegalArgumentException(); this.name = name; this.price = price; bulkQuantity = 1; bulkPrice = price; } public Item(String name, double price, int bulkQuantity, double bulkPrice) { if (price < 0.0 || bulkQuantity < 1 || bulkPrice < 0.0) throw new IllegalArgumentException(); this.name = name; this.price = price; this.bulkQuantity = bulkQuantity; this.bulkPrice = bulkPrice; } @Override public boolean equals(Object object) { if (object instanceof Item) { Item other = (Item) object; return name == other.name && price == other.price && bulkQuantity == other.bulkQuantity && bulkPrice == other.bulkPrice; } else return false; } @Override public String toString() { String s = String.format("%s @ %.2f", name, price); if (bulkQuantity > 1) s += String.format(" (%d for %.2f)", bulkQuantity, bulkPrice); return s; } public double priceFor(int quantity) { if (quantity < 0) throw new IllegalArgumentException(); int remainder = quantity % bulkQuantity; double total = bulkPrice * ((quantity - remainder) / bulkQuantity); return total += remainder * price; } private String name; private double price, bulkPrice; private int bulkQuantity; }
package algorithms.strings.compression.transform; import java.util.ArrayList; import java.util.List; import lombok.Getter; import lombok.Setter; @Getter @Setter public class MoveToFront { public List<Integer> encode(String string, String alphabet) { StringBuilder stringBuilder = new StringBuilder(alphabet); List<Integer> result = new ArrayList<>(); for (int i = 0; i < string.length(); i++) { char ch = string.charAt(i); int index = stringBuilder.indexOf(String.valueOf(ch)); result.add(index); stringBuilder.deleteCharAt(index).insert(0, ch); } return result; } public String decode(List<Integer> encodedList, String alphabet) { StringBuilder result = new StringBuilder(); StringBuilder sb = new StringBuilder(alphabet); for (Integer index : encodedList) { String ch = String.valueOf(sb.charAt(index)); result.append(ch); if (index != 0) { sb.deleteCharAt(index).insert(0, ch); } } return result.toString(); } }
package com.Exception; import java.io.FileNotFoundException; import java.io.IOException; public class ExceptionHandling { public static void main(String[]args)throws FileNotFoundException,IOException { try { testException(-5); testException(-10); } catch(FileNotFoundException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } finally { System.out.println("Rleasing resource"); } testException(16); } public static void testException(int i)throws FileNotFoundException,IOException { if(i < 0) { FileNotFoundException myexception = new FileNotFoundException("Negative Integer"+i); throw myexception; } else if(i>10) { throw new IOException("only supported for index 1 to 10"); } } }
package Lithe_Data; /** * Created by Timothy on 9/2/2015. */ public class Board { }
package com.allmsi.plugin.flow.service; import java.util.List; import com.allmsi.plugin.flow.model.ivo.FlowRouteIVo; import com.allmsi.plugin.flow.model.ovo.FlowRouteOVo; public interface FlowRouteService { List<FlowRouteOVo> selectRouteList(String flowId); FlowRouteOVo selectRouteInfo(String id); String addFlowRoute(FlowRouteIVo flowRouteIVo); String updateFlowRoute(FlowRouteIVo flowRouteIVo); boolean delFlowRoute(String id, String uUserId); List<FlowRouteOVo> selectRouteListByPreNode(String flowId, String preNode); }
package com.community.yuequ.gui; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.community.yuequ.R; import com.community.yuequ.gui.adapter.PayListAdapter; import com.community.yuequ.imple.OrderTipsOneListener; import com.community.yuequ.imple.OrderTipsTowListener; import com.community.yuequ.modle.OrderTip; import com.community.yuequ.pay.SPUtils; import com.community.yuequ.view.TitleBarLayout; import java.util.ArrayList; public class PayListActivity extends AppCompatActivity implements View.OnClickListener,OrderTipsOneListener,OrderTipsTowListener{ private TitleBarLayout mTitleBarLayout; private RecyclerView mRecyclerView; private LinearLayoutManager mLayoutManager; private PayListAdapter mListAdapter; private ArrayList<OrderTip> mOrderTips; private int programId; SPUtils mSmsPayUtils; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pay_list); mSmsPayUtils = new SPUtils(this); mOrderTips = getIntent().getParcelableArrayListExtra("ordertips"); programId = getIntent().getIntExtra("programId",0); mTitleBarLayout = new TitleBarLayout(this) .setText("购买") .setLeftButtonVisibility(true) .setLeftButtonClickListener(this); mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView); mLayoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(mLayoutManager); mListAdapter = new PayListAdapter(this,mOrderTips,mSmsPayUtils); mRecyclerView.setAdapter(mListAdapter); } public int getProgramId(){ return programId; } @Override public void onClick(View v) { switch (v.getId()){ case R.id.btn_back: finish(); break; default: break; } } @Override public void one_confirm(int programId,OrderTip orderTip) { mSmsPayUtils.showConfirmOrderTips(programId,orderTip); } @Override public void one_cancel(int programId,OrderTip orderTip) { } @Override public void tow_confirm(int programId,OrderTip orderTip) { mSmsPayUtils.sendSms(programId,orderTip); } @Override public void tow_cancel(int programId,OrderTip orderTip) { } }
package com.gaoshin.onsaleflyer.service; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import com.gaoshin.onsaleflyer.beans.UserAsset; public interface AssetService { void upload(String userId, UserAsset ua, InputStream uploadedInputStream) throws IOException; void rename(String userId, UserAsset ua, String newName) throws IOException; void remove(String userId, UserAsset ua); void get(String userId, UserAsset ua, OutputStream outputStream) throws IOException; }
package com.auro.scholr.teacher.presentation.view.fragment; import android.content.pm.ActivityInfo; import android.os.Bundle; import androidx.databinding.DataBindingUtil; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProviders; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.auro.scholr.R; import com.auro.scholr.core.application.AuroApp; import com.auro.scholr.core.application.base_component.BaseFragment; import com.auro.scholr.core.application.di.component.ViewModelFactory; import com.auro.scholr.databinding.FragmentTeacherSaveDetailBinding; import com.auro.scholr.teacher.presentation.viewmodel.TeacherKycViewModel; import com.auro.scholr.teacher.presentation.viewmodel.TeacherSaveDetailViewModel; import javax.inject.Inject; import javax.inject.Named; /** * A simple {@link Fragment} subclass. * Use the {@link TeacherSaveDetailFragment#newInstance} factory method to * create an instance of this fragment. */ public class TeacherSaveDetailFragment extends BaseFragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; @Inject @Named("TeacherSaveDetailFragment") ViewModelFactory viewModelFactory; boolean isStateRestore; TeacherSaveDetailViewModel teacherSaveDetailViewModel; FragmentTeacherSaveDetailBinding binding; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; public TeacherSaveDetailFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment TeacherSaveDetailFragment. */ // TODO: Rename and change types and number of parameters public static TeacherSaveDetailFragment newInstance(String param1, String param2) { TeacherSaveDetailFragment fragment = new TeacherSaveDetailFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment // return inflater.inflate(R.layout.fragment_teacher_save_detail, container, false); if (binding != null) { isStateRestore = true; return binding.getRoot(); } binding = DataBindingUtil.inflate(inflater, getLayout(), container, false); AuroApp.getAppComponent().doInjection(this); AuroApp.getAppContext().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); teacherSaveDetailViewModel = ViewModelProviders.of(this, viewModelFactory).get(TeacherSaveDetailViewModel.class); binding.setLifecycleOwner(this); binding.setTeacherSaveDetailViewModel(teacherSaveDetailViewModel); setRetainInstance(true); return binding.getRoot(); } @Override protected void init() { binding.headerParent.cambridgeHeading.setVisibility(View.GONE); } @Override protected void setToolbar() { } @Override protected void setListener() { } @Override protected int getLayout() { return R.layout.fragment_teacher_save_detail; } }
package mekfarm.client; import mekfarm.common.BlocksRegistry; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; /** * Created by CF on 2016-10-26. */ final class BlockRendererRegistry { @SideOnly(Side.CLIENT) static void registerBlockRenderers() { BlocksRegistry.animalFarmBlock.registerRenderer(); BlocksRegistry.animalReleaserBlock.registerRenderer(); BlocksRegistry.electricButcherBlock.registerRenderer(); BlocksRegistry.cropFarmBlock.registerRenderer(); BlocksRegistry.cropClonerBlock.registerRenderer(); } }
package entityData; public class Enemies { }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mycompany.helloworldapp; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; /** * * @author quan */ public class PersonFilter { public static List<Person> filterByPredicate(List<Person> persons, Predicate<Person> predicate) { List<Person> filteredPersons = new ArrayList<>(); for (Person person: persons) { if (predicate.test(person)) { filteredPersons.add(person); } } return filteredPersons; } }
package personalassistant; import Trader.AgentData; import buying.BuyerInputGui; import wholesalemarket_LMP.Wholesale_InputData; import jade.core.AID; import jade.core.Agent; import jade.core.behaviours.CyclicBehaviour; import jade.lang.acl.ACLMessage; import jade.lang.acl.MessageTemplate; import jade.wrapper.AgentController; import jade.wrapper.PlatformController; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.BorderFactory; import javax.swing.DefaultListModel; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.border.BevelBorder; import javax.swing.border.Border; import javax.swing.border.EtchedBorder; import javax.swing.plaf.basic.BasicArrowButton; import market.panel.DR; import market.panel.deadline; import market.panel.protocol; import market.panel.rbuyer; import market.panel.rseller; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFDataFormat; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; import scheduling.EnterGENCO; import tools.TimeChooser; public class PersonalAssistant extends Agent { private Bilateral_ContractType_Form contractTypeForm; Bilateral_NegotiationOption negotiationForm; private HashMap<String, ArrayList<String>> beliefs_about_others = new HashMap(); private ArrayList<String> beliefs_about_myagent = new ArrayList<>(); private String[] contract_list = {"Forward Contract", "Contract For Difference", "Option Contract"}; private String[] protocol_list = {"Alternating Offers"}; public String agent_type = ""; public ArrayList<AID> seller_names = new ArrayList<>(); public ArrayList<AID> buyer_names = new ArrayList<>(); public ArrayList<AID> producer_names = new ArrayList<>(); public ArrayList<AID> largeConsumer_names = new ArrayList<>(); public ArrayList<AID> mediumConsumer_names = new ArrayList<>(); private AID MarketOperator = new AID("MarketOperator", AID.ISLOCALNAME); public PersonalAssistantGUI mo_gui; private AID[] new_pair; public BuyerInputGui buy_gui; private ArrayList<AID[]> negotiation_pairs = new ArrayList<>(); private HashMap<AID, ArrayList<ArrayList<ACLMessage>>> message_history = new HashMap<>(); private HashMap<AID, Integer> message_conversation_ids = new HashMap<>(); public int text = 0; public int N_PERIODS = 24; public javax.swing.JSlider jS1; public javax.swing.JTextField jT1; public javax.swing.JTextField jT2; public javax.swing.JTextField jTseller; public javax.swing.JTextField jTbuyer; ImageIcon negicon = new ImageIcon("images\\icon1.png"); ImageIcon conicon = new ImageIcon("images\\contract.png"); ImageIcon buyicon = new ImageIcon("images\\buyicon.png"); ImageIcon sellicon = new ImageIcon("images\\retailicon.jpg"); public int demandresponse = 0, seller_risk = 0, buyer_risk = 0; public double buyer_risk_exposure = 0, seller_risk_exposure = 1; public int contractduration = 5; public String contract = "Forward Contract"; public ArrayList<String> HOURS = new ArrayList<>(); private Font font_1 = new Font("Arial", Font.BOLD, 13); private String location = "images\\"; private String icon_agenda_location = location + "icon1.png"; private String icon_risk = location + "icon1.png"; public Date sellerdeadline, buyerdeadline; private JTextField[] limits, duration, periods; public ArrayList<String> hours = new ArrayList<>(); JCheckBox chinButton; JCheckBox chinButton2; public ArrayList<BuyerData> Buyers_Information = new ArrayList(); public ArrayList<ProducerData> Producers_Information = new ArrayList(); //private int inteiro = Wholesale_InputData. // <------------------------------------------------------------------------------------------------------------- // TEMPORARIO!!!! private MarketParticipants participants; // <------------------------------------------------------------------------------------------------------------- //================================ Bilateral Var Info ================================ private int bilateral_contractType = 0; // 1- Standarized; 2-Negotiated private int bilateral_contractDuration; private int bilateral_tradingProcess = 0; //1- Alternating Offers; 2- Contract Net private int bilateral_tariff; private int bilateral_hoursPeriod; private int bilateral_year, bilateral_month, bilateral_day, bilateral_hour, bilateral_minutes; private EnterGENCO genco; // Usar os métodos get já desenvolvidos para obtenção das variáveis do contrato bilateral estabelecidas no menu "Markets" //===================================================================================== @Override protected void setup() { this.addBehaviour(new MessageManager()); mo_gui = new PersonalAssistantGUI(this); // buy_gui = new Init(this); } public void addAgent(AID agent, String type, ProducerData newProducer, BuyerData newBuyer) { if (type.equals("seller")) { this.seller_names.add(agent); } else if (type.equals("producer")) { this.Producers_Information.add(newProducer); this.producer_names.add(agent); String name; name = newProducer.getName().replace(" ", "_"); addBelif(newProducer.getName(), name + ";" + "isSeller"); addBelif(newProducer.getName(), name + ";" + "name_" + "name"); addBelif(newProducer.getName(), name + ";" + "address_" + newProducer.getAddress()); addBelif(newProducer.getName(), name + ";" + "telephone_" + newProducer.getPhone_number()); addBelif(newProducer.getName(), name + ";" + "email_" + newProducer.getEmail()); } else if (type.equals("buyer")) { this.Buyers_Information.add(newBuyer); this.buyer_names.add(agent); String name; name = newBuyer.getName().replace(" ", "_"); addBelif(newBuyer.getName(), name + ";" + "isBuyer"); addBelif(newBuyer.getName(), name + ";" + "name_" + "name"); addBelif(newBuyer.getName(), name + ";" + "address_" + newBuyer.getAddress()); addBelif(newBuyer.getName(), name + ";" + "telephone_" + newBuyer.getPhone_number()); addBelif(newBuyer.getName(), name + ";" + "email_" + newBuyer.getEmail()); } else if (type.equals("large_consumer")) { this.largeConsumer_names.add(agent); } else if (type.equals("coalition")) { this.largeConsumer_names.add(agent); }else if (type.equals("consumer")) { this.mediumConsumer_names.add(agent); } else if (type.equals("MarketOperator")) { this.MarketOperator = agent; } mo_gui.addAgent(agent.getLocalName(), type); } private HashMap<String, ArrayList<String>> getBelifsAboutOthers() { return this.beliefs_about_others; } public void startsimulation(boolean isSMPsym, boolean isSMPasym, boolean isLMP, boolean isOTC){ // Sends message to MarketOperator to start the simulation AID rec = new AID("MarketOperator", AID.ISLOCALNAME); ACLMessage msg = new ACLMessage(ACLMessage.INFORM); msg.setOntology("market_ontology"); msg.setProtocol("no_protocol"); if(isSMPsym){ this.Write_Input_File(); msg.setContent("Start Simulation SMPsym"); } else if(isSMPasym) { msg.setContent("Start Simulation SMPasym"); } else if(isLMP) { msg.setContent("Start Simulation LMP"); } else if(isOTC) { msg.setContent("Start Simulation OTC"); } msg.addReceiver(rec); send(msg); } public void Write_Input_File(){ try { //create .xls and create a worksheet. int rownumber = 0; FileOutputStream fos = new FileOutputStream("input.xls"); HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet worksheet = workbook.createSheet("Sheet1"); HSSFRow row; HSSFCell cell; row = worksheet.createRow((short) rownumber); rownumber++; cell = row.createCell((short) 0); cell.setCellValue("Player"); cell = row.createCell((short) 1); cell.setCellValue("Period"); cell = row.createCell((short) 2); cell.setCellValue("Power"); cell = row.createCell((short) 3); cell.setCellValue("Price"); for(int i = 0; i < this.Buyers_Information.size(); i++){ if(this.Buyers_Information.get(i).getParticipating()){ for(int j=0; j < this.Buyers_Information.get(i).getPower().size(); j++){ row = worksheet.createRow((short) (rownumber)); rownumber++; cell = row.createCell((short) 0); cell.setCellValue(this.Buyers_Information.get(i).getName()); cell = row.createCell((short) 1); cell.setCellValue("" + (j+1)); cell = row.createCell((short) 2); cell.setCellValue("" + this.Buyers_Information.get(i).getPower().get(j)); cell = row.createCell((short) 3); cell.setCellValue("" + this.Buyers_Information.get(i).getPrice().get(j)); } } } row = worksheet.createRow((short) rownumber); rownumber++; row = worksheet.createRow((short) rownumber); rownumber++; cell = row.createCell((short) 0); cell.setCellValue("Player"); cell = row.createCell((short) 1); cell.setCellValue("Period"); cell = row.createCell((short) 2); cell.setCellValue("Power"); cell = row.createCell((short) 3); cell.setCellValue("Price"); for(int i = 0; i < this.Producers_Information.size(); i++){ if(this.Producers_Information.get(i).getParticipating()){ for(int j=0; j < this.Producers_Information.get(i).getPower().size(); j++){ row = worksheet.createRow((short) (rownumber)); rownumber++; cell = row.createCell((short) 0); cell.setCellValue(this.Producers_Information.get(i).getName()); cell = row.createCell((short) 1); cell.setCellValue("" + (j+1)); cell = row.createCell((short) 2); cell.setCellValue("" + this.Producers_Information.get(i).getPower().get(j)); cell = row.createCell((short) 3); cell.setCellValue("" + this.Producers_Information.get(i).getPrice().get(j)); } } } // // //Create ROW-1 // HSSFRow row1 = worksheet.createRow((short) 0); // // //Create COL-A from ROW-1 and set data // HSSFCell cellA1 = row1.createCell((short) 0); // cellA1.setCellValue("Sno"); // // // //Create COL-B from row-1 and set data // HSSFCell cellB1 = row1.createCell((short) 1); // cellB1.setCellValue("Name"); // // // //Create COL-C from row-1 and set data // HSSFCell cellC1 = row1.createCell((short) 2); // cellC1.setCellValue("Coisas"); // // //Create COL-D from row-1 and set data // HSSFCell cellD1 = row1.createCell((short) 3); // cellD1.setCellValue("Cenas"); //Save the workbook in .xls file workbook.write(fos); fos.flush(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // João de Sá // <--------------------------------------------------------------------------------------------------- // TEMPORARIO!!! /* public void chooseParticipants(boolean isProducer, boolean isDayAhead, boolean isSMP, boolean isOTC){ String[] agentNames = null; participants = new MarketParticipants(this, isProducer, isDayAhead, isSMP, isOTC); participants.setVisible(true); } */ // <------------------------------------------------------------------------------------------------------ public void start_OTC_simul(String Agent){ AID rec = new AID(Agent, AID.ISLOCALNAME); ACLMessage msg = new ACLMessage(ACLMessage.CFP); msg.setOntology("market_ontology"); msg.setProtocol("no_protocol"); msg.setContent("Sending simulation information"); msg.addReceiver(rec); send(msg); } public void send_OTC_sim_data(String Agent, String[] message){ AID rec = new AID(Agent, AID.ISLOCALNAME); ACLMessage msg = new ACLMessage(ACLMessage.INFORM); msg.setOntology("market_ontology"); msg.setProtocol("no_protocol"); msg.setContent("" + message[0] + " " + message[1] + " " + message[2] + " " + message[3] + " volume_bids " + message[4] + "price_bids " + message[5] + "end"); msg.addReceiver(rec); send(msg); } // Inform Method makes market agent send the results of the SMP simulation to // the respective agent. The receiver of the message comes as an argument (Rec) public void inform(AID Rec, String prices, String volumes){ //Send prices ACLMessage msg_prices = new ACLMessage(ACLMessage.INFORM); msg_prices.setOntology("Market_Ontology"); msg_prices.setProtocol("hello_protocol"); msg_prices.setContent(prices); //Need to make this send prices and volumes msg_prices.addReceiver(Rec); send(msg_prices); //Send Volumes ACLMessage msg_volumes = new ACLMessage(ACLMessage.INFORM); msg_volumes.setOntology("Market_Ontology"); msg_volumes.setProtocol("hello_protocol"); msg_volumes.setContent(volumes); //Need to make this send prices and volumes msg_volumes.addReceiver(Rec); send(msg_volumes); //Need to make agents handle the messages } // Modificações <--------------------------------------------------------------- public class MessageManager extends CyclicBehaviour { MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchOntology("market_ontology"), MessageTemplate.MatchProtocol("no_protocol")); MessageTemplate hello_mt = MessageTemplate.and(MessageTemplate.MatchOntology("market_ontology"), MessageTemplate.MatchProtocol("hello_protocol")); @Override public void action() { ACLMessage msg = myAgent.receive(mt); ACLMessage hello_msg = myAgent.receive(hello_mt); if (msg != null) { if (msg.getOntology().equals("market_ontology")) { MarketOntology market_ontology = new MarketOntology(); market_ontology.resolve(msg); } } else if(hello_msg != null){ if (hello_msg.getOntology().equals("market_ontology")) { MarketOntology market_ontology = new MarketOntology(); market_ontology.resolve_hello(hello_msg); } } else { block(); } } } class MarketOntology { private void resolve(ACLMessage msg) { if (msg.getPerformative() == ACLMessage.INFORM) { resolveInform(msg); } if (msg.getPerformative() == ACLMessage.CFP) { resolveCFP(msg); } if (msg.getPerformative() == ACLMessage.ACCEPT_PROPOSAL) { if (text == 0) { mo_gui.text_log.append(msg.getContent()); text++; } else { // JPanel panel = new JPanel(new BorderLayout()); // //Panel center - icon // JPanel panel_center = new JPanel(); // panel_center.setMinimumSize(new Dimension(100, 50)); // panel_center.setPreferredSize(new Dimension(200, 150)); Object aux = msg.getContent(); String[] choices4 = {"OK"}; // JOptionPane.showOptionDialog(null,aux, "System: New Bilateral Contract deal Received", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, choices4,null); // System.out.println(msg.getContent()); } } } private void resolve_hello(ACLMessage msg) { if(msg.getContent().contains("isProducer")){ String info = msg.getContent(); StoreProducerInfo(info); }else if(msg.getContent().contains("isBuyer")){ String info = msg.getContent(); StoreBuyerInfo(info); } } private void resolveCFP(ACLMessage msg) { String content = msg.getContent(); if (content.contains("propose_opponent")) { addBelif(msg.getSender().getLocalName(), msg.getSender().getLocalName() + ";waiting_for_opponent"); } } public void resolveInform(ACLMessage msg) { String content = msg.getContent(); if (content.contains(";is_buyer") || content.contains(";is_producer") ||content.contains(";is_seller") || content.contains(";is_coalition") || content.contains(";is_consumer")) { String[] content_information = content.split(";"); String agent_name = content_information[0]; // String agent_type = content_information[1].split("_")[1]; if (agent_name.equals(msg.getSender().getLocalName())) { String[] content_split = content.split(";"); addBelif(agent_name, content_split[0] + ";" + content_split[1]); addBelif(agent_name, content_split[0] + ";" + content_split[2]); addBelif(agent_name, content_split[0] + ";" + content_split[3]); addBelif(agent_name, content_split[0] + ";" + content_split[4]); addBelif(agent_name, content_split[0] + ";" + content_split[5]); // if (agent_type.equals("buyer")){ // if(largeConsumer_names.contains(agent_name)){ // agent_type="large_consumer"; // }else if(mediumConsumer_names.contains(agent_name)){ // agent_type="consumer";} // } // addAgent(new AID(agent_name, AID.ISLOCALNAME), agent_type); } }else if(content.contains("Offer")){ Store_Offer_Data(content); }else if(content.contains("Results")){ if(content.contains("SMPsym")){ Store_and_send_SMP_results(content); }else if(content.contains("SMPasym")){ Store_and_send_SMP_results(content); } } } } private void Store_and_send_SMP_results(String Results){ String[] Data; // contains whole message String Price; // contains period price String[] Info; // contains message part that refers to a single Agent String content; // content of message to be sent to each participating agent int k = -1; // contains agent index int f = -1; // contains buyers information start AID rec; // receiver of message // Set up message with results to be sent to each participating Agent ACLMessage Propose_msg = new ACLMessage(ACLMessage.PROPOSE); Propose_msg.setOntology("market_ontology"); Propose_msg.setProtocol("no_protocol"); Data = Results.split(";"); if(Data[0].contains("SMPsym")){ content = Data[0] + ";" + Data[1] + ";"; Price = Data[1]; //Data[2] is "Producers" for(int i = 3; !Data[i].contains("Buyers"); i++){ Info = Data[i].split(" "); // Find Producer index for(int l = 0; l < this.Producers_Information.size(); l++){ if(this.Producers_Information.get(l).getName().equals(Info[0])){ k = l; // k contains Producer Index } } if(k!=-1){ this.Producers_Information.get(k).Initialize_Market_Price_Sym(); this.Producers_Information.get(k).Initialize_Traded_power_Sym(); for(int j = 1; !Info[j].contains("end"); j++){ this.Producers_Information.get(k).setMarket_Price_Sym(Double.parseDouble(Price)); this.Producers_Information.get(k).setTraded_power_Sym(Double.parseDouble(Info[j])); } content = Data[0] + ";" + Data[1] + ";" + Data[i]; rec = new AID("" + Info[0], AID.ISLOCALNAME); Propose_msg.setContent(content); Propose_msg.addReceiver(rec); send(Propose_msg); Propose_msg.clearAllReceiver(); }else{ System.out.println("Agent " + Info[0] + " was not found on list"); } f = i; } k = -1; // Data[f+1] = Buyers for(int i = f+2; i < Data.length; i++){ Info = Data[i].split(" "); // Find Producer index for(int l = 0; l < this.Buyers_Information.size(); l++){ if(this.Buyers_Information.get(l).getName().equals(Info[0])){ k = l; // k contains Producer Index } } if(k!=-1){ this.Buyers_Information.get(k).Initialize_Market_Price_Sym(); this.Buyers_Information.get(k).Initialize_Traded_power_Sym(); for(int j = 1; !Info[j].contains("end"); j++){ this.Buyers_Information.get(k).setMarket_Price_Sym(Double.parseDouble(Price)); this.Buyers_Information.get(k).setTraded_power_Sym(Double.parseDouble(Info[j])); } content = Data[0] + ";" + Data[1] + ";" + Data[i]; rec = new AID("" + Info[0], AID.ISLOCALNAME); Propose_msg.setContent(content); Propose_msg.addReceiver(rec); send(Propose_msg); Propose_msg.clearAllReceiver(); }else{ System.out.println("Agent " + Info[0] + " was not found on list"); } } }else if(Data[0].contains("SMPasym")){ content = Data[0] + ";" + Data[1] + ";"; Price = Data[1]; //Data[2] is "Producers" for(int i = 3; !Data[i].contains("Buyers"); i++){ Info = Data[i].split(" "); // Find Producer index for(int l = 0; l < this.Producers_Information.size(); l++){ if(this.Producers_Information.get(l).getName().equals(Info[0])){ k = l; // k contains Producer Index } } if(k!=-1){ this.Producers_Information.get(k).Initialize_Market_Price_aSym(); this.Producers_Information.get(k).Initialize_Traded_power_aSym(); for(int j = 1; !Info[j].contains("end"); j++){ this.Producers_Information.get(k).setMarket_Price_aSym(Double.parseDouble(Price)); this.Producers_Information.get(k).setTraded_power_aSym(Double.parseDouble(Info[j])); } content = Data[0] + ";" + Data[1] + ";" + Data[i]; rec = new AID("" + Info[0], AID.ISLOCALNAME); Propose_msg.setContent(content); Propose_msg.addReceiver(rec); send(Propose_msg); Propose_msg.clearAllReceiver(); }else{ System.out.println("Agent " + Info[0] + " was not found on list"); } f = i; } k = -1; // Data[f+1] = Buyers for(int i = f+2; i < Data.length; i++){ Info = Data[i].split(" "); // Find Producer index for(int l = 0; l < this.Buyers_Information.size(); l++){ if(this.Buyers_Information.get(l).getName().equals(Info[0])){ k = l; // k contains Producer Index } } if(k!=-1){ this.Buyers_Information.get(k).Initialize_Market_Price_aSym(); this.Buyers_Information.get(k).Initialize_Traded_power_aSym(); for(int j = 1; !Info[j].contains("end"); j++){ this.Buyers_Information.get(k).setMarket_Price_aSym(Double.parseDouble(Price)); this.Buyers_Information.get(k).setTraded_power_aSym(Double.parseDouble(Info[j])); } content = Data[0] + ";" + Data[1] + ";" + Data[i]; rec = new AID("" + Info[0], AID.ISLOCALNAME); Propose_msg.setContent(content); Propose_msg.addReceiver(rec); send(Propose_msg); Propose_msg.clearAllReceiver(); }else{ System.out.println("Agent " + Info[0] + " was not found on list"); } } } } private void Store_Offer_Data(String content){ String[] data; int k = -1; int j = 0; data = content.split(" "); if(data[2].contains("Producer")){ for(int i = 0; i < this.Producers_Information.size(); i++){ if(this.Producers_Information.get(i).getName().equals(data[1])){ k=i; break; } } if(k!=-1){ for(int i = 4; !data[i].contains("Power"); i++){ this.Producers_Information.get(k).setPrice(Float.parseFloat(data[i])); j=i; } for(int i = j+2; !data[i].contains("end"); i++){ this.Producers_Information.get(k).setPower(Float.parseFloat(data[i])); } this.mo_gui.show_offer_window(k, true); }else{ System.out.println("Error: Producer name on message and producer name on list don't match!!"); } }else if(data[2].contains("Buyer")){ for(int i = 0; i < this.Buyers_Information.size(); i++){ if(this.Buyers_Information.get(i).getName().equals(data[1])){ k=i; break; } } if(k!=-1){ for(int i = 4; !data[i].contains("Power"); i++){ this.Buyers_Information.get(k).setPrice(Float.parseFloat(data[i])); j=i; } for(int i = j+2; !data[i].contains("end"); i++){ this.Buyers_Information.get(k).setPower(Float.parseFloat(data[i])); } this.mo_gui.show_offer_window(k, false); }else{ System.out.println("Error: Buyer name on message and buyer name on list don't match!!"); } } } private void StoreProducerInfo(String info){ // Info string has the following format // "Name";"Address";"PhoneNumber";"Email";"Objective";tech;"ThermalTechnolgies";"WindTechnologies";"HydroTechnologies" // The fields between "" refer to information about the current Agent // If the agent doesn't have a particular technology, the respective field will be empty // Differente avaliable technologies of a ceratain type will be separated by "_" ProducerData newProducer = new ProducerData(); String Name; String Address; String Phone_Number; String EMail; String Objective; // data[0] to data[5] will be basic producer agent info String[] data; data = info.split(";"); Name = data[0]; Address = data[2]; Phone_Number = data[3]; EMail = data[4]; Objective = data[5]; newProducer.setName(Name); newProducer.setAddress(Address); newProducer.setPhone_number(Phone_Number); newProducer.setEmail(EMail); newProducer.setObjective(Objective); newProducer.setParticipating(false); newProducer.setStrategy("None"); // data[6] will be "tech" // data[7] is for thermal technologies String[] TechData; TechData = data[7].split("_"); int i = 0; if(!TechData[0].equals(" ")){ while(i<TechData.length){ newProducer.addDataThermal(TechData[i], Double.parseDouble(TechData[i+1]), Double.parseDouble(TechData[i+2]), TechData[i+3], Double.parseDouble(TechData[i+4])); i=i+5; } } // data[8] is for wind technologies TechData = data[8].split("_"); i = 0; if(!TechData[0].equals(" ")){ while(i<TechData.length){ newProducer.addDataWind(TechData[i], Double.parseDouble(TechData[i+1]), Double.parseDouble(TechData[i+2]), Double.parseDouble(TechData[i+3])); i=i+4; } } // data[9] is for Hydro technologies TechData = data[9].split("_"); i = 0; if(!TechData[0].equals(" ")){ while(i<TechData.length){ newProducer.addDataHydro(TechData[i], Double.parseDouble(TechData[i+1]), Double.parseDouble(TechData[i+2])); i=i+3; } } NewAgent_Info AgentInfo = new NewAgent_Info(true, newProducer, null, this); AgentInfo.setVisible(true); } private void StoreBuyerInfo(String info){ BuyerData newBuyer = new BuyerData(); String Name; String Address; String Phone_Number; String EMail; String Objective; // data[0] to data[5] will be basic producer agent info String[] data; data = info.split(";"); Name = data[0]; Address = data[2]; Phone_Number = data[3]; EMail = data[4]; Objective = data[5]; newBuyer.setName(Name); newBuyer.setAddress(Address); newBuyer.setPhone_number(Phone_Number); newBuyer.setEmail(EMail); newBuyer.setObjective(Objective); newBuyer.setParticipating(false); NewAgent_Info AgentInfo = new NewAgent_Info(false, null, newBuyer, this); AgentInfo.setVisible(true); } public void sendMarketSelection(boolean isDayahead, boolean isSMP, boolean isOTC){ AID rec; ACLMessage msg = new ACLMessage(ACLMessage.INFORM); msg.setOntology("market_ontology"); msg.setProtocol("no_protocol"); String content; content = "Market "; if(isDayahead){ content = content + "Dayahead "; if(isSMP){ content = content + "SMP"; }else{ content = content + "LMP"; } } if(isOTC){ content = content + "OTC"; } msg.setContent(content); for(int i = 0; i < Buyers_Information.size(); i++){ rec = new AID(Buyers_Information.get(i).getName().replace(" ", "_"), AID.ISLOCALNAME); msg.addReceiver(rec); } send(msg); msg.clearAllReceiver(); for(int i = 0; i < Producers_Information.size(); i++){ rec = new AID(Producers_Information.get(i).getName().replace(" ", "_"), AID.ISLOCALNAME); msg.addReceiver(rec); } send(msg); } public void inform_participants(boolean isProducer, String AgentName, String Strategy){ AID rec; String content; ACLMessage msg = new ACLMessage(ACLMessage.INFORM); msg.setOntology("market_ontology"); msg.setProtocol("no_protocol"); content = "Participating " + Strategy; msg.setContent(content); rec = new AID(AgentName.replace(" ", "_"), AID.ISLOCALNAME); msg.addReceiver(rec); send(msg); } public void addNegotiationPairAndInformThem(AID[] new_pair) { this.new_pair = new_pair; this.negotiation_pairs.add(new_pair); ACLMessage msg_seller = new ACLMessage(ACLMessage.PROPOSE); msg_seller.setOntology("market_ontology"); msg_seller.setProtocol("hello_protocol"); msg_seller.setContent(new_pair[1].getLocalName() + ";opponent_proposal"); msg_seller.addReceiver(new_pair[0]); ACLMessage msg_buyer = new ACLMessage(ACLMessage.PROPOSE); msg_buyer.setOntology("market_ontology"); msg_buyer.setProtocol("hello_protocol"); msg_buyer.setContent(new_pair[0].getLocalName() + ";opponent_proposal"); msg_buyer.addReceiver(new_pair[1]); send(msg_seller); send(msg_buyer); msg_buyer = new ACLMessage(ACLMessage.PROPOSE); msg_buyer.setOntology("market_ontology"); msg_buyer.setProtocol("hello_protocol"); msg_buyer.setContent(new_pair[0].getLocalName() + ";opponent_proposal"); msg_buyer.addReceiver(MarketOperator); send(msg_buyer); msg_seller = new ACLMessage(ACLMessage.PROPOSE); msg_seller.setOntology("contract_ontology"); msg_seller.setProtocol("hello_protocol"); msg_seller.setContent(contract); msg_seller.addReceiver(new_pair[0]); msg_buyer = new ACLMessage(ACLMessage.PROPOSE); msg_buyer.setOntology("contract_ontology"); msg_buyer.setProtocol("hello_protocol"); msg_buyer.setContent(contract); msg_buyer.addReceiver(new_pair[1]); send(msg_seller); send(msg_buyer); msg_seller = new ACLMessage(ACLMessage.PROPOSE); msg_seller.setOntology("day_ontology"); msg_seller.setProtocol("hello_protocol"); msg_seller.setContent(String.valueOf(contractduration)); msg_seller.addReceiver(new_pair[0]); msg_buyer = new ACLMessage(ACLMessage.PROPOSE); msg_buyer.setOntology("day_ontology"); msg_buyer.setProtocol("hello_protocol"); msg_buyer.setContent(String.valueOf(contractduration)); msg_buyer.addReceiver(new_pair[1]); send(msg_seller); send(msg_buyer); msg_seller = new ACLMessage(ACLMessage.PROPOSE); msg_seller.setOntology("inf_ontology"); msg_seller.setProtocol("hello_protocol"); msg_seller.setContent(String.valueOf(N_PERIODS)); msg_seller.addReceiver(new_pair[0]); msg_buyer = new ACLMessage(ACLMessage.PROPOSE); msg_buyer.setOntology("inf_ontology"); msg_buyer.setProtocol("hello_protocol"); msg_buyer.setContent(String.valueOf(N_PERIODS)); msg_buyer.addReceiver(new_pair[1]); send(msg_seller); send(msg_buyer); if (N_PERIODS != 24) { String[] hoursaux = new String[1]; hoursaux[0] = ""; for (int i = 0; i < HOURS.size(); i++) { hoursaux[0] = hoursaux[0] + HOURS.get(i) + ","; } msg_seller = new ACLMessage(ACLMessage.PROPOSE); msg_seller.setOntology("hour_ontology"); msg_seller.setProtocol("hello_protocol"); msg_seller.setContent(hoursaux[0]); msg_seller.addReceiver(new_pair[0]); msg_buyer = new ACLMessage(ACLMessage.PROPOSE); msg_buyer.setOntology("hour_ontology"); msg_buyer.setProtocol("hello_protocol"); msg_buyer.setContent(hoursaux[0]); msg_buyer.addReceiver(new_pair[1]); send(msg_seller); send(msg_buyer); } msg_seller = new ACLMessage(ACLMessage.PROPOSE); msg_seller.setOntology("volume_ontology"); msg_seller.setProtocol("hello_protocol"); msg_seller.setContent(String.valueOf(demandresponse)); msg_seller.addReceiver(new_pair[0]); msg_buyer = new ACLMessage(ACLMessage.PROPOSE); msg_buyer.setOntology("volume_ontology"); msg_buyer.setProtocol("hello_protocol"); msg_buyer.setContent(String.valueOf(demandresponse)); msg_buyer.addReceiver(new_pair[1]); send(msg_seller); send(msg_buyer); msg_seller = new ACLMessage(ACLMessage.PROPOSE); msg_seller.setOntology("risk_ontology"); msg_seller.setProtocol("hello_protocol"); msg_seller.setContent("" + seller_risk); msg_seller.addReceiver(new_pair[0]); msg_buyer = new ACLMessage(ACLMessage.PROPOSE); msg_buyer.setOntology("risk_ontology"); msg_buyer.setProtocol("hello_protocol"); msg_buyer.setContent("" + buyer_risk); msg_buyer.addReceiver(new_pair[1]); send(msg_seller); send(msg_buyer); } public PersonalAssistant Init() { N_PERIODS = 24; return this; } // @SuppressWarnings("unchecked") // // <editor-fold defaultstate="collapsed" desc="Generated Code"> // public void initComponents() { // // // jLabel1 = new javax.swing.JLabel(); // jLabel2 = new javax.swing.JLabel(); // jLabel3 = new javax.swing.JLabel(); // jComboBox1 = new javax.swing.JComboBox(); // jComboBox2 = new javax.swing.JComboBox(); // jLabel4 = new javax.swing.JLabel(); // jSlider1 = new javax.swing.JSlider(); // jLabel5 = new javax.swing.JLabel(); // jTextField1 = new javax.swing.JTextField(); // jTextField2 = new javax.swing.JTextField(); // jSeparator1 = new javax.swing.JSeparator(); // jLabel6 = new javax.swing.JLabel(); // jLabel7 = new javax.swing.JLabel(); // jCheckBox1 = new javax.swing.JCheckBox(); // jCheckBox2 = new javax.swing.JCheckBox(); // jSeparator2 = new javax.swing.JSeparator(); // jLabel8 = new javax.swing.JLabel(); // jLabel9 = new javax.swing.JLabel(); // jCheckBox3 = new javax.swing.JCheckBox(); // jCheckBox4 = new javax.swing.JCheckBox(); // jSeparator3 = new javax.swing.JSeparator(); //// jLabel10 = new javax.swing.JLabel(); //// jLabel11 = new javax.swing.JLabel(); // jLabel12 = new javax.swing.JLabel(); //// jCheckBox5 = new javax.swing.JCheckBox(); //// jCheckBox6 = new javax.swing.JCheckBox(); //// jCheckBox7 = new javax.swing.JCheckBox(); //// jLabel13 = new javax.swing.JLabel(); //// jCheckBox8 = new javax.swing.JCheckBox(); //// jCheckBox9 = new javax.swing.JCheckBox(); //// jCheckBox10 = new javax.swing.JCheckBox(); // // /////////////////ALTERAÇÔES////////////////////////// // ///////////////////////////////////////////////////// // jCheckBox1.setSelected(false); // jCheckBox2.setSelected(true); // jCheckBox3.setSelected(false); // jCheckBox4.setSelected(true); //// jCheckBox5.setSelected(false); //// jCheckBox6.setSelected(false); //// jCheckBox7.setSelected(true); //// jCheckBox8.setSelected(false); //// jCheckBox9.setSelected(false); //// jCheckBox10.setSelected(true); // //////////////////////////////////////////////////// // /////////////////////////////////////////////////// // //jLabel1.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N // jLabel1.setText("Contract"); // // jLabel3.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N // jLabel3.setText("Type:"); // // jComboBox2.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N // jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Forward Contract", "Contract For Difference", "Option Contract" })); // // jSlider1.setFont(new java.awt.Font("Arial", 0, 10)); // NOI18N // jSlider1.setMajorTickSpacing(1); // jSlider1.setMaximum(24); // jSlider1.setMinimum(1); // jSlider1.setMinorTickSpacing(1); // jSlider1.setPaintLabels(true); // jSlider1.setPaintTicks(true); // jSlider1.setToolTipText(""); // // jLabel5.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N // jLabel5.setText("Hour"); // // jTextField2.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N // jTextField2.setText("365"); // // jLabel6.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N // jLabel6.setText("Demand Response Management"); // // jLabel7.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N // jLabel7.setText("Managing Energy Volumes During Negotiation:"); // // jCheckBox1.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N // jCheckBox1.setText("yes"); // jCheckBox1.addItemListener(new java.awt.event.ItemListener() { // public void itemStateChanged(java.awt.event.ItemEvent evt) { // jCheckBox1ItemStateChanged(evt); // } // }); // // jCheckBox2.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N // jCheckBox2.setText("no"); // jCheckBox2.addItemListener(new java.awt.event.ItemListener() { // public void itemStateChanged(java.awt.event.ItemEvent evt) { // jCheckBox2ItemStateChanged(evt); // } // }); // // jSeparator2.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); // jSeparator2.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N // // jLabel8.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N // jLabel8.setText("Price Risk"); // // jLabel9.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N // jLabel9.setText("Managing Price Risk During Negotiation:"); // // jCheckBox3.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N // jCheckBox3.setText("yes"); // jCheckBox3.addItemListener(new java.awt.event.ItemListener() { // public void itemStateChanged(java.awt.event.ItemEvent evt) { // jCheckBox3ItemStateChanged(evt); // } // }); // // jCheckBox4.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N // jCheckBox4.setText("no"); // jCheckBox4.addItemListener(new java.awt.event.ItemListener() { // public void itemStateChanged(java.awt.event.ItemEvent evt) { // jCheckBox4ItemStateChanged(evt); // } // }); // // jLabel12.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N // jLabel12.setText("Duration (days):"); // // jTextField1.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N //// jTextField1.setText("1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18;19;20;21;22;23;24"); // jTextField1.setText("1-4;5-8;9-12;13-16;17-20;21-24"); // // // jSeparator3.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); // jSeparator3.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N // // jLabel2.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N // jLabel2.setText("Day Periods"); // // javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); // this.setLayout(layout); // layout.setHorizontalGroup( // layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) // .addComponent(jSeparator1) // .addComponent(jSeparator2) // .addGroup(layout.createSequentialGroup() // .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) // .addGroup(layout.createSequentialGroup() // .addGap(0, 0, Short.MAX_VALUE) // .addComponent(jLabel9)) // .addComponent(jLabel8)) // .addGap(8, 8, 8) // .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) // .addComponent(jCheckBox4) // .addComponent(jCheckBox3)) // .addGap(100, 100, 100)) // .addGroup(layout.createSequentialGroup() // .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) // .addComponent(jLabel1) // .addGroup(layout.createSequentialGroup() // .addGap(79, 79, 79) // .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) // .addGroup(layout.createSequentialGroup() // .addComponent(jLabel12) // .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) // .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)) // .addGroup(layout.createSequentialGroup() // .addComponent(jLabel3) // .addGap(29, 29, 29) // .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) // .addComponent(jLabel6) // .addGroup(layout.createSequentialGroup() // .addGap(85, 85, 85) // .addComponent(jLabel7) // .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) // .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) // .addComponent(jCheckBox1) // .addComponent(jCheckBox2)))) // .addContainerGap()) // .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() // .addGap(0, 0, Short.MAX_VALUE) // .addComponent(jLabel5) // .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) // .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 356, javax.swing.GroupLayout.PREFERRED_SIZE) // .addContainerGap()) // .addComponent(jSeparator3) // .addGroup(layout.createSequentialGroup() // .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) // .addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, 472, javax.swing.GroupLayout.PREFERRED_SIZE) // .addComponent(jLabel2)) // .addGap(0, 0, Short.MAX_VALUE)) // ); // layout.setVerticalGroup( // layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) // .addGroup(layout.createSequentialGroup() // .addContainerGap() // .addComponent(jLabel1) // .addGap(18, 18, 18) // .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) // .addComponent(jLabel3) // .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) // .addGap(10, 10, 10) // .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) // .addComponent(jLabel12) // .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) // .addGap(18, 18, 18) // .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) // .addGap(2, 2, 2) // .addComponent(jLabel2) // .addGap(18, 18, 18) // .addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) // .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) // .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) // .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) // .addComponent(jLabel5)) // .addGap(18, 18, 18) // .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) // .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) // .addGroup(layout.createSequentialGroup() // .addGap(4, 4, 4) // .addComponent(jLabel8) // .addGap(18, 18, 18) // .addComponent(jLabel9) // .addGap(27, 27, 27)) // .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() // .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) // .addComponent(jCheckBox3) // .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) // .addComponent(jCheckBox4) // .addGap(11, 11, 11))) // .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) // .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) // .addGroup(layout.createSequentialGroup() // .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) // .addComponent(jLabel6) // .addGap(18, 18, 18) // .addComponent(jLabel7)) // .addGroup(layout.createSequentialGroup() // .addGap(26, 26, 26) // .addComponent(jCheckBox1) // .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) // .addComponent(jCheckBox2))) // .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) // ); // }// </editor-fold> // // //////////////////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////////////// // // // // // private void jCheckBox1ItemStateChanged(java.awt.event.ItemEvent evt) { // // if((evt.getStateChange() != ItemEvent.DESELECTED)){ // if(jCheckBox2.isSelected()){ // jCheckBox2.setSelected(false); // demandresponse=1; // } // }else{ // if((evt.getStateChange() == ItemEvent.DESELECTED)){ // if(jCheckBox2.isSelected()){ // // }else{ // jCheckBox2.setSelected(true); // demandresponse=0; // } // } // } // } // // private void jCheckBox2ItemStateChanged(java.awt.event.ItemEvent evt) { // if((evt.getStateChange() != ItemEvent.DESELECTED)){ // if(jCheckBox1.isSelected()){ // jCheckBox1.setSelected(false); // demandresponse=0; // } // }else{ // if((evt.getStateChange() == ItemEvent.DESELECTED)){ // if(jCheckBox1.isSelected()){ // // }else{ // jCheckBox1.setSelected(true); // demandresponse=1; // } // } // TODO add your handling code here: // } // } // private void jCheckBox3ItemStateChanged(java.awt.event.ItemEvent evt) { // // if((evt.getStateChange() != ItemEvent.DESELECTED)){ // if(jCheckBox4.isSelected()){ // jCheckBox4.setSelected(false); // buyer_risk=1; // seller_risk=1; // } // }else{ // if((evt.getStateChange() == ItemEvent.DESELECTED)){ // if(jCheckBox4.isSelected()){ // // }else{ // jCheckBox4.setSelected(true); // buyer_risk=0; // seller_risk=0; // } // } // } // } // // private void jCheckBox4ItemStateChanged(java.awt.event.ItemEvent evt) { // if((evt.getStateChange() != ItemEvent.DESELECTED)){ // if(jCheckBox3.isSelected()){ // jCheckBox3.setSelected(false); // buyer_risk=0; // seller_risk=0; // } // }else{ // if((evt.getStateChange() == ItemEvent.DESELECTED)){ // if(jCheckBox3.isSelected()){ // // }else{ // jCheckBox3.setSelected(true); // buyer_risk=1; // seller_risk=1; // } // } // TODO add your handling code here: // } // } //// private void jCheckBox567ItemStateChanged(java.awt.event.ItemEvent evt) { //// //// Object source = evt.getItemSelectable(); //// //// if(source==jCheckBox5 &&(evt.getStateChange() != ItemEvent.DESELECTED)){ //// if(jCheckBox6.isSelected()){ //// jCheckBox6.setSelected(false); //// ESseller=0; //// }else{ //// if(jCheckBox7.isSelected()){ //// jCheckBox7.setSelected(false); //// ESseller=0; //// } //// } //// }else{ //// if(source==jCheckBox6 &&(evt.getStateChange() != ItemEvent.DESELECTED)){ //// if(jCheckBox5.isSelected()){ //// jCheckBox5.setSelected(false); //// ESseller=1; //// }else{ //// if(jCheckBox7.isSelected()){ //// jCheckBox7.setSelected(false); //// ESseller=1; //// } //// } //// }else{ //// if(source==jCheckBox7 &&(evt.getStateChange() != ItemEvent.DESELECTED)){ //// if(jCheckBox6.isSelected()){ //// jCheckBox6.setSelected(false); //// ESseller=2; //// }else{ //// if(jCheckBox5.isSelected()){ //// jCheckBox5.setSelected(false); //// ESseller=2; //// } //// } //// //// //// //// }else{ //// if(source==jCheckBox5&&(evt.getStateChange() == ItemEvent.DESELECTED)){ //// if(jCheckBox6.isSelected()||jCheckBox7.isSelected()){ //// //// }else{ //// jCheckBox5.setSelected(true); //// } ////// } // TODO add your handling code here: ////// } //// //// }else{ //// if(source==jCheckBox6&&(evt.getStateChange() == ItemEvent.DESELECTED)){ //// if(jCheckBox5.isSelected()||jCheckBox7.isSelected()){ //// //// }else{ //// jCheckBox6.setSelected(true); //// } ////// } // TODO add your handling code here: ////// } //// //// }else{ //// if(source==jCheckBox7&&(evt.getStateChange() == ItemEvent.DESELECTED)){ //// if(jCheckBox6.isSelected()||jCheckBox5.isSelected()){ //// //// }else{ //// jCheckBox7.setSelected(true); //// } ////// } // TODO add your handling code here: ////// } //// } //// } //// } //// } //// } //// } //// } //// private void jCheckBox8910ItemStateChanged(java.awt.event.ItemEvent evt) { //// //// Object source = evt.getItemSelectable(); //// //// if(source==jCheckBox8 &&(evt.getStateChange() != ItemEvent.DESELECTED)){ //// if(jCheckBox9.isSelected()){ //// jCheckBox9.setSelected(false); //// ESbuyer=0; //// }else{ //// if(jCheckBox10.isSelected()){ //// jCheckBox10.setSelected(false); //// ESbuyer=0; //// } //// } //// }else{ //// if(source==jCheckBox9 &&(evt.getStateChange() != ItemEvent.DESELECTED)){ //// if(jCheckBox8.isSelected()){ //// jCheckBox8.setSelected(false); //// ESbuyer=1; //// }else{ //// if(jCheckBox10.isSelected()){ //// jCheckBox10.setSelected(false); //// ESbuyer=1; //// } //// } //// }else{ //// if(source==jCheckBox10 &&(evt.getStateChange() != ItemEvent.DESELECTED)){ //// if(jCheckBox9.isSelected()){ //// jCheckBox9.setSelected(false); //// ESbuyer=2; //// }else{ //// if(jCheckBox8.isSelected()){ //// jCheckBox8.setSelected(false); //// ESbuyer=2; //// } //// } //// //// //// //// }else{ //// if(source==jCheckBox8&&(evt.getStateChange() == ItemEvent.DESELECTED)){ //// if(jCheckBox9.isSelected()||jCheckBox10.isSelected()){ //// //// }else{ //// jCheckBox8.setSelected(true); //// } ////// } // TODO add your handling code here: ////// } //// //// }else{ //// if(source==jCheckBox9&&(evt.getStateChange() == ItemEvent.DESELECTED)){ //// if(jCheckBox8.isSelected()||jCheckBox10.isSelected()){ //// //// }else{ //// jCheckBox9.setSelected(true); //// } ////// } // TODO add your handling code here: ////// } //// //// }else{ //// if(source==jCheckBox10&&(evt.getStateChange() == ItemEvent.DESELECTED)){ //// if(jCheckBox9.isSelected()||jCheckBox8.isSelected()){ //// //// }else{ //// jCheckBox10.setSelected(true); //// } ////// } // TODO add your handling code here: ////// } //// } //// } //// } //// } //// } //// } //// } // // Variables declaration - do not modify // // private javax.swing.JLabel jLabel1; //// private javax.swing.JLabel jLabel10; //// private javax.swing.JLabel jLabel11; // private javax.swing.JLabel jLabel12; //// private javax.swing.JLabel jLabel13; // private javax.swing.JLabel jLabel2; // private javax.swing.JLabel jLabel3; // private javax.swing.JLabel jLabel4; // private javax.swing.JLabel jLabel5; // private javax.swing.JLabel jLabel6; // private javax.swing.JLabel jLabel7; // private javax.swing.JLabel jLabel8; // private javax.swing.JLabel jLabel9; // private javax.swing.JSeparator jSeparator1; // private javax.swing.JSeparator jSeparator2; // private javax.swing.JSeparator jSeparator3; // // // // End of variables declaration //} public void demandmanagement(PersonalAssistantGUI parent) { String[] choices = {"Save", "Cancel"}; JPanel panel = new JPanel(new BorderLayout()); // Panel north // Listener2 listener2 = new Listener2(); JPanel panel_north = new JPanel(); panel_north.setLayout(new BorderLayout()); panel_north.setMinimumSize(new Dimension(350, 60)); panel_north.setPreferredSize(new Dimension(350, 60)); panel_north.setBorder(new BevelBorder(BevelBorder.LOWERED)); JPanel panel_text_background = new JPanel(); JLabel label_text = new JLabel(); panel_text_background.setMinimumSize(new Dimension(295, 6)); panel_text_background.setPreferredSize(new Dimension(295, 60)); label_text.setMinimumSize(new Dimension(290, 50)); label_text.setPreferredSize(new Dimension(290, 50)); label_text.setHorizontalAlignment(SwingConstants.CENTER); label_text.setText("<html>Customer's Demand Response Program</html>"); label_text.setFont(font_1); panel_text_background.add(label_text); panel_north.add(panel_text_background, BorderLayout.CENTER); try { BufferedImage picture = ImageIO.read(new File(icon_risk)); JPanel panel_pic_background = new JPanel(); JLabel label_pic = new JLabel(new ImageIcon(picture)); panel_pic_background.setMinimumSize(new Dimension(55, 55)); panel_pic_background.setPreferredSize(new Dimension(55, 55)); panel_pic_background.add(label_pic); panel_north.add(panel_pic_background, BorderLayout.EAST); } catch (IOException ex) { Logger.getLogger(BuyerInputGui.class.getName()).log(Level.SEVERE, null, ex); } JPanel panel_center = new DR(this); panel_center.setMinimumSize(new Dimension(350, 100)); panel_center.setPreferredSize(new Dimension(350, 250)); panel.add(panel_north, BorderLayout.NORTH); panel.add(panel_center, BorderLayout.CENTER); int result = JOptionPane.showOptionDialog(parent, panel, "DR Management", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, choices, null); if (result == 1) { demandresponse = 0; } } public void tools(PersonalAssistantGUI parent) { String[] choices = {"Save", "Cancel"}; JPanel panel1 = new JPanel(); // panel1=new Tools(this); // Tools mainFrame = new Tools(this); // mainFrame.setVisible( true ); int result = JOptionPane.showOptionDialog(parent, new Tools(this), "Preferences", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, choices, null); // if(result==1){ // demandresponse=0; // // } } public void newAgentForm(int _agentType) { NewAgent_Name newForm = new NewAgent_Name(this, _agentType); newForm.setVisible(true); } // public void genco_menu(PersonalAssistantGUI parent) { // // JPanel panel = new JPanel(new BorderLayout()); // // genco = new EnterGENCO(); // genco.setVisible(true); //// agentInfo = "producing.Producer"; // String[] choices1 = {"Cancel", "Next"}; // } public void producer_menu(PersonalAssistantGUI parent) { String[] GENCOs = {"GenCo1","GenCo2","GenCo3","GenCo4","GenCo5","GenCo6","GenCo7","GenCo8", "GenCo9", "GenCo10"}; JPanel panel = new JPanel(new BorderLayout()); JPanel panel_center = new JPanel(); panel_center.setLayout(new GridBagLayout()); panel_center.setPreferredSize(new Dimension(270, 100)); panel_center.setMinimumSize(new Dimension(270, 100)); JLabel l = new JLabel("GenCos: "); l.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(0, 50, 40, 40); panel_center.add(l, gridBagConstraints); JComboBox menu2 = new JComboBox(); String[] auxName; for (String gen1 : GENCOs) { if (checkseller(gen1) == 0) { menu2.addItem(gen1); } } auxName = new String[menu2.getItemCount()]; for (int i = 0; i < auxName.length; i++) { auxName[i] = menu2.getItemAt(i).toString(); } if (auxName.length > 0) { LoadAgent_Name openWindow = new LoadAgent_Name(this, 4, auxName); openWindow.setVisible(true); } menu2.setMinimumSize(new Dimension(190, 25)); menu2.setPreferredSize(new Dimension(190, 25)); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new Insets(-3, -30, 25, 50); panel_center.add(menu2, gridBagConstraints); panel.add(panel_center, BorderLayout.CENTER); String[] choices1 = {"Cancel", "Next"}; /*int result = JOptionPane.showOptionDialog(parent, panel, "Generators (GenCos)", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, choices1, choices1[1]); if (result == 0) { return; } else if (result == 1) { createAgent((String) menu2.getSelectedItem(), "selling.Seller"); }*/ } public int checkseller(String Seller) { int j = 0; for (int i = 0; i < seller_names.size(); i++) { if (Seller.trim().replace(" ", "_").equals(seller_names.get(i).getLocalName().trim().replace(" ", "_"))) { i = seller_names.size(); j = 1; } } return j; } public void coallition_menu(PersonalAssistantGUI parent){ JMenuItem Cm1 = new JMenuItem("Coalition_One"); JMenuItem Cm2 = new JMenuItem("Coalition_Two"); JMenuItem Cm0 = new JMenuItem("Coalition"); JMenu Coalition = new JMenu("Coalition"); JMenu menu = ComboMenuBar.createMenu("Coalition"); JPanel panel = new JPanel(new BorderLayout()); JPanel panel_center = new JPanel(); panel_center.setLayout(new GridBagLayout()); panel_center.setPreferredSize(new Dimension(100, 100)); panel_center.setMinimumSize(new Dimension(100, 100)); JLabel l = new JLabel("Coalition :"); l.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(0, 40, 40, 30); panel_center.add(l, gridBagConstraints); menu.add(Cm0); menu.add(Cm1); menu.add(Cm2); ComboMenuBar comboMenu = new ComboMenuBar(menu); comboMenu.setMinimumSize(new Dimension(180, 25)); comboMenu.setPreferredSize(new Dimension(180, 25)); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new Insets(-3, -30, 25, 50); panel_center.add(comboMenu, gridBagConstraints); panel.add(panel_center, BorderLayout.CENTER); // String toString = menu.getSelectedObjects().toString(); String[] choices1 = {"Cancel","OK"}; int result = JOptionPane.showOptionDialog(parent, panel, "Coalition: ", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, choices1, null); if (result == 0) { return; }else if (result == 1) { //createAgent(toString,"Coalition.CoalitionFront"); createAgent("Coalition","Coalition.CoalitionFront"); } } public void consumer_menu(PersonalAssistantGUI parent) { /* JMenuItem DO = new JMenuItem("David_Owen"); JMenuItem SCO = new JMenuItem("SCO_Corporation"); JMenuItem EC = new JMenuItem("Electro_Center"); */ String[] LSEs = {"David_Owen", "David_Aggregation"}; /*String DO = "David_Owen"; String SCO = "SCO_Corporation"; String EC = "Electro_Center"; String TE = "Electrical_Supplier";*/ // JMenuItem David_Owen = new JMenuItem("D"); // JMenu Buyer = new JMenu("Buyer"); JPanel panel = new JPanel(new BorderLayout()); //Panel center - icon JPanel panel_center = new JPanel(); panel_center.setLayout(new GridBagLayout()); panel_center.setPreferredSize(new Dimension(270, 100)); panel_center.setMinimumSize(new Dimension(270, 100)); // panel_center.add(split_pane_log_image, BorderLayout.NORTH); // JPanel panel_north = new JPanel(new GridLayout(1, 2)); JLabel l = new JLabel("ConsumerCos: "); l.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(0, 40, 40, 30); panel_center.add(l, gridBagConstraints); // JMenu[] menus = new JMenu[1]; // // menus[0] = Seller; // // // menus[0].add(RES); //JMenu menu = ComboMenuBar.createMenu("Supplier"); JComboBox menu2 = new JComboBox(); String[] auxName; for (String lse1 : LSEs) { if (checkbuyer(lse1) == 0) { menu2.addItem(lse1); } } auxName = new String[menu2.getItemCount()]; for (int i = 0; i < auxName.length; i++) { auxName[i] = menu2.getItemAt(i).toString(); } if (auxName.length > 0) { LoadAgent_Name openWindow = new LoadAgent_Name(this, 3, auxName); openWindow.setVisible(true); } /* if(checkbuyer(DO)==0) { menu2.addItem(DO); } if(checkbuyer(EC)==0) { menu2.addItem(EC); } if(checkbuyer(SCO)==0) { menu2.addItem(SCO); } if(checkbuyer(TE)==0) { menu2.addItem(TE); } */ /*int j = checkbuyer(DO.getText()); if (j == 0) { menu.add(DO); } j = checkbuyer(EC.getText());; if (j == 0) { menu.add(EC); } j = checkbuyer(SCO.getText()); if (j == 0) { menu.add(SCO); }*/ //// menu.addSeparator(); // menu.add(menus[2]); // menu.add(menus[3]); /*ComboMenuBar comboMenu = new ComboMenuBar(menu); comboMenu.setMinimumSize(new Dimension(180, 25)); comboMenu.setPreferredSize(new Dimension(180, 25));*/ menu2.setMinimumSize(new Dimension(180, 25)); menu2.setPreferredSize(new Dimension(180, 25)); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new Insets(-3, -30, 25, 50); //panel_center.add(comboMenu, gridBagConstraints); panel_center.add(menu2, gridBagConstraints); panel.add(panel_center, BorderLayout.CENTER); String[] choices1 = {"Cancel", "Next"}; /*int result = JOptionPane.showOptionDialog(parent, panel, "Retailers (RetailCos) ", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, choices1, choices1[1]); if (result == 0 || result == -1) { return; } else if (result == 1) { //createAgent((String) comboMenu.getSelectedItem(), "buying.Buyer"); createAgent((String) menu2.getSelectedItem(), "buying.Buyer"); // createAgent("David_Owen","buying.Buyer"); }*/ } public void buyer_menu(PersonalAssistantGUI parent) { /* JMenuItem DO = new JMenuItem("David_Owen"); JMenuItem SCO = new JMenuItem("SCO_Corporation"); JMenuItem EC = new JMenuItem("Electro_Center"); */ String[] LSEs = {"RetailCO1", "RetailCO2", "RetailCO3", "RetailCO4"}; /*String DO = "David_Owen"; String SCO = "SCO_Corporation"; String EC = "Electro_Center"; String TE = "Electrical_Supplier";*/ // JMenuItem David_Owen = new JMenuItem("D"); // JMenu Buyer = new JMenu("Buyer"); JPanel panel = new JPanel(new BorderLayout()); //Panel center - icon JPanel panel_center = new JPanel(); panel_center.setLayout(new GridBagLayout()); panel_center.setPreferredSize(new Dimension(270, 100)); panel_center.setMinimumSize(new Dimension(270, 100)); // panel_center.add(split_pane_log_image, BorderLayout.NORTH); // JPanel panel_north = new JPanel(new GridLayout(1, 2)); JLabel l = new JLabel("RetailCos: "); l.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(0, 40, 40, 30); panel_center.add(l, gridBagConstraints); // JMenu[] menus = new JMenu[1]; // // menus[0] = Seller; // // // menus[0].add(RES); //JMenu menu = ComboMenuBar.createMenu("Supplier"); JComboBox menu2 = new JComboBox(); String[] auxName; for (String lse1 : LSEs) { if (checkbuyer(lse1) == 0) { menu2.addItem(lse1); } } auxName = new String[menu2.getItemCount()]; for (int i = 0; i < auxName.length; i++) { auxName[i] = menu2.getItemAt(i).toString(); } if (auxName.length > 0) { LoadAgent_Name openWindow = new LoadAgent_Name(this, 2, auxName); openWindow.setVisible(true); } /* if(checkbuyer(DO)==0) { menu2.addItem(DO); } if(checkbuyer(EC)==0) { menu2.addItem(EC); } if(checkbuyer(SCO)==0) { menu2.addItem(SCO); } if(checkbuyer(TE)==0) { menu2.addItem(TE); } */ /*int j = checkbuyer(DO.getText()); if (j == 0) { menu.add(DO); } j = checkbuyer(EC.getText());; if (j == 0) { menu.add(EC); } j = checkbuyer(SCO.getText()); if (j == 0) { menu.add(SCO); }*/ //// menu.addSeparator(); // menu.add(menus[2]); // menu.add(menus[3]); /*ComboMenuBar comboMenu = new ComboMenuBar(menu); comboMenu.setMinimumSize(new Dimension(180, 25)); comboMenu.setPreferredSize(new Dimension(180, 25));*/ menu2.setMinimumSize(new Dimension(180, 25)); menu2.setPreferredSize(new Dimension(180, 25)); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new Insets(-3, -30, 25, 50); //panel_center.add(comboMenu, gridBagConstraints); panel_center.add(menu2, gridBagConstraints); panel.add(panel_center, BorderLayout.CENTER); String[] choices1 = {"Cancel", "Next"}; /*int result = JOptionPane.showOptionDialog(parent, panel, "Retailers (RetailCos) ", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, choices1, choices1[1]); if (result == 0 || result == -1) { return; } else if (result == 1) { //createAgent((String) comboMenu.getSelectedItem(), "buying.Buyer"); createAgent((String) menu2.getSelectedItem(), "buying.Buyer"); // createAgent("David_Owen","buying.Buyer"); }*/ } public int checkbuyer(String Buyer) { int j = 0; for (int i = 0; i < buyer_names.size(); i++) { if (Buyer.trim().replace(" ", "_").equals(buyer_names.get(i).getLocalName().trim().replace(" ", "_"))) { i = buyer_names.size(); j = 1; } } return j; } public void createAgent(String AgentName, String ClassName) { // Creates a new agent via the platform controller PlatformController container = getContainerController(); // In - Agent Name * Agent Type i.e. "buying.Buyer" "selling.Seller" ... try { AgentController newBuyer = container.createNewAgent(AgentName, ClassName, null); newBuyer.start(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Entrou no catch!", "Warning", JOptionPane.WARNING_MESSAGE); } } public void killAgent(String AgentName, String ClassName) { PlatformController container = getContainerController(); try { AgentController x = container.getAgent(AgentName); x.kill(); } catch (Exception e) { } } public void seller_risk(PersonalAssistantGUI parent) { String[] choices = {"Save", "Cancel"}; JPanel panel = new JPanel(new BorderLayout()); // Panel north // Listener2 listener2 = new Listener2(); JPanel panel_north = new JPanel(); panel_north.setLayout(new BorderLayout()); panel_north.setMinimumSize(new Dimension(350, 60)); panel_north.setPreferredSize(new Dimension(350, 60)); panel_north.setBorder(new BevelBorder(BevelBorder.LOWERED)); JPanel panel_text_background = new JPanel(); JLabel label_text = new JLabel(); panel_text_background.setMinimumSize(new Dimension(295, 6)); panel_text_background.setPreferredSize(new Dimension(295, 60)); label_text.setMinimumSize(new Dimension(290, 50)); label_text.setPreferredSize(new Dimension(290, 50)); label_text.setHorizontalAlignment(SwingConstants.CENTER); label_text.setText("<html>Enter the Generators's Risk Preferences</html>"); label_text.setFont(font_1); panel_text_background.add(label_text); panel_north.add(panel_text_background, BorderLayout.CENTER); try { BufferedImage picture = ImageIO.read(new File(icon_risk)); JPanel panel_pic_background = new JPanel(); JLabel label_pic = new JLabel(new ImageIcon(picture)); panel_pic_background.setMinimumSize(new Dimension(55, 55)); panel_pic_background.setPreferredSize(new Dimension(55, 55)); panel_pic_background.add(label_pic); panel_north.add(panel_pic_background, BorderLayout.EAST); } catch (IOException ex) { Logger.getLogger(BuyerInputGui.class.getName()).log(Level.SEVERE, null, ex); } JPanel panel_center = new rseller(this); panel_center.setMinimumSize(new Dimension(350, 100)); panel_center.setPreferredSize(new Dimension(350, 250)); panel.add(panel_north, BorderLayout.NORTH); panel.add(panel_center, BorderLayout.CENTER); int result = JOptionPane.showOptionDialog(parent, panel, "Risk Preferences", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, choices, null); if (result == 1) { seller_risk_exposure = 1.0; seller_risk = 0; } if (result == 0) { // seller_risk_exposure=Double.valueOf(jTseller.getText()); } } public void buyer_risk(PersonalAssistantGUI parent) { String[] choices = {"Save", "Cancel"}; JPanel panel = new JPanel(new BorderLayout()); // Panel north // Listener2 listener2 = new Listener2(); JPanel panel_north = new JPanel(); panel_north.setLayout(new BorderLayout()); panel_north.setMinimumSize(new Dimension(350, 60)); panel_north.setPreferredSize(new Dimension(350, 60)); panel_north.setBorder(new BevelBorder(BevelBorder.LOWERED)); JPanel panel_text_background = new JPanel(); JLabel label_text = new JLabel(); panel_text_background.setMinimumSize(new Dimension(295, 6)); panel_text_background.setPreferredSize(new Dimension(295, 60)); label_text.setMinimumSize(new Dimension(290, 50)); label_text.setPreferredSize(new Dimension(290, 50)); label_text.setHorizontalAlignment(SwingConstants.CENTER); label_text.setText("<html>Enter the Buyer's Risk Preferences</html>"); label_text.setFont(font_1); panel_text_background.add(label_text); panel_north.add(panel_text_background, BorderLayout.CENTER); try { BufferedImage picture = ImageIO.read(new File(icon_risk)); JPanel panel_pic_background = new JPanel(); JLabel label_pic = new JLabel(new ImageIcon(picture)); panel_pic_background.setMinimumSize(new Dimension(55, 55)); panel_pic_background.setPreferredSize(new Dimension(55, 55)); panel_pic_background.add(label_pic); panel_north.add(panel_pic_background, BorderLayout.EAST); } catch (IOException ex) { Logger.getLogger(BuyerInputGui.class.getName()).log(Level.SEVERE, null, ex); } JPanel panel_center = new rbuyer(this); panel_center.setMinimumSize(new Dimension(350, 100)); panel_center.setPreferredSize(new Dimension(350, 250)); panel.add(panel_north, BorderLayout.NORTH); panel.add(panel_center, BorderLayout.CENTER); int result = JOptionPane.showOptionDialog(parent, panel, "Risk Preferences", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, choices, null); if (result == 1) { buyer_risk_exposure = 0; buyer_risk = 0; } if (result == 0) { // buyer_risk_exposure=Double.valueOf(jTbuyer.getText()); } } public void setContractOption_Windows(PersonalAssistantGUI parent) { contractTypeForm = new Bilateral_ContractType_Form(this); contractTypeForm.setVisible(false); negotiationForm = new Bilateral_NegotiationOption(this); negotiationForm.setVisible(false); } public void setContractType() { contractTypeForm.setVisible(true); negotiationForm.setVisible(false); } public void setNegotiationType() { negotiationForm.setVisible(true); contractTypeForm.setVisible(false); } public int getBilateral_contractType() { return bilateral_contractType; } public void setBilateral_contractType(int bilateral_contractType) { this.bilateral_contractType = bilateral_contractType; if(bilateral_contractType == 1) { mo_gui.setMarketSimulAvailable(false, false); } } public int getBilateral_contractDuration() { return bilateral_contractDuration; } public void setBilateral_contractDuration(int bilateral_contractDuration) { this.bilateral_contractDuration = bilateral_contractDuration; } public int getBilateral_tradingProcess() { return bilateral_tradingProcess; } public void setBilateral_tradingProcess(int bilateral_tradingProcess) { this.bilateral_tradingProcess = bilateral_tradingProcess; } public int getBilateral_tariff() { return bilateral_tariff; } public void setBilateral_tariff(int bilateral_tariff) { this.bilateral_tariff = bilateral_tariff; } public int getBilateral_hoursPeriod() { return bilateral_hoursPeriod; } public void setBilateral_hoursPeriod(int bilateral_hoursPeriod) { this.bilateral_hoursPeriod = bilateral_hoursPeriod; } public void setBilateral_DeadlineDate(int _year, int _month, int _day, int _hour, int _minutes) { bilateral_year = _year; bilateral_month = _month; bilateral_day = _day; bilateral_hour = _hour; bilateral_minutes = _minutes; } public int getBilateral_year() { return bilateral_year; } public int getBilateral_month() { return bilateral_month; } public int getBilateral_day() { return bilateral_day; } public int getBilateral_hour() { return bilateral_hour; } public int getBilateral_minutes() { return bilateral_minutes; } public void setMenus_availability(boolean _isContractNet) { mo_gui.setMarketOptionsAvailable(false, false, _isContractNet); } public void setprotocol(PersonalAssistantGUI parent) { String[] choices = {"Next", "Cancel"}; JPanel panel = new JPanel(new BorderLayout()); // Panel north // Listener2 listener2 = new Listener2(); JPanel panel_north = new JPanel(); panel_north.setLayout(new BorderLayout()); panel_north.setMinimumSize(new Dimension(350, 60)); panel_north.setPreferredSize(new Dimension(350, 60)); panel_north.setBorder(new BevelBorder(BevelBorder.LOWERED)); JPanel panel_text_background = new JPanel(); JLabel label_text = new JLabel(); panel_text_background.setMinimumSize(new Dimension(295, 6)); panel_text_background.setPreferredSize(new Dimension(295, 60)); label_text.setMinimumSize(new Dimension(290, 50)); label_text.setPreferredSize(new Dimension(290, 50)); label_text.setHorizontalAlignment(SwingConstants.CENTER); label_text.setText("<html>Select a Format for the Trading Process</html>"); label_text.setFont(font_1); panel_text_background.add(label_text); panel_north.add(panel_text_background, BorderLayout.CENTER); try { BufferedImage picture = ImageIO.read(new File(icon_risk)); JPanel panel_pic_background = new JPanel(); JLabel label_pic = new JLabel(new ImageIcon(picture)); panel_pic_background.setMinimumSize(new Dimension(55, 55)); panel_pic_background.setPreferredSize(new Dimension(55, 55)); panel_pic_background.add(label_pic); panel_north.add(panel_pic_background, BorderLayout.EAST); } catch (IOException ex) { Logger.getLogger(BuyerInputGui.class.getName()).log(Level.SEVERE, null, ex); } JPanel panel_center = new protocol(this); panel_center.setMinimumSize(new Dimension(350, 100)); panel_center.setPreferredSize(new Dimension(350, 200)); panel.add(panel_north, BorderLayout.NORTH); panel.add(panel_center, BorderLayout.CENTER); int result = JOptionPane.showOptionDialog(parent, panel, "Trading Protocol", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, choices, choices[0]); // If Next Button -> result = 0 // If Cancel Button -> result = 1; if (result == 0) { timeperiods(null); // buyer_risk_exposure=0; // buyer_risk=0; } else { } } public void setcontract(PersonalAssistantGUI parent) { String[] choices = {"Save", "Cancel", "<< Back"}; JPanel panel = new JPanel(new BorderLayout()); // Panel north // Listener2 listener2 = new Listener2(); JPanel panel_north = new JPanel(); panel_north.setLayout(new BorderLayout()); panel_north.setMinimumSize(new Dimension(350, 60)); panel_north.setPreferredSize(new Dimension(350, 60)); panel_north.setBorder(new BevelBorder(BevelBorder.LOWERED)); JPanel panel_text_background = new JPanel(); JLabel label_text = new JLabel(); panel_text_background.setMinimumSize(new Dimension(295, 6)); panel_text_background.setPreferredSize(new Dimension(295, 60)); label_text.setMinimumSize(new Dimension(290, 50)); label_text.setPreferredSize(new Dimension(290, 50)); label_text.setHorizontalAlignment(SwingConstants.CENTER); label_text.setText("<html>Indicate the type of Contract and Duration</html>"); label_text.setFont(font_1); panel_text_background.add(label_text); panel_north.add(panel_text_background, BorderLayout.CENTER); try { BufferedImage picture = ImageIO.read(new File(icon_risk)); JPanel panel_pic_background = new JPanel(); JLabel label_pic = new JLabel(new ImageIcon(picture)); panel_pic_background.setMinimumSize(new Dimension(55, 55)); panel_pic_background.setPreferredSize(new Dimension(55, 55)); panel_pic_background.add(label_pic); panel_north.add(panel_pic_background, BorderLayout.EAST); } catch (IOException ex) { Logger.getLogger(BuyerInputGui.class.getName()).log(Level.SEVERE, null, ex); } JPanel panel_center = new contract(); panel_center.setMinimumSize(new Dimension(350, 100)); panel_center.setPreferredSize(new Dimension(350, 200)); panel.add(panel_north, BorderLayout.NORTH); panel.add(panel_center, BorderLayout.CENTER); int result = JOptionPane.showOptionDialog(parent, panel, "Contract Type and Duration", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, choices, choices[0]); limits = new JTextField[2]; limits[0] = new JTextField(64); limits[1] = new JTextField(64); if (result == 2) { askDeadline(null, 1); } if (result == 1) { contract = "Forward Contract"; } if (result == 0) { double day = 0; day = (Double.valueOf(jT2.getText())); this.contractduration = (int) day; } } public void timeperiods(PersonalAssistantGUI parent) { String[] choices = {"Next >>", "Cancel", "<< Back"}; JPanel panel = new JPanel(new BorderLayout()); // Panel north // Listener2 listener2 = new Listener2(); JPanel panel_north = new JPanel(); panel_north.setLayout(new BorderLayout()); panel_north.setMinimumSize(new Dimension(500, 60)); panel_north.setPreferredSize(new Dimension(500, 60)); panel_north.setBorder(new BevelBorder(BevelBorder.LOWERED)); JPanel panel_text_background = new JPanel(); JLabel label_text = new JLabel(); panel_text_background.setMinimumSize(new Dimension(500, 6)); panel_text_background.setPreferredSize(new Dimension(500, 60)); label_text.setMinimumSize(new Dimension(500, 50)); label_text.setPreferredSize(new Dimension(500, 50)); label_text.setHorizontalAlignment(SwingConstants.CENTER); label_text.setText("<html>Enter the Periods of the Day</html>"); label_text.setFont(font_1); panel_text_background.add(label_text); panel_north.add(panel_text_background, BorderLayout.CENTER); try { BufferedImage picture = ImageIO.read(new File(icon_risk)); JPanel panel_pic_background = new JPanel(); JLabel label_pic = new JLabel(new ImageIcon(picture)); panel_pic_background.setMinimumSize(new Dimension(55, 55)); panel_pic_background.setPreferredSize(new Dimension(55, 55)); panel_pic_background.add(label_pic); panel_north.add(panel_pic_background, BorderLayout.EAST); } catch (IOException ex) { Logger.getLogger(BuyerInputGui.class.getName()).log(Level.SEVERE, null, ex); } JPanel panel_center = new tperiods(); panel_center.setMinimumSize(new Dimension(500, 100)); panel_center.setPreferredSize(new Dimension(500, 200)); panel.add(panel_north, BorderLayout.NORTH); panel.add(panel_center, BorderLayout.CENTER); int result = JOptionPane.showOptionDialog(parent, panel, "Time Periods", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, choices, choices[0]); String s = jT1.getText(); // limits[0].setText(jT1.getText()); // limits[1].setText(jT1.getText()); while (result != -1 && s == null) { JOptionPane.showMessageDialog(parent, new JLabel("<html>Please insert the negotiation Hours</html>"), "Targets", JOptionPane.ERROR_MESSAGE); result = JOptionPane.showOptionDialog(parent, new tperiods(), "Time Periods", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, choices, null); s = jT1.getText(); } switch (result) { case 0: // Save Button // contract=((String) jComboBox2.getSelectedItem()); // double d=0, day=0; // d=(Double.valueOf(jSlider1.getValue())); // this.N_PERIODS=(int)d; this.N_PERIODS = jS1.getValue(); int[] array = new int[N_PERIODS + 1]; // day=(Double.valueOf(jTextField2.getText())); // this.contractduration=(int)day; // for (int i=0; i<N_PERIODS; i++){ // array[i]=0; // } if (this.N_PERIODS != 24) { // String s =jT1.getText(); String[] my_hours_array_aux = s.split(";"); String[] my_hours_array = new String[24 + N_PERIODS]; String[] hours_aux = new String[2]; for (int i = 0; i < my_hours_array_aux.length; i++) { if (my_hours_array_aux[i].contains(",")) { String[] hours = my_hours_array_aux[i].split(","); for (int j = 0; j < hours.length; j++) { if (hours[j].contains("-")) { hours_aux = hours[j].split("-"); for (int z = 0; z < 1 + (Double.valueOf(hours_aux[1])) - (Double.valueOf(hours_aux[0])); z++) { my_hours_array[array[0]] = String.valueOf(Double.valueOf(hours_aux[0]) + z); array[0]++; } } else { my_hours_array[array[0]] = hours[j]; array[0]++; } } } else { if (my_hours_array_aux[i].contains("-")) { hours_aux = my_hours_array_aux[i].split("-"); for (int z = 0; z < 1 + (Double.valueOf(hours_aux[1])) - (Double.valueOf(hours_aux[0])); z++) { my_hours_array[array[0]] = String.valueOf(Double.valueOf(hours_aux[0]) + z); array[0]++; } } } array[i + 1] = array[0]; for (int y = 0; y < i; y++) { array[i + 1] = array[i + 1] - array[i]; } if (array[i + 1] <= 0) { my_hours_array[i] = my_hours_array_aux[i]; array[i + 1] = 1; } my_hours_array[24 + i] = String.valueOf(array[i + 1]); } for (int j = 0; j < my_hours_array.length; j++) { getHours().add(my_hours_array[j]); } // buy_gui.redefine(); } // Seller Deadline askDeadline(null, 0); break; case 1: // Cancel Button break; case 2: // Back Button this.setprotocol(null); break; } } public void askDeadline(PersonalAssistantGUI parent, int agent) { Date date_proposed = new Date(); date_proposed.setTime(System.currentTimeMillis()); // // // JPanel panel = new JPanel(new BorderLayout()); // // //Panel north // JPanel panel_north = new JPanel(); // // panel_north.setLayout(new BorderLayout()); // panel_north.setMinimumSize(new Dimension(400, 70)); // panel_north.setPreferredSize(new Dimension(400, 70)); // panel_north.setBorder(new BevelBorder(BevelBorder.LOWERED)); // // JPanel panel_text_background = new JPanel(); // JLabel label_text = new JLabel(); // panel_text_background.setMinimumSize(new Dimension(345, 60)); // panel_text_background.setPreferredSize(new Dimension(345, 60)); // label_text.setMinimumSize(new Dimension(345, 60)); // label_text.setPreferredSize(new Dimension(345, 60)); // label_text.setHorizontalAlignment(SwingConstants.CENTER); // // label_text.setText("<html>Enter your deadline </html>"); // // label_text.setFont(font_1); // panel_text_background.add(label_text); // panel_north.add(panel_text_background, BorderLayout.CENTER); // // // try { // BufferedImage picture = ImageIO.read(new File(icon_agenda_location)); // JPanel panel_pic_background = new JPanel(); // JLabel label_pic = new JLabel(new ImageIcon(picture)); // panel_pic_background.setMinimumSize(new Dimension(55, 55)); // panel_pic_background.setPreferredSize(new Dimension(55, 55)); // panel_pic_background.add(label_pic); // panel_north.add(panel_pic_background, BorderLayout.EAST); // } catch (IOException ex) { // Logger.getLogger(BuyerInputGui.class.getName()).log(Level.SEVERE, null, ex); // } //// // panel.add(panel_north, BorderLayout.NORTH); String[] choices = {"Set", "<< Back"}; String title = ""; switch (agent) { case 0: title = "Seller Deadline"; break; case 1: title = "Buyer Deadline"; break; default: JOptionPane.showMessageDialog(null, "AGENT ERROR", "Warning", JOptionPane.WARNING_MESSAGE); break; } int result = JOptionPane.showOptionDialog(parent, new deadline(), title, JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, choices, choices[0]); switch (result) { case 1: switch (agent) { case 0: // Get back to Time Periods timeperiods(null); break; case 1: // Get back to Seller Deadline askDeadline(null, 0); break; default: JOptionPane.showMessageDialog(null, "AGENT ERROR", "Warning", JOptionPane.WARNING_MESSAGE); break; } break; case 0: // Button Set TimeChooser tc = new TimeChooser(date_proposed); int result_date = tc.showEditTimeDlg(parent); while (tc.getDate().getTime() <= System.currentTimeMillis()) { String[] choices2 = {"OK"}; int aux = JOptionPane.showOptionDialog(parent, "You must choose a date higher than the current date.", " WARNING", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, choices2, null); if (aux == 0) { tc = new TimeChooser(date_proposed); result_date = tc.showEditTimeDlg(parent); System.out.println(tc.getDate().getTime() + " " + System.currentTimeMillis()); } } while (result_date == 1) { tc = new TimeChooser(date_proposed); result_date = tc.showEditTimeDlg(parent); } if (agent == 0) { sellerdeadline = tc.getDate(); askDeadline(null, 1); } if (agent == 1) { buyerdeadline = tc.getDate(); setcontract(null); } break; } } public void Volumes(PersonalAssistantGUI parent) { periods = new JTextField[1]; // limits = new JTextField[1]; Listener listener = new Listener(); JPanel panel = new JPanel(new BorderLayout()); JPanel panel_center = new JPanel(); panel_center.setLayout(new GridBagLayout()); panel_center.setMinimumSize(new Dimension(200, 75)); panel_center.setPreferredSize(new Dimension(200, 75)); // Panel north chinButton = new JCheckBox("Yes"); chinButton.setMnemonic(KeyEvent.VK_0); chinButton.setSelected(true); //Register a listener for the check boxes. chinButton.addItemListener(listener); chinButton.setMinimumSize(new Dimension(50, 25)); chinButton.setPreferredSize(new Dimension(50, 25)); GridBagConstraints gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = GridBagConstraints.WEST; gridBagConstraints.insets = new Insets(0, 30, 0, 100); panel_center.add(chinButton, gridBagConstraints); chinButton2 = new JCheckBox("No"); chinButton2.setMnemonic(KeyEvent.VK_0); chinButton2.setSelected(false); //Register a listener for the check boxes. chinButton2.addItemListener(listener); chinButton2.setMinimumSize(new Dimension(50, 25)); chinButton2.setPreferredSize(new Dimension(50, 25)); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = GridBagConstraints.CENTER; gridBagConstraints.insets = new Insets(0, 100, 0, 0); panel_center.add(chinButton2, gridBagConstraints); JLabel l = new JLabel("<html>Do you want to change your Volumes?</html>"); l.setHorizontalAlignment(SwingConstants.LEFT); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 0); panel_center.add(l, gridBagConstraints); panel.add(panel_center, BorderLayout.CENTER); String[] choices = {"Save", "Cancel"}; int result = JOptionPane.showOptionDialog(parent, panel, "Demand Response", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, choices, null); // while (result != -1 && (checkEmptyFields(periods) || checkEmptyFields(limits))) { // // JOptionPane.showMessageDialog(parent, new JLabel("<html>Some inputs are missing</html>"), "Targets", JOptionPane.ERROR_MESSAGE); // result = JOptionPane.showOptionDialog(parent, panel, "Targets", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, choices, null); // // } if (result == 0) { } } private class Listener implements ItemListener { public void itemStateChanged(ItemEvent e) { Object source = e.getItemSelectable(); if (source == chinButton && e.getStateChange() != ItemEvent.DESELECTED) { demandresponse = 1; // buyer.setDemandResponse(demandresponse); if (chinButton2.isSelected()) { chinButton2.setSelected(false); } // chinButton.setSelected(true); } if (source == chinButton && e.getStateChange() == ItemEvent.DESELECTED) { demandresponse = 0; // buyer.setDemandResponse(demandresponse); if (!chinButton2.isSelected()) { chinButton2.setSelected(true); } // chinButton.setSelected(false); } if (source == chinButton2 && e.getStateChange() != ItemEvent.DESELECTED) { demandresponse = 0; // buyer.setDemandResponse(demandresponse); if (chinButton.isSelected()) { chinButton.setSelected(false); } // chinButton.setSelected(true); } if (source == chinButton2 && e.getStateChange() == ItemEvent.DESELECTED) { demandresponse = 1; // buyer.setDemandResponse(demandresponse); if (!chinButton.isSelected()) { chinButton.setSelected(true); } // chinButton.setSelected(false); } } } public boolean checkEmptyFields(JTextField[] text_fields) { for (int i = 0; i < text_fields.length; i++) { if (text_fields[i].getText().isEmpty()) { return true; } } return false; } public void removeNegotiationPair(AID[] pair) { this.negotiation_pairs.remove(pair); } public ArrayList<String> getBelifsAboutMyAgent() { return this.beliefs_about_myagent; } public ArrayList<String> getHours() { return this.HOURS; } private void addBelif(String name, String belief) { if (name.equals("myagent")) { getBelifsAboutMyAgent().add(belief); } else if (getBelifsAboutOthers().containsKey(name)) { ArrayList<String> list = getBelifsAboutOthers().get(name); list.add(belief); getBelifsAboutOthers().put(name, list); } else { ArrayList<String> list = new ArrayList<>(); list.add(belief); getBelifsAboutOthers().put(name, list); } } public boolean beliefExists(String name, String belief) { if (name.equals("myagent")) { for (int i = 0; i < getBelifsAboutMyAgent().size(); i++) { if (getBelifsAboutMyAgent().get(i).equals(belief)) { return true; } } } else if (getBelifsAboutOthers().containsKey(name)) { for (int i = 0; i < getBelifsAboutOthers().get(name).size(); i++) { if (getBelifsAboutOthers().get(name).get(i).equals(belief)) { return true; } } } return false; } public String searchPartialBelief(String name, String belief) { if (name.equals("myagent")) { for (int i = 0; i < getBelifsAboutMyAgent().size(); i++) { if (getBelifsAboutMyAgent().get(i).contains(belief)) { return getBelifsAboutMyAgent().get(i); } } } else if (getBelifsAboutOthers().containsKey(name)) { for (int i = 0; i < getBelifsAboutOthers().get(name).size(); i++) { if (getBelifsAboutOthers().get(name).get(i).contains(belief)) { return getBelifsAboutOthers().get(name).get(i); } } } return null; } public void removeBelief(String name, String belief) { if (name.equals("myagent")) { for (int i = 0; i < getBelifsAboutMyAgent().size(); i++) { if (getBelifsAboutMyAgent().get(i).equals(belief)) { getBelifsAboutMyAgent().remove(i); } } } else if (getBelifsAboutOthers().containsKey(name)) { for (int i = 0; i < getBelifsAboutOthers().get(name).size(); i++) { if (getBelifsAboutOthers().get(name).get(i).equals(belief)) { getBelifsAboutOthers().get(name).remove(i); if (getBelifsAboutOthers().get(name).isEmpty()) { getBelifsAboutOthers().remove(name); return; } } } } } public ArrayList<AID> getBuyerNames() { return buyer_names; } public ArrayList<AID> getSellerNames() { return seller_names; } public ArrayList<AID> getLargeConsumersNames() { return largeConsumer_names; } public ArrayList<AID> getMediumConsumerNames() { return mediumConsumer_names; } public ArrayList<AID> getProducerNames() { return producer_names; } public class BuyerAgentsName { public String BuyerAgentsName() { return getSellerNames().toString(); } } public class tperiods extends javax.swing.JPanel { /** * Creates new form tperiods */ public tperiods() { initComponents(); } /** * 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"> private void initComponents() { jT1 = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); // jSeparator3 = new javax.swing.JSeparator(); jLabel5 = new javax.swing.JLabel(); jS1 = new javax.swing.JSlider(); // jLabel3 = new javax.swing.JLabel(); jT1.setFont(new java.awt.Font("Arial", 0, 13)); // NOI18N jT1.setText("1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18;19;20;21;22;23;24"); jLabel2.setFont(new java.awt.Font("Arial", 1, 13)); // NOI18N jLabel2.setText("Periods"); // jSeparator3.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); // jSeparator3.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N jLabel5.setFont(new java.awt.Font("Arial", 1, 13)); // NOI18N jLabel5.setText("Hour"); jS1.setFont(new java.awt.Font("Arial", 0, 13)); // NOI18N jS1.setMajorTickSpacing(1); jS1.setMaximum(24); jS1.setMinimum(1); jS1.setMinorTickSpacing(1); jS1.setPaintLabels(true); jS1.setPaintTicks(true); jS1.setToolTipText(""); // jLabel3.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N // jLabel3.setText("Please enter the Periods of the day that you want to Negotiate."); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(50, Short.MAX_VALUE) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jT1, javax.swing.GroupLayout.PREFERRED_SIZE, 356, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(50, 50, 50)) .addGroup(layout.createSequentialGroup() .addGap(78, 78, 78) // .addComponent(jLabel3) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) // .addComponent(jSeparator3) .addComponent(jS1, javax.swing.GroupLayout.PREFERRED_SIZE, 472, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(30, 30, 30) // .addComponent(jLabel3) // .addGap(26, 26, 26) // .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) // .addGap(2, 2, 2) .addComponent(jLabel2) .addGap(18, 18, 18) .addComponent(jS1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jT1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) .addGap(30, 30, 30)) ); }// </editor-fold> // Variables declaration - do not modify private javax.swing.JLabel jLabel2; // private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel5; // private javax.swing.JSeparator jSeparator3; // End of variables declaration } public class contract extends javax.swing.JPanel { /** * Creates new form risk */ public contract() { initComponents(); } /** * 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"> private void initComponents() { jLabel1 = new javax.swing.JLabel(); // jSeparator1 = new javax.swing.JSeparator(); // jLabel2 = new javax.swing.JLabel(); jCheckBox5 = new javax.swing.JCheckBox(); jCheckBox6 = new javax.swing.JCheckBox(); jCheckBox7 = new javax.swing.JCheckBox(); jLabel12 = new javax.swing.JLabel(); jT2 = new javax.swing.JTextField(); jLabel1.setFont(new java.awt.Font("Arial", 1, 13)); // NOI18N jLabel1.setText("Type:"); // jLabel2.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N // jLabel2.setText("Indicate the type of Contract and the duration "); jCheckBox5.setFont(new java.awt.Font("Arial", 1, 13)); // NOI18N jCheckBox5.setText("Forward Contract"); jCheckBox5.setSelected(true); // jCheckBox5.setEnabled(false); jCheckBox6.setFont(new java.awt.Font("Arial", 1, 13)); // NOI18N jCheckBox6.setText("Contract For Differences"); // jCheckBox6.setEnabled(false); jCheckBox7.setFont(new java.awt.Font("Arial", 1, 13)); // NOI18N jCheckBox7.setText("Option Contract"); // jCheckBox7.setEnabled(false); jLabel12.setFont(new java.awt.Font("Arial", 1, 13)); // NOI18N jLabel12.setText("Duration (days):"); jT2.setFont(new java.awt.Font("Arial", 0, 13)); // NOI18N jT2.setText("" + contractduration); jT2.setPreferredSize(new Dimension(40, 25)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) // .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(19, 19, 19) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel12) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jT2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addGap(33, 33, 33) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jCheckBox6) .addComponent(jCheckBox5) .addComponent(jCheckBox7))))) .addGroup(layout.createSequentialGroup() .addGap(22, 22, 22) // .addComponent(jLabel2) )) .addContainerGap(22, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() // .addGap(21, 21, 21) // .addComponent(jLabel2) // .addGap(27, 27, 27) // .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(24, 24, 24) .addComponent(jCheckBox5) .addGap(0, 0, 0) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jCheckBox6) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBox7) .addGap(50, 50, 50) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel12) .addComponent(jT2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(50, Short.MAX_VALUE)) ); }// </editor-fold> private class ContractListener implements ItemListener { public void itemStateChanged(ItemEvent e) { Object source = e.getItemSelectable(); if (source == jCheckBox5 && e.getStateChange() != ItemEvent.DESELECTED) { contract = jCheckBox5.getName(); // buyer.setDemandResponse(demandresponse); if (jCheckBox6.isSelected()) { jCheckBox6.setSelected(false); } if (jCheckBox7.isSelected()) { jCheckBox7.setSelected(false); } // chinButton.setSelected(true); } if (source == jCheckBox5 && e.getStateChange() == ItemEvent.DESELECTED) { // buyer.setDemandResponse(demandresponse); if (jCheckBox6.isSelected()) { contract = jCheckBox6.getName(); } if (jCheckBox7.isSelected()) { contract = jCheckBox7.getName(); } if (!jCheckBox6.isSelected() && !jCheckBox7.isSelected()) { jCheckBox5.setSelected(true); } // chinButton.setSelected(false); } if (source == jCheckBox6 && e.getStateChange() != ItemEvent.DESELECTED) { contract = jCheckBox6.getName();; // buyer.setDemandResponse(demandresponse); if (jCheckBox5.isSelected()) { jCheckBox5.setSelected(false); } if (jCheckBox7.isSelected()) { jCheckBox7.setSelected(false); } } if (source == jCheckBox6 && e.getStateChange() == ItemEvent.DESELECTED) { // buyer.setDemandResponse(demandresponse); if (jCheckBox5.isSelected()) { contract = jCheckBox5.getName(); } if (jCheckBox7.isSelected()) { contract = jCheckBox7.getName(); } if (!jCheckBox5.isSelected() && !jCheckBox7.isSelected()) { jCheckBox6.setSelected(true); } // chinButton.setSelected(false); } if (source == jCheckBox7 && e.getStateChange() != ItemEvent.DESELECTED) { contract = jCheckBox7.getName(); // buyer.setDemandResponse(demandresponse); if (jCheckBox5.isSelected()) { jCheckBox5.setSelected(false); } if (jCheckBox6.isSelected()) { jCheckBox6.setSelected(false); } } if (source == jCheckBox7 && e.getStateChange() == ItemEvent.DESELECTED) { // buyer.setDemandResponse(demandresponse); if (jCheckBox5.isSelected()) { contract = jCheckBox5.getName(); } if (jCheckBox6.isSelected()) { contract = jCheckBox6.getName(); } if (!jCheckBox6.isSelected() && !jCheckBox5.isSelected()) { jCheckBox7.setSelected(true); } // chinButton.setSelected(false); } } } // Variables declaration - do not modify public javax.swing.JCheckBox jCheckBox5; public javax.swing.JCheckBox jCheckBox6; public javax.swing.JCheckBox jCheckBox7; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel12; // private javax.swing.JLabel jLabel2; // private javax.swing.JSeparator jSeparator1; // End of variables declaration } /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Hugo */ public class risk_seller extends javax.swing.JPanel { public PersonalAssistant mark; /** * Creates new form risk */ public risk_seller(PersonalAssistant market) { mark = market; initComponents(); } /** * 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"> private void initComponents() { jLabel1 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); jLabel2 = new javax.swing.JLabel(); jCheckBox5 = new javax.swing.JCheckBox(); jCheckBox6 = new javax.swing.JCheckBox(); jCheckBox7 = new javax.swing.JCheckBox(); jLabel3 = new javax.swing.JLabel(); jTseller = new javax.swing.JTextField(); // SpinnerModel sm = new SpinnerNumberModel(0.0, 0.0, 1.0, 0.1); // jSpinner1 = new javax.swing.JSpinner(sm); Listener listener = new Listener(); jLabel1.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N jLabel1.setText("Agent:"); jLabel2.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N jLabel2.setText("Please enter the Generator's Risk Preference"); jCheckBox5.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N jCheckBox5.setText("Risk-Averse"); jCheckBox5.addItemListener(listener); jCheckBox6.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N jCheckBox6.setText("Risk-Neutral"); jCheckBox6.setSelected(true); jCheckBox6.addItemListener(listener); jCheckBox7.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N jCheckBox7.setText("Risk-Seeking"); jCheckBox7.addItemListener(listener); jLabel3.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N jLabel3.setText("Risk Exposure:"); // jSpinner1.setRequestFocusEnabled(false); // jSpinner1.addChangeListener(new ChangeListener() { // // @Override // public void stateChanged(ChangeEvent e) { // mark.seller_risk_exposure=(double)jSpinner1.getValue(); // } // }); // JSpinner.NumberEditor editor = (JSpinner.NumberEditor)jSpinner1.getEditor(); // DecimalFormat format = editor.getFormat(); // format.setMinimumFractionDigits(1); // editor.getTextField().setHorizontalAlignment(SwingConstants.CENTER); // Dimension d = jSpinner1.getPreferredSize(); // d.width = 40; // jSpinner1.setPreferredSize(d); // jSpinner1.setMinimumSize(new Dimension(20, 20)); jTseller.setText("0.0"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGap(19, 19, 19) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTseller, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addGap(28, 28, 28) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jCheckBox6) .addComponent(jCheckBox5) .addComponent(jCheckBox7)))) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addComponent(jLabel2) .addGap(24, 24, 24) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(24, 24, 24) .addComponent(jCheckBox5) .addGap(0, 0, 0) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jCheckBox6) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBox7) .addGap(24, 24, 24) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jTseller, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); }// </editor-fold> private class Listener implements ItemListener { public void itemStateChanged(ItemEvent e) { Object source = e.getItemSelectable(); if (source == jCheckBox5 && e.getStateChange() != ItemEvent.DESELECTED) { mark.seller_risk = 1; // seller.setDemandResponse(demandresponse); if (jCheckBox6.isSelected()) { jCheckBox6.setSelected(false); } if (jCheckBox7.isSelected()) { jCheckBox7.setSelected(false); } // chinButton.setSelected(true); } if (source == jCheckBox5 && e.getStateChange() == ItemEvent.DESELECTED) { // seller.setDemandResponse(demandresponse); if (jCheckBox6.isSelected()) { mark.seller_risk = 0; } if (jCheckBox7.isSelected()) { mark.seller_risk = 2; } if (!jCheckBox6.isSelected() && !jCheckBox7.isSelected()) { jCheckBox5.setSelected(true); } // chinButton.setSelected(false); } if (source == jCheckBox6 && e.getStateChange() != ItemEvent.DESELECTED) { mark.seller_risk = 0; // seller.setDemandResponse(demandresponse); if (jCheckBox5.isSelected()) { jCheckBox5.setSelected(false); } if (jCheckBox7.isSelected()) { jCheckBox7.setSelected(false); } } if (source == jCheckBox6 && e.getStateChange() == ItemEvent.DESELECTED) { // seller.setDemandResponse(demandresponse); if (jCheckBox5.isSelected()) { mark.seller_risk = 1; } if (jCheckBox7.isSelected()) { mark.seller_risk = 2; } if (!jCheckBox5.isSelected() && !jCheckBox7.isSelected()) { jCheckBox6.setSelected(true); } // chinButton.setSelected(false); } if (source == jCheckBox7 && e.getStateChange() != ItemEvent.DESELECTED) { mark.seller_risk = 2; // seller.setDemandResponse(demandresponse); if (jCheckBox5.isSelected()) { jCheckBox5.setSelected(false); } if (jCheckBox6.isSelected()) { jCheckBox6.setSelected(false); } } if (source == jCheckBox7 && e.getStateChange() == ItemEvent.DESELECTED) { // seller.setDemandResponse(demandresponse); if (jCheckBox5.isSelected()) { mark.seller_risk = 1; } if (jCheckBox6.isSelected()) { mark.seller_risk = 0; } if (!jCheckBox6.isSelected() && !jCheckBox5.isSelected()) { jCheckBox7.setSelected(true); } // chinButton.setSelected(false); } } } // private class Listener2 implements ChangeListener { //public void StateChanged(ChangeEvent e) { // // Object source = e.getSource(); // // if (source == JSpinner1 && e.getStateChange() != ItemEvent.DESELECTED) { // //} //} // } // Variables declaration - do not modify public javax.swing.JCheckBox jCheckBox5; public javax.swing.JCheckBox jCheckBox6; public javax.swing.JCheckBox jCheckBox7; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JSeparator jSeparator1; // public javax.swing.JSpinner jSpinner1; // End of variables declaration } /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Hugo */ public class risk_buyer extends javax.swing.JPanel { public PersonalAssistant mark; /** * Creates new form risk */ public risk_buyer(PersonalAssistant market) { mark = market; initComponents(); } /** * 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"> private void initComponents() { jLabel1 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); jLabel2 = new javax.swing.JLabel(); jCheckBox5 = new javax.swing.JCheckBox(); jCheckBox6 = new javax.swing.JCheckBox(); jCheckBox7 = new javax.swing.JCheckBox(); jLabel3 = new javax.swing.JLabel(); // SpinnerModel sm = new SpinnerNumberModel(0.0, 0.0, 1.0, 0.1); // jSpinner1 = new javax.swing.JSpinner(sm); jTbuyer = new javax.swing.JTextField(); Listener listener = new Listener(); jLabel1.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N jLabel1.setText("Agent:"); jLabel2.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N jLabel2.setText("Please enter the buyer's Risk Preference"); jCheckBox5.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N jCheckBox5.setText("Risk-Averse"); jCheckBox5.addItemListener(listener); jCheckBox6.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N jCheckBox6.setText("Risk-Neutral"); jCheckBox6.addItemListener(listener); jCheckBox6.setSelected(true); jCheckBox7.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N jCheckBox7.setText("Risk-Seeking"); jCheckBox7.addItemListener(listener); jLabel3.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N jLabel3.setText("Risk Exposure:"); jTbuyer.setText("0.0"); // jSpinner1.setRequestFocusEnabled(false); // jSpinner1.addChangeListener(new ChangeListener() { // //// @Override //// public void stateChanged(ChangeEvent e) { //// mark.buyer_risk_exposure=(double)jSpinner1.getValue(); //// } //// }); // JSpinner.NumberEditor editor = (JSpinner.NumberEditor)jSpinner1.getEditor(); // DecimalFormat format = editor.getFormat(); // format.setMinimumFractionDigits(1); // editor.getTextField().setHorizontalAlignment(SwingConstants.CENTER); // Dimension d = jSpinner1.getPreferredSize(); // d.width = 40; // jSpinner1.setPreferredSize(d); // jSpinner1.setMinimumSize(new Dimension(20, 20)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGap(19, 19, 19) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTbuyer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addGap(28, 28, 28) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jCheckBox6) .addComponent(jCheckBox5) .addComponent(jCheckBox7)))) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addComponent(jLabel2) .addGap(24, 24, 24) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(24, 24, 24) .addComponent(jCheckBox5) .addGap(0, 0, 0) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jCheckBox6) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBox7) .addGap(24, 24, 24) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jTbuyer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); }// </editor-fold> private class Listener implements ItemListener { public void itemStateChanged(ItemEvent e) { Object source = e.getItemSelectable(); if (source == jCheckBox5 && e.getStateChange() != ItemEvent.DESELECTED) { mark.buyer_risk = 1; // buyer.setDemandResponse(demandresponse); if (jCheckBox6.isSelected()) { jCheckBox6.setSelected(false); } if (jCheckBox7.isSelected()) { jCheckBox7.setSelected(false); } // chinButton.setSelected(true); } if (source == jCheckBox5 && e.getStateChange() == ItemEvent.DESELECTED) { // buyer.setDemandResponse(demandresponse); if (jCheckBox6.isSelected()) { mark.buyer_risk = 0; } if (jCheckBox7.isSelected()) { mark.buyer_risk = 2; } if (!jCheckBox6.isSelected() && !jCheckBox7.isSelected()) { jCheckBox5.setSelected(true); } // chinButton.setSelected(false); } if (source == jCheckBox6 && e.getStateChange() != ItemEvent.DESELECTED) { mark.buyer_risk = 0; // buyer.setDemandResponse(demandresponse); if (jCheckBox5.isSelected()) { jCheckBox5.setSelected(false); } if (jCheckBox7.isSelected()) { jCheckBox7.setSelected(false); } } if (source == jCheckBox6 && e.getStateChange() == ItemEvent.DESELECTED) { // buyer.setDemandResponse(demandresponse); if (jCheckBox5.isSelected()) { mark.buyer_risk = 1; } if (jCheckBox7.isSelected()) { mark.buyer_risk = 2; } if (!jCheckBox5.isSelected() && !jCheckBox7.isSelected()) { jCheckBox6.setSelected(true); } // chinButton.setSelected(false); } if (source == jCheckBox7 && e.getStateChange() != ItemEvent.DESELECTED) { mark.buyer_risk = 2; // buyer.setDemandResponse(demandresponse); if (jCheckBox5.isSelected()) { jCheckBox5.setSelected(false); } if (jCheckBox6.isSelected()) { jCheckBox6.setSelected(false); } } if (source == jCheckBox7 && e.getStateChange() == ItemEvent.DESELECTED) { // buyer.setDemandResponse(demandresponse); if (jCheckBox5.isSelected()) { mark.buyer_risk = 1; } if (jCheckBox6.isSelected()) { mark.buyer_risk = 0; } if (!jCheckBox6.isSelected() && !jCheckBox5.isSelected()) { jCheckBox7.setSelected(true); } // chinButton.setSelected(false); } } } // private class Listener2 implements ChangeListener { //public void StateChanged(ChangeEvent e) { // // Object source = e.getSource(); // // if (source == JSpinner1 && e.getStateChange() != ItemEvent.DESELECTED) { // //} //} // } // Variables declaration - do not modify public javax.swing.JCheckBox jCheckBox5; public javax.swing.JCheckBox jCheckBox6; public javax.swing.JCheckBox jCheckBox7; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JSeparator jSeparator1; // public javax.swing.JSpinner jSpinner1; // public javax.swing.JTextField jTbuyer; // End of variables declaration } public class Tools extends JInternalFrame { private JTabbedPane tabbedPane; private JTabbedPane panel1; private JTabbedPane panel2; private JTabbedPane panel3; private JTabbedPane panel4; public Tools(PersonalAssistant market) { // NOTE: to reduce the amount of code in this example, it uses // panels with a NULL layout. This is NOT suitable for // production code since it may not display correctly for // a look-and-feel. setTitle("Preferences"); setSize(600, 600); setBackground(Color.gray); JPanel topPanel = new JPanel(); topPanel.setLayout(new BorderLayout()); getContentPane().add(topPanel); // Create the tab pages // createPage1(); // createPage2(); // createPage3(); panel1 = new JTabbedPane(); panel1.add("Time Periods", new tperiods()); panel1.add("Trading Protocol", new protocol(market)); panel2 = new JTabbedPane(); panel2.add("Type and Duration", new contract()); panel3 = new JTabbedPane(); panel3.add("Risk Preference", new risk_seller(market)); panel4 = new JTabbedPane(); panel4.add("Risk Preference", new risk_buyer(market)); panel4.add("DR Management", new DR(market)); // panel3.add("Deadline", new deadline()); // panel3.add("Deadline", new setDeadline()); // panel2.add("Trading Protocol", new protocol(market)); // Create a tabbed pane tabbedPane = new JTabbedPane(); Border emptyBorder = BorderFactory.createEmptyBorder(); // tabbedPane.setMaximumSize(new Dimension(negicon.getIconHeight(), negicon.getIconWidth())); tabbedPane.setBorder(emptyBorder); UIManager.getDefaults().put("tabbedPane.contentBorderInsets", new Insets(0, 0, 0, 0)); UIManager.getDefaults().put("tabbedPane.tabsOverlapBorder", true); UIManager.getDefaults().put("panel1.contentBorderInsets", new Insets(0, 0, 0, 0)); UIManager.getDefaults().put("panel1.tabsOverlapBorder", true); // panel1.setMaximumSize(new Dimension(20, 20)); panel1.setBorder(emptyBorder); tabbedPane.addTab(null, negicon, panel1); tabbedPane.setBorder(emptyBorder); // tabbedPane.setMaximumSize(new Dimension(20, 20)); tabbedPane.setBorder(emptyBorder); tabbedPane.addTab(null, conicon, panel2); tabbedPane.addTab(null, sellicon, panel3); tabbedPane.addTab(null, buyicon, panel4); // tabbedPane.setMaximumSize(new Dimension(20, 20)); tabbedPane.setBorder(emptyBorder); // UIManager.getDefaults().put("tabbedPane.contentBorderInsets", new Insets(0,0,0,0)); // UIManager.getDefaults().put("tabbedPane.tabsOverlapBorder", true); // UIManager.getDefaults().put("panel1.contentBorderInsets", new Insets(0,0,0,0)); // UIManager.getDefaults().put("panel1.tabsOverlapBorder", true); // tabbedPane.setUI(new BasicTabbedPaneUI() { // private final Insets borderInsets = new Insets(0, 0, 0, 0); // @Override // protected void paintContentBorder(Graphics g, int tabPlacement, int selectedIndex) { // } // @Override // protected Insets getContentBorderInsets(int tabPlacement) { // return borderInsets; // } // }); // tabbedPane.addTab( "Page 2", panel2 ); // tabbedPane.addTab( "Page 3", panel3 ); // topPanel.setBorder(emptyBorder); topPanel.add(tabbedPane, BorderLayout.CENTER); this.setVisible(true); // topPanel.setVisible( true ); } } } class ComboMenuBar extends JMenuBar { JMenu menu; Dimension preferredSize; public ComboMenuBar(JMenu menu) { this.menu = menu; Color color = UIManager.getColor("Menu.selectionBackground"); UIManager.put("Menu.selectionBackground", UIManager .getColor("Menu.background")); menu.updateUI(); UIManager.put("Menu.selectionBackground", color); ComboMenuBar.MenuItemListener listener = new ComboMenuBar.MenuItemListener(); setListener(menu, listener); add(menu); } class MenuItemListener implements ActionListener { public void actionPerformed(ActionEvent e) { JMenuItem item = (JMenuItem) e.getSource(); menu.setText(item.getText()); menu.requestFocus(); } } private void setListener(JMenuItem item, ActionListener listener) { if (item instanceof JMenu) { JMenu menu = (JMenu) item; int n = menu.getItemCount(); for (int i = 0; i < n; i++) { setListener(menu.getItem(i), listener); } } else if (item != null) { // null means separator item.addActionListener(listener); } } public String getSelectedItem() { return menu.getText(); } public void setPreferredSize(Dimension size) { preferredSize = size; } public Dimension getPreferredSize() { if (preferredSize == null) { Dimension sd = super.getPreferredSize(); Dimension menuD = getItemSize(menu); Insets margin = menu.getMargin(); Dimension retD = new Dimension(menuD.width, margin.top + margin.bottom + menuD.height); menu.setPreferredSize(retD); preferredSize = retD; } return preferredSize; } private Dimension getItemSize(JMenu menu) { Dimension d = new Dimension(0, 0); int n = menu.getItemCount(); for (int i = 0; i < n; i++) { Dimension itemD; JMenuItem item = menu.getItem(i); if (item instanceof JMenu) { itemD = getItemSize((JMenu) item); } else if (item != null) { itemD = item.getPreferredSize(); } else { itemD = new Dimension(0, 0); // separator } d.width = Math.max(d.width, itemD.width); d.height = Math.max(d.height, itemD.height); } return d; } public static class ComboMenu extends JMenu { personalassistant.ArrowIcon iconRenderer; public ComboMenu(String label) { super(label); iconRenderer = new personalassistant.ArrowIcon(SwingConstants.SOUTH, true); setBorder(new EtchedBorder()); setIcon(new personalassistant.BlankIcon(null, 11)); setHorizontalTextPosition(JButton.LEFT); setFocusPainted(true); } public void paintComponent(Graphics g) { super.paintComponent(g); Dimension d = this.getPreferredSize(); int x = Math.max(0, d.width - iconRenderer.getIconWidth() - 3); int y = Math.max(0, (d.height - iconRenderer.getIconHeight()) / 2 - 2); iconRenderer.paintIcon(this, g, x, y); } } public static JMenu createMenu(String label) { return new personalassistant.ComboMenuBar.ComboMenu(label); } } class ArrowIcon implements Icon, SwingConstants { private static final int DEFAULT_SIZE = 11; //private static final int DEFAULT_SIZE = 5; private int size; private int iconSize; private int direction; private boolean isEnabled; private BasicArrowButton iconRenderer; public ArrowIcon(int direction, boolean isPressedView) { this(DEFAULT_SIZE, direction, isPressedView); } public ArrowIcon(int iconSize, int direction, boolean isEnabled) { this.size = iconSize / 2; this.iconSize = iconSize; this.direction = direction; this.isEnabled = isEnabled; iconRenderer = new BasicArrowButton(direction); } public void paintIcon(Component c, Graphics g, int x, int y) { iconRenderer.paintTriangle(g, x, y, size, direction, isEnabled); } public int getIconWidth() { //int retCode; switch (direction) { case NORTH: case SOUTH: return iconSize; case EAST: case WEST: return size; } return iconSize; } public int getIconHeight() { switch (direction) { case NORTH: case SOUTH: return size; case EAST: case WEST: return iconSize; } return size; } } class BlankIcon implements Icon { private Color fillColor; private int size; public BlankIcon() { this(null, 11); } public BlankIcon(Color color, int size) { //UIManager.getColor("control") //UIManager.getColor("controlShadow") fillColor = color; this.size = size; } public void paintIcon(Component c, Graphics g, int x, int y) { if (fillColor != null) { g.setColor(fillColor); g.drawRect(x, y, size - 1, size - 1); } } public int getIconWidth() { return size; } public int getIconHeight() { return size; } }
import java.util.Scanner; public class Triples { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int a = sc.nextInt(); sc.close(); for(int i = 0; i < a; i++){ for(int j = 0; j < i; j++){ if(i*i + j*j == a*a){ System.out.print(a + "^2 = " + i +"^2 + " + j + "^2"); int b = reduce(a, i, j); if(b != 0){ System.out.print(" => " + a/b + "^2 = " + i/b + "^2 + " + j/b + "^2"); } System.out.print("\n"); } } } } public static int reduce(int a, int i, int j){ int n = 0; for(int k = 2; k <= 0.5 * j; k++){ if(j % k == 0 && i % k == 0 && a % k == 0){ n = k; } } return n; } }
package com.generic.rest.dto; import java.io.Serializable; public class CategoryDto implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private String categoryId; private String categoryName; private String parentCategory; public CategoryDto() { } public CategoryDto(String categoryId, String categoryName) { this.categoryId = categoryId; this.categoryName = categoryName; } public CategoryDto(String categoryId, String categoryName, String parentCategory) { this.categoryId = categoryId; this.categoryName = categoryName; this.parentCategory = parentCategory; } public String getCategoryId() { return categoryId; } public void setCategoryId(String categoryId) { this.categoryId = categoryId; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } @Override public boolean equals(Object other) { if(other == null || !(other instanceof CategoryDto)) return false; if(this == other) return true; CategoryDto otherCategory = (CategoryDto)other; return this.categoryId.equals(otherCategory.categoryId); } @Override public int hashCode() { int hashcode = this.categoryId == null ? 17 : this.categoryId.hashCode(); return hashcode; } @Override public String toString() { return this.categoryId + ":" + this.categoryName; } public String getParentCategory() { return parentCategory; } public void setParentCategory(String parentCategory) { this.parentCategory = parentCategory; } }
package com.wzk.demo.springboot.shardingswagger.service.impl; import com.wzk.demo.springboot.shardingswagger.mapper.OrderMapper; import com.wzk.demo.springboot.shardingswagger.pojo.Order; import com.wzk.demo.springboot.shardingswagger.service.OrderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class OrderServiceImpl implements OrderService{ @Autowired private OrderMapper orderMapper; @Override public List<Order> getOrderService() { return orderMapper.getOrderList(); } }
package crawler; import java.beans.PropertyVetoException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.slf4j.Logger; import com.mchange.v2.c3p0.ComboPooledDataSource; import edu.uci.ics.crawler4j.crawler.Page; import edu.uci.ics.crawler4j.parser.HtmlParseData; import edu.uci.ics.crawler4j.url.WebURL; public class PostgresDBServiceImpl implements PostgresDBService { private ComboPooledDataSource comboPooledDataSource; private PreparedStatement updatePageStatement, insertPageStatement, getByUrlStatement, insertLinkStatement ; private static final Logger logger = org.slf4j.LoggerFactory.getLogger(PostgresDBServiceImpl.class); public PostgresDBServiceImpl(String dbUrl, String dbUser, String dbPw, String driver) throws PropertyVetoException, SQLException { comboPooledDataSource = new ComboPooledDataSource(); comboPooledDataSource.setDriverClass(driver); comboPooledDataSource.setJdbcUrl(dbUrl); comboPooledDataSource.setUser(dbUser); comboPooledDataSource.setPassword(dbPw); setup(); } private void setup() throws SQLException { updatePageStatement = comboPooledDataSource.getConnection().prepareStatement("UPDATE public.\"Page\" SET \"Content\"=? , \"Title\"=? WHERE \"Url\"=?"); insertPageStatement = comboPooledDataSource.getConnection().prepareStatement("INSERT INTO public.\"Page\"(\"ID\", \"Url\", \"Content\", \"Title\",\"PageRank\") VALUES (nextval('id_master-seq'), ?, ?, ?, ?)"); getByUrlStatement = comboPooledDataSource.getConnection().prepareStatement("SELECT \"ID\" FROM public.\"Page\" WHERE \"Url\"=?"); insertLinkStatement = comboPooledDataSource.getConnection().prepareStatement("INSERT INTO public.\"Link\"(\"ID_From\", \"ID_TO\", \"Strength\") VALUES (?, ?, ?)"); } public void store(Page page) { if (page.getParseData() instanceof HtmlParseData) { String url = page.getWebURL().getURL(); try { getByUrlStatement.setString(1, url); ResultSet rs = getByUrlStatement.executeQuery(); HtmlParseData htmlParseData = (HtmlParseData) page.getParseData(); System.out.println(htmlParseData.getTitle()); if(!rs.next()){ insertPageStatement.setString(1, url); insertPageStatement.setString(2, htmlParseData.getText()); insertPageStatement.setString(3, htmlParseData.getTitle()); insertPageStatement.setInt(4, 1); insertPageStatement.executeUpdate(); } else{ updatePageStatement.setString(1, htmlParseData.getText()); updatePageStatement.setString(2, htmlParseData.getTitle()); updatePageStatement.setString(3, url); updatePageStatement.executeUpdate(); } } catch (SQLException e) { logger.error("SQL Exception while storing webpage for url'{}'", page.getWebURL().getURL(), e); throw new RuntimeException(e); } } } public void storeWithoutContent(String url) { try { getByUrlStatement.setString(1, url); ResultSet rs = getByUrlStatement.executeQuery(); if(!rs.next()){ insertPageStatement.setString(1, url); insertPageStatement.setString(2, ""); insertPageStatement.setString(3, ""); insertPageStatement.setInt(4, 1); insertPageStatement.executeUpdate(); } } catch (SQLException e) { logger.error("SQL Exception while storing webpage for url'{}'", url, e); throw new RuntimeException(e); } } public void close() { if (comboPooledDataSource != null) { comboPooledDataSource.close(); } } public void storeLink(String from, String to, double strength) { int idFrom = getPageID(from); int idTo = getPageID(to); if(idFrom > 0 && idTo > 0){ try { insertLinkStatement.setInt(1, idFrom); insertLinkStatement.setInt(2, idTo); insertLinkStatement.setDouble(3, strength); insertLinkStatement.executeUpdate(); } catch (SQLException e) { logger.error("SQL Exception while requesting", from, e); throw new RuntimeException(e); } } } private boolean pageInDatabase(String url){ try { getByUrlStatement.setString(1, url); ResultSet rs = getByUrlStatement.executeQuery(); return rs.next(); } catch (SQLException e) { logger.error("SQL Exception while requesting", url, e); throw new RuntimeException(e); } } private int getPageID(String url){ try { getByUrlStatement.setString(1, url); ResultSet rs = getByUrlStatement.executeQuery(); //System.out.println(url); rs.next(); return rs.getInt(1); } catch (SQLException e) { logger.error("SQL Exception while requesting", url, e); throw new RuntimeException(e); } } }
package org.lucene.searchengine; import java.io.File; import java.io.IOException; import java.util.Date; import jeasy.analysis.MMAnalyzer; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.RAMDirectory; public class IndexHTML { public static final String INDEX_STORE_PATH = "D:\\Index"; public IndexHTML(){} public void createIndexes() { try { Date start = new Date(); RAMDirectory ramDir = new RAMDirectory(); FSDirectory fsDir = FSDirectory.getDirectory(INDEX_STORE_PATH,true); IndexWriter fsWriter = new IndexWriter(fsDir,new MMAnalyzer(),true); IndexWriter ramWriter = new IndexWriter(ramDir,new MMAnalyzer(),true); indexDocs(ramWriter,new File(HTMLDocument.FILE_STORE_PATH)); ramWriter.setMergeFactor(500); ramWriter.optimize(); ramWriter.close(); fsWriter.addIndexes(new Directory[]{ramDir}); fsWriter.optimize(); fsWriter.close(); Date end = new Date(); System.out.println("Time cost: "+(end.getTime()-start.getTime())/1000.0/60.0+" m"); }catch(IOException e) { System.out.println("[Error] Index Document failed!"); } } private void indexDocs(IndexWriter writer, File file) throws CorruptIndexException, IOException { if (file.isDirectory()) { String []files = file.list(); for (String f:files) { indexDocs(writer,new File(file,f)); } } else if (file.getName().endsWith(".html")|| file.getName().endsWith(".htm")|| file.getName().endsWith(".shtml")) { writer.addDocument(new HTMLDocument().getDocument(file)); } } }
package com.beike.dao.flagship.impl; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Repository; import com.beike.dao.GenericDaoImpl; import com.beike.dao.flagship.FlagshipDao; import com.beike.entity.flagship.Flagship; import com.beike.form.MerchantForm; import com.beike.mapper.FlagshipMapper; import com.beike.page.Pager; /** * @ClassName: FlagshipDaoImpl * @Description: TODO(这里用一句话描述这个类的作用) * @author Grace Guo guoqingcun@gmail.com * @date 2013-1-16 下午3:29:11 * */ @Repository("flagshipDao") public class FlagshipDaoImpl extends GenericDaoImpl<Flagship, Long> implements FlagshipDao { private final Log logger = LogFactory.getLog(FlagshipDaoImpl.class); @Override public Flagship getFlagshipByRealmName(String realmName,Boolean isPreview) throws Exception { StringBuilder sql = new StringBuilder("SELECT DISTINCT(BF.id),BF.guest_id,BF.brand_id,BF.city,BF.realm_name,BF.sina_microBlog,BF.qq_microBlog,BF.flagship_name, BF.flagship_background_color,BF.flagship_background_img,BFM.id AS mould_id,BFM.mould_name,BFM.mould_img,BFM.mould_url,GROUP_CONCAT(DISTINCT(BFB.branch_id)) AS branchs,flagship_logo,sina_microBlog_name "); sql.append("FROM beiker_flagship BF LEFT JOIN beiker_flagship_mould BFM ON BF.mould = BFM.id LEFT JOIN beiker_flagship_branch BFB ON BF.id = BFB.flagship_id JOIN beiker_merchant BM ON BFB.branch_id = BM.merchantid "); if(isPreview) sql.append("WHERE realm_name=? "); else sql.append("WHERE realm_name=? AND BF.is_online = '1' "); sql.append("GROUP BY BFB.flagship_id "); sql.append("limit 1"); return this.getSimpleJdbcTemplate().queryForObject(sql.toString(), new FlagshipMapper(), new Object[]{realmName}); } @Override public Long getLastInsertId() { // TODO Auto-generated method stub return null; } @Override public List<MerchantForm> getChildMerchnatById(String branchs, Pager pager) { // modify by qiaowb 2011-12-30 只查询曾经有过商品的分店地址 String sql = "select distinct m.merchantname as merchantname,m.merchantid as id,m.addr as addr,m.latitude as latitude,m.tel as tel,m.buinesstime as buinesstime,m.city as city, m.is_support_takeaway as is_support_takeaway, m.is_support_online_meal as is_support_online_meal,m.environment,m.capacity,m.otherservice from beiker_merchant m where m.merchantid in("+branchs+") order by m.sort_number asc,m.merchantid desc limit " + pager.getStartRow() + "," + pager.getPageSize(); List list = this.getJdbcTemplate().queryForList(sql); if (list == null || list.size() == 0) return null; List<MerchantForm> listForm = new ArrayList<MerchantForm>(); for (int i = 0; i < list.size(); i++) { Map map = (Map) list.get(i); MerchantForm merchantForm = new MerchantForm(); String merchantname = (String) map.get("merchantname"); merchantForm.setMerchantname(merchantname); Long mid = (Long) map.get("id"); merchantForm.setId(String.valueOf(mid)); String addr = (String) map.get("addr"); merchantForm.setAddr(addr); String latitude = (String) map.get("latitude"); merchantForm.setLatitude(latitude); String tel = (String) map.get("tel"); merchantForm.setTel(tel); String buinesstime = (String) map.get("buinesstime"); merchantForm.setBuinesstime(buinesstime); String city = (String) map.get("city"); merchantForm.setCity(city); merchantForm.setIs_Support_Takeaway(map.get("is_support_takeaway").toString()); merchantForm.setIs_Support_Online_Meal(map.get("is_support_online_meal").toString()); //author wenjie.mai 添加environment、capacity、otherservice三个字段 String environment = (String) map.get("environment"); String capacity = (String) map.get("capacity"); String otherservice= (String) map.get("otherservice"); if(StringUtils.isNotBlank(environment)){ if(environment.indexOf(",") !=-1){ environment = environment.trim().replaceAll(",","、"); } if(StringUtils.isNotBlank(capacity) || StringUtils.isNotBlank(otherservice)) environment += "、"; }else{ environment = ""; } if(StringUtils.isNotBlank(capacity)){ capacity = capacity.trim(); if(StringUtils.isNotBlank(otherservice)) capacity += "、"; }else{ capacity = ""; } if(StringUtils.isNotBlank(otherservice)){ if(otherservice.indexOf(",") !=-1){ otherservice = otherservice.trim().replaceAll(",","、"); } }else{ otherservice = ""; } merchantForm.setEnvironment(environment); merchantForm.setCapacity(capacity); merchantForm.setOtherservice(otherservice); listForm.add(merchantForm); } return listForm; } @SuppressWarnings("rawtypes") @Override public int getFlagShipTotalCountForCity(Long cityId) { StringBuilder countsql = new StringBuilder(); countsql.append("SELECT DISTINCT(bf.brand_id),bf.realm_name,bm.virtualcount,bmp.mc_sale_count,bmp.mc_logo2, "); countsql.append("bmp.mc_well_count,bmp.mc_satisfy_count,bmp.mc_poor_count,bm.merchantname FROM beiker_flagship bf "); countsql.append("LEFT JOIN beiker_merchant bm ON bf.brand_id = bm.merchantid "); countsql.append("LEFT JOIN beiker_merchant_profile bmp ON bmp.merchantid = bm.merchantid "); countsql.append("WHERE bf.is_online = '1' AND bf.city = ").append(cityId); countsql.append(" ORDER BY bf.online_time DESC "); List countlist = this.getJdbcTemplate().queryForList(countsql.toString()); if(countlist == null || countlist.size() == 0) return 0; return countlist.size(); } @SuppressWarnings({"rawtypes"}) @Override public List getFlagShipInfo(Long cityId,int start,int end) { StringBuilder flagsql = new StringBuilder(); flagsql.append("SELECT DISTINCT(bf.brand_id),bf.realm_name,bm.virtualcount,bmp.mc_sale_count,bmp.mc_logo2, "); flagsql.append("bmp.mc_well_count,bmp.mc_satisfy_count,bmp.mc_poor_count,bm.merchantname FROM beiker_flagship bf "); flagsql.append("LEFT JOIN beiker_merchant bm ON bf.brand_id = bm.merchantid "); flagsql.append("LEFT JOIN beiker_merchant_profile bmp ON bmp.merchantid = bm.merchantid "); flagsql.append("WHERE bf.is_online = '1' AND bf.city = ").append(cityId); flagsql.append(" ORDER BY bf.online_time DESC "); flagsql.append(" Limit ").append(start).append(",").append(end); List flaglist = this.getJdbcTemplate().queryForList(flagsql.toString()); if(flaglist == null || flaglist.size() == 0) return null; return flaglist; } @SuppressWarnings("rawtypes") @Override public List getFlagshipByMerchantId(Long merchantId) { StringBuilder flagsql = new StringBuilder(); flagsql.append("SELECT DISTINCT(BF.id),BF.guest_id,BF.brand_id,BF.city,BF.realm_name,BF.sina_microBlog,"); flagsql.append("BF.qq_microBlog,BF.flagship_name, BF.flagship_background_color,BF.flagship_background_img,"); flagsql.append("BFM.id AS mould_id,BFM.mould_name,BFM.mould_img,BFM.mould_url,GROUP_CONCAT(DISTINCT(BFB.branch_id)) AS branchs,"); flagsql.append("flagship_logo,sina_microBlog_name FROM beiker_flagship BF "); flagsql.append("LEFT JOIN beiker_flagship_mould BFM ON BF.mould = BFM.id "); flagsql.append("LEFT JOIN beiker_flagship_branch BFB ON BF.id = BFB.flagship_id "); flagsql.append("LEFT JOIN beiker_merchant BM ON BFB.branch_id = BM.merchantid "); flagsql.append("WHERE BF.is_online = '1' AND BF.brand_id = ").append(merchantId); flagsql.append(" GROUP BY BFB.flagship_id "); flagsql.append(" LIMIT 1"); List li = this.getSimpleJdbcTemplate().queryForList(flagsql.toString()); return li; } @SuppressWarnings("rawtypes") @Override public List getOfferContentByMerchantId(Long merchantId,String nowTime) { StringBuilder offer_sql = new StringBuilder(); offer_sql.append("SELECT offers_id,guest_id,brand_id,begin_time,end_time,offers_contents,offers_status "); offer_sql.append("FROM beiker_special_offers "); offer_sql.append(" WHERE offers_status = 'ONLINE' AND begin_time <= '").append(nowTime).append("' "); offer_sql.append(" AND end_time >= '").append(nowTime).append("' AND brand_id = ").append(merchantId); offer_sql.append(" ORDER BY begin_time DESC "); List offerlist = this.getJdbcTemplate().queryForList(offer_sql.toString()); return offerlist; } }
package com.example.qr_code_tracer; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.WindowManager; import androidx.appcompat.app.AppCompatActivity; public class RegisterActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); } }
package stepDefinition; import org.apache.commons.lang3.RandomStringUtils; import org.openqa.selenium.WebDriver; import pageObject.createAccountLoginPage; //import pageObject.createAccountPage; public class BaseClass { public WebDriver ldriver; //public createAccountLoginPage createAccountLoginPageObject; //public createAccountPage createAccountPageObject; //createAccountLoginPage createAccountLoginPageObject; createAccountLoginPage createAccountLoginPageObject; public static String createRandomString() { String generatedstring = RandomStringUtils.randomAlphabetic(8); String emailaddress=generatedstring+"@gmail.com"; return (emailaddress); } }
package edu.dlsu.securde.model; import javax.persistence.*; @Entity @Table(name = "itemsList") public class Item { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="ID") private Integer id; @Column(name="ItemName") private String itemName; @Column(name="Location") private String location; @Column(name="Author") private String author; @Column(name="Publisher") private String publisher; @Column(name="YearPublished") private Integer yearPublished; @Column(name="ItemStatus") private Integer itemStatus; @Column(name="DateOfAvailability") private String dateOfAvailability; @Column(name="ItemType") private Integer itemType; public Item() { } public Item(int itemid, String itemName, String location, String author, String publisher, int yearPublished, int itemStatus, String dateOfAvailability, int itemType) { super(); this.id = itemid; this.itemName = itemName; this.location = location; this.author = author; this.publisher = publisher; this.yearPublished = yearPublished; this.itemStatus = itemStatus; this.dateOfAvailability = dateOfAvailability; this.itemType = itemType; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getItemName() { return itemName; } public String setItemName(String itemName) { this.itemName = itemName; return this.itemName; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public int getYearPublished() { return yearPublished; } public void setYearPublished(int yearPublished) { this.yearPublished = yearPublished; } public int getItemStatus() { return itemStatus; } public void setItemStatus(int itemStatus) { this.itemStatus = itemStatus; } public String getDateOfAvailability() { return dateOfAvailability; } public void setDateOfAvailability(String dateOfAvailability) { this.dateOfAvailability = dateOfAvailability; } public int getItemType() { return itemType; } public void setItemType(int itemType) { this.itemType = itemType; } }
/** * Licensee: Juan José(University of Almeria) * License Type: Academic */ package ormsamples; import org.orm.*; public class CreateProyectoMDSData { public void createTestData() throws PersistentException { PersistentTransaction t = database.ProyectoMDSPersistentManager.instance().getSession().beginTransaction(); try { database.Usuarios ldatabaseUsuarios = database.UsuariosDAO.createUsuarios(); // Initialize the properties of the persistent object here database.UsuariosDAO.save(ldatabaseUsuarios); database.Usuario_registrado ldatabaseUsuario_registrado = database.Usuario_registradoDAO.createUsuario_registrado(); // TODO Initialize the properties of the persistent object here, the following properties must be initialized before saving : suscriptor, listas_de_reproduccion, video_visualizado, video_subido, videos_que_gustan, comentarios, suscrito, edad, numeroVisitas, id_Usuario_registrado database.Usuario_registradoDAO.save(ldatabaseUsuario_registrado); database.Videos ldatabaseVideos = database.VideosDAO.createVideos(); // TODO Initialize the properties of the persistent object here, the following properties must be initialized before saving : usuario_visualizador, listas_de_videos, autor, comentarios_en_videos, duracion, numVisualizaciones, categoria, usuarios_que_dan_me_gusta database.VideosDAO.save(ldatabaseVideos); database.Listas_de_reproduccion ldatabaseListas_de_reproduccion = database.Listas_de_reproduccionDAO.createListas_de_reproduccion(); // TODO Initialize the properties of the persistent object here, the following properties must be initialized before saving : videos_en_lista, num_videos, usuario_registrado database.Listas_de_reproduccionDAO.save(ldatabaseListas_de_reproduccion); database.Usuario_Administrador ldatabaseUsuario_Administrador = database.Usuario_AdministradorDAO.createUsuario_Administrador(); // TODO Initialize the properties of the persistent object here, the following properties must be initialized before saving : id_Usuario_Administrador database.Usuario_AdministradorDAO.save(ldatabaseUsuario_Administrador); database.Categorias ldatabaseCategorias = database.CategoriasDAO.createCategorias(); // TODO Initialize the properties of the persistent object here, the following properties must be initialized before saving : videos, edad database.CategoriasDAO.save(ldatabaseCategorias); database.Comentarios ldatabaseComentarios = database.ComentariosDAO.createComentarios(); // TODO Initialize the properties of the persistent object here, the following properties must be initialized before saving : usuarios_que_comentan, videosComentados database.ComentariosDAO.save(ldatabaseComentarios); t.commit(); } catch (Exception e) { t.rollback(); } } public static void main(String[] args) { try { CreateProyectoMDSData createProyectoMDSData = new CreateProyectoMDSData(); try { createProyectoMDSData.createTestData(); } finally { database.ProyectoMDSPersistentManager.instance().disposePersistentManager(); } } catch (Exception e) { e.printStackTrace(); } } }
package arraylisttesters; import static org.junit.Assert.*; import myarraylist.AbstractArrayMyList; import myarraylist.ArrayListUnsorted; import org.junit.Before; import org.junit.Test; public class ArrayListUnsortedTest { private AbstractArrayMyList<Integer> myList; @Before public void setUp() throws Exception { myList = new ArrayListUnsorted<Integer>(); myList.insert(4); myList.insert(5); } @Test public void testInsertFront() { myList.insertFront(3); assertEquals(myList.get(0).intValue(), 3); assertEquals(myList.getSize(), 3); } @Test public void testSet() { myList.set(0, 2); assertEquals(myList.get(0).intValue(), 2); } @Test public void testRemove() { myList.remove(4); assertEquals(myList.get(0).intValue(), 5); assertEquals(myList.getSize(), 1); } @Test public void testInsert() { assertEquals(myList.getSize(), 2); } @Test public void testGetIndex() { assertEquals(myList.get(0).intValue(), 4); assertEquals(myList.get(1).intValue(), 5); } @Test public void testRemoveAtIndex() { myList.removeAtIndex(0); assertEquals(myList.get(0).intValue(), 5); } @Test public void testClear() { myList.clear(); assertTrue(myList.isEmpty()); } }
package com.edasaki.rpg.chat; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import com.edasaki.core.chat.ChatFilter; import com.edasaki.core.options.SakiOption; import com.edasaki.core.players.Rank; import com.edasaki.core.punishments.PunishmentManager; import com.edasaki.core.shield.SakiShieldCore; import com.edasaki.core.shield.SakiShieldCore.Activity; import com.edasaki.core.utils.RMath; import com.edasaki.core.utils.RScheduler; import com.edasaki.core.utils.RSound; import com.edasaki.core.utils.fanciful.FancyMessage; import com.edasaki.rpg.AbstractManagerRPG; import com.edasaki.rpg.PlayerDataRPG; import com.edasaki.rpg.SakiRPG; import com.edasaki.rpg.tips.TipManager; public class ChatManager extends AbstractManagerRPG { private static HashMap<String, Long> lastChat = new HashMap<String, Long>(); private static long lastDiscord = 0; private static long lastMap = 0; private static long lastTwitter = 0; private static long lastBully = 0; private static long lastForums = 0; private static long lastStaff = 0; private static long lastTip = 0; private static long lastIP = 0; private static long lastStore = 0; private static long lastWiki = 0; private static long lastWebsite = 0; private static long lastPatch = 0; private static long lastHelp = 0; public static HashMap<String, Long> lastGlobalChat = new HashMap<String, Long>(); public static HashMap<String, String> lastReceivedWhisperFrom = new HashMap<String, String>(); public static HashMap<String, Long> lastReceivedWhisperTime = new HashMap<String, Long>(); public static HashSet<String> monitors = new HashSet<String>(); private long lastTrigger = 0; public static ArrayList<String> shadowMute = new ArrayList<String>(); public static HashMap<String, Long> lastSentPM = new HashMap<String, Long>(); public ChatManager(SakiRPG plugin) { super(plugin); } @Override public void initialize() { } public static void sendWhisper(Player sender, String targetName, PlayerDataRPG pd, String message) { if (System.currentTimeMillis() - lastSentPM.getOrDefault(pd.getName(), 0l) < 100) { SakiShieldCore.warn(pd, Activity.FAST_CHAT); return; } if (PunishmentManager.isMuted(sender)) { pd.sendMessage(ChatColor.RED + "You are muted and cannot message others!"); pd.sendMessage(ChatColor.RED + PunishmentManager.getMuteReason(sender)); return; } Player target = plugin.getServer().getPlayerExact(targetName); if (target != null && target.isOnline() && plugin.getPD(target) != null) { if (target == sender) { sender.sendMessage(ChatColor.RED + "You can't message yourself, silly! That's what thinking is for."); return; } PlayerDataRPG pd2 = plugin.getPD(target); if (pd2.isIgnoring(pd)) { pd.sendMessage(ChatColor.RED + pd2.getName() + " is ignoring you and is not receiving your messages."); return; } String senderName = pd.getChatNameColor() + sender.getName(); String receiverName = pd2.getChatNameColor() + target.getName(); FancyMessage fm = new FancyMessage(); fm.text("["); fm.color(ChatColor.GRAY); fm.then(senderName); ChatManager.chatHover(fm, pd); fm.then("->"); fm.color(ChatColor.GRAY); fm.then(receiverName); ChatManager.chatHover(fm, pd2); fm.then("] "); fm.color(ChatColor.GRAY); fm.then(pd.getOption(SakiOption.CHAT_FILTER) || pd2.getOption(SakiOption.CHAT_FILTER) ? ChatFilter.getFiltered(message) : message); fm.style(ChatColor.ITALIC); fm.send(sender); if (PunishmentManager.isMuted(target)) { sender.sendMessage(ChatColor.RED + target.getName() + " is currently muted and won't be able to respond."); } if (!ChatManager.shadowMute.contains(sender.getName())) { fm.send(target); if (!ChatManager.lastReceivedWhisperFrom.containsKey(target.getName()) || !ChatManager.lastReceivedWhisperFrom.get(target.getName()).equals(sender.getName())) RSound.playSound(target, Sound.ENTITY_EXPERIENCE_ORB_PICKUP); else if (!ChatManager.lastReceivedWhisperTime.containsKey(target.getName()) || System.currentTimeMillis() - ChatManager.lastReceivedWhisperTime.get(target.getName()) > 30000) RSound.playSound(target, Sound.ENTITY_EXPERIENCE_ORB_PICKUP); ChatManager.lastReceivedWhisperFrom.put(target.getName(), sender.getName()); ChatManager.lastReceivedWhisperFrom.put(sender.getName(), target.getName()); ChatManager.lastReceivedWhisperTime.put(target.getName(), System.currentTimeMillis()); } for (String m : ChatManager.monitors) { Player monitor = plugin.getServer().getPlayerExact(m); if (monitor != null && monitor.isOnline()) { if (sender != monitor && target != monitor) { monitor.sendMessage(ChatColor.DARK_GRAY + "[MONITOR]"); fm.send(monitor); } } } Bukkit.getConsoleSender().sendMessage(ChatColor.AQUA + ChatColor.stripColor(fm.toOldMessageFormat())); } else { sender.sendMessage(ChatColor.RED + "Could not find online player '" + targetName + "'."); } } private HashMap<ChatMention, Long> mentions = new HashMap<ChatMention, Long>(); private static class ChatMention { public final String talker; public final String mentioned; @Override public boolean equals(Object other) { if (other == null) return false; if (!(other instanceof ChatMention)) return false; ChatMention cm = (ChatMention) other; return cm.talker.equals(this.talker) && cm.mentioned.equals(this.mentioned); } @Override public int hashCode() { return talker.hashCode() + mentioned.hashCode(); } public ChatMention(String talker, String mentioned) { this.talker = talker.toLowerCase(); this.mentioned = mentioned.toLowerCase(); } } public static FancyMessage chatHover(FancyMessage fm, PlayerDataRPG pd) { StringBuilder sb = new StringBuilder(); sb.append(pd.getChatNameColor()); sb.append(pd.getPlayer().getName()); sb.append(ChatColor.GRAY); sb.append(" | "); sb.append(ChatColor.GREEN); sb.append(pd.classType); sb.append(ChatColor.GRAY); sb.append(" | "); sb.append(ChatColor.AQUA); sb.append("Level "); sb.append(pd.level); sb.append(ChatColor.GRAY); sb.append(" | "); sb.append(ChatColor.GOLD); sb.append("Rank: "); sb.append(pd.getChatNameColor()); sb.append(pd.getFullRankClean()); return fm.tooltip(sb.toString()).command("/information " + pd.getPlayer().getName()); } @EventHandler public void onPlayerChat(AsyncPlayerChatEvent event) { boolean global = false; // Tips only fire if someone is talking if (System.currentTimeMillis() - lastTrigger > 30000) { TipManager.schedule(); lastTrigger = System.currentTimeMillis(); } // Get PlayerData PlayerDataRPG pd = plugin.getPD(event.getPlayer()); if (pd == null || pd.getPlayer() == null || !pd.loadedSQL) { event.setCancelled(true); return; } if (!pd.check(Rank.VIP)) { if (lastChat.containsKey(pd.getName()) && System.currentTimeMillis() - lastChat.get(pd.getName()) < 2000) { pd.sendMessage(ChatColor.RED + " You can only chat once every 2 seconds."); pd.sendMessage(ChatColor.RED + " Get a rank at " + ChatColor.YELLOW + "store.zentrela.net" + ChatColor.RED + " to have no chat limits!"); event.setCancelled(true); return; } lastChat.put(pd.getName(), System.currentTimeMillis()); } if (System.currentTimeMillis() - lastSentPM.getOrDefault(pd.getName(), 0l) < 100) { SakiShieldCore.warn(pd, Activity.FAST_CHAT); return; } // Handle Party Chat if (event.getMessage().startsWith("\\") && event.getMessage().length() > 1) { if (pd.party != null) { pd.party.sendMessage(event.getPlayer(), event.getMessage().substring(1)); Bukkit.getConsoleSender().sendMessage(ChatColor.AQUA + "Party ID " + pd.party.id + " " + event.getPlayer().getName() + ": " + event.getMessage()); } else { event.getPlayer().sendMessage(ChatColor.RED + "You are not in a party, so you can't use Party Chat! " + ChatColor.YELLOW + "/party"); } event.setCancelled(true); return; } // No chat if muted if (PunishmentManager.isMuted(event.getPlayer())) { pd.sendMessage(ChatColor.RED + "You are muted and cannot talk!"); pd.sendMessage(ChatColor.RED + PunishmentManager.getMuteReason(event.getPlayer())); event.setCancelled(true); return; } if ((!pd.getOption(SakiOption.FORCE_GLOBAL_CHAT) && event.getMessage().startsWith("#")) || (pd.getOption(SakiOption.FORCE_GLOBAL_CHAT) && !event.getMessage().startsWith("#"))) { if (!SakiRPG.TEST_REALM && !pd.check(Rank.VIP) && lastGlobalChat.containsKey(pd.getName()) && System.currentTimeMillis() - lastGlobalChat.get(pd.getName()) < 5000) { global = false; pd.sendMessage(ChatColor.RED + " You can only global chat once every 5 seconds."); pd.sendMessage(ChatColor.RED + " Get a rank at " + ChatColor.YELLOW + "store.zentrela.net" + ChatColor.RED + " to have no chat limits!"); } else { global = true; lastGlobalChat.put(pd.getName(), System.currentTimeMillis()); if (!pd.getOption(SakiOption.FORCE_GLOBAL_CHAT)) event.setMessage(event.getMessage().substring(1).trim()); } } else if (SakiRPG.TEST_REALM) { global = true; } // Create two versions of message, one filtered and one unfiltered FancyMessage fm_unfiltered = new FancyMessage(); FancyMessage fm_filtered = new FancyMessage(); boolean sentLinkLimitMessage = false; FancyMessage[] fms = new FancyMessage[] { fm_unfiltered, fm_filtered }; for (int k = 0; k < fms.length; k++) { FancyMessage fm = fms[k]; chatHover(fm.text("[" + pd.level + "] ").color(ChatColor.GRAY), pd); chatHover(fm.then(pd.getChatRankPrefix()), pd); chatHover(fm.then(event.getPlayer().getName()), pd); pd.addBadgesSuffix(fm); fm.then(": ").color(ChatColor.WHITE); if (global) { fm.then("[Global] ").color(ChatColor.DARK_GRAY).tooltip("Type # at the start of your message to use global chat!\nNormal chat is local, meaning only nearby players can see it."); } // super ugly code bug basically check if this is the filtered one String[] data = (k == 1 ? ChatFilter.getFiltered(event.getMessage()) : event.getMessage()).split(" "); ChatColor playerChatColor = pd.getChatColor(); int linkCount = 0; for (int a = 0; a < data.length; a++) { String tmp = data[a].trim(); boolean itemLink = false; if (pd.check(Rank.VIP) && pd.loadedSQL) { if (tmp.toLowerCase().matches("\\[slot\\d\\]")) { int slot = 0; try { slot = Integer.parseInt(tmp.replaceAll("[^0-9]", "")); } catch (Exception e) { } if (slot < 1 || slot > 9) { pd.sendMessage(ChatColor.RED + "Invalid slot! Slot must be from 1 to 9, such as [slot2]."); } else { if (linkCount >= 5) { if (!sentLinkLimitMessage) { sentLinkLimitMessage = true; RScheduler.schedule(plugin, () -> { pd.sendMessage(ChatColor.RED + "You may only link up to 5 items in one message."); }, 2); } } else { linkCount++; itemLink = true; ItemStack item = pd.getPlayer().getInventory().getItem(slot - 1); String name = ChatColor.GRAY + "null"; List<String> hover = new ArrayList<String>(); if (item != null) { ItemMeta im = item.getItemMeta(); if (im != null) { if (im.hasDisplayName()) { name = im.getDisplayName(); } if (im.hasLore()) { hover.add(name); for (String s : im.getLore()) hover.add(s); } } } String[] namedata = name.split(" "); String lastColor = ChatColor.getLastColors(name); for (int i = 0; i < namedata.length; i++) { if (ChatColor.getLastColors(namedata[i]).length() > 0) { lastColor = ChatColor.getLastColors(namedata[i]); } fm.then(lastColor + namedata[i]); fm.tooltip(hover); fm.then(i == namedata.length - 1 ? "" : " "); fm.tooltip(hover); } fm.tooltip(hover); } } } } if (!itemLink) { fm.then(tmp + (a == data.length - 1 ? "" : " ")); fm.color(playerChatColor); if (tmp.startsWith("http://") || tmp.startsWith("https://") || tmp.endsWith(".net") || tmp.endsWith(".com") || tmp.endsWith("org")) { if (!tmp.startsWith("http://") && !tmp.startsWith("https://")) tmp = "http://" + tmp; fm.link(tmp); } } else { if (a != data.length - 1) fm.then(" "); } } } // Make sure the vanilla message isn't sent String message = event.getMessage(); event.setFormat(""); event.setCancelled(true); // Show in console Bukkit.getConsoleSender().sendMessage(ChatColor.AQUA + ChatColor.stripColor(fm_unfiltered.toOldMessageFormat())); // Check mentions ArrayList<String> finalMentioned = new ArrayList<String>(); if (pd.check(Rank.MOD) && (event.getMessage().contains("@everyone"))) { for (Player p : plugin.getServer().getOnlinePlayers()) { RSound.playSound(p, Sound.ENTITY_EXPERIENCE_ORB_PICKUP); p.sendMessage(ChatColor.GRAY + "> " + event.getPlayer().getName() + " just mentioned everyone."); } } else if (message.contains("@")) { ArrayList<String> mentioned = new ArrayList<String>(); String[] split = message.split(" "); for (int k = 0; k < split.length; k++) { String s = split[k]; if (s.startsWith("@")) { if (s.length() > 1) { mentioned.add(s.substring(1)); } else if (s.length() == 1 && k + 1 < split.length) { mentioned.add(split[k + 1]); } } } boolean mentionedSomeone = false; for (String s : mentioned) { Player p = plugin.getServer().getPlayerExact(s); if (p != null && p.isValid() && p.isOnline()) { ChatMention cm = new ChatMention(event.getPlayer().getName(), s); if (mentions.containsKey(cm)) { if (System.currentTimeMillis() - mentions.get(cm) < 60000) { event.getPlayer().sendMessage(ChatColor.RED + "> You already mentioned " + p.getName() + " in the past minute!"); continue; } } event.getPlayer().sendMessage(ChatColor.GREEN + "> You mentioned " + p.getName() + "."); mentions.put(cm, System.currentTimeMillis()); finalMentioned.add(p.getName()); if (!ChatManager.shadowMute.contains(event.getPlayer().getName())) { RSound.playSound(p, Sound.ENTITY_EXPERIENCE_ORB_PICKUP); p.sendMessage(ChatColor.GRAY + "> Your name was just mentioned by " + event.getPlayer().getName() + "."); } mentionedSomeone = true; } else { event.getPlayer().sendMessage(ChatColor.RED + "> Mentioned player '" + s + "' is not online."); } } if (mentionedSomeone) RSound.playSound(event.getPlayer(), Sound.ENTITY_EXPERIENCE_ORB_PICKUP); } // Make sure not shadowmuted, then send the actual message to everyone Location talkerLoc = pd.getPlayer().getLocation(); boolean messaged = false; FancyMessage fm_filtered_mention = null, fm_unfiltered_mention = null; if (!ChatManager.shadowMute.contains(event.getPlayer().getName())) { for (Player p : plugin.getServer().getOnlinePlayers()) { if (plugin.getPD(p) != null) { PlayerDataRPG pd2 = plugin.getPD(p); if (pd2.isIgnoring(pd)) continue; if (!global && pd2.getOption(SakiOption.LOCAL_CHAT) && RMath.flatDistance(p.getLocation(), talkerLoc) > 50) { continue; } if (global && !pd2.getOption(SakiOption.GLOBAL_CHAT)) { continue; } if (pd2 != pd && pd2.getOption(SakiOption.LOCAL_CHAT)) messaged = true; if (finalMentioned.contains(p.getName())) { if (fm_filtered_mention == null) { try { fm_filtered_mention = fm_filtered.clone().color(ChatColor.YELLOW); } catch (CloneNotSupportedException e) { e.printStackTrace(); } } if (fm_unfiltered_mention == null) { try { fm_unfiltered_mention = fm_unfiltered.clone().color(ChatColor.YELLOW); } catch (CloneNotSupportedException e) { e.printStackTrace(); } } (plugin.getPD(p).getOption(SakiOption.CHAT_FILTER) ? fm_filtered_mention : fm_unfiltered_mention).send(p); } else { (plugin.getPD(p).getOption(SakiOption.CHAT_FILTER) ? fm_filtered : fm_unfiltered).send(p); } } } } else { messaged = true; (pd.getOption(SakiOption.CHAT_FILTER) ? fm_filtered : fm_unfiltered).send(event.getPlayer()); } if (!messaged && !global) { pd.sendMessage(ChatColor.RED + "> There was no one nearby to see your chat message..."); if (pd.getOption(SakiOption.LOCAL_CHAT_WARNING)) { pd.sendMessage(""); pd.sendMessage(ChatColor.GRAY + "> You can talk in " + ChatColor.AQUA + "Global Chat " + ChatColor.GRAY + "by starting your message with a " + ChatColor.YELLOW + "#"); pd.sendMessage(ChatColor.GRAY + "> Like this: " + ChatColor.YELLOW + "#Hi everyone!"); pd.sendMessage(ChatColor.GRAY + "> Turn off this message in /options (\"Local Chat Warning\")."); } } // Rensa commands String lower = event.getMessage().toLowerCase(); if (lower.startsWith("!discord")) { if (System.currentTimeMillis() - lastDiscord > 30000) { fm_unfiltered = new FancyMessage(); String link = "http://zentrela.net/discord"; fm_unfiltered.text("[0] ").color(ChatColor.GRAY).link(link); fm_unfiltered.then("Bot ").color(ChatColor.AQUA).style(ChatColor.BOLD).link(link); fm_unfiltered.then("Rensa: ").color(ChatColor.WHITE).link(link); fm_unfiltered.then("Join the Discord chat! Click for more info.").color(ChatColor.YELLOW).link(link); fm_unfiltered.send(plugin.getServer().getOnlinePlayers()); lastDiscord = System.currentTimeMillis(); } else { event.getPlayer().sendMessage(ChatColor.RED + "The Discord link was requested less than 30 seconds ago. Scroll up in chat to find it!"); } } else if (lower.startsWith("!map")) { if (System.currentTimeMillis() - lastMap > 30000) { fm_unfiltered = new FancyMessage(); String link = "http://zentrela.net/map/"; fm_unfiltered.text("[0] ").color(ChatColor.GRAY).link(link); fm_unfiltered.then("Bot ").color(ChatColor.AQUA).style(ChatColor.BOLD).link(link); fm_unfiltered.then("Rensa: ").color(ChatColor.WHITE).link(link); fm_unfiltered.then("Check out the Zentrela map! Click for a link.").color(ChatColor.YELLOW).link(link); fm_unfiltered.send(plugin.getServer().getOnlinePlayers()); lastMap = System.currentTimeMillis(); } else { event.getPlayer().sendMessage(ChatColor.RED + "The Map link was requested less than 30 seconds ago. Scroll up in chat to find it!"); } } else if (lower.startsWith("!twitter")) { if (System.currentTimeMillis() - lastTwitter > 30000) { fm_unfiltered = new FancyMessage(); String link = "https://twitter.com/Zentrela"; fm_unfiltered.text("[0] ").color(ChatColor.GRAY).link(link); fm_unfiltered.then("Bot ").color(ChatColor.AQUA).style(ChatColor.BOLD).link(link); fm_unfiltered.then("Rensa: ").color(ChatColor.WHITE).link(link); fm_unfiltered.then("Follow Zentrela on Twitter!.").color(ChatColor.YELLOW).link(link); fm_unfiltered.send(plugin.getServer().getOnlinePlayers()); lastTwitter = System.currentTimeMillis(); } else { event.getPlayer().sendMessage(ChatColor.RED + "The Twitter link was requested less than 30 seconds ago. Scroll up in chat to find it!"); } } else if (lower.startsWith("!bully")) { if (System.currentTimeMillis() - lastBully > 30000) { fm_unfiltered = new FancyMessage(); String link = "https://twitter.com/antibullyranger"; fm_unfiltered.text("[0] ").color(ChatColor.GRAY).link(link); fm_unfiltered.then("Bot ").color(ChatColor.AQUA).style(ChatColor.BOLD).link(link); fm_unfiltered.then("Rensa: ").color(ChatColor.WHITE).link(link); fm_unfiltered.then("Hey! No bullying.").color(ChatColor.YELLOW).link(link); fm_unfiltered.send(plugin.getServer().getOnlinePlayers()); lastBully = System.currentTimeMillis(); } else { event.getPlayer().sendMessage(ChatColor.RED + "The bully link was requested less than 30 seconds ago. Scroll up in chat to find it!"); } } else if (lower.startsWith("!forum")) { if (System.currentTimeMillis() - lastForums > 30000) { fm_unfiltered = new FancyMessage(); String link = "http://zentrela.net/forums/"; fm_unfiltered.text("[0] ").color(ChatColor.GRAY).link(link); fm_unfiltered.then("Bot ").color(ChatColor.AQUA).style(ChatColor.BOLD).link(link); fm_unfiltered.then("Rensa: ").color(ChatColor.WHITE).link(link); fm_unfiltered.then("Click for a link to the Zentrela forums!").color(ChatColor.YELLOW).link(link); fm_unfiltered.send(plugin.getServer().getOnlinePlayers()); lastForums = System.currentTimeMillis(); } else { event.getPlayer().sendMessage(ChatColor.RED + "The forums link was requested less than 30 seconds ago. Scroll up in chat to find it!"); } } else if (lower.startsWith("!staff")) { if (System.currentTimeMillis() - lastStaff > 30000) { fm_unfiltered = new FancyMessage(); String link = "http://zentrela.net/staff.html"; fm_unfiltered.text("[0] ").color(ChatColor.GRAY).link(link); fm_unfiltered.then("Bot ").color(ChatColor.AQUA).style(ChatColor.BOLD).link(link); fm_unfiltered.then("Rensa: ").color(ChatColor.WHITE).link(link); fm_unfiltered.then("Click for a link to the Staff Handbook!").color(ChatColor.YELLOW).link(link); fm_unfiltered.send(plugin.getServer().getOnlinePlayers()); lastStaff = System.currentTimeMillis(); } else { event.getPlayer().sendMessage(ChatColor.RED + "The staff handbook link was requested less than 30 seconds ago. Scroll up in chat to find it!"); } } else if (lower.startsWith("!tip")) { if (System.currentTimeMillis() - lastTip > 15000) { TipManager.sayTip(); lastTip = System.currentTimeMillis(); } else { event.getPlayer().sendMessage(ChatColor.RED + "A tip was requested less than 15 seconds ago."); } } else if (lower.startsWith("!ip")) { if (System.currentTimeMillis() - lastIP > 30000) { fm_unfiltered = new FancyMessage(); String link = "play.zentrela.net"; fm_unfiltered.text("[0] ").color(ChatColor.GRAY).link(link); fm_unfiltered.then("Bot ").color(ChatColor.AQUA).style(ChatColor.BOLD).link(link); fm_unfiltered.then("Rensa: ").color(ChatColor.WHITE).link(link); fm_unfiltered.then("The server IP is play.zentrela.net!").color(ChatColor.YELLOW).link(link); fm_unfiltered.send(plugin.getServer().getOnlinePlayers()); lastIP = System.currentTimeMillis(); } else { event.getPlayer().sendMessage(ChatColor.RED + "The server IP was requested less than 30 seconds ago. Scroll up in chat to find it!"); } } else if (lower.startsWith("!store") || lower.startsWith("!crates")) { if (System.currentTimeMillis() - lastStore > 30000) { fm_unfiltered = new FancyMessage(); String link = "http://store.zentrela.net/"; fm_unfiltered.text("[0] ").color(ChatColor.GRAY).link(link); fm_unfiltered.then("Bot ").color(ChatColor.AQUA).style(ChatColor.BOLD).link(link); fm_unfiltered.then("Rensa: ").color(ChatColor.WHITE).link(link); fm_unfiltered.then("Click for a link to the Zentrela Store!").color(ChatColor.YELLOW).link(link); fm_unfiltered.send(plugin.getServer().getOnlinePlayers()); lastStore = System.currentTimeMillis(); } else { event.getPlayer().sendMessage(ChatColor.RED + "The store link was requested less than 30 seconds ago. Scroll up in chat to find it!"); } } else if (lower.startsWith("!wiki")) { if (System.currentTimeMillis() - lastWiki > 30000) { fm_unfiltered = new FancyMessage(); String link = "http://zentrela.wikia.com/"; fm_unfiltered.text("[0] ").color(ChatColor.GRAY).link(link); fm_unfiltered.then("Bot ").color(ChatColor.AQUA).style(ChatColor.BOLD).link(link); fm_unfiltered.then("Rensa: ").color(ChatColor.WHITE).link(link); fm_unfiltered.then("Click for a link to the Zentrela Wiki!").color(ChatColor.YELLOW).link(link); fm_unfiltered.send(plugin.getServer().getOnlinePlayers()); lastWiki = System.currentTimeMillis(); } else { event.getPlayer().sendMessage(ChatColor.RED + "The wiki link was requested less than 30 seconds ago. Scroll up in chat to find it!"); } } else if (lower.startsWith("!website") || lower.startsWith("!site")) { if (System.currentTimeMillis() - lastWebsite > 30000) { fm_unfiltered = new FancyMessage(); String link = "http://www.zentrela.net/"; fm_unfiltered.text("[0] ").color(ChatColor.GRAY).link(link); fm_unfiltered.then("Bot ").color(ChatColor.AQUA).style(ChatColor.BOLD).link(link); fm_unfiltered.then("Rensa: ").color(ChatColor.WHITE).link(link); fm_unfiltered.then("Click for a link to the Zentrela Website!").color(ChatColor.YELLOW).link(link); fm_unfiltered.send(plugin.getServer().getOnlinePlayers()); lastWebsite = System.currentTimeMillis(); } else { event.getPlayer().sendMessage(ChatColor.RED + "The website link was requested less than 30 seconds ago. Scroll up in chat to find it!"); } } else if (lower.startsWith("!update") || lower.startsWith("!patch")) { if (System.currentTimeMillis() - lastPatch > 30000) { fm_unfiltered = new FancyMessage(); String link = "http://www.zentrela.net/p"; fm_unfiltered.text("[0] ").color(ChatColor.GRAY).link(link); fm_unfiltered.then("Bot ").color(ChatColor.AQUA).style(ChatColor.BOLD).link(link); fm_unfiltered.then("Rensa: ").color(ChatColor.WHITE).link(link); fm_unfiltered.then("Click for a link to the Zentrela Patch Notes!").color(ChatColor.YELLOW).link(link); fm_unfiltered.send(plugin.getServer().getOnlinePlayers()); lastPatch = System.currentTimeMillis(); } else { event.getPlayer().sendMessage(ChatColor.RED + "The patch notes link was requested less than 30 seconds ago. Scroll up in chat to find it!"); } } else if (lower.startsWith("!help")) { if (System.currentTimeMillis() - lastHelp > 30000) { fm_unfiltered = new FancyMessage(); ArrayList<String> tt = new ArrayList<String>(); tt.add(ChatColor.AQUA + ChatColor.BOLD.toString() + "Rensa's Chat Commands"); tt.add(ChatColor.GREEN + " !help " + ChatColor.GRAY + "- " + ChatColor.DARK_AQUA + "View all chat commands"); tt.add(ChatColor.GREEN + " !discord " + ChatColor.GRAY + "- " + ChatColor.DARK_AQUA + "Link to the Discord chat"); tt.add(ChatColor.GREEN + " !map " + ChatColor.GRAY + "- " + ChatColor.DARK_AQUA + "Link to the Online Map"); tt.add(ChatColor.GREEN + " !twitter " + ChatColor.GRAY + "- " + ChatColor.DARK_AQUA + "Link to the Official Twitter"); tt.add(ChatColor.GREEN + " !bully " + ChatColor.GRAY + "- " + ChatColor.DARK_AQUA + "Call the Anti-bully Ranger"); tt.add(ChatColor.GREEN + " !forums " + ChatColor.GRAY + "- " + ChatColor.DARK_AQUA + "Link to the Forums"); tt.add(ChatColor.GREEN + " !staff " + ChatColor.GRAY + "- " + ChatColor.DARK_AQUA + "Link to the Staff Handbook"); tt.add(ChatColor.GREEN + " !tip " + ChatColor.GRAY + "- " + ChatColor.DARK_AQUA + "Get a random tip"); tt.add(ChatColor.GREEN + " !ip " + ChatColor.GRAY + "- " + ChatColor.DARK_AQUA + "Get the server IP"); tt.add(ChatColor.GREEN + " !wiki " + ChatColor.GRAY + "- " + ChatColor.DARK_AQUA + "Link to the Zentrela Wiki"); tt.add(ChatColor.GREEN + " !store " + ChatColor.GRAY + "- " + ChatColor.DARK_AQUA + "Link to the Zentrela Store"); tt.add(ChatColor.GREEN + " !website " + ChatColor.GRAY + "- " + ChatColor.DARK_AQUA + "Link to the Zentrela Website"); tt.add(ChatColor.GREEN + " !updates " + ChatColor.GRAY + "- " + ChatColor.DARK_AQUA + "Link to the Zentrela Patch Notes"); tt.add(""); tt.add(ChatColor.GRAY + "\"Chat Commands\" start with !"); tt.add(ChatColor.GRAY + "\"Commands\" start with /"); fm_unfiltered.text("[0] ").color(ChatColor.GRAY).tooltip(tt); fm_unfiltered.then("Bot ").color(ChatColor.AQUA).style(ChatColor.BOLD).tooltip(tt); fm_unfiltered.then("Rensa: ").color(ChatColor.WHITE).tooltip(tt); fm_unfiltered.then("Hover over this message for a list of chat commands!").color(ChatColor.GOLD).tooltip(tt); fm_unfiltered.send(plugin.getServer().getOnlinePlayers()); lastHelp = System.currentTimeMillis(); } else { event.getPlayer().sendMessage(ChatColor.RED + "The chat commands list was requested less than 30 seconds ago."); } } } }
package interfaceFunction; import java.util.function.Supplier; public interface DefaultableFactory { // 接口可以声明(并且可以提供实现)静态方法 // Interfaces now allow static methods static Defaultable create( Supplier< Defaultable > supplier ) { return supplier.get(); } }
/** * Copyright (C) 2015-2016, Zhichun Wu * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.github.cassandra.jdbc; import com.google.common.base.Strings; import java.sql.*; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executor; import static com.github.cassandra.jdbc.CassandraUtils.*; /** * This is the base class for implementing Cassandra connection. * * @author Zhichun Wu */ public abstract class BaseCassandraConnection extends BaseJdbcObject implements Connection { private final Properties _clientInfo = new Properties(); private int _txIsolationLevel; private final Map<String, Class<?>> _typeMap = new HashMap<String, Class<?>>(); protected final CassandraConfiguration config; protected final CassandraDatabaseMetaData metaData; public BaseCassandraConnection(CassandraConfiguration driverConfig) { super(driverConfig.isQuiet()); _txIsolationLevel = TRANSACTION_NONE; this.config = driverConfig; metaData = new CassandraDatabaseMetaData(this); metaData.setProperty(CassandraConfiguration.KEY_CONNECTION_URL, driverConfig.getConnectionUrl()); metaData.setProperty(CassandraConfiguration.KEY_USERNAME, driverConfig.getUserName()); } protected abstract <T> T createObject(Class<T> clazz) throws SQLException; protected ResultSet getObjectMetaData(CassandraObjectType objectType, Properties queryPatterns, Object... additionalHints) throws SQLException { ResultSet rs; switch (objectType) { case TABLE_TYPE: rs = new DummyCassandraResultSet(TABLE_TYPE_COLUMNS, TABLE_TYPE_DATA); break; case TYPE: rs = new DummyCassandraResultSet(TYPE_COLUMNS, CassandraDataTypeMappings.instance.getTypeMetaData()); break; default: throw CassandraErrors.notSupportedException(); } return rs; } public CassandraConfiguration getConfiguration() { return config; } public void abort(Executor executor) throws SQLException { validateState(); if (!quiet) { throw CassandraErrors.notSupportedException(); } } public void commit() throws SQLException { validateState(); // better to be quiet and do nothing as we always commit in Cassandra if (!quiet) { throw CassandraErrors.notSupportedException(); } } public Array createArrayOf(String typeName, Object[] elements) throws SQLException { validateState(); // FIXME incomplete Array result = createObject(Array.class); return result; } public Blob createBlob() throws SQLException { validateState(); return createObject(Blob.class); } public Clob createClob() throws SQLException { validateState(); return createObject(Clob.class); } public NClob createNClob() throws SQLException { validateState(); return createObject(NClob.class); } public SQLXML createSQLXML() throws SQLException { validateState(); return createObject(SQLXML.class); } public Statement createStatement() throws SQLException { return createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { return createStatement(resultSetType, resultSetConcurrency, ResultSet.HOLD_CURSORS_OVER_COMMIT); } public Struct createStruct(String typeName, Object[] attributes) throws SQLException { validateState(); // FIXME incomplete Struct result = createObject(Struct.class); return result; } public boolean getAutoCommit() throws SQLException { validateState(); return config.isAutoCommit(); } public Properties getClientInfo() throws SQLException { validateState(); Properties props = new Properties(); props.putAll(_clientInfo); return props; } public String getClientInfo(String name) throws SQLException { validateState(); return _clientInfo.getProperty(name); } public int getHoldability() throws SQLException { validateState(); return ResultSet.HOLD_CURSORS_OVER_COMMIT; } public DatabaseMetaData getMetaData() throws SQLException { validateState(); if (!quiet && metaData == null) { throw CassandraErrors.databaseMetaDataNotAvailableException(); } return metaData; } public int getNetworkTimeout() throws SQLException { validateState(); return config.getConnectionTimeout(); } public String getCatalog() throws SQLException { validateState(); return null; } public int getTransactionIsolation() throws SQLException { validateState(); return _txIsolationLevel; } public Map<String, Class<?>> getTypeMap() throws SQLException { validateState(); Map<String, Class<?>> map = new HashMap<String, Class<?>>(); map.putAll(_typeMap); return map; } public boolean isReadOnly() throws SQLException { validateState(); return config.isReadOnly(); } public boolean isValid(int timeout) throws SQLException { validateState(); // FIXME incomplete return !closed; } public String nativeSQL(String sql) throws SQLException { validateState(); if (config.isSqlFriendly()) { CassandraCqlStatement stmt = CassandraCqlParser.parse(config, sql); sql = stmt.getCql(); } return Strings.nullToEmpty(sql); } public CallableStatement prepareCall(String sql) throws SQLException { return prepareCall(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); } public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return prepareCall(sql, resultSetType, resultSetConcurrency, ResultSet.HOLD_CURSORS_OVER_COMMIT); } public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { validateState(); if (!quiet) { throw CassandraErrors.notSupportedException(); } return null; } public PreparedStatement prepareStatement(String sql) throws SQLException { return prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); } public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { return prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); } public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return prepareStatement(sql, resultSetType, resultSetConcurrency, ResultSet.HOLD_CURSORS_OVER_COMMIT); } public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { // FIXME incomplete return prepareStatement(sql); } public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { // FIXME incomplete return prepareStatement(sql); } public void releaseSavepoint(Savepoint savepoint) throws SQLException { validateState(); if (!quiet) { throw CassandraErrors.notSupportedException(); } } public void rollback() throws SQLException { validateState(); // better to be quiet and do nothing as we always commit in Cassandra if (!quiet) { throw CassandraErrors.notSupportedException(); } } public void rollback(Savepoint savepoint) throws SQLException { validateState(); if (!quiet) { throw CassandraErrors.notSupportedException(); } } public void setAutoCommit(boolean autoCommit) throws SQLException { validateState(); if (!quiet && !autoCommit) { throw CassandraErrors.notSupportedException(); } } public void setClientInfo(Properties properties) throws SQLClientInfoException { // FIXME incomplete _clientInfo.clear(); if (properties != null) { _clientInfo.putAll(properties); } } public void setClientInfo(String name, String value) throws SQLClientInfoException { // FIXME incomplete _clientInfo.setProperty(name, value); } public void setHoldability(int holdability) throws SQLException { validateState(); if (!quiet && holdability != ResultSet.HOLD_CURSORS_OVER_COMMIT) { throw CassandraErrors.notSupportedException(); } } public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { validateState(); // FIXME incomplete if (!quiet) { throw CassandraErrors.notSupportedException(); } } public void setReadOnly(boolean readOnly) throws SQLException { validateState(); // FIXME incomplete if (!quiet) { throw CassandraErrors.notSupportedException(); } } public Savepoint setSavepoint() throws SQLException { return setSavepoint(null); } public Savepoint setSavepoint(String name) throws SQLException { validateState(); if (!quiet) { throw CassandraErrors.notSupportedException(); } return null; } public void setCatalog(String catalog) throws SQLException { validateState(); validateState(); if (!quiet) { throw CassandraErrors.notSupportedException(); } } public void setTransactionIsolation(int level) throws SQLException { validateState(); // ignore isolation level and always use TRANSACTION_READ_COMMITTED if (!quiet && level != TRANSACTION_NONE) { throw CassandraErrors.notSupportedException(); } } public void setTypeMap(Map<String, Class<?>> map) throws SQLException { validateState(); _typeMap.clear(); if (map != null) { _typeMap.putAll(map); } } }
package ru.gb.jtwo.lesson_2.homework; import java.util.Arrays; public class Test { public static void main(String[] args) { String string = "10 3 1 2\n2 3 2 2\n5 6 7 1\n300 3 1 0"; string = string.replace(" ", ","); // System.out.println(string); String[] oneDimensionalArray = string.split("\n"); // System.out.println(Arrays.toString(oneDimensionalArray)); String[][] twoDimensionalArray = new String[oneDimensionalArray.length][oneDimensionalArray.length]; // System.out.println(Arrays.deepToString(twoDimensionalArray)); for (int i = 0; i <oneDimensionalArray.length ; i++) { oneDimensionalArray[i] = oneDimensionalArray[i].trim(); String [] singleInt = oneDimensionalArray[i].split(","); for (int j = 0; j <singleInt.length ; j++) { twoDimensionalArray[i][j]=singleInt[j]; } } // System.out.println(Arrays.deepToString(twoDimensionalArray)); // // System.out.println(twoDimensionalArray[0][0]); int[][] stringToInt = new int[twoDimensionalArray.length][twoDimensionalArray[0].length]; for (int i = 0; i <twoDimensionalArray.length ; i++) { for (int j = 0; j <twoDimensionalArray.length ; j++) { stringToInt[i][j] = Integer.parseInt(twoDimensionalArray[i][j]); } } System.out.println(Arrays.deepToString(stringToInt)); int sumOfNumbers = 0; for (int i = 0; i <stringToInt.length ; i++) { for (int j = 0; j <stringToInt.length ; j++) { sumOfNumbers += stringToInt[i][j]; } } System.out.println(sumOfNumbers); int result = sumOfNumbers/2; } }
package f.star.iota.milk.ui.mzitu.mzi; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import f.star.iota.milk.R; import f.star.iota.milk.base.BaseAdapter; public class MZITUAdapter extends BaseAdapter<MZITUViewHolder, MZITUBean> { @Override public MZITUViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new MZITUViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_description_with_tag, parent, false)); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { ((MZITUViewHolder) holder).bindView(mBeans.get(position)); } }