text
stringlengths
10
2.72M
package br.com.drem.testes; /** * @author AndreMart * @contacts: andremartins@outlook.com.br;andre.drem@gmail.com * @tel: 63 8412 1921 * @site: drem.com.br */ import javax.persistence.EntityManager; import br.com.drem.entity.Cidade; import br.com.drem.entity.Estado; import br.com.drem.entity.Pais; import br.com.drem.entity.Pessoa; import br.com.drem.util.JPAUtil; public class TesteConexaoPostgre { public static void main(String[] args) { Pais pais = new Pais(); pais.setNome("Portugal"); pais.setSigla("PT"); EntityManager em = JPAUtil.getEntityManager(); em.getTransaction().begin(); em.persist(pais); em.getTransaction().commit(); em.close(); Estado estado = new Estado(); estado.setPais(pais); estado.setNome("Goias"); estado.setUf("GO"); EntityManager em1 = JPAUtil.getEntityManager(); em1.getTransaction().begin(); em1.persist(estado); em1.getTransaction().commit(); em1.close(); Cidade cidade = new Cidade(); cidade.setEstado(estado); cidade.setNome("Goiania"); EntityManager em2 = JPAUtil.getEntityManager(); em2.getTransaction().begin(); em2.persist(cidade); em2.getTransaction().commit(); em2.close(); Pessoa pes = new Pessoa(); pes.setNome("Andrades"); pes.setEndereco("67 sul"); pes.setCep("7700000"); pes.setCidade(cidade); EntityManager em3 = JPAUtil.getEntityManager(); em3.getTransaction().begin(); em3.persist(pes); em3.getTransaction().commit(); em3.close(); } }
/** * Created by Joe on 8/28/2014. */ public class HelloWorld { public static void main(String[] args) { //Scott Hadzik and Joe Grundvig boolean myBoolean = true; byte myByte = 10; //1 byte int myInt = 101; //4 bytes long myLong = 1000; //8 bytes float myFloat; //4 bytes floating, needs F after the number double myDouble; //8 bytes floating char myChar; //2 bytes short myShort; //2 bytes myDouble = 56771234.54321235; myFloat = 100.1F; myChar = 'z'; myShort = 200; String myString = "Hello World!"; //The float will be converted to a double prior to the evaluation of the expression. No data loss System.out.println(myDouble*myFloat); //The byte will be converted to a float prior to evaluation. No data loss System.out.println(myFloat-myByte); //The short will be converted to a long, no precision loss System.out.println(myLong/myShort); //The byte will be converted to an int. No data loss System.out.println(myInt%myByte); //The int and float will be converted to doubles, everything else is already a double. No data loss System.out.println(Math.PI * Math.sin(myDouble+Math.pow(myInt, myFloat))); //Precision will be lost. The double's value is outside the range of a byte, so the value is truncated and a different value System.out.println((byte)myDouble); StringBuilder stringBuilder = new StringBuilder(); stringBuilder .append("boolean: " + myBoolean) .append(", byte: " + myByte) .append(", int: " + myInt) .append(", long: " + myLong) .append(", int: " + myInt) .append(", float: " + myFloat) .append(", double: " + myDouble) .append(", char: " + myChar) .append(", short: " + myShort); System.out.println(stringBuilder); //Check to see if myString is equivalent to "Hello World!" System.out.println("Hello World!".equals(myString)); //Find the first character in myString System.out.println(myString.charAt(0)); //Find the length of myString System.out.println(myString.length()); //Check to see if myString ends with an ! System.out.println(myString.endsWith("!")); //Find the index of the first "o" System.out.println(myString.indexOf("o")); //Find the index of the last "o" System.out.println(myString.lastIndexOf("o")); } }
package alien4cloud.it.topology; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.List; import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ArrayUtils; import alien4cloud.it.Context; import alien4cloud.it.utils.JsonTestUtil; import alien4cloud.model.components.IndexedNodeType; import alien4cloud.model.topology.NodeTemplate; import alien4cloud.model.topology.RelationshipTemplate; import alien4cloud.rest.model.RestResponse; import alien4cloud.rest.topology.NodeTemplateRequest; import alien4cloud.topology.TopologyDTO; import alien4cloud.rest.utils.JsonUtil; import com.fasterxml.jackson.databind.ObjectMapper; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; @Slf4j public class NodeTemplateStepDefinitions { private TopologyStepDefinitions topoSteps = new TopologyStepDefinitions(); private ObjectMapper jsoMapper = Context.getInstance().getJsonMapper(); @When("^I ask for replacements for the node \"([^\"]*)\"$") public void I_ask_for_replacements_for_the_node(String nodeTemplateName) throws Throwable { String topologyId = Context.getInstance().getTopologyId(); Context.getInstance().registerRestResponse( Context.getRestClientInstance().get("/rest/topologies/" + topologyId + "/nodetemplates/" + nodeTemplateName + "/replace")); } @Then("^the possible replacements nodes types should be$") public void the_possible_replacements_nodes_types_should_be(List<String> expectedElementIds) throws Throwable { IndexedNodeType[] replacements = JsonUtil.read(Context.getInstance().getRestResponse(), IndexedNodeType[].class).getData(); assertNotNull(replacements); String[] elementIds = topoSteps.getElementsId(replacements); assertEquals(expectedElementIds.size(), elementIds.length); String[] expectedArrayElementIds = expectedElementIds.toArray(new String[expectedElementIds.size()]); Arrays.sort(expectedArrayElementIds); Arrays.sort(elementIds); assertArrayEquals(expectedArrayElementIds, elementIds); } @Then("^the possible replacements nodes types should be \"([^\"]*)\"$") public void the_possible_replacements_nodes_types_should_be(String expectedElementId) throws Throwable { IndexedNodeType[] replacements = JsonUtil.read(Context.getInstance().getRestResponse(), IndexedNodeType[].class).getData(); assertNotNull(replacements); assertEquals(1, replacements.length); assertEquals(expectedElementId, replacements[0].getElementId()); } @When("^I replace the node template \"([^\"]*)\" with a node \"([^\"]*)\" related to the \"([^\"]*)\" node type$") public void I_replace_the_node_template_with_a_node_related_to_the_node_type(String oldNodetemplateName, String newNodeTemplateName, String indexedNodeTypeId) throws Throwable { NodeTemplateRequest req = new NodeTemplateRequest(newNodeTemplateName, indexedNodeTypeId); String jSon = jsoMapper.writeValueAsString(req); String topologyId = Context.getInstance().getTopologyId(); Context.getInstance().registerRestResponse( Context.getRestClientInstance().putJSon("/rest/topologies/" + topologyId + "/nodetemplates/" + oldNodetemplateName + "/replace", jSon)); } @When("^I delete the relationship \"([^\"]*)\" from the node template \"([^\"]*)\"$") public void I_delete_the_relationship_from_the_node_template(String relName, String nodeTempName) throws Throwable { Context.getInstance().registerRestResponse( Context.getRestClientInstance().delete( "/rest/topologies/" + Context.getInstance().getTopologyId() + "/nodetemplates/" + nodeTempName + "/relationships/" + relName)); } @Then("^I should not have the relationship \"([^\"]*)\" in \"([^\"]*)\" node template$") public void I_should_not_have_a_relationship_in_node_template(String relName, String nodeTempName) throws Throwable { String topologyJson = Context.getRestClientInstance().get("/rest/topologies/" + Context.getInstance().getTopologyId()); RestResponse<TopologyDTO> topologyResponse = JsonTestUtil.read(topologyJson, TopologyDTO.class); NodeTemplate sourceNode = topologyResponse.getData().getTopology().getNodeTemplates().get(nodeTempName); Map<String, RelationshipTemplate> rels = sourceNode.getRelationships(); if (rels != null) { assertFalse(rels.containsKey(relName)); } else { log.info("No relationship found in I_should_not_have_a_relationship_in_node_template(String relName, String nodeTempName)"); } } // @Then("^The RestResponse should contain a node template with a relationship \"([^\"]*)\" of type \"([^\"]*)\" and target \"([^\"]*)\"$") // public void The_RestResponse_should_contain_a_node_template_with_a_relationship_of_type_and_target(String expectedRelationshipName, // String expectedRelationshipType, String expectedRelationshipTarget) throws Throwable { // NodeTemplateDTO restNodeTemplateDTO = JsonUtil.read(Context.getInstance().getRestResponse(), NodeTemplateDTO.class).getData(); // assertNotNull(restNodeTemplateDTO); // assertNotNull(restNodeTemplateDTO.getNodeTemplate()); // Map<String, RelationshipTemplate> relationships = restNodeTemplateDTO.getNodeTemplate().getRelationships(); // assertNotNull(relationships); // RelationshipTemplate relTemplate = relationships.get(expectedRelationshipName.trim()); // assertNotNull(relTemplate); // assertEquals(expectedRelationshipType.trim(), relTemplate.getType()); // assertEquals(expectedRelationshipTarget.trim(), relTemplate.getTarget()); // } @Then("^there should be the followings in replacements nodes types$") public void there_should_be_the_followings_in_replacements_nodes_types(List<String> expectedElementIds) throws Throwable { IndexedNodeType[] replacements = JsonUtil.read(Context.getInstance().getRestResponse(), IndexedNodeType[].class).getData(); assertNotNull(replacements); String[] elementIds = topoSteps.getElementsId(replacements); String[] expectedElementIdsArray = expectedElementIds.toArray(new String[expectedElementIds.size()]); for (String expected : expectedElementIdsArray) { assertTrue(ArrayUtils.contains(elementIds, expected)); } } }
package main; import java.util.Scanner; import DaoClass.AllPrint; import DaoClass.DeleteClass; import DaoClass.FileSaveClass; import DaoClass.InsertClass; import DaoClass.SelectClass; import DaoClass.UpdateClass; import DaoInterface.DaoImpl; import fileload.FileLoadClass; public class mainClass { public static void main(String[] args) { Scanner scan = new Scanner(System.in); (new FileLoadClass()).process(); while(true) { DaoImpl dao = null; System.out.println("1. 선수 등록 "); System.out.println("2. 선수 삭제 "); System.out.println("3. 선수 검색 "); System.out.println("4. 선수 수정 "); System.out.println("5. 선수 모두 출력 "); System.out.println("6. 데이터 저장 "); System.out.println("0. 프로그램 종료 "); System.out.print("메뉴 번호 입력 >>> "); int choice = scan.nextInt(); switch(choice) { case 1: dao = new InsertClass(); break; case 2: dao = new DeleteClass(); break; case 3: dao = new SelectClass(); break; case 4: dao = new UpdateClass(); break; case 5: dao = new AllPrint(); break; case 6: dao = new FileSaveClass(); break; } dao.process(); } } }
package me.bayanov.lambdas; public class Person { private String name; private int age; public Person(String name, int age) { if (name == null) { throw new NullPointerException("Name must be not null"); } if (age < 0) { throw new IllegalArgumentException("Age must be >= 0"); } this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } }
package almacenes; public enum DireccionMovimiento { ADENTRO, AFUERA }
package defenseSystem; import java.awt.Graphics; import java.util.LinkedList; public class Handler { public LinkedList<Sprite> sprite = new LinkedList<Sprite>(); public void tick() { for(int n=0; n<sprite.size(); n++) { sprite.get(n).tick(); } } public void render(Graphics g) { for(int n=0;n<sprite.size();n++) { sprite.get(n).drwRect(g); sprite.get(n).drwImage(g); } } public void addObject(Sprite sprite) { Sprite tempObject = sprite; this.sprite.add(sprite); } public void removeObject(Sprite sprite) { this.sprite.remove(sprite); } public void collission() { for(int n=0; n<sprite.size(); n++) { sprite.get(n).collission(); } } public void clearOutOfBounds() { for(int n=0; n<sprite.size(); n++) { if(sprite.get(n).getY() >= (Universal.HEIGHT+20)) sprite.remove(n); } } }
package com.cse118.movementdetector; import androidx.appcompat.app.AppCompatActivity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.util.Date; public class MainActivity extends AppCompatActivity { private TextView mTextViewStatus; private Button mButtonReset; private Button mButtonExit; private MovementService movementService; private final long TIME_WAIT = 15000; private boolean isBound = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextViewStatus = findViewById(R.id.AM_textView_moved); mButtonReset = findViewById(R.id.AM_button_reset); mButtonExit = findViewById(R.id.AM_button_exit); mTextViewStatus.setText(R.string.status_not_moved); mButtonReset.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { reset(); } }); mButtonExit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } @Override protected void onStart() { super.onStart(); } @Override protected void onResume() { Intent intent = new Intent(this, MovementService.class); this.startService(intent); this.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE); if (isBound && movementService != null) { Date timeNow = new Date(); if ((movementService.didItMove()) && (movementService.getFirstTimeMoved() != 0) && (timeNow.getTime() > movementService.getFirstTimeMoved() + TIME_WAIT)) { mTextViewStatus.setText(R.string.status_moved); } } super.onResume(); } @Override protected void onPause() { if (serviceConnection != null) { unbindService(serviceConnection); } super.onPause(); } @Override protected void onStop() { super.onStop(); } @Override protected void onDestroy() { super.onDestroy(); } public ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { MovementService.LocalBinder localBinder = (MovementService.LocalBinder) service; movementService = localBinder.getService(); isBound = true; } @Override public void onServiceDisconnected(ComponentName name) { movementService = null; isBound = false; } }; public void reset() { mTextViewStatus.setText(R.string.status_not_moved); if (movementService != null) { movementService.reset(); } } }
package com.ut.module_lock.entity; import com.ut.database.entity.Record; import java.io.Serializable; import java.util.List; /** * author : chenjiajun * time : 2018/12/3 * desc : */ public class OperationRecord implements Serializable { private String time; private List<Record> records; public String getTime() { return time; } public void setTime(String time) { this.time = time; } public List<Record> getRecords() { return records; } public void setRecords(List<Record> records) { this.records = records; } }
package com.rachelgrau.rachel.health4theworldstroke.Activities; import android.content.Context; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import com.rachelgrau.rachel.health4theworldstroke.Adapters.InfoListAdapter; import com.rachelgrau.rachel.health4theworldstroke.R; import java.util.ArrayList; public class InfoListActivity extends AppCompatActivity { public static final String EXTRA_INFO_TYPE = "infoType"; public static final String EXTRA_INFO_TYPE_SPAN= "infoType"; public static final String INFO_TYPE_ABOUT_US = "About Us"; public static final String INFO_TYPE_TERMS = "Terms & Conditions"; public static final String INFO_TYPE_PRIVACY_POLICY = "Privacy Policy"; public static final String INFO_TYPE_ABOUT_US_SPAN = "Sobre nosotros"; public static final String INFO_TYPE_TERMS_SPAN = "Términos y condiciones"; public static final String INFO_TYPE_PRIVACY_POLICY_SPAN = "Política de privacidad"; public static final String INFO_TYPE_COPYRIGHT = "Copyright"; public static final String INFO_TYPE_COPYRIGHT_SPAN = "Copyright"; private ListView listView; // list of read or video content, depending which tab is selected private InfoListAdapter adapter; private ArrayList<String> content; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_info_list); setUpToolbar(); setUpListView(); } /* Sets up the top toolbar. */ private void setUpToolbar() { Toolbar myToolbar = (Toolbar) findViewById(R.id.info_list_toolbar); myToolbar.setTitle(""); Typeface font = Typeface.createFromAsset(getAssets(), "Roboto-Light.ttf"); TextView toolbarTitle = (TextView) myToolbar.findViewById(R.id.toolbar_title); toolbarTitle.setText(R.string.info_title); myToolbar.setTitle(R.string.info_title); toolbarTitle.setTypeface(font); setSupportActionBar(myToolbar); } private void setUpListView() { content = new ArrayList<String>(); Toolbar myToolbar = (Toolbar) findViewById(R.id.info_list_toolbar); if(myToolbar.getTitle().equals("Información")) { myToolbar.setTitle(""); content.add(INFO_TYPE_ABOUT_US_SPAN); content.add(INFO_TYPE_TERMS_SPAN); content.add(INFO_TYPE_PRIVACY_POLICY_SPAN); } if(myToolbar.getTitle().equals("Info")){ myToolbar.setTitle(""); content.add(INFO_TYPE_ABOUT_US); content.add(INFO_TYPE_TERMS); content.add(INFO_TYPE_PRIVACY_POLICY); } /* Populate list view with read content to start */ listView = (ListView)findViewById(R.id.info_list_view); adapter = new InfoListAdapter(this, content); listView.setAdapter(adapter); /* Set up callback for when an item in the list is selected. */ final Context context = this; listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { /* Transition to content activity */ String infoType = content.get(position); System.out.println("GO TO: " + infoType); Intent infoIntent = new Intent(context, InfoActivity.class); infoIntent.putExtra(EXTRA_INFO_TYPE, infoType); startActivity(infoIntent); } }); } }
package edu.udc.psw.modelo; import edu.udc.psw.modelo.manipulador.ManipuladorFormaGeometrica; public class Circulo implements FormaGeometrica { private static final long serialVersionUID = 6L; private double raio; private double perimetro; private double area; public Circulo() { this.raio = 0;this.perimetro = 0;this.area = 0; } public Circulo(double raio) { this.raio = raio; this.perimetro = 0; this.area = 0; } public double getRaio() { return raio; } public void setRaio(double raio) { this.raio = raio; } public double getApotema() { return (raio != 0) ? this.raio / 2 : 0; } public double getAreaTrianguloEquilateroInscrito() { return (raio != 0) ? ((3 * Math.pow(raio, 2) * Math.sqrt(3)) / 4) : 0; } @Override public String toString() { return ("Raio:[" + this.raio + " Perimetro:[" + this.perimetro() + "] Area:[" + this.area() + "] Area trinagulo Inscrito:[" + this.getAreaTrianguloEquilateroInscrito() + "]"); } @Override public Ponto2D centro() { // TODO Auto-generated method stub return null; } @Override public double area() { this.area = (raio != 0) ? 2 * Math.PI * Math.pow(raio, 2) : area; return area; } @Override public double perimetro() { this.perimetro = (raio != 0) ? 2 * Math.PI * raio : perimetro; return perimetro; } @Override public double base() { // TODO Auto-generated method stub return 0; } @Override public double altura() { // TODO Auto-generated method stub return 0; } @Override public byte[] toArray() { // TODO Auto-generated method stub return null; } @Override public ManipuladorFormaGeometrica getManipulador() { // TODO Auto-generated method stub return null; } @Override public FormaGeometrica clone() { // TODO Auto-generated method stub return null; } }
package com.itheima.health.service.impl; import com.alibaba.dubbo.config.annotation.Service; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.itheima.health.dao.PermissionDao; import com.itheima.health.entity.PageResult; import com.itheima.health.entity.QueryPageBean; import com.itheima.health.pojo.Permission; import com.itheima.health.service.PermissionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import java.util.List; /** * @Author: ZhangYongLiang * @Date: 2020/10/7 23:17 **/ @Service(interfaceClass = PermissionService.class) public class PermissionServiceImpl implements PermissionService { @Autowired private PermissionDao permissionDao; @Override public PageResult<Permission> findPage(QueryPageBean queryPageBean) { // 使用PageHelper分页插件 // 检查配置了插件没有sqlMapConfig.xml sqlSessionFactoryBean // 放入threadlocal 页码及大小 Page PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize()); // 判断是否有查询条件,有则要拼接% if(!StringUtils.isEmpty(queryPageBean.getQueryString())){ // 模糊查询 queryPageBean.setQueryString("%" + queryPageBean.getQueryString() + "%"); } // 紧接着的查询语句会被分页, 从线程中获取threadlocal 页码与大小, total放入threadlocal Page Page<Permission> page = permissionDao.findByCondition(queryPageBean.getQueryString()); // 防止数据丢失Page属性用的是基础数据类型,没有实现序列化 // web与service代码解耦 return new PageResult<Permission>(page.getTotal(),page.getResult()); } @Override public void add(Permission permission) { permissionDao.add(permission); } @Override public Permission findById(Integer id) { return permissionDao.findById(id); } @Override public void update(Permission permission) { permissionDao.update(permission); } @Override public boolean deleteById(Integer id) { // 查询权限是否被使用 List<Integer> roleIds = permissionDao.getRoleById(id); if (roleIds == null||roleIds.size()==0) { permissionDao.deleteById(id); return true; }else { return false; } } }
/* * 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 services; import com.google.gson.Gson; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Properties; import model.ArticleDetails; import model.TicketDetails; /** * * @author it177479 */ public class ArticleDetailsService { public String getArticleDetails(String ticketNo) throws Exception{ List<ArticleDetails> adlist = new ArrayList<ArticleDetails>(); String result = null; Connection conn = null; connection newConn = new connection(); Properties prop = new Properties(); conn = newConn.connectAs400DB(5,"",""); if (!conn.isClosed()){ // load a properties file prop.load(connection.class.getResourceAsStream("dbConfig.properties")); Statement st2 = conn.createStatement(); String sql1 = "SELECT * FROM " + prop.getProperty("DATA_LIB")+"/PWTMTKA1 a,"+prop.getProperty("DATA_LIB")+"/PWTMART1 aty " + "WHERE MTKANUMB='"+ticketNo+"' AND a.MTKATYCD = aty.MARTTYCD "; //System.out.println("sql:---"+sql1); ResultSet rs2 = st2.executeQuery(sql1); int i = 0; //while(rs2.next()) { // i++; //} //ad = new ArticleDetails[5]; int counter = 0; while (rs2.next()) { //result = rs2.getString("usbstat"); ArticleDetails ad = null; try { ad = new ArticleDetails(); // System.out.println("Desc : "+rs2.getString("MARTDESC")); ad.setArticletypecode(rs2.getString("MTKATYCD")); ad.setNoofitems(rs2.getString("MTKANOIT")); ad.setAssessedvalue(rs2.getString("MTKAASVL")); ad.setCaretage(rs2.getString("MTKACRTG")); ad.setGrossweight(rs2.getString("MTKAGRWT")); ad.setNetweight(rs2.getString("MTKANTWT")); ad.setTypedescription(rs2.getString("MARTDESC")); } catch (Exception e) { System.out.println(e); } //counter++; adlist.add(ad); } } Gson gson = new Gson(); String retobj = gson.toJson(adlist); System.out.println(retobj ); return retobj; } }
package rmi; import java.rmi.Remote; import java.rmi.RemoteException; public interface MathInterface extends Remote { int sum( int num1, int num2 ) throws RemoteException; int sub( int num1, int num2 ) throws RemoteException; }
import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import java.io.IOException; import java.nio.charset.CharacterCodingException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class WikipediaPageRankMapper extends Mapper<LongWritable, Text, Text, Text> { private static final Pattern Patterns = Pattern.compile("\\[.+?\\]"); @Override public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String[] val = parseLink(value); String pageString = val[0]; if(isValidPage(pageString)) return; Text pg = new Text(pageString.replace(' ', '_')); Matcher matcher = Patterns.matcher(val[1]); while (matcher.find()) { String otherPage = matcher.group(); otherPage = getWikiPage(otherPage); if(otherPage == null || otherPage.isEmpty()) continue; context.write(pg, new Text(otherPage)); } } private boolean isValidPage(String pageString) { return pageString.contains(":"); } private String getWikiPage(String Link){ if(checkWikiLink(Link)) return null; int start = Link.startsWith("[[") ? 2 : 1; int end = Link.indexOf("]"); int pos = Link.indexOf("|"); if(pos > 0){ end = pos; } int pt = Link.indexOf("#"); if(pt > 0){ end = pt; } Link = Link.substring(start, end); Link = Link.replaceAll("\\s", "_"); Link = Link.replaceAll(",", ""); Link = remAmp(Link); return Link; } private String remAmp(String LinkText) { if(LinkText.contains("&amp;")) return LinkText.replace("&amp;", "&"); return LinkText; } private String[] parseLink(Text value) throws CharacterCodingException { String[] val = new String[2]; int start = value.find("<title>"); int end = value.find("</title>", start); start += 7; val[0] = Text.decode(value.getBytes(), start, end-start); start = value.find("<text"); start = value.find(">", start); end = value.find("</text>", start); start += 1; if(start == -1 || end == -1) { return new String[]{"",""}; } val[1] = Text.decode(value.getBytes(), start, end-start); return val; } private boolean checkWikiLink(String Link) { int start = 1; if(Link.startsWith("[[")){ start = 2; } if( Link.length() < start+2 || Link.length() > 100) return true; char firstChar = Link.charAt(start); if( firstChar == '{') return true; if( firstChar == '&') return true; if( firstChar == '#') return true; if( firstChar == ',') return true; if( firstChar == '.') return true; if( firstChar == '-') return true; if( firstChar == '\'') return true; if( Link.contains(":")) return true; if( Link.contains(",")) return true; if( Link.contains("&")) return true; return false; } }
/* * Copyright 2002-2020 the original author or authors. * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cache.interceptor; import java.io.Serializable; import java.lang.reflect.Method; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** * AOP Alliance MethodInterceptor for declarative cache * management using the common Spring caching infrastructure * ({@link org.springframework.cache.Cache}). * * <p>Derives from the {@link CacheAspectSupport} class which * contains the integration with Spring's underlying caching API. * CacheInterceptor simply calls the relevant superclass methods * in the correct order. * * <p>CacheInterceptors are thread-safe. * * @author Costin Leau * @author Juergen Hoeller * @since 3.1 */ @SuppressWarnings("serial") public class CacheInterceptor extends CacheAspectSupport implements MethodInterceptor, Serializable { @Override @Nullable public Object invoke(final MethodInvocation invocation) throws Throwable { Method method = invocation.getMethod(); CacheOperationInvoker aopAllianceInvoker = () -> { try { return invocation.proceed(); } catch (Throwable ex) { throw new CacheOperationInvoker.ThrowableWrapper(ex); } }; Object target = invocation.getThis(); Assert.state(target != null, "Target must not be null"); try { return execute(aopAllianceInvoker, target, method, invocation.getArguments()); } catch (CacheOperationInvoker.ThrowableWrapper th) { throw th.getOriginal(); } } }
package com.j1902.shopping.controller; import com.github.pagehelper.PageInfo; import com.j1902.shopping.mapper.CountOrderMapper; import com.j1902.shopping.model.OrdersQv; import com.j1902.shopping.model.Remember; import com.j1902.shopping.pojo.Admin; import com.j1902.shopping.pojo.CountOrder; import com.j1902.shopping.pojo.Item; import com.j1902.shopping.service.AdminService; import com.j1902.shopping.service.ItemService; import com.j1902.shopping.service.OrderService; import com.j1902.shopping.utils.JsonUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.servlet.server.Session; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller public class Test { @Autowired private ItemService itemService; @Autowired private AdminService adminService; @Autowired private OrderService orderService; @RequestMapping("/AdminLogin") public String L(HttpServletRequest request, HttpSession session, Map<String, Object> map) throws UnsupportedEncodingException { Remember cookAdmin = adminService.showPwd(request); if (cookAdmin != null) { session.setAttribute("adminName", cookAdmin.getAdminName()); session.setAttribute("adminPwd", cookAdmin.getAdminPwd()); session.setAttribute("adminRemember", cookAdmin.getRemember()); } else { if (session.getAttribute("to")== null&&session.getAttribute("one")==null) { session.removeAttribute("adminName"); session.removeAttribute("adminPwd"); session.removeAttribute("adminRemember"); } else if (session.getAttribute("to")==null&&session.getAttribute("one")!=null){ session.removeAttribute("adminRemember"); session.removeAttribute("one"); }else { session.removeAttribute("to"); session.removeAttribute("one"); } } return "back/login"; } @RequestMapping("/order") public String Order(Map<String, Object> map) { List<Item> byItem = itemService.getByItem(); map.put("ITEM", byItem); return "back/goods"; } @RequestMapping("/goodsAdd") public String goodsAdd() { return "back/goods_add"; } @RequestMapping("/adminOrder") public String adminOrder(Map<String, Object> map, Integer number) { PageInfo<OrdersQv> pa = null; String order = "count_createtime desc"; if (number != null) { pa = orderService.seletCountOrderByPage(number, 2,order, "已处理"); } else { pa = orderService.seletCountOrderByPage(1, 2, order,"已处理"); } map.put("del", pa); System.out.println(pa); return "back/order"; } @RequestMapping("/adminOrder_unfinished") public String adminOrder_unfinished(Map<String, Object> map,Integer currentPage) { PageInfo<OrdersQv> pa = null; String order = "count_createtime desc"; if (currentPage != null) { pa = orderService.seletCountOrderByPage(currentPage, 2,order ,"未处理"); } else { pa = orderService.seletCountOrderByPage(1, 2, order,"未处理"); } map.put("undel", pa); return "back/order_unfinished"; } @RequestMapping("/forget") public String forget(){ return "front/forget"; } @RequestMapping("/logout") public String logout(HttpSession session) { session.removeAttribute("ADMIN_LOGIN"); return "back/login"; } @RequestMapping("/dealwith") public String OrderDealWith(Integer id,Integer Page){ orderService.updateCountOrderStaById(id); return "redirect:adminOrder_unfinished?currentPage="+Page; } @RequestMapping("/dealWait") public String OrderDealWait(){ orderService.updateCountOrderStaBySat(); return "redirect:adminOrder_unfinished"; } @RequestMapping("/message") @ResponseBody public Integer getWaitOrder(){ Map<String,Object> map = new HashMap<>(); int i = orderService.selectWaitCountOrder(); return i; } }
/* * Copyright 2002-2023 the original author or authors. * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.util.pattern; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.http.server.PathContainer; import org.springframework.web.util.pattern.PatternParseException.PatternMessage; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; /** * Exercise the {@link PathPatternParser}. * * @author Andy Clement * @author Sam Brannen */ public class PathPatternParserTests { private PathPattern pathPattern; @Test public void basicPatterns() { checkStructure("/"); checkStructure("/foo"); checkStructure("foo"); checkStructure("foo/"); checkStructure("/foo/"); checkStructure(""); } @Test public void singleCharWildcardPatterns() { pathPattern = checkStructure("?"); assertPathElements(pathPattern, SingleCharWildcardedPathElement.class); checkStructure("/?/"); checkStructure("/?abc?/"); } @Test public void multiwildcardPattern() { pathPattern = checkStructure("/**"); assertPathElements(pathPattern, WildcardTheRestPathElement.class); // this is not double wildcard, it's / then **acb (an odd, unnecessary use of double *) pathPattern = checkStructure("/**acb"); assertPathElements(pathPattern, SeparatorPathElement.class, RegexPathElement.class); } @Test public void toStringTests() { assertThat(checkStructure("/{*foobar}").toChainString()).isEqualTo("CaptureTheRest(/{*foobar})"); assertThat(checkStructure("{foobar}").toChainString()).isEqualTo("CaptureVariable({foobar})"); assertThat(checkStructure("abc").toChainString()).isEqualTo("Literal(abc)"); assertThat(checkStructure("{a}_*_{b}").toChainString()).isEqualTo("Regex({a}_*_{b})"); assertThat(checkStructure("/").toChainString()).isEqualTo("Separator(/)"); assertThat(checkStructure("?a?b?c").toChainString()).isEqualTo("SingleCharWildcarded(?a?b?c)"); assertThat(checkStructure("*").toChainString()).isEqualTo("Wildcard(*)"); assertThat(checkStructure("/**").toChainString()).isEqualTo("WildcardTheRest(/**)"); } @Test public void captureTheRestPatterns() { pathPattern = parse("{*foobar}"); assertThat(pathPattern.computePatternString()).isEqualTo("/{*foobar}"); assertPathElements(pathPattern, CaptureTheRestPathElement.class); pathPattern = checkStructure("/{*foobar}"); assertPathElements(pathPattern, CaptureTheRestPathElement.class); checkError("/{*foobar}/", 10, PatternMessage.NO_MORE_DATA_EXPECTED_AFTER_CAPTURE_THE_REST); checkError("/{*foobar}abc", 10, PatternMessage.NO_MORE_DATA_EXPECTED_AFTER_CAPTURE_THE_REST); checkError("/{*f%obar}", 4, PatternMessage.ILLEGAL_CHARACTER_IN_CAPTURE_DESCRIPTOR); checkError("/{*foobar}abc", 10, PatternMessage.NO_MORE_DATA_EXPECTED_AFTER_CAPTURE_THE_REST); checkError("/{f*oobar}", 3, PatternMessage.ILLEGAL_CHARACTER_IN_CAPTURE_DESCRIPTOR); checkError("/{*foobar}/abc", 10, PatternMessage.NO_MORE_DATA_EXPECTED_AFTER_CAPTURE_THE_REST); checkError("/{*foobar:.*}/abc", 9, PatternMessage.ILLEGAL_CHARACTER_IN_CAPTURE_DESCRIPTOR); checkError("/{abc}{*foobar}", 1, PatternMessage.CAPTURE_ALL_IS_STANDALONE_CONSTRUCT); checkError("/{abc}{*foobar}{foo}", 15, PatternMessage.NO_MORE_DATA_EXPECTED_AFTER_CAPTURE_THE_REST); } @Test public void equalsAndHashcode() { PathPatternParser caseInsensitiveParser = new PathPatternParser(); caseInsensitiveParser.setCaseSensitive(false); PathPatternParser caseSensitiveParser = new PathPatternParser(); PathPattern pp1 = caseInsensitiveParser.parse("/abc"); PathPattern pp2 = caseInsensitiveParser.parse("/abc"); PathPattern pp3 = caseInsensitiveParser.parse("/def"); assertThat(pp2).isEqualTo(pp1); assertThat(pp2.hashCode()).isEqualTo(pp1.hashCode()); assertThat(pp3).isNotEqualTo(pp1); pp1 = caseInsensitiveParser.parse("/abc"); pp2 = caseSensitiveParser.parse("/abc"); assertThat(pp1.equals(pp2)).isFalse(); assertThat(pp2.hashCode()).isNotEqualTo(pp1.hashCode()); } @Test public void regexPathElementPatterns() { checkError("/{var:[^/]*}", 8, PatternMessage.MISSING_CLOSE_CAPTURE); checkError("/{var:abc", 8, PatternMessage.MISSING_CLOSE_CAPTURE); // Do not check the expected position due a change in RegEx parsing in JDK 13. // See https://github.com/spring-projects/spring-framework/issues/23669 checkError("/{var:a{{1,2}}}", PatternMessage.REGEX_PATTERN_SYNTAX_EXCEPTION); pathPattern = checkStructure("/{var:\\\\}"); PathElement next = pathPattern.getHeadSection().next; assertThat(next.getClass().getName()).isEqualTo(CaptureVariablePathElement.class.getName()); assertMatches(pathPattern, "/\\"); pathPattern = checkStructure("/{var:\\/}"); next = pathPattern.getHeadSection().next; assertThat(next.getClass().getName()).isEqualTo(CaptureVariablePathElement.class.getName()); assertNoMatch(pathPattern, "/aaa"); pathPattern = checkStructure("/{var:a{1,2}}"); next = pathPattern.getHeadSection().next; assertThat(next.getClass().getName()).isEqualTo(CaptureVariablePathElement.class.getName()); pathPattern = checkStructure("/{var:[^\\/]*}"); next = pathPattern.getHeadSection().next; assertThat(next.getClass().getName()).isEqualTo(CaptureVariablePathElement.class.getName()); PathPattern.PathMatchInfo result = matchAndExtract(pathPattern, "/foo"); assertThat(result.getUriVariables().get("var")).isEqualTo("foo"); pathPattern = checkStructure("/{var:\\[*}"); next = pathPattern.getHeadSection().next; assertThat(next.getClass().getName()).isEqualTo(CaptureVariablePathElement.class.getName()); result = matchAndExtract(pathPattern, "/[[["); assertThat(result.getUriVariables().get("var")).isEqualTo("[[["); pathPattern = checkStructure("/{var:[\\{]*}"); next = pathPattern.getHeadSection().next; assertThat(next.getClass().getName()).isEqualTo(CaptureVariablePathElement.class.getName()); result = matchAndExtract(pathPattern, "/{{{"); assertThat(result.getUriVariables().get("var")).isEqualTo("{{{"); pathPattern = checkStructure("/{var:[\\}]*}"); next = pathPattern.getHeadSection().next; assertThat(next.getClass().getName()).isEqualTo(CaptureVariablePathElement.class.getName()); result = matchAndExtract(pathPattern, "/}}}"); assertThat(result.getUriVariables().get("var")).isEqualTo("}}}"); pathPattern = checkStructure("*"); assertThat(pathPattern.getHeadSection().getClass().getName()).isEqualTo(WildcardPathElement.class.getName()); checkStructure("/*"); checkStructure("/*/"); checkStructure("*/"); checkStructure("/*/"); pathPattern = checkStructure("/*a*/"); next = pathPattern.getHeadSection().next; assertThat(next.getClass().getName()).isEqualTo(RegexPathElement.class.getName()); pathPattern = checkStructure("*/"); assertThat(pathPattern.getHeadSection().getClass().getName()).isEqualTo(WildcardPathElement.class.getName()); checkError("{foo}_{foo}", 0, PatternMessage.ILLEGAL_DOUBLE_CAPTURE, "foo"); checkError("/{bar}/{bar}", 7, PatternMessage.ILLEGAL_DOUBLE_CAPTURE, "bar"); checkError("/{bar}/{bar}_{foo}", 7, PatternMessage.ILLEGAL_DOUBLE_CAPTURE, "bar"); pathPattern = checkStructure("{symbolicName:[\\p{L}\\.]+}-sources-{version:[\\p{N}\\.]+}.jar"); assertThat(pathPattern.getHeadSection().getClass().getName()).isEqualTo(RegexPathElement.class.getName()); } @Test public void completeCapturingPatterns() { pathPattern = checkStructure("{foo}"); assertThat(pathPattern.getHeadSection().getClass().getName()).isEqualTo(CaptureVariablePathElement.class.getName()); checkStructure("/{foo}"); checkStructure("/{f}/"); checkStructure("/{foo}/{bar}/{wibble}"); checkStructure("/{mobile-number}"); // gh-23101 } @Test public void noEncoding() { // Check no encoding of expressions or constraints PathPattern pp = parse("/{var:f o}"); assertThat(pp.toChainString()).isEqualTo("Separator(/) CaptureVariable({var:f o})"); pp = parse("/{var:f o}_"); assertThat(pp.toChainString()).isEqualTo("Separator(/) Regex({var:f o}_)"); pp = parse("{foo:f o}_ _{bar:b\\|o}"); assertThat(pp.toChainString()).isEqualTo("Regex({foo:f o}_ _{bar:b\\|o})"); } @Test public void completeCaptureWithConstraints() { pathPattern = checkStructure("{foo:...}"); assertPathElements(pathPattern, CaptureVariablePathElement.class); pathPattern = checkStructure("{foo:[0-9]*}"); assertPathElements(pathPattern, CaptureVariablePathElement.class); checkError("{foo:}", 5, PatternMessage.MISSING_REGEX_CONSTRAINT); } @Test public void partialCapturingPatterns() { pathPattern = checkStructure("{foo}abc"); assertThat(pathPattern.getHeadSection().getClass().getName()).isEqualTo(RegexPathElement.class.getName()); checkStructure("abc{foo}"); checkStructure("/abc{foo}"); checkStructure("{foo}def/"); checkStructure("/abc{foo}def/"); checkStructure("{foo}abc{bar}"); checkStructure("{foo}abc{bar}/"); checkStructure("/{foo}abc{bar}/"); } @Test public void illegalCapturePatterns() { checkError("{abc/", 4, PatternMessage.MISSING_CLOSE_CAPTURE); checkError("{abc:}/", 5, PatternMessage.MISSING_REGEX_CONSTRAINT); checkError("{", 1, PatternMessage.MISSING_CLOSE_CAPTURE); checkError("{abc", 4, PatternMessage.MISSING_CLOSE_CAPTURE); checkError("{/}", 1, PatternMessage.MISSING_CLOSE_CAPTURE); checkError("/{", 2, PatternMessage.MISSING_CLOSE_CAPTURE); checkError("}", 0, PatternMessage.MISSING_OPEN_CAPTURE); checkError("/}", 1, PatternMessage.MISSING_OPEN_CAPTURE); checkError("def}", 3, PatternMessage.MISSING_OPEN_CAPTURE); checkError("/{/}", 2, PatternMessage.MISSING_CLOSE_CAPTURE); checkError("/{{/}", 2, PatternMessage.ILLEGAL_NESTED_CAPTURE); checkError("/{abc{/}", 5, PatternMessage.ILLEGAL_NESTED_CAPTURE); checkError("/{0abc}/abc", 2, PatternMessage.ILLEGAL_CHARACTER_AT_START_OF_CAPTURE_DESCRIPTOR); checkError("/{a?bc}/abc", 3, PatternMessage.ILLEGAL_CHARACTER_IN_CAPTURE_DESCRIPTOR); checkError("/{abc}_{abc}", 1, PatternMessage.ILLEGAL_DOUBLE_CAPTURE); checkError("/foobar/{abc}_{abc}", 8, PatternMessage.ILLEGAL_DOUBLE_CAPTURE); checkError("/foobar/{abc:..}_{abc:..}", 8, PatternMessage.ILLEGAL_DOUBLE_CAPTURE); PathPattern pp = parse("/{abc:foo(bar)}"); assertThatIllegalArgumentException().isThrownBy(() -> pp.matchAndExtract(toPSC("/foo"))) .withMessage("No capture groups allowed in the constraint regex: foo(bar)"); assertThatIllegalArgumentException().isThrownBy(() -> pp.matchAndExtract(toPSC("/foobar"))) .withMessage("No capture groups allowed in the constraint regex: foo(bar)"); } @Test public void badPatterns() { // checkError("/{foo}{bar}/",6,PatternMessage.CANNOT_HAVE_ADJACENT_CAPTURES); checkError("/{?}/", 2, PatternMessage.ILLEGAL_CHARACTER_AT_START_OF_CAPTURE_DESCRIPTOR, "?"); checkError("/{a?b}/", 3, PatternMessage.ILLEGAL_CHARACTER_IN_CAPTURE_DESCRIPTOR, "?"); checkError("/{%%$}", 2, PatternMessage.ILLEGAL_CHARACTER_AT_START_OF_CAPTURE_DESCRIPTOR, "%"); checkError("/{ }", 2, PatternMessage.ILLEGAL_CHARACTER_AT_START_OF_CAPTURE_DESCRIPTOR, " "); checkError("/{%:[0-9]*}", 2, PatternMessage.ILLEGAL_CHARACTER_AT_START_OF_CAPTURE_DESCRIPTOR, "%"); } @Test public void patternPropertyGetCaptureCountTests() { // Test all basic section types assertThat(parse("{foo}").getCapturedVariableCount()).isEqualTo(1); assertThat(parse("foo").getCapturedVariableCount()).isEqualTo(0); assertThat(parse("{*foobar}").getCapturedVariableCount()).isEqualTo(1); assertThat(parse("/{*foobar}").getCapturedVariableCount()).isEqualTo(1); assertThat(parse("/**").getCapturedVariableCount()).isEqualTo(0); assertThat(parse("{abc}asdf").getCapturedVariableCount()).isEqualTo(1); assertThat(parse("{abc}_*").getCapturedVariableCount()).isEqualTo(1); assertThat(parse("{abc}_{def}").getCapturedVariableCount()).isEqualTo(2); assertThat(parse("/").getCapturedVariableCount()).isEqualTo(0); assertThat(parse("a?b").getCapturedVariableCount()).isEqualTo(0); assertThat(parse("*").getCapturedVariableCount()).isEqualTo(0); // Test on full templates assertThat(parse("/foo/bar").getCapturedVariableCount()).isEqualTo(0); assertThat(parse("/{foo}").getCapturedVariableCount()).isEqualTo(1); assertThat(parse("/{foo}/{bar}").getCapturedVariableCount()).isEqualTo(2); assertThat(parse("/{foo}/{bar}_{goo}_{wibble}/abc/bar").getCapturedVariableCount()).isEqualTo(4); } @Test public void patternPropertyGetWildcardCountTests() { // Test all basic section types assertThat(parse("{foo}").getScore()).isEqualTo(computeScore(1, 0)); assertThat(parse("foo").getScore()).isEqualTo(computeScore(0, 0)); assertThat(parse("{*foobar}").getScore()).isEqualTo(computeScore(0, 0)); // assertEquals(1,parse("/**").getScore()); assertThat(parse("{abc}asdf").getScore()).isEqualTo(computeScore(1, 0)); assertThat(parse("{abc}_*").getScore()).isEqualTo(computeScore(1, 1)); assertThat(parse("{abc}_{def}").getScore()).isEqualTo(computeScore(2, 0)); assertThat(parse("/").getScore()).isEqualTo(computeScore(0, 0)); // currently deliberate assertThat(parse("a?b").getScore()).isEqualTo(computeScore(0, 0)); assertThat(parse("*").getScore()).isEqualTo(computeScore(0, 1)); // Test on full templates assertThat(parse("/foo/bar").getScore()).isEqualTo(computeScore(0, 0)); assertThat(parse("/{foo}").getScore()).isEqualTo(computeScore(1, 0)); assertThat(parse("/{foo}/{bar}").getScore()).isEqualTo(computeScore(2, 0)); assertThat(parse("/{foo}/{bar}_{goo}_{wibble}/abc/bar").getScore()).isEqualTo(computeScore(4, 0)); assertThat(parse("/{foo}/*/*_*/{bar}_{goo}_{wibble}/abc/bar").getScore()).isEqualTo(computeScore(4, 3)); } @Test public void multipleSeparatorPatterns() { pathPattern = checkStructure("///aaa"); assertThat(pathPattern.getNormalizedLength()).isEqualTo(6); assertPathElements(pathPattern, SeparatorPathElement.class, SeparatorPathElement.class, SeparatorPathElement.class, LiteralPathElement.class); pathPattern = checkStructure("///aaa////aaa/b"); assertThat(pathPattern.getNormalizedLength()).isEqualTo(15); assertPathElements(pathPattern, SeparatorPathElement.class, SeparatorPathElement.class, SeparatorPathElement.class, LiteralPathElement.class, SeparatorPathElement.class, SeparatorPathElement.class, SeparatorPathElement.class, SeparatorPathElement.class, LiteralPathElement.class, SeparatorPathElement.class, LiteralPathElement.class); pathPattern = checkStructure("/////**"); assertThat(pathPattern.getNormalizedLength()).isEqualTo(5); assertPathElements(pathPattern, SeparatorPathElement.class, SeparatorPathElement.class, SeparatorPathElement.class, SeparatorPathElement.class, WildcardTheRestPathElement.class); } @Test public void patternPropertyGetLengthTests() { // Test all basic section types assertThat(parse("{foo}").getNormalizedLength()).isEqualTo(1); assertThat(parse("foo").getNormalizedLength()).isEqualTo(3); assertThat(parse("{*foobar}").getNormalizedLength()).isEqualTo(1); assertThat(parse("/{*foobar}").getNormalizedLength()).isEqualTo(1); assertThat(parse("/**").getNormalizedLength()).isEqualTo(1); assertThat(parse("{abc}asdf").getNormalizedLength()).isEqualTo(5); assertThat(parse("{abc}_*").getNormalizedLength()).isEqualTo(3); assertThat(parse("{abc}_{def}").getNormalizedLength()).isEqualTo(3); assertThat(parse("/").getNormalizedLength()).isEqualTo(1); assertThat(parse("a?b").getNormalizedLength()).isEqualTo(3); assertThat(parse("*").getNormalizedLength()).isEqualTo(1); // Test on full templates assertThat(parse("/foo/bar").getNormalizedLength()).isEqualTo(8); assertThat(parse("/{foo}").getNormalizedLength()).isEqualTo(2); assertThat(parse("/{foo}/{bar}").getNormalizedLength()).isEqualTo(4); assertThat(parse("/{foo}/{bar}_{goo}_{wibble}/abc/bar").getNormalizedLength()).isEqualTo(16); } @Test public void compareTests() { PathPattern p1, p2, p3; // Based purely on number of captures p1 = parse("{a}"); p2 = parse("{a}/{b}"); p3 = parse("{a}/{b}/{c}"); // Based on number of captures assertThat(p1.compareTo(p2)).isEqualTo(-1); List<PathPattern> patterns = new ArrayList<>(); patterns.add(p2); patterns.add(p3); patterns.add(p1); Collections.sort(patterns); assertThat(patterns.get(0)).isEqualTo(p1); // Based purely on length p1 = parse("/a/b/c"); p2 = parse("/a/boo/c/doo"); p3 = parse("/asdjflaksjdfjasdf"); assertThat(p1.compareTo(p2)).isEqualTo(1); patterns = new ArrayList<>(); patterns.add(p2); patterns.add(p3); patterns.add(p1); Collections.sort(patterns); assertThat(patterns.get(0)).isEqualTo(p3); // Based purely on 'wildness' p1 = parse("/*"); p2 = parse("/*/*"); p3 = parse("/*/*/*_*"); assertThat(p1.compareTo(p2)).isEqualTo(-1); patterns = new ArrayList<>(); patterns.add(p2); patterns.add(p3); patterns.add(p1); Collections.sort(patterns); assertThat(patterns.get(0)).isEqualTo(p1); // Based purely on catchAll p1 = parse("{*foobar}"); p2 = parse("{*goo}"); assertThat(p1.compareTo(p2)).isNotEqualTo(0); p1 = parse("/{*foobar}"); p2 = parse("/abc/{*ww}"); assertThat(p1.compareTo(p2)).isEqualTo(+1); assertThat(p2.compareTo(p1)).isEqualTo(-1); p3 = parse("/this/that/theother"); assertThat(p1.isCatchAll()).isTrue(); assertThat(p2.isCatchAll()).isTrue(); assertThat(p3.isCatchAll()).isFalse(); patterns = new ArrayList<>(); patterns.add(p2); patterns.add(p3); patterns.add(p1); Collections.sort(patterns); assertThat(patterns.get(0)).isEqualTo(p3); assertThat(patterns.get(1)).isEqualTo(p2); } @Test public void captureTheRestWithinPatternNotSupported() { PathPatternParser parser = new PathPatternParser(); assertThatThrownBy(() -> parser.parse("/resources/**/details")) .isInstanceOf(PatternParseException.class) .extracting("messageType").isEqualTo(PatternMessage.NO_MORE_DATA_EXPECTED_AFTER_CAPTURE_THE_REST); } @Test public void separatorTests() { PathPatternParser parser = new PathPatternParser(); parser.setPathOptions(PathContainer.Options.create('.', false)); String rawPattern = "first.second.{last}"; PathPattern pattern = parser.parse(rawPattern); assertThat(pattern.computePatternString()).isEqualTo(rawPattern); } private PathPattern parse(String pattern) { PathPatternParser patternParser = new PathPatternParser(); return patternParser.parse(pattern); } /** * Verify the pattern string computed for a parsed pattern matches the original pattern text */ private PathPattern checkStructure(String pattern) { PathPattern pp = parse(pattern); assertThat(pp.computePatternString()).isEqualTo(pattern); return pp; } /** * Delegates to {@link #checkError(String, int, PatternMessage, String...)}, * passing {@code -1} as the {@code expectedPos}. * @since 5.2 */ private void checkError(String pattern, PatternMessage expectedMessage, String... expectedInserts) { checkError(pattern, -1, expectedMessage, expectedInserts); } /** * @param expectedPos the expected position, or {@code -1} if the position should not be checked */ private void checkError(String pattern, int expectedPos, PatternMessage expectedMessage, String... expectedInserts) { assertThatExceptionOfType(PatternParseException.class) .isThrownBy(() -> pathPattern = parse(pattern)) .satisfies(ex -> { if (expectedPos >= 0) { assertThat(ex.getPosition()).as(ex.toDetailedString()).isEqualTo(expectedPos); } assertThat(ex.getMessageType()).as(ex.toDetailedString()).isEqualTo(expectedMessage); if (expectedInserts.length != 0) { assertThat(ex.getInserts()).isEqualTo(expectedInserts); } }); } @SafeVarargs private final void assertPathElements(PathPattern p, Class<? extends PathElement>... sectionClasses) { PathElement head = p.getHeadSection(); for (Class<? extends PathElement> sectionClass : sectionClasses) { if (head == null) { fail("Ran out of data in parsed pattern. Pattern is: " + p.toChainString()); } assertThat(head.getClass().getSimpleName()).as("Not expected section type. Pattern is: " + p.toChainString()).isEqualTo(sectionClass.getSimpleName()); head = head.next; } } // Mirrors the score computation logic in PathPattern private int computeScore(int capturedVariableCount, int wildcardCount) { return capturedVariableCount + wildcardCount * 100; } private void assertMatches(PathPattern pp, String path) { assertThat(pp.matches(PathPatternTests.toPathContainer(path))).isTrue(); } private void assertNoMatch(PathPattern pp, String path) { assertThat(pp.matches(PathPatternTests.toPathContainer(path))).isFalse(); } private PathPattern.PathMatchInfo matchAndExtract(PathPattern pp, String path) { return pp.matchAndExtract(PathPatternTests.toPathContainer(path)); } private PathContainer toPSC(String path) { return PathPatternTests.toPathContainer(path); } }
package com.emg.projectsmanage.common; /** * 质检项集合类型 * * @author zsen * */ public enum ProcessType { /** * -1, "未知项目类型" */ UNKNOWN(-1, "未知项目类型"), /** * 1, "改错项目" */ ERROR(1, "改错项目"), /** * 2, "NR/FC项目" */ NRFC(2, "NR/FC项目"), /** * 3, "关系附属表项目" */ ATTACH(3, "关系附属表项目"), /** * 4, "全国质检项目" */ COUNTRY(4, "全国质检项目"), /** * 5, "POI编辑项目" */ POIEDIT(5, "POI编辑项目"); private Integer value; private String des; public String getDes() { return des; } public void setDes(String des) { this.des = des; } private ProcessType(Integer value, String des) { this.setValue(value); this.des = des; } public Integer getValue() { return value; } public void setValue(Integer value) { this.value = value; } public static ProcessType valueOf(Integer value) { ProcessType ret = ProcessType.UNKNOWN; for(ProcessType v : ProcessType.values()) { if(v.getValue().equals(value)) { ret = v; break; } } return ret; } public static String toJsonStr() { String str = new String("{"); for (ProcessType val : ProcessType.values()) { if(val.equals(UNKNOWN)) continue; str += "\"" + val.getValue() + "\":\"" + val.getDes() + "\","; } str += "}"; return str; } }
package riomaissaude.felipe.com.br.riosaude.utils; import android.content.Context; import android.content.SharedPreferences; /** * Classe utilizada para centralizar a inserção e recuperação de dados * salvos na memória do aplicativo. * * Obs: O SharedPreferences é perdido quando o aplicativo é reinstalado ou removido. * * Created by felipe on 9/30/15. */ public class PreferenciasUtil { public static final String VALOR_INVALIDO = "_blank"; public static final String KEY_PREFERENCIAS_DICAS_MAPA = "dicas_mapa"; public static final String KEY_PREFERENCIAS_DICAS_DETALHE = "dicas_detalhe"; public static final String KEY_PREFERENCIAS_DIA_ATUAL_VERIFICACAO = "dia_atual"; public static void salvarPreferencias(String key, String value, Context contexto) { SharedPreferences preferencias = contexto.getSharedPreferences( key, Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferencias.edit(); editor.putString(key, value.trim()); editor.commit(); } public static String getPreferencias(String key, Context contexto) { SharedPreferences sharedPreferences = contexto.getSharedPreferences( key, Context.MODE_PRIVATE); return sharedPreferences.getString(key, VALOR_INVALIDO); } }
package Day4NG; import org.testng.annotations.Test; import util.StartBrowser; import org.testng.annotations.BeforeTest; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.testng.annotations.AfterTest; public class FirstNG { WebDriver driver; @Test(priority=1) public void titleTest() { driver.get("http://google.com"); String title=driver.getTitle(); Assert.assertEquals(title,"Google"); } @Test(priority=2,description="Search Box Detail Testing") public void searchBoxTest() { WebElement E=driver.findElement(By.name("q")); Assert.assertEquals(E.isDisplayed(),true); Assert.assertEquals(E.isEnabled(),true); Assert.assertEquals(E.getAttribute("maxlength"),"2048"); } @BeforeTest public void beforeTest() { driver=StartBrowser.startBrowser("chrome"); } @AfterTest public void afterTest() { } }
package id.web.herlangga.badulik.backend.rms; import java.util.*; import id.web.herlangga.badulik.*; import id.web.herlangga.badulik.definition.*; /** * In order to make impression that an {@link ObjectStorage} behave like * in-memory {@link ObjectStorage} thus can stores polymorphic object, we * need several {@link ObjectStorage} to support it. In such scenario, * {@link RMSStorageGroupManager} will comes in handy. </p> * * {@link RMSStorageGroupManager} will create several * {@link ObjectStorage}s with name prefixed to achieve uniquely named * {@link ObjectStorage}. Thus, it have two drop methods, a drop method to * drop specific {@link ObjectStorage}, and a dropAll method to drop all * {@link ObjectStorage}s created by this Object. </p> * * @author angga * */ public class RMSStorageGroupManager implements ObjectStorageManager { private final String prefix; private final RMSStorageManager repositoryManager; private final Vector openedRepositoriesLog = new Vector(); public RMSStorageGroupManager(String prefix, RMSStorageManager repositoryManager) { this.prefix = prefix; this.repositoryManager = repositoryManager; } public ObjectStorage get(String name, Schema objectSchema) { String repositoryName = prefix + name; ObjectStorage repository = repositoryManager.get(repositoryName, objectSchema); appendToLog(repositoryName); return repository; } public void drop(String name) { String completeRepositoryName = prefix + name; repositoryManager.drop(completeRepositoryName); openedRepositoriesLog.removeElement(completeRepositoryName); } /** * Drop all {@link ObjectStorage}s created by this Object. */ public void dropAll() { dropRepositoryGroupBasedOnLog(); resetLog(); } private void appendToLog(String repositoryName) { if (!openedRepositoriesLog.contains(repositoryName)) { openedRepositoriesLog.addElement(repositoryName); } } private void dropRepositoryGroupBasedOnLog() { Enumeration repositoryNamesEnumeration = openedRepositoriesLog .elements(); while (repositoryNamesEnumeration.hasMoreElements()) { String repositoryName = (String) repositoryNamesEnumeration .nextElement(); repositoryManager.drop(repositoryName); } } private void resetLog() { openedRepositoriesLog.removeAllElements(); } }
package com.ecjtu.hotel.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ecjtu.hotel.dao.IncomeMapper; import com.ecjtu.hotel.pojo.Income; import com.ecjtu.hotel.service.IIncomeService; @Service public class IncomeService implements IIncomeService { @Autowired IncomeMapper incomeMapper; @Override public int addIncome(Income income) { // TODO Auto-generated method stub return incomeMapper.addIncome(income); } @Override public int deleteIncomeById(Integer id) { // TODO Auto-generated method stub return incomeMapper.deleteIncomeById(id); } @Override public int updateIncomeById(Income income) { // TODO Auto-generated method stub return incomeMapper.updateIncomeById(income); } @Override public List<Income> getAllIncomes() { // TODO Auto-generated method stub return incomeMapper.getAllIncomes(); } @Override public Income getIncomeById(Integer id) { // TODO Auto-generated method stub return incomeMapper.getIncomeById(id); } }
package com.nextLevel.hero.main.model.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Mapper; import com.nextLevel.hero.common.SelectCriteria; import com.nextLevel.hero.workattitude.model.dto.WorkAttitudeDTO; import com.nextLevel.hero.workattitude.model.dto.WorkCommuteDTO; @Mapper public interface MainMapper { int selectMemberCount(Map searchMap, int companyNo, int idNo); List<WorkAttitudeDTO> selectMemberList(Map searchMap, int companyNo, int idNo, SelectCriteria selectCriteria); List<WorkCommuteDTO> selectWorkAttitudeList(WorkAttitudeDTO memberInfo, String formatedNow, int idNo); }
package acueducto.data; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ArrayList; import acueducto.util.MedidorDTO; import acueducto.domain.MedidorRepository; import acueducto.util.MedidorAssembler; import acueducto.domain.Medidor; /** * * @author Karla Salas M. | Leonardo Sanchez J. */ public class MedidorRepositoryDAOImpl implements MedidorRepository { private MedidorDAO medDAO; MedidorRepositoryDAOImpl(MedidorDAO medDAO) { this.medDAO = medDAO; } /** * Ejecuta la accion para la insercion de un objeto Medidor. * @param med * @return true o false. */ public boolean insertMedidor(Medidor med) { MedidorDTO medDTO = MedidorAssembler.CreateDTO(med); return (medDAO.insert(medDTO)); } /** * Ejecuta la accion para la eliminacion de un objeto Medidor. * @param med * @return true o false. */ public boolean deleteMedidor(Medidor med) { MedidorDTO medDTO = MedidorAssembler.CreateDTO(med); return (medDAO.delete(medDTO)); } /** * Ejecuta la accion para la buscar un objeto Medidor. * @param id * @return Ojjeto tipo Medidor. */ public Medidor findMedidor(int id) { MedidorDTO medDTO = medDAO.findById(id); if (medDTO != null) { Medidor med = new Medidor(); MedidorAssembler.Update(med, medDTO); return med; } return null; } /** * Ejecuta la accion para la actualizacion de un objeto Medidor. * @param med * @return true o false. */ public boolean updateMedidor(Medidor med) { MedidorDTO medDTO = MedidorAssembler.CreateDTO(med); return (medDAO.update(medDTO)); } /** * Ejecuta la accion para la listar todos los objetos Medidor. * @return coleccion de Medidors. */ public Collection findAllMedidor() { Collection medsDTO = medDAO.findAll(); List medList = new ArrayList(); Iterator itr = medsDTO.iterator(); while (itr.hasNext()) { Medidor med = new Medidor(); MedidorDTO medDTO = (MedidorDTO) itr.next(); MedidorAssembler.Update(med, medDTO); medList.add(med); } return medList; } }
package behavioral.chain_of_responsibility; public class Test { public static void main(String[] args){ AHandler handlerA = new HandlerA(); AHandler handlerB = new HandlerB(); handlerA.setSuccessor(handlerB); int[] reqs = {1,3,6,9,12,17,44,5478}; for (int i = 0; i < reqs.length; i++) { handlerA.handle(reqs[i]); } } }
package isaacais; import org.joml.Matrix4f; import org.joml.Vector4f; import java.util.ArrayList; public class Console { public ArrayList<String> lines; public StringBuffer typing; private Font font; private BoxRenderer boxRender; public int displayLines = 7; public float x = 0, y = 40; public float jump = 40; public float width = 500; public boolean visible = false; public boolean focus = false; public static final float FOCUS_TIME = 5; public static final int CAPACITY = 40; public float focusTimer = 0; public float lineTimer = 0; public ArrayList<String> commands = new ArrayList<>(); public Console(Font f, BoxRenderer b) { lines = new ArrayList<>(); typing = new StringBuffer(); font = f; boxRender = b; } public void update(double delta) { if(visible) { if(!focus) { focusTimer -= delta; if(focusTimer < 0) { visible = false; } } else { focusTimer = FOCUS_TIME; lineTimer += delta; } } } public void draw(Matrix4f ortho) { if(visible) { boxRender.draw(new Matrix4f(ortho).translate(x + width / 2, y + displayLines * jump / 2, 0) .scale(width, displayLines * jump, 0), new Vector4f(0, 0, 0, 0.3f * focusTimer / FOCUS_TIME)); float pos = y; for (int i = 0; i < displayLines - 1; ++i) { int next = lines.size() - (displayLines - 1) + i; if (next >= 0 && next < lines.size()) { font.draw(lines.get(lines.size() - (displayLines - 1) + i), x, pos, ortho, new Vector4f(1, 1, 1, focusTimer / FOCUS_TIME)); } pos += jump; } if((int) (lineTimer * 4) % 2 == 0) { font.draw(typing.toString(), x, pos, ortho, new Vector4f(1, 1, 1, focusTimer / FOCUS_TIME)); } else { font.draw(typing.toString() + "|", x, pos, ortho, new Vector4f(1, 1, 1, focusTimer / FOCUS_TIME)); } } } public void add(String s) { if(lines.size() + 1 > CAPACITY) { lines.remove(0); } lines.add(s); } public void println(String s) { focusTimer = FOCUS_TIME; int index = 0, start = 0; while(index < s.length()) { float width = 0; while (width < this.width && index < s.length()) { ++index; width = font.textWidth(s.substring(start, index)); } add(s.substring(start, index)); start = index; } } public void enable() { visible = true; focus = true; focusTimer = FOCUS_TIME; lineTimer = 0; } public void disable() { focus = false; visible = true; focusTimer = FOCUS_TIME; lineTimer = 0; } public boolean send() { if(typing.length() == 0) return false; commands.add(typing.toString()); typing.delete(0, typing.length()); return true; } }
public class AB { private boolean[][][] dp; private int K; private int N; public String createString(int N, int K) { this.N = N; this.K = K; dp = new boolean[K + 1][N + 1][N + 1]; return createString(0, 0, 0); } private String createString(int score, int As, int Bs) { if(K < score) { return "#"; } if(dp[score][As][Bs]) { return "#"; } dp[score][As][Bs] = true; if(As + Bs == N) { if(score == K) { return ""; } } else { String result = 'A' + createString(score, As + 1, Bs); if(result.charAt(result.length() - 1) != '#') { return result; } result = 'B' + createString(score + As, As, Bs + 1); if(result.charAt(result.length() - 1) != '#') { return result; } } if(As + Bs == 0) { return ""; } return "#"; } }
package com.project.weapons; import java.awt.Graphics; import java.util.ArrayList; import java.util.List; import java.util.Random; import com.project.Actionable; import com.project.Animation; import com.project.Crew; import com.project.CrewAction; import com.project.CrewActionID; import com.project.ImageHandler; import com.project.ProjectileAnimation; import com.project.Slottable; import com.project.battle.BattleScreen; import com.project.button.Button; import com.project.button.ButtonID; import com.project.ship.Ship; import com.project.ship.Slot; public class Weapon implements Slottable, Actionable{ // Holds the shared functionality between all weapons protected int cooldownDuration; // weapons will have a cooldown period? protected int cooldownTurnsLeft; protected String name; protected int projectileGap; // this is in pixels for ProjAnim but for Ship-Weapon It will be used as if it were a Distance // as ProjAnim will be removed protected Target target; protected List<WeaponEffect> effects; protected Animation outboundAnimation; protected Animation inboundAnimation; protected Animation weaponBody; protected Slot slot; protected ImageHandler backgroundImg; protected ImageHandler weaponImg; protected boolean isPhysical; protected int radiusOfHit; protected int roundsTilHit; protected List<CrewAction> actions = new ArrayList<CrewAction>(); protected ProjectileAnimation projAnim = null; protected float accuracy; protected int rateOfFire; protected int projSpeed; public Animation getSlotItemBody() { return weaponBody; } public Weapon(List<WeaponEffect> effects, int rateOfFire,float accuracy, String name,Animation outboundAnimation,Animation inboundAnimation,int projectileGap,Animation weaponBody,List<CrewAction>actions, ImageHandler backgroundImg, ImageHandler weaponImg, Target target, int projSpeed){ this.roundsTilHit = 0; this.backgroundImg = backgroundImg; this.weaponImg = weaponImg; this.outboundAnimation = outboundAnimation; this.inboundAnimation = inboundAnimation; this.actions = actions; this.name = name; this.target = target; this.projectileGap = projectileGap; this.weaponBody = weaponBody.copy(); this.weaponBody.setMonitored(true); this.accuracy = accuracy; this.rateOfFire = rateOfFire; this.effects = effects; this.projSpeed = projSpeed; } public Animation getWeaponBody() { return weaponBody; } public void setWeaponBody(Animation weaponBody) { this.weaponBody = weaponBody; } public void setEffects(List<WeaponEffect> effects) { this.effects = effects; } public Animation getInboundAnimation() { return inboundAnimation.copy(); } public Animation getOutboundAnimation() { return outboundAnimation.copy(); } public boolean isPhysical() { return isPhysical; } public void setPhysical(boolean isPhysical) { this.isPhysical = isPhysical; } public boolean isTargetSelf() { return Target.Self == target; } public void setTargetSelf(Target target) { this.target = target; } protected int getCooldownDuration() { return cooldownDuration; } public Buffer getBuff(){ return null; } public String getName() { return name; } public String getSprite() { return "res/missileSpritesheet.png"; } public int getProjectileGap() { return projectileGap; } public List<CrewAction> getActions() { return actions; } public Slot getSlot() { return slot; } public void setSlot(Slot slot) { this.slot = slot; } public List<WeaponEffect> getEffects(){ return effects; } private void resetCooldown(){ // made a function for it in case it got more complicated with buffs/debuffs this.cooldownTurnsLeft = getCooldownDuration(); } public double getAccuracy() { return accuracy; } public void render(Graphics g, Slot slot) { if(!weaponBody.isRunning() && projAnim!=null) { projAnim.start(); projAnim =null; } weaponBody.setxCoordinate(slot.getX()); weaponBody.setyCoordinate(slot.getY()+slot.getHeight()/2-weaponBody.getTileHeight()); if(!slot.isFront()) { weaponBody.setxCoordinate((float) (slot.getX()+slot.getWidth())); weaponBody.setxFlip(-1); } weaponBody.render(g); } public Weapon copy() { // ToDo //WHEN NEW TYPES OF WEAPON BESIDES FIREABLE NEED TO ADD CHECK List<CrewAction> newActions = new ArrayList<CrewAction>(); for(int i = 0 ; i < actions.size();i++) { newActions.add(actions.get(i).copy()); } Weapon w = new Weapon(effects, rateOfFire, accuracy, name, inboundAnimation,outboundAnimation, projectileGap, weaponBody, newActions, backgroundImg, weaponImg, target,projSpeed); w.setSlot(slot); return w; } @Override public void doAction(Crew crew, CrewAction action, Ship ship, BattleScreen bs) { if(action.getActionType() == CrewActionID.Fire && action.isOffCooldown()) { if(ship == bs.getPlayerShip()) { bs.addPlayerChoice(this); } ship.incEnergy(-75); } action.updateCooldown(); } public String getFlavorText() { return null; } public ImageHandler getCardBackground() { return backgroundImg.copy(); } public ImageHandler getCardImage() { // TODO Auto-generated method stub return weaponImg.copy(); } public void setProjAnim(ProjectileAnimation pro) { projAnim = pro; } @Override public void tick() { // TODO Auto-generated method stub } public Target getTarget() { return target; } public int getRadiusOfHit() { return radiusOfHit; } public int getSpeed(){ return projSpeed; } public int getRateOfFire() { return rateOfFire; } }
package com.example.lap60020_local.rxjavademo; import android.Manifest; import android.content.pm.PackageManager; import android.os.Build; import android.os.Environment; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.ListView; import android.widget.TextView; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.concurrent.TimeUnit; import io.reactivex.BackpressureStrategy; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.Single; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.functions.BiFunction; import io.reactivex.internal.subscriptions.ArrayCompositeSubscription; import io.reactivex.schedulers.Schedulers; public class MainActivity extends AppCompatActivity { private MyAdapter myAdapter; ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},100); } listView = findViewById(R.id.listView); myAdapter = new MyAdapter(this); listView.setAdapter(myAdapter); } public void onDownloads(View view) { ArrayList<String> arrayList = new ArrayList<>(); arrayList.add("https://www.w3schools.com/w3css/img_fjords.jpg"); arrayList.add("https://imagejournal.org/wp-content/uploads/bb-plugin/cache/23466317216_b99485ba14_o-panorama.jpg"); arrayList.add("http://www.math.hcmus.edu.vn/~ptbao/TRR/TRR_KHTN_ch1.pdf"); myAdapter.load(arrayList); } @Override protected void onDestroy() { super.onDestroy(); myAdapter.disconnect(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if(grantResults.length < 1 || grantResults[0] != PackageManager.PERMISSION_GRANTED) { finish(); } } }
package dao.user; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Vector; import javax.servlet.http.Part; import dao.DatabaseGateway; import dto.user.UserConfigDTO; import dto.user.UserDTO; import dto.user.UserSimpleDTO; import dto.user.menu.MenuDTO; import dto.user.menu.submenu.SubMenuDTO; import herramientas.herrramientasrs.HerramientasResultSet; public class UserDAO { private DatabaseGateway database = null; private HerramientasResultSet herramientasResultSet; public UserDAO(){ if(this.getDatabase() == null){ this.setDatabase(new DatabaseGateway()); } if(this.herramientasResultSet == null){ this.herramientasResultSet = new HerramientasResultSet(); } InitializeComponents(); } public void InitializeComponents(){ } public UserSimpleDTO insertUserSimpleDTO(UserSimpleDTO userSimpleDTO){ if(userSimpleDTO != null){ int res = -1; if(getDatabase().openDatabase()){ System.out.println("conexion abierta en " + this.getClass().getSimpleName()); String query = "INSERT INTO sec_users" + " (" + "login" + ", fk_id_user_config" + ", name" + ", email" + ", session_timeout" + ", active" + ", fk_id_empleado" + ")" + " VALUES (" + "'" + userSimpleDTO.getLogin() + "'" + ", " + userSimpleDTO.getFkIdUserConfig() + ", '" + userSimpleDTO.getName() + "'" + ", '" + userSimpleDTO.getEmail() + "'" + ", " + userSimpleDTO.getSessionTimeOut() + ", '" + userSimpleDTO.getActive() + "'" + ", " + userSimpleDTO.getFkIdEmpleado() + ");"; System.out.println("query de alta de usario: " + query); try { res = getDatabase().executeNonQuery(query); } catch (SQLException e) { e.printStackTrace(); } if(res > 0){ query = "SELECT LAST_INSERT_ID() AS max_user_id"; ResultSet rs; try { rs = getDatabase().executeQuery(query); while(rs.next()){ res = rs.getInt("max_user_id"); } userSimpleDTO.setIdUser(res); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(userSimpleDTO.getIdUser() > 0){ query = "INSERT INTO sec_users_groups" + " (" + "login" + ", group_id" + ")" + " VALUES (" + "'" + userSimpleDTO.getLogin() + "'" + ", " + userSimpleDTO.getUserProfile().getIdPerfil() + ");"; // System.out.println("query de perfil de usario: " + query); try { res = getDatabase().executeNonQuery(query); } catch (SQLException e) { e.printStackTrace(); } } if(getDatabase().closeDatabase()){ System.out.println("conexion cerrada en " + this.getClass().getSimpleName()); }else{ System.out.println("conexion no cerrada en " + this.getClass().getSimpleName()); } }else{ System.out.println("conexion no abierta en " + this.getClass().getSimpleName()); } }else{ System.out.println("sin usuario lipio en " + this.getClass().getSimpleName()); } return userSimpleDTO; } public UserSimpleDTO actualizaUserSimpleDTO(UserSimpleDTO userSimpleDTO){ if(userSimpleDTO != null){ if(userSimpleDTO.getIdUser() > 0){ int res = -1; if(getDatabase().openDatabase()){ System.out.println("conexion abierta en " + this.getClass().getSimpleName()); String query = "UPDATE sec_users" + " SET" + " login = " + "'" + userSimpleDTO.getLogin() + "'" + ", fk_id_user_config = " + userSimpleDTO.getFkIdUserConfig() + ", name = "+ "'" + userSimpleDTO.getName() + "'" + ", email = " + "'" + userSimpleDTO.getEmail() + "'" + ", session_timeout = "+ userSimpleDTO.getSessionTimeOut() + ", active = " + "'" + userSimpleDTO.getActive() + "'" + ", fk_id_empleado = " + userSimpleDTO.getFkIdEmpleado() + " WHERE" + " id_user = " + userSimpleDTO.getIdUser() + ";"; System.out.println("query de update de usario: " + query); try { res = getDatabase().executeNonQuery(query); if(res > 0){ }else{ userSimpleDTO.setIdUser(0); } } catch (SQLException e) { e.printStackTrace(); } query = "UPDATE sec_users_groups" + " SET" + " group_id = " + userSimpleDTO.getUserProfile().getIdPerfil() + " WHERE" + " login = " + "'" + userSimpleDTO.getLogin() + "'" + ";"; // System.out.println("query de perfil de usario: " + query); try { res = getDatabase().executeNonQuery(query); if(res > 0){ }else{ userSimpleDTO.setIdUser(0); } } catch (SQLException e) { e.printStackTrace(); } if(getDatabase().closeDatabase()){ System.out.println("conexion cerrada en " + this.getClass().getSimpleName()); }else{ System.out.println("conexion no cerrada en " + this.getClass().getSimpleName()); } }else{ System.out.println("conexion no abierta en " + this.getClass().getSimpleName()); } }else{ System.out.println("sin id de usaurio simple en " + this.getClass().getSimpleName()); } }else{ System.out.println("sin usuario simple en " + this.getClass().getSimpleName()); } return userSimpleDTO; } /** * Selecciona todos los usaurios en la tabla * @return Vector<UserDTO> */ public Vector<UserDTO> selectUsers(){ Vector<UserDTO> usuarios = null; if(getDatabase().openDatabase()){ System.out.println("conexion abierta en " + this.getClass().getSimpleName()); ResultSet rs = null; String query = "SELECT * FROM sec_users \r\n" + " LEFT JOIN sec_users_config ON sec_users.fk_id_user_config = sec_users_config.id_user_config\r\n" + " LEFT JOIN sec_users_groups ON sec_users.login = sec_users_groups.login\r\n" + " LEFT JOIN sec_groups ON sec_users_groups.group_id = sec_groups.group_id\r\n" + " LEFT JOIN tb_empleados ON sec_users.fk_id_empleado = tb_empleados.id_empleado\r\n" + " ;"; try { rs = getDatabase().executeQuery(query); } catch (SQLException e) { e.printStackTrace(); } try { if(rs != null){ usuarios = new Vector<UserDTO>(); while(rs.next()){ UserDTO usuario = herramientasResultSet.inicializaUserDTConEmpleadoSimpleConPerfilDTO(rs); if(usuario != null){ usuarios.add(usuario); } } try{ rs.close(); }catch (Exception e) { e.printStackTrace(); } }else{ System.out.println("rs == nullo en selectUserPorUsernameAndPassword"); } } catch (SQLException e) { e.printStackTrace(); } if(getDatabase().closeDatabase()){ System.out.println("conexion cerrada en " + this.getClass().getSimpleName()); }else{ System.out.println("conexion no cerrada en " + this.getClass().getSimpleName()); } }else{ System.out.println("conexion no abierta en " + this.getClass().getSimpleName()); } return usuarios; } /** * * @param username * @param password * @return */ public UserDTO selectUserPorUsernameAndPassword(String username, String password){ UserDTO user = null; if(username != null && !username.equals("") && username.length() > 0){ if(getDatabase().openDatabase()){ System.out.println("conexion abierta en " + this.getClass().getSimpleName()); ResultSet rs = null; String query = "SELECT * FROM sec_users " + "LEFT JOIN tb_empleados ON sec_users.fk_id_empleado = tb_empleados.id_empleado " + "LEFT JOIN sec_users_config ON sec_users.fk_id_user_config = sec_users_config.id_user_config " + "WHERE sec_users.login = '" + username + "' AND sec_users.pswd_txt = '"+ password +"' AND sec_users.active = 'Y';"; try { rs = getDatabase().executeQuery(query); } catch (SQLException e) { e.printStackTrace(); } try { if(rs != null){ while(rs.next()){ user = herramientasResultSet.inicializaUserDTO(rs); UserConfigDTO userConfig = herramientasResultSet.inicializaUserConfigDTO(rs); user.setUserConfigDTO(userConfig); } try{ rs.close(); }catch (Exception e) { e.printStackTrace(); } }else{ System.out.println("rs == nullo en selectUserPorUsernameAndPassword"); } } catch (SQLException e) { e.printStackTrace(); } if(getDatabase().closeDatabase()){ System.out.println("conexion cerrada en " + this.getClass().getSimpleName()); }else{ System.out.println("conexion no cerrada en " + this.getClass().getSimpleName()); } }else{ System.out.println("conexion no abierta en " + this.getClass().getSimpleName()); } }else{ System.out.println("parametro de usuario nulo"); } return user; } public UserDTO selectUserPorUsername(String username){ UserDTO user = null; if(username != null && !username.equals("") && username.length() > 0){ if(getDatabase().openDatabase()){ System.out.println("conexion abierta en " + this.getClass().getSimpleName()); ResultSet rs = null; String query = "SELECT * FROM sec_users " + "LEFT JOIN tb_empleados ON sec_users.fk_id_empleado = tb_empleados.id_empleado " + "LEFT JOIN sec_users_config ON sec_users.fk_id_user_config = sec_users_config.id_user_config " + "WHERE sec_users.login = '" + username + "' AND sec_users.active = 'Y';"; try { rs = getDatabase().executeQuery(query); } catch (SQLException e) { e.printStackTrace(); } try { if(rs != null){ while(rs.next()){ user = herramientasResultSet.inicializaUserDTO(rs); UserConfigDTO userConfig = herramientasResultSet.inicializaUserConfigDTO(rs); user.setUserConfigDTO(userConfig); } try{ rs.close(); }catch (Exception e) { e.printStackTrace(); } }else{ System.out.println("rs == nullo en selectUserPorUsername"); } } catch (SQLException e) { e.printStackTrace(); } if(getDatabase().closeDatabase()){ System.out.println("conexion cerrada en " + this.getClass().getSimpleName()); }else{ System.out.println("conexion no cerrada en " + this.getClass().getSimpleName()); } }else{ System.out.println("conexion no abierta en " + this.getClass().getSimpleName()); } }else{ System.out.println("parametro de usuario nulo"); } return user; } public UserDTO selectUserPorUserId(int userId){ UserDTO user = null; if(userId > 0){ if(getDatabase().openDatabase()){ System.out.println("conexion abierta en " + this.getClass().getSimpleName()); ResultSet rs = null; String query = "SELECT * FROM sec_users " + "LEFT JOIN tb_empleados ON sec_users.fk_id_empleado = tb_empleados.id_empleado " + "LEFT JOIN sec_users_config ON sec_users.fk_id_user_config = sec_users_config.id_user_config " + "WHERE sec_users.id_user = " + userId + " AND sec_users.active = 'Y';"; try { System.out.println(query); rs = getDatabase().executeQuery(query); } catch (SQLException e) { e.printStackTrace(); } try { if(rs != null){ while(rs.next()){ user = herramientasResultSet.inicializaUserDTO(rs); UserConfigDTO userConfig = herramientasResultSet.inicializaUserConfigDTO(rs); user.setUserConfigDTO(userConfig); System.out.println(userConfig.getUserInitService()); } try{ rs.close(); }catch (Exception e) { e.printStackTrace(); } }else{ System.out.println("rs == nullo en selectUserPorUserId"); } } catch (SQLException e) { e.printStackTrace(); } if(getDatabase().closeDatabase()){ System.out.println("conexion cerrada en " + this.getClass().getSimpleName()); }else{ System.out.println("conexion no cerrada en " + this.getClass().getSimpleName()); } }else{ System.out.println("conexion no abierta en " + this.getClass().getSimpleName()); } }else{ System.out.println("parametro de usuario nulo"); } return user; } /** * SELECCIONA LAS CONFIGURACIONES DE UISER INIT SERVICE POR STATUS * -VERDADERO: SOLO LOS ACTIVOS * -FALSO: TODOS * @param activos * @return Vector<UserConfigDTO> */ public Vector<UserConfigDTO> selectUserConfigDTO(boolean activos){ Vector<UserConfigDTO> userConfigs = new Vector<>(); if(getDatabase().openDatabase()){ System.out.println("conexion abierta en " + this.getClass().getSimpleName()); ResultSet rs = null; String query = "SELECT * FROM sec_users_config"; if(activos) query += " WHERE sec_users_config.status = 1 ORDER BY sec_users_config.nombre ASC"; query += ";"; try { // System.out.println(query); rs = getDatabase().executeQuery(query); } catch (SQLException e) { e.printStackTrace(); } try { if(rs != null){ while(rs.next()){ UserConfigDTO userConfig = herramientasResultSet.inicializaUserConfigDTO(rs); if(userConfig != null){ userConfigs.add(userConfig); } } try{ rs.close(); }catch (Exception e) { e.printStackTrace(); } }else{ System.out.println("rs == nullo en selectUserConfigDTO"); } } catch (SQLException e) { e.printStackTrace(); } if(getDatabase().closeDatabase()){ System.out.println("conexion cerrada en " + this.getClass().getSimpleName()); }else{ System.out.println("conexion no cerrada en " + this.getClass().getSimpleName()); } }else{ System.out.println("conexion no abierta en " + this.getClass().getSimpleName()); } return userConfigs; } public Vector<MenuDTO> selectUserMenu(UserDTO user){ Vector<MenuDTO> menus = null; if(user != null ){ if(getDatabase().openDatabase()){ System.out.println("conexion abierta en " + this.getClass().getSimpleName()); menus = new Vector<MenuDTO>(); ResultSet rs = null; String query = "SELECT * FROM sec_groups_apps_actions" + " LEFT JOIN sec_groups ON sec_groups_apps_actions.fk_group = sec_groups.group_id" + " LEFT JOIN sec_users_groups ON sec_groups.group_id = sec_users_groups.group_id" + " LEFT JOIN sec_users ON sec_users_groups.login = sec_users.login" + " LEFT JOIN sec_apps_actions ON sec_groups_apps_actions.fk_app_action = sec_apps_actions.id_action" + " LEFT JOIN sec_apps ON sec_apps_actions.fk_app = sec_apps.id_app" + " WHERE sec_users.id_user = "+user.getUserId()+" AND sec_groups.`status` = 1 AND sec_apps_actions.status_action = 1" + " ORDER BY sec_apps.index_app, sec_apps_actions.fk_app, sec_groups_apps_actions.`index` ASC;"; try { rs = getDatabase().executeQuery(query); } catch (SQLException e) { e.printStackTrace(); } if(rs != null){ try { int idApp = 0; int i = -1; MenuDTO menu = null; Vector<SubMenuDTO> subMenus = null; while(rs.next()){ if(idApp == 0){ idApp = rs.getInt("sec_apps.id_app"); user.getPerfil().setDescription(rs.getString("sec_groups.description")); menu = herramientasResultSet.inicializaUserMenuDTO(rs); if(menu != null){ subMenus = new Vector<SubMenuDTO>(); SubMenuDTO subMenu = new SubMenuDTO(); subMenu = herramientasResultSet.inicializaUserSubMenuDTO(rs); if(subMenu != null){ subMenus.add(subMenu); menu.setSubMenu(subMenus); }else{ System.out.println("un item del subMenu es nullo"); } menus.add(menu); i++; }else{ System.out.println("un item del menu es nullo"); } }else{ if(idApp != rs.getInt("sec_apps.id_app")){ idApp = rs.getInt("sec_apps.id_app"); menu = herramientasResultSet.inicializaUserMenuDTO(rs); if(menu != null){ subMenus = new Vector<SubMenuDTO>(); SubMenuDTO subMenu = new SubMenuDTO(); subMenu = herramientasResultSet.inicializaUserSubMenuDTO(rs); if(subMenu != null){ subMenus.add(subMenu); menu.setSubMenu(subMenus); }else{ System.out.println("un item del subMenu es nullo"); } menus.add(menu); i++; }else{ System.out.println("un item del menu es nullo"); } }else{ SubMenuDTO subMenu = new SubMenuDTO(); subMenu = herramientasResultSet.inicializaUserSubMenuDTO(rs); if(subMenu != null){ subMenus.add(subMenu); menu.setSubMenu(subMenus); }else{ System.out.println("un item del subMenu es nullo"); } menus.set(i, menu); } } } user.setMenu(menus); } catch (SQLException e) { e.printStackTrace(); } try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } }else{ System.out.println("rs == null en selectUserMenu:" + this.getClass().getSimpleName()); } if(getDatabase().closeDatabase()){ System.out.println("conexion cerrada en " + this.getClass().getSimpleName()); }else{ System.out.println("conexion no cerrada en " + this.getClass().getSimpleName()); } }else{ System.out.println("conexion no abierta en " + this.getClass().getSimpleName()); } }else{ System.out.println("parametro de usuario nulo"); } return menus; } public int actualizarPswdUsuario(UserDTO user){ int res = -1; if(user != null && user.getIdEmpleado() > 0){ if(getDatabase().openDatabase()){ System.out.println("conexion abierta en " + this.getClass().getSimpleName() + " metodo actualizarDatosUsuario"); String query = "UPDATE sec_users SET sec_users.pswd_txt ='" + user.getPassword() + "' WHERE sec_users.id_user = " + user.getUserId(); try { res = getDatabase().executeNonQuery(query); } catch (SQLException e) { e.printStackTrace(); } if(getDatabase().closeDatabase()){ System.out.println("conexion cerrada en " + this.getClass().getSimpleName() + " metodo actualizarDatosUsuario"); }else{ System.out.println("conexion no cerrada en " + this.getClass().getSimpleName() + " metodo actualizarDatosUsuario"); } }else{ System.out.println("conexion no abierta en " + this.getClass().getSimpleName() + " metodo actualizarDatosUsuario"); } }else{ System.out.println("parametro de usuario nulo"); } return res; } /** * ACTUALIZA UNA IMAGEN PARA EL USUARIO * @param user * @param filePart * @return */ public int actualizarAvatarUsuario(UserDTO user, Part filePart){ int res = -1; if(user != null && user.getUserId() > 0){ if(getDatabase().openDatabase()){ System.out.println("conexion abierta en " + this.getClass().getSimpleName() + " metodo actualizarAvatarUsuario"); String sql = "UPDATE sec_users SET sec_users.user_avatar = ? WHERE sec_users.id_user = ?"; java.sql.PreparedStatement statement = null; try { statement = getDatabase().getCon().prepareStatement(sql); statement.setInt(2,user.getUserId()); } catch (SQLException e2) { e2.printStackTrace(); } try { if (filePart.getInputStream() != null) { // fetches input stream of the upload file for the blob column statement.setBlob(1, filePart.getInputStream()); } } catch (IOException e1) { e1.printStackTrace(); } catch (SQLException e1) { e1.printStackTrace(); } try { res = statement.executeUpdate(); } catch (SQLException e1) { e1.printStackTrace(); } if(getDatabase().closeDatabase()){ System.out.println("conexion cerrada en " + this.getClass().getSimpleName() + " metodo actualizarDatosUsuario"); }else{ System.out.println("conexion no cerrada en " + this.getClass().getSimpleName() + " metodo actualizarDatosUsuario"); } }else{ System.out.println("conexion no abierta en " + this.getClass().getSimpleName() + " metodo actualizarDatosUsuario"); } }else{ System.out.println("parametro de usuario nulo"); } return res; } /** * @return the database */ private DatabaseGateway getDatabase() { return database; } /** * @param database the database to set */ private void setDatabase(DatabaseGateway database) { this.database = database; } }//Termina clase
package com.dinh.customdate.adapter; public class ProductDemoTestAdapter { }
package JavaExe; import java.util.Scanner; public class Recur5 { public static void main(String[] args) { System.out.println("累乗する数値を入力してください。"); Scanner stdInt = new Scanner(System.in); double x = stdInt.nextDouble(); System.out.println("何乗しますか?"); double n = stdInt.nextDouble(); if (x < 0) { System.out.println("正の数値を入力してください"); x = stdInt.nextInt(); } System.out.println("xの" + n + "乗は" + power(x, n)); } static double power(double x, double n) { double result = 1.0; if (n == 0) { return result; } else if (n < 0) { for (int i = 0; i < (-n); i++) { result = 1 / (result * x); } } else if (n > 0) { for (int i = 0; i < n; i++) { result = result * x; } } return result; } }
package com.zoe.springboot.web; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class MemberController { @Autowired com.zoe.springboot.mapper.MemberMapper memberMapper; @RequestMapping("/listMember") public String listMember(Model m) throws Exception { List<com.zoe.springboot.pojo.Member> cs=memberMapper.findAll(); m.addAttribute("cs", cs); return "listMember"; } }
package com.esum.appframework.service.impl; import com.esum.appcommon.constant.ConstantList; import com.esum.appframework.dao.IBaseDAO; import com.esum.appframework.exception.ApplicationException; import com.esum.appframework.service.IBaseService; public class BaseService implements IBaseService { protected IBaseDAO iBaseDAO = null; protected String moduleName = ConstantList.acube; public void setDAO(IBaseDAO iBaseDAO) { this.iBaseDAO = iBaseDAO; } public Object insert(Object object) { try { iBaseDAO.insert(object); return object; } catch (ApplicationException e) { e.printStackTrace(); e.setMouduleName(moduleName); e.printException(""); return e; } catch (Exception e) { e.printStackTrace(); ApplicationException ae = new ApplicationException(e); ae.setMouduleName(moduleName); return ae; } } public Object update(Object object) { try { return new Integer(iBaseDAO.update(object)); } catch (ApplicationException e) { e.setMouduleName(moduleName); e.printException(""); return e; } catch (Exception e) { ApplicationException ae = new ApplicationException(e); ae.setMouduleName(moduleName); return ae; } } public Object delete(Object object) { try { return new Integer(iBaseDAO.delete(object)); } catch (ApplicationException e) { e.setMouduleName(moduleName); e.printException(""); return e; } catch (Exception e) { ApplicationException ae = new ApplicationException(e); ae.setMouduleName(moduleName); return ae; } } public Object deleteList(Object object) { try { return new Integer(iBaseDAO.deleteList(object)); } catch (ApplicationException e) { e.setMouduleName(moduleName); e.printException(""); return e; } catch (Exception e) { ApplicationException ae = new ApplicationException(e); ae.setMouduleName(moduleName); return ae; } } public Object select(Object object) { try { return iBaseDAO.select(object); } catch (ApplicationException e) { e.setMouduleName(moduleName); e.printException(""); return e; } catch (Exception e) { ApplicationException ae = new ApplicationException(e); ae.setMouduleName(moduleName); return ae; } } public Object selectList(Object object){ try { return iBaseDAO.selectList(object); } catch (ApplicationException e) { e.setMouduleName(moduleName); e.printException(""); return e; } catch (Exception e) { ApplicationException ae = new ApplicationException(e); ae.setMouduleName(moduleName); return ae; } } }
package com.jgw.supercodeplatform.trace.interceptor; import com.jgw.supercodeplatform.web.WebMvcCustomizeFunUrlInterceptorPathConfigurer; import org.springframework.stereotype.Component; import java.util.Arrays; import java.util.List; /** * 描述: * <p> * Created by corbett on 2018/12/27. */ @Component public class MyCustomizeFunUrlInterceptor implements WebMvcCustomizeFunUrlInterceptorPathConfigurer { @Override public List<String> addPathPatterns() { String[] add = new String[]{ "/trace/dynamic/fun/addFunData", "/trace/dynamic/fun/list", "/trace/dynamic/fun/update", "/trace/dynamic/fun/delete" }; return Arrays.asList(add); } }
package uk.co.travelai_public.model.travel; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import uk.co.travelai_public.model.Location; import uk.co.travelai_public.model.place.Dwell; import uk.co.travelai_public.model.place.Place; import uk.co.travelai_public.obfuscation.PrivacyCategory; import java.util.ArrayList; import java.util.List; /** * Class representing a Route * <p> * Created by S.Hemminki 06.03.2018 */ @Setter @Getter @NoArgsConstructor public class Route { private static int routeIDCounter = 0; private int uid = ++routeIDCounter; private Dwell startDwell; private Dwell endDwell; private Place startPlace; private Place endPlace; private List<Location> routeLocs = new ArrayList<>(); private double startTime = -1; private double endTime = -1; private double duration = -1; private double distance = -1; private double gisDistance = -1; private double originTZOffset; private double destinationTZOffset; private double distFromStartDwell = -1; private double distToEndDwell = -1; private List<Leg> matchedLegs = new ArrayList<>(); private String label; private PrivacyCategory privacyCategory = PrivacyCategory.UNKNOWN; }
package swea_d5; import java.awt.Point; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class Solution_7793_오나의여신님 { static StringBuilder sb = new StringBuilder(); static int[][] dirs = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } }; static int T, R, C; static char[][] map; static Queue<Point> devil, player; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); T = Integer.parseInt(br.readLine()); for (int tc = 1; tc <= T; tc++) { sb.append("#").append(tc).append(" "); StringTokenizer tokens = new StringTokenizer(br.readLine()); R = Integer.parseInt(tokens.nextToken()); C = Integer.parseInt(tokens.nextToken()); map = new char[R][C]; devil = new LinkedList<>(); player = new LinkedList<>(); for (int r = 0; r < R; r++) { map[r] = br.readLine().toCharArray(); for (int c = 0; c < C; c++) { if (map[r][c] == '*') { devil.offer(new Point(r, c, 0)); } else if (map[r][c] == 'S') { player.offer(new Point(r, c, 0)); } } } while (true) { if (player.size() == 0) { sb.append("GAME OVER"); break; } bfsDevil(); int result = bfsPlayer(); if(result != -1) { sb.append(result); break; } } sb.append("\n"); } System.out.println(sb); } private static int bfsPlayer() { int size = player.size(); while (size-- > 0) { Point front = player.poll(); for (int d = 0; d < dirs.length; d++) { int nr = front.row + dirs[d][0]; int nc = front.col + dirs[d][1]; if (isIN(nr, nc)) { if (map[nr][nc] == 'D') { return front.depth + 1; } else if (map[nr][nc] == '.') { map[nr][nc] = 'S'; player.offer(new Point(nr, nc, front.depth + 1)); } } } } return -1; } private static void bfsDevil() { int size = devil.size(); while (size-- > 0) { Point front = devil.poll(); for (int d = 0; d < dirs.length; d++) { int nr = front.row + dirs[d][0]; int nc = front.col + dirs[d][1]; if (isIN(nr, nc)) { if (map[nr][nc] == '.' || map[nr][nc] == 'S') { map[nr][nc] = '*'; devil.offer(new Point(nr, nc, front.depth + 1)); } } } } } private static boolean isIN(int r, int c) { return 0 <= r && 0 <= c && r < R && c < C; } static class Point { int row, col, depth; public Point(int row, int col, int depth) { super(); this.row = row; this.col = col; this.depth = depth; } } }
import java.io.*; class HW01_4 { public static int readTextFile(String path,String compare) throws IOException{ BufferedReader br= new BufferedReader(new InputStreamReader( new FileInputStream(path),"UTF-8")); String line=null; int all=0; while ((line=br.readLine())!=null) { String tmp[]=line.split(" "); for (int i=0; i<tmp.length; i++) { if (tmp[i].equals(compare)) { all++; } } } br.close(); return all; } public static void main (String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String loc=br.readLine().trim(); String zbor=br.readLine().trim(); int tmp=HW01_4.readTextFile(loc,zbor); System.out.println(tmp); } }
/** * This hand consists of five cards with consecutive ranks. For the sake of simplicity, 2 and A can only form a straight with K but not with 3. The card with the highest rank in a straight is referred to as the top card of this straight. A straight having a top card with a higher rank beats a straight having a top card with a lower rank. For straights having top cards with the same rank, the one having a top card with a higher suit beats the one having a top card with a lower suit. * @author Marco Brian * */ public class Straight extends Hand{ /** * Constructs the Straight object * @param player player having this hand * @param cards cards to be made into a hand */ public Straight(CardGamePlayer player, CardList cards) { super(player,cards); } public String getType(){ return "Straight"; } /** * We check if the hand is a valid straight *To do so there are a few special cases we have to consider, the fact that * 2 and A can only form a straight with K we need to consider these cases. * (10 J Q K A) - valid * (J Q K A 2) - valid * (A 2 3 4 5) - invalid * (2 3 4 5 6) - invalid * The rest of the cards we can just check whether or not the cards are increasing * incrementally * */ public boolean isValid() { if(size()==5) { if( getCard(0).getRank() == 9 && getCard(1).getRank() == 10 && getCard(2).getRank() == 11 && getCard(3).getRank() == 12 && getCard(4).getRank() == 0) //(10 J Q K A) - valid { return true; } else if( getCard(0).getRank() == 10 && getCard(1).getRank() == 11 && getCard(2).getRank() == 12 && getCard(3).getRank() == 0 && getCard(4).getRank() == 1 ) //(J Q K A 2) - valid { return true; } else if(getCard(0).getRank() == 0 && getCard(1).getRank() == 1 && getCard(2).getRank() == 2 && getCard(3).getRank() == 3 && getCard(4).getRank() == 4) { //(A 2 3 4 5) - invalid return false; } else if (getCard(0).getRank() == 1 && getCard(1).getRank() == 2 && getCard(2).getRank() == 3 && getCard(3).getRank() == 4 && getCard(4).getRank() == 5) { //(2 3 4 5 6) - invalid return false; } else { //Check if it is a normal straight. Cards are increasing value for(int i=0;i<4;i++) { if(getCard(i).getRank()+1 != getCard(i+1).getRank()) { return false; } } return true; } } return false; } public boolean beats(Hand hand) { if(hand.size()==5) { if(hand.getType()==this.getType()) { Card hand_top_card = hand.getTopCard(); Card player_top_card = this.getTopCard(); if(player_top_card.compareTo(hand_top_card)==1) { return true; } else { return false; } } else { return false; } } else { return false; } } }
package baseline; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class Solution28Test { @Test public void test_LoopIsCorrect()throws Exception{ Solution28 sol = new Solution28(); for( int i = 0; i < 5; i++) { sol.number = 1; sol.total += sol.number; } assertEquals(5, sol.total); } }
package io.breen.socrates.test; import javax.swing.*; import javax.swing.text.BadLocationException; import javax.swing.text.Document; /** * Class representing a single test specified by the criteria. Instances of non-abstract subclasses * of this class are immutable, and are created when a Criteria object is created. * * All tests are associated with a "target" file. This target file is created after instances of its * tests are created. * * Minimally, a test must define a deduction: the points deducted from a student's score if the test * fails during grading. * * By default, tests are marked as passing or failing by a human grader. However, some tests support * automation. Those tests subclass Test but also implement the Automatable interface. * * @see io.breen.socrates.file.File * @see io.breen.socrates.criteria.Criteria * @see io.breen.socrates.test.Automatable */ public abstract class Test { public double deduction; public String description; /** * This empty constructor is used by SnakeYAML. */ public Test() {} public Test(double deduction, String description) { this.deduction = deduction; this.description = description; } /** * A utility function for appending a string to a Document object. Useful for appending strings * to the notes of a test, or the transcript document. */ public static void appendToDocument(final Document doc, final String s) { SwingUtilities.invokeLater( new Runnable() { @Override public void run() { int length = doc.getLength(); try { doc.insertString(length, s, null); } catch (BadLocationException ignored) {} } } ); } public String toString() { return "Test(deduction=" + deduction + ")"; } /** * Returns the human-readable, user-friendly string representing the type of the test. This is * used by the GUI. */ public abstract String getTestTypeName(); }
import java.util.*; public class ChristmasTree{ private String type; private String size; private ArrayList<Decoratable> branches; public ChristmasTree(String type, String size) { this.type = type; this.size = size; this.branches = new ArrayList<Decoratable>(); } public String getType() { return this.type; } public String getSize() { return this.size; } public int decorationCount(){ return branches.size(); } public void addDecoration(Decoratable decoration){ branches.add(decoration); } public Decoratable breakDecoration() { if (decorationCount() > 0) { return branches.remove(0); } return null; } public void removeAllDecorations(){ branches.clear(); } }
package com.itheima.day_01.phone; class NewPhone extends Phone{ @Override void call(String name) { System.out.println("正在发起视频通话"); super.call(name); } }
package com.fuzzy.metro.listeners; import java.awt.Color; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import javax.swing.text.JTextComponent; import com.fuzzy.metro.components.MyOptionPane; public class MyFocusListener implements FocusListener{ public String placeholder = ""; public JTextComponent contextField = null; MyOptionPane messageBox; public MyFocusListener(JTextComponent field,String placeholder){ this.contextField = field; this.placeholder = placeholder; } @Override public void focusGained(FocusEvent e) { // TODO Auto-generated method stub if(contextField.getForeground().equals(new Color(216,225,228)) && (contextField.getText().equalsIgnoreCase(placeholder))){ contextField.setForeground(Color.BLACK); contextField.setText(""); } } @Override public void focusLost(FocusEvent e) { // TODO Auto-generated method stub if(contextField.getText().equalsIgnoreCase("")){ contextField.setForeground(new Color(216,225,228)); contextField.setText(placeholder); } } }
package com.example.buildpc.ActivityListItem; import android.annotation.SuppressLint; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.ListView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import com.example.buildpc.Adapter.PC_Adapter; import com.example.buildpc.Dialog.LoadingDialog; import com.example.buildpc.Main.MainBuild; import com.example.buildpc.Model.Model_Cart; import com.example.buildpc.Model.Model_PC; import com.example.buildpc.R; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; public class RecommendPCActivity extends AppCompatActivity { private ListView listView_recommendPC; final ArrayList<Model_PC> model_buildArrayList = new ArrayList<>(); PC_Adapter build_adapter; ImageButton imagebutton_pcbacktomain; LoadingDialog loadingDialog = new LoadingDialog(this); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_buildpc); listView_recommendPC = findViewById(R.id.listView_recommendPC); imagebutton_pcbacktomain = findViewById(R.id.imagebutton_pcbacktomain); String urlPC = "http://android-api.thaolx.com/api/get/pc"; loadingDialog.startLoadingDialog(); GetDataPC(urlPC, MainBuild.cart); build_adapter = new PC_Adapter(this,R.layout.line_pc_layout, model_buildArrayList); listView_recommendPC.setAdapter(build_adapter); imagebutton_pcbacktomain.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } private void GetDataPC(String url, Model_Cart cart){ RequestQueue requestQueue = Volley.newRequestQueue(this); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { if (response.getBoolean("success")){ JSONArray jsonArray = response.getJSONArray("data"); for (int position = 0; position < jsonArray.length(); position++){ JSONObject jsonObject = jsonArray.getJSONObject(position); //name, image, type, desciption, pc_id, cpu_id, ram_id, main_id, vga_id, psu_id, hdd_id, ssd_id, case_id; String name = jsonObject.getString("name"); String image = jsonObject.getString("image"); String type = jsonObject.getString("type"); String desciption = jsonObject.getString("description"); int pc_id = jsonObject.getInt("pc_id"); int cpu_id = jsonObject.getInt("cpu_id"); int ram_id = jsonObject.getInt("ram_id"); int main_id = jsonObject.getInt("main_id"); int vga_id = jsonObject.getInt("vga_id"); int psu_id = jsonObject.getInt("psu_id"); int hdd_id = jsonObject.getInt("hdd_id"); int ssd_id = jsonObject.getInt("ssd_id"); int case_id = jsonObject.getInt("case_id"); int price = jsonObject.getInt("price"); model_buildArrayList.add(new Model_PC(image, desciption, name, type, pc_id, cpu_id, ram_id, main_id, psu_id, vga_id, hdd_id, ssd_id, case_id, price)); } build_adapter.notifyDataSetChanged(); loadingDialog.dismissDialog(); } else { loadingDialog.dismissDialog(); Toast.makeText(RecommendPCActivity.this, "Ôi không, có vẻ như đã xảy ra lỗi!", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(RecommendPCActivity.this, "Xảy ra lỗi trong quá trình kết nối máy chủ!", Toast.LENGTH_SHORT).show(); } }); requestQueue.add(jsonObjectRequest); } }
package com.example.breno.pokemobile.Service; import android.content.Context; import com.example.breno.pokemobile.db.ExpLevelDAO; import com.example.breno.pokemobile.modelo.ExpLevel; import com.example.breno.pokemobile.modelo.PokemonTreinador; /** * Created by Breno on 30/11/2016. */ public class ExpLevelService { public Integer buscarExpRequeridaLvl(PokemonTreinador pokemon, Context ctx) { ExpLevelDAO expLevelDAO = new ExpLevelDAO(ctx); ExpLevel expLevel = expLevelDAO.buscarPorLevel(pokemon.getLevel()); return expLevel.getExperiencia(); } }
package rss.printlnstuidios.com.myapplication; import android.os.Debug; import android.util.Log; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by Justin Hill on 12/25/2014. * * Stores the data for an individual post from a feed */ public class Post implements Comparable { //variables to store the data public String title; public String description; public String url; public String date; public String source; public String image; public String text; public boolean read = false; public Feed feed; public boolean star = false; /** * Constructor to set the variables equal to the content parsed from the Rss feed */ public Post(String title, String description, String url, String date, String image, String source, Feed feed, boolean read, String text, boolean star) { this.title = title; this.description = description; this.date = date; this.image = image; this.url = url; this.source = source; this.feed = feed; this.read = read; if(text!=null&&!text.equals("")) { this.text = text; } else { this.text = description; } this.star = star; } /** * Returns if two posts have the same title and date */ @Override public boolean equals(Object o) { return (title.equals(((Post)o).title)&&date.equals(((Post)o).date)); } /** * Determines which of two posts comes first in chronological order */ @Override public int compareTo(Object another) { DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); DateFormat atomDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm"); try { if(date.equals("")) { return 1; } else if(((Post)another).date.equals("")) { return -1; } Date thisDate, thatDate; if(date.contains(",")) thisDate = formatter.parse(date); else { thisDate = atomDate.parse(date.substring(0,16)); } if(((Post)another).date.contains(",")) thatDate = formatter.parse(((Post)another).date); else thatDate = atomDate.parse(((Post)another).date.substring(0,16)); if(thisDate.getTime()>thatDate.getTime()) { return -1; } else { return 1; } } catch (ParseException e) { e.printStackTrace(); } return 0; } /** * Returns the data necessary to save the post as a string */ public String getSaveData() { description = description.replace("\n","<br />"); return title + "qzpsfaaa" + description + "qzpsfaaa" + url + "qzpsfaaa" + date + "qzpsfaaa" + source + "qzpsfaaa" + image + "qzpsfaaa" + text + "qzpsfaaa" + read + "qzpsfaaa" + star; } }
package com.xnarum.th.ib_service; import java.io.File; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.ism.bizservice.online.BizServiceHandler; import com.xnarum.bi.common.CustomClassLoader; import com.xnarum.bi.common.PropertyReader; import lombok.extern.slf4j.Slf4j; @RestController @SpringBootApplication @Slf4j @RequestMapping("/services") public class IBApplication { public static void main(String[] args) { SpringApplication.run(IBApplication.class, args); } @PostMapping(path="/ib") public BaseResponse execute(@RequestBody BaseRequest request) { BaseResponse response = new BaseResponse(); response.setMessageId(request.getMessageId()); response.setTransactionId(request.getTransactionId()); try { String classpath = PropertyReader.getProperty("biz.classpath", System.getenv("BICOM_HOME") + File.separator + "classes"); CustomClassLoader ccl = CustomClassLoader.getInstance(Thread.currentThread().getContextClassLoader(), classpath); String bizClass = request.getBusinessClass(); BizServiceHandler handler = (BizServiceHandler)ccl.loadClass(bizClass).newInstance(); handler.execute(request.getData()); response.setCode("0000"); response.setData("Hello".getBytes()); response.setMessage("Success"); }catch( Exception ex ) { log.error("Failed to process request", ex); response.setCode("9999"); response.setMessage(ex.getMessage()); } return response; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.vishal.si.main; import au.com.bytecode.opencsv.CSVReader; import com.vishal.si.struct.Scaffold; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.List; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Om Sai Ram */ public class ReadScaffold { public static void main(String[] args) { String[] row = null; String csvFilename = "C:/Users/Om Sai Ram/Desktop/scaffolds.csv"; CSVReader csvReader; try { csvReader = new CSVReader(new FileReader(csvFilename)); // entry map <Moleculename, SMILES> TreeMap<String, Scaffold> scfList = new TreeMap<String, Scaffold>(); List<String[]> content = csvReader.readAll(); int i = 0; for (Object object : content) { row = (String[]) object; Scaffold s = new Scaffold(); s.setIUPACname(row[0]); s.setLogP(Double.parseDouble(row[1])); s.setBMframework(row[2]); s.setUniqueSmile(row[3]); scfList.put(s.getUniqueSmile(), s); } System.out.println("Size is: "+scfList.size()); String scList = "C:/Users/Om Sai Ram/Desktop/scaffoldList.hmap"; Utility.saveObjectToFile(new File(scList), scfList); } catch (Exception ex) { Logger.getLogger(ReadScaffold.class.getName()).log(Level.SEVERE, null, ex); } } }
package com.zjf.myself.codebase.util; import android.content.Context; import android.content.pm.ApplicationInfo; public class AppLog { public static final String TAG = "Codebase"; public static boolean saveErrorLog = false; public static boolean DEBUG = true; public static void v(String msg) { if (DEBUG) android.util.Log.v(TAG, buildMessage(msg)); } public static void v(String msg, Throwable thr) { if (DEBUG) android.util.Log.v(TAG, buildMessage(msg), thr); } public static void d(String msg) { if (DEBUG) android.util.Log.d(TAG, buildMessage(msg)); } public static void d(String msg, Throwable thr) { if (DEBUG) android.util.Log.d(TAG, buildMessage(msg), thr); } public static void i(String msg) { if (DEBUG) android.util.Log.i(TAG, buildMessage(msg)); } public static void i(String msg, Throwable thr) { if (DEBUG) android.util.Log.i(TAG, buildMessage(msg), thr); } public static void w(String msg) { android.util.Log.w(TAG, buildMessage(msg)); } public static void w(String msg, Throwable thr) { if (DEBUG) android.util.Log.w(TAG, buildMessage(msg), thr); } public static void e(String msg) { if (DEBUG) android.util.Log.e(TAG, buildMessage(msg)); } public static void e(String msg, Throwable thr) { if (DEBUG) android.util.Log.e(TAG, buildMessage(msg), thr); } public static void p(Throwable thr) { if (DEBUG) android.util.Log.w(TAG, "", thr); } public static void e(String tag, String msg) { if (DEBUG) android.util.Log.e(tag, msg); } public static void e(Throwable thr) { if (DEBUG) android.util.Log.e(TAG, "", thr); } public static void i(String tag, String msg) { if (DEBUG) android.util.Log.i(tag, msg); } public static void v(String tag, String msg) { if (DEBUG) android.util.Log.v(tag, msg); } public static void d(String tag, String msg) { if (DEBUG) android.util.Log.d(tag, msg); } protected static String buildMessage(String msg) { StackTraceElement caller = new Throwable().fillInStackTrace().getStackTrace()[2]; try { String name = caller.getClassName(); return new StringBuilder() .append(name.substring(name.lastIndexOf(".") + 1, name.length())).append(".") .append(caller.getMethodName()).append("(): ").append(msg).toString(); } catch (Exception e) { } return new StringBuilder().append(caller.getClassName()).append(".") .append(caller.getMethodName()).append("(): ").append(msg).toString(); } public static boolean isApkDebugable(Context context) { try { ApplicationInfo info= context.getApplicationInfo(); return (info.flags&ApplicationInfo.FLAG_DEBUGGABLE)!=0; } catch (Exception e) { } return false; } }
package engine.view; import javax.swing.*; import java.awt.*; import java.util.ArrayList; /** * This JComponent subclass is the canvas that will be repainted on every tick of the GameLoop. When the GameLoop * (or any other object) calls canvas.repaint(), this class will go through its own list of painters, and have * all of them draw their own content on the canvas. * Created by thomas on 4-2-17. */ public class Canvas extends JComponent { /** * List of painters that will draw upon the board, in order of index. * TODO: Design more elegant way to handle the order of painting */ private ArrayList<CanvasPainter> painters = new ArrayList<>(); /** * This method gets called when repaint() is called by another object (the GameLoop). It sets the screen to * its background color by calling super.paint(), then it calls the paint() method of all painters in the * painter array, by order of index. * @param graphics the graphics object that gets passed to the method when repaint() is called */ @Override public void paint(Graphics graphics) { super.paint(graphics); for (CanvasPainter painter : painters) { painter.paint((Graphics2D) graphics); } } /** * Adds a painter to the end of the list. * @param painter the painter to add */ public void addPainter(CanvasPainter painter) { painters.add(painter); } /** * Removes a painter from the list of. * @param painter the painter to remove */ public void removePainter(CanvasPainter painter) { assert painters.contains(painter); painters.remove(painter); } }
package com.padeltrophy.util.file; import com.padeltrophy.util.log.Tracer; import org.imgscalr.Scalr; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.util.Date; public class FileUtil { private Tracer tracer = new Tracer(FileUtil.class.getName()); private String getTmpFileName(){ Date now = new Date(); return "tmp_"+now.getTime(); } public File scaleImage(File originalImageFile) { tracer.trace("scaleImage :> originalImageFile: "+originalImageFile.getPath()+" / "+originalImageFile.getAbsolutePath()); FileOutputStream fos = null; Integer targetWidth = 300; Integer targetHeight = 300; String imageFormat = "jpg"; try { BufferedImage image = ImageIO.read(originalImageFile); BufferedImage scaledImg = Scalr.resize(image, Scalr.Method.BALANCED, Scalr.Mode.FIT_TO_WIDTH, targetWidth, targetHeight, Scalr.OP_BRIGHTER); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(scaledImg, imageFormat, baos); baos.flush(); byte[] scaledImageInByte = baos.toByteArray(); baos.close(); String fileName = this.getTmpFileName(); File outputFile = new File("/tmp/"+fileName+"."+imageFormat); tracer.trace("scaleImage :> file name: "+fileName); fos = new FileOutputStream(outputFile); fos.write(scaledImageInByte); tracer.trace("scaleImage :> originalFile deleted: "+originalImageFile.delete()); tracer.trace("scaleImage :> outputfile: "+outputFile.getPath()); return outputFile; }catch (Exception e){ tracer.trace("scaleImage :> error:"+e.getMessage()); e.printStackTrace(); return null; } } }
package com.mingrisoft; public class Test { public static void main(String[] args) { Person person1 = new Person();// 创建对象 Person person2 = new Person("明日科技", "男", 11);// 创建对象 System.out.println("员工1的信息"); System.out.println("员工姓名:" + person1.getName()); // 输出姓名 System.out.println("员工性别:" + person1.getGender()); // 输出性别 System.out.println("员工年龄:" + person1.getAge()); // 输出年龄 System.out.println("员工2的信息"); System.out.println("员工姓名:" + person2.getName()); // 输出姓名 System.out.println("员工性别:" + person2.getGender()); // 输出性别 System.out.println("员工年龄:" + person2.getAge()); // 输出年龄 } }
package DesignPatterns.AbstractFactoryPattern; public class ConcreteFactory2 implements Factory { @Override public ProductA createProductA() { System.out.println("AFP ConcreteFactory2 createProductA"); return new ConcreteProductA1(); } @Override public ProductB createProductB() { System.out.println("AFP ConcreteFactory2 createProductB"); return new ConcreteProductB1(); } @Override public ProductC createProductC() { System.out.println("AFP ConcreteFactory2 createProductC"); return new ConcreteProductC1(); } }
package algorithm._10; public class Solution { public static void main(String[] args) { String s = "aa"; String p = "a*"; System.out.println(new Solution().isMatch(s, p)); } public boolean isMatch(String s, String p) { if (p.isEmpty()) { return s.isEmpty(); } boolean isMatched = !s.isEmpty() && (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.'); if (p.length() > 1 && p.substring(1, 2).equals("*")) { return isMatch(s, p.substring(2)) || (isMatched && isMatch(s.substring(1), p)); } else { return isMatched && isMatch(s.substring(1), p.substring(1)); } } }
package com.androidbook.location; import java.util.List; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.os.Bundle; import com.google.android.maps.GeoPoint; import com.google.android.maps.ItemizedOverlay; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.Overlay; import com.google.android.maps.OverlayItem; public class Huts extends MapActivity { @Override protected void onCreate(Bundle data) { super.onCreate(data); setContentView(R.layout.huts); Drawable marker = getResources().getDrawable(R.drawable.paw); // work around to issue // see http://groups.google.com/group/android-developers/msg/a7998c2c08bddc2a marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight()); HutsItemizedOverlay huts = new HutsItemizedOverlay(marker); MapView map = (MapView)findViewById(R.id.map); map.setSatellite(true); List<Overlay> overlays = map.getOverlays(); overlays.add(huts); map.setBuiltInZoomControls(true); final MapController mapControl = map.getController(); mapControl.setCenter(huts.getCenter()); mapControl.zoomToSpan(huts.getLatSpanE6(), huts.getLonSpanE6()); } @Override protected boolean isRouteDisplayed() { // we do not show routes return false; } private class HutsItemizedOverlay extends ItemizedOverlay<OverlayItem> { public HutsItemizedOverlay(Drawable defaultMarker) { super(defaultMarker); // change the direction of the shadow so the bottom of the marker is the part "touching" boundCenterBottom(defaultMarker); //static data, so we call this right away populate(); } @Override public GeoPoint getCenter() { Integer averageLat = 0; Integer averageLon = 0; for (GeoPoint point : hutPoints) { averageLat += point.getLatitudeE6(); averageLon += point.getLongitudeE6(); } averageLat /= hutPoints.length; averageLon /= hutPoints.length; return new GeoPoint(averageLat, averageLon); } @Override public void draw(Canvas canvas, MapView mapView, boolean shadow) { super.draw(canvas, mapView, false); } public GeoPoint hutPoints[] = new GeoPoint[] { // Lakes of the Clouds new GeoPoint(44258793, -71318940), // Zealand Falls new GeoPoint(44195798, -71494402), // Greanleaf new GeoPoint(44160372, -71660385), // Galehead new GeoPoint(44187866, -71568734), // Carter Notch new GeoPoint(44259224, -71195633), // Mizpah Spring new GeoPoint(44219362, -71369473), // Lonesome new GeoPoint(44138452, -71703064), // Madison Spring new GeoPoint(44327751, -71283283), }; @Override protected OverlayItem createItem(int i) { // the "title" and "snippet" fields aren't used anywhere just yet... so // we've ignored them here OverlayItem item = new OverlayItem(hutPoints[i], null, null); return item; } @Override public int size() { return hutPoints.length; } } }
package com.karya.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.karya.dao.IBudgetCostCenterDao; import com.karya.model.Budget001MB; import com.karya.model.BudgetAccountType001MB; import com.karya.model.BudgetMonthlyDistribution001MB; import com.karya.model.BudgetVarianceReport001MB; import com.karya.model.CostCenter001MB; import com.karya.service.IBudgetCostCenterService; @Service("budgetcostcenterService") @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) public class BudgetCostCenterServiceImpl implements IBudgetCostCenterService{ @Autowired private IBudgetCostCenterDao budgetcostcenterDao; @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void addcostcenter(CostCenter001MB costcenter001MB) { budgetcostcenterDao.addcostcenter(costcenter001MB); } public List<CostCenter001MB> listcostcenter() { return budgetcostcenterDao.listcostcenter(); } public CostCenter001MB getcostcenter(int centId) { return budgetcostcenterDao.getcostcenter(centId); } public void deletecostcenter(int centId) { budgetcostcenterDao.deletecostcenter(centId); } // Budget account type @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void addbudgetaccounttype(BudgetAccountType001MB budgetaccounttype001MB) { budgetcostcenterDao.addbudgetaccounttype(budgetaccounttype001MB); } public List<BudgetAccountType001MB> listbudgetaccounttype() { return budgetcostcenterDao.listbudgetaccounttype(); } public BudgetAccountType001MB getbudgetaccounttype(int bgaccId) { return budgetcostcenterDao.getbudgetaccounttype(bgaccId); } public void deletebudgetaccounttype(int bgaccId) { budgetcostcenterDao.deletebudgetaccounttype(bgaccId); } //budget @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void addbudget(Budget001MB budget001MB) { budgetcostcenterDao.addbudget(budget001MB); } public List<Budget001MB> listbudget() { return budgetcostcenterDao.listbudget(); } public Budget001MB getbudget(int bgId) { return budgetcostcenterDao.getbudget(bgId); } public void deletebudget(int bgId) { budgetcostcenterDao.deletebudget(bgId); } //budget monthly distribution @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void addbudgetmonthlydistribution(BudgetMonthlyDistribution001MB budgetmonthlydistribution001MB) { budgetcostcenterDao.addbudgetmonthlydistribution(budgetmonthlydistribution001MB); } public List<BudgetMonthlyDistribution001MB> listbudgetmonthlydistribution() { return budgetcostcenterDao.listbudgetmonthlydistribution(); } public BudgetMonthlyDistribution001MB getbudgetmonthlydistribution(int bmdId) { return budgetcostcenterDao.getbudgetmonthlydistribution(bmdId); } public void deletebudgetmonthlydistribution(int bmdId) { budgetcostcenterDao.deletebudgetmonthlydistribution(bmdId); } //budget variance report @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void addbudgetvariancereport(BudgetVarianceReport001MB budgetvariancereport001MB) { budgetcostcenterDao.addbudgetvariancereport(budgetvariancereport001MB); } public List<BudgetVarianceReport001MB> listbudgetvariancereport() { return budgetcostcenterDao.listbudgetvariancereport(); } public BudgetVarianceReport001MB getbudgetvariancereport(int varId) { return budgetcostcenterDao.getbudgetvariancereport(varId); } public void deletebudgetvariancereport(int varId) { budgetcostcenterDao.deletebudgetvariancereport(varId); } }
import java.util.Scanner; public class qishui{ public static void main(String args[]){ Scanner sc = new Scanner(System.in); int result = 0; while(sc.hasNext()){ result = sc.nextInt(); bottle(result); } sc.close(); } private static void bottle(int num2) { int num=0,num1=0,bnum=0,bnum1=0; num = num2; bnum1 = num/3; num = num%3; bnum = bnum1 + bnum; num1 = num + bnum1; while(num1>=3){ num = num1%3; bnum1 = num1/3; bnum = bnum1 + bnum; num1 = num + bnum1; } if(num1==2) bnum++; System.out.println(bnum); } }
package com.tntdjs.midi; public interface IReceiver { public void setMidiInputReciever(String receiver); }
import java.util.Iterator; //Department class public class Department implements Entity_{ String dname; LL<Student> studentList; //Constructor public Department(String name) { dname = name; studentList = new LL<Student>(); } //Studiter class class Studiter implements Iterator<Student_>{ Position_<Student> obj; public Studiter(LL<Student> list) { obj = list.getHead(); } public boolean hasNext() { return !(obj==null); } public Student next() { Position_<Student> temp = obj; obj = obj.after(); return temp.value(); } } //Inherited functions public String name() { return dname; } public Iterator<Student_> studentList() { return new Studiter(studentList); } //Method to add student to studentList public void addStudent(Student x) { studentList.add(x); } }
package Java; import java.util.HashMap; import java.util.Map; /** *Numbers Numbers in Java can be written in many different forms. Depending on the prefix or suffix we use, we can declare it’s base (binary, hex, octal), and even it’s type (int, long, float). Alterations in the base: With literal prefixes we can define 4 different numeric bases, and they are: Octal, Hexadecimal, Decimal and Binary. We can represent an Octal number by adding the 0 prefix to it. We can represent a Hexadecimal number by adding the 0x prefix to it. When we don’t add any prefix, the number is treated as a decimal number. And with Java 7 we have a new literal prefix to represent binary base, which is the 0b prefix. public vodi numberSystem(){ int decimal = 100; // 100 em decimal. int octal = 0144; // decimal 100 represented in octal base. int hex = 0x64; // decimal 100 represented in hexadecimal base. int bin = 0b1100100; // decimal 100 represented in binary base // Only works in Java 7 version or higher. System.out.println(decimal); // Prints '100' System.out.println(octal); // Prints '100' System.out.println(hex); // Prints '100' System.out.println(bin); // Prints '100' } * * For the computer information is stored in bytes, each one formed by 8 on/off values called bits. Those on/off values can be seen in base 2 a 0 and 1, grouped by 3 as octal (base 8) numbers, by 4 as hexadecimal (base 16) numbers. As you dont have enough different digits in base 10, to represent the extra digits over 9 are used letters from A to F, so 15 decimal is F and 16 decimal is 10 hexadecimal. So you can represent the value of a byte with an 8 digit binary number, with a digital number between 0 and 255, or an hexadecimal number between 0 and FF. Why using other base to represent them? Because there are operations that take into account specific bits on a byte, in decimal they are not as obvious as in binary or hexadecimal. */ public class NumericSystemOp { static Map<Integer, Character> map = null; static { map = new HashMap<>(); map.put(10, 'a'); map.put(11, 'b'); map.put(12, 'c'); map.put(13, 'd'); map.put(14, 'e'); map.put(15, 'f'); } public int hex2Decimal(String s) { String digits = "0123456789ABCDEF"; s = s.toUpperCase(); int val = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); int d = digits.indexOf(c); val = 16*val + d; } return val; } public String decimal2Hex(int d) { String digits = "0123456789ABCDEF"; if (d == 0) return "0"; StringBuffer hex = new StringBuffer(); int val = 0; while (d > 0) { int digit = d % 16;// rightmost digit hex.append(digits.charAt(digit)); d = d / 16; } return hex.reverse().toString(); } //decimal string to a custom base 7 notation. public String dec2Base7(int dec) { String octal = Integer.toOctalString(dec);/* public String hex2Binary(String hex) { int decimal = Integer.parseInt(hex, 16); String bin = Integer.toBinaryString(decimal); System.out.println(bin); String digits = "0123456789ABCDEF"; int val = 0; for (int i = 0; i < hex.length(); i++) { char c = hex.charAt(i); } return bin; }*/ String toBase16 = Integer.toString(dec, 16); String toBase8 = Integer.toString(dec, 8); return octal; } public String decToHex(int num) { //Scanner sc = new Scanner(System.in); //int num = sc.nextInt(); //String str = Integer.toHexString(num); //System.out.println(str); StringBuffer sb = new StringBuffer(); boolean isNeg = false; if (num < 0) { num = -num; isNeg = true; } while (num > 0) { int rem = num % 16; if (rem > 9) { sb.append(map.get(rem)); } else sb.append(rem); num = num / 16; } System.out.println(sb.reverse().toString()); return sb.reverse().toString(); } public String itoa(int num, int base) { if (num == 0) return ""; boolean isNeg = false; if (num < 0 && base == 10) { isNeg = true; num = -num; } StringBuffer sb = new StringBuffer(); while (num > 0) { int rem = num % base; int temp = (rem > 9)? (rem-10) + 'a' : rem + '0'; num = num / base; } if (isNeg) sb.append("-"); return sb.reverse().toString(); } public static void main(String a[]) { NumericSystemOp ns = new NumericSystemOp(); //System.out.println(ns.decimal2Hex(1234)); //System.out.println(ns.hex2Decimal("4D2")); //ns.dec2Base7(1234); System.out.println(ns.itoa(1234, 16)); System.out.println(ns.itoa(1234, 8)); System.out.println(ns.itoa(1234, 2)); System.out.println(ns.itoa(1234, 10)); } }
package lize; import com.lize.test.P; public class Test { public static void main(String[] args){ P p = new P(); } }
package com.example; import java.util.List; import com.google.cloud.vision.v1.AnnotateImageResponse; import com.google.cloud.vision.v1.EntityAnnotation; import com.google.cloud.vision.v1.Feature.Type; import com.google.cloud.vision.v1.ImageAnnotatorClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.gcp.vision.CloudVisionTemplate; import org.springframework.core.io.ResourceLoader; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; @RestController public class VisionController { @Autowired private ResourceLoader resourceLoader; @Autowired private CloudVisionTemplate cloudVisionTemplate; @GetMapping("/extractLabels") public ModelAndView extractLabels(String imageUrl, ModelMap map) { AnnotateImageResponse response = this.cloudVisionTemplate .analyzeImage(this.resourceLoader.getResource(imageUrl), Type.LABEL_DETECTION);// passing resourceLoader /* * running with no page mapping-- Resource imageResource = * this.resourceLoader.getResource("file:src/main/resources/cat.jpg"); * AnnotateImageResponse response = this.cloudVisionTemplate.analyzeImage( * imageResource, Feature.Type.LABEL_DETECTION); return * response.getLabelAnnotationsList().toString(); */ // This gets the annotations of the image from the response object. List<EntityAnnotation> annotations = response.getLabelAnnotationsList(); map.addAttribute("annotations", annotations); map.addAttribute("imageUrl", imageUrl); return new ModelAndView("result", map); } @GetMapping("/extractText") public ModelAndView extractText(String imageUrl, ModelMap map) { AnnotateImageResponse text = this.cloudVisionTemplate.analyzeImage( this.resourceLoader.getResource(imageUrl), Type.DOCUMENT_TEXT_DETECTION); map.addAttribute("text", text); map.addAttribute("imageUrl", imageUrl); return new ModelAndView("result", map); } }
package me.gabreuw.bearapi.api.mapper; import me.gabreuw.bearapi.api.dto.BeerDTO; import me.gabreuw.bearapi.domain.model.Beer; import org.mapstruct.Mapper; import org.mapstruct.factory.Mappers; import java.util.List; @Mapper public interface BeerMapper { BeerMapper INSTANCE = Mappers.getMapper(BeerMapper.class); BeerDTO toDTO(Beer beer); List<BeerDTO> toCollectionDTO(List<Beer> beers); Beer toEntity(BeerDTO beerDTO); }
package model.access; import javax.persistence.EntityManager; import model.Project; import model.RatingObject; public interface IRatingObjectExistenceChecker { public void useEntityManager(EntityManager em); public Boolean check(Project project, RatingObject ratingObject) throws Exception; }
package patterns.behavioral.state; public class SoldState implements State { private GumballMachine gumballMachine; public SoldState(GumballMachine gumballMachine) { this.gumballMachine = gumballMachine; } @Override public void insertQuarter() { System.out.println("你已经插入过卡币"); } @Override public void ejectQuarter() { System.out.println("不好意思,你已经使用过,不能退还卡币"); } @Override public void turnCrank() { System.out.println("一个卡币只能摇一次手杆"); } @Override public void disPens() { gumballMachine.releaseBall(); if(gumballMachine.getCount() > 0) { gumballMachine.setCurrentState(gumballMachine.getNoQuarterState()); } else { System.out.println("机器已售罄"); gumballMachine.setCurrentState(gumballMachine.getSoldOutState()); } } }
package Worker; import Models.Event; import Protocols.ClientEventReportProtocol; import Protocols.ClientLoginProtocol; import Protocols.ClientRegistrationProtocol; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.ArrayList; import javax.swing.JLabel; public class ClientHandler implements Runnable { private JLabel label = null; private String HOST = "localhost"; private int centralServerPort = 2050; private String workerUsername = null; private WorkerSharedObject sharedObject = null; private Socket clientSocket = null; private String serverMessage = null; private PrintWriter messageToClient = null; private BufferedReader messageFromClient = null; private String clientMessage = null; private String MulticastIP = "undefined"; private int clientPortNumber = 0; public ClientHandler(JLabel label, WorkerSharedObject sharedObject, String HOST, int centralServerPort, String MulticastIP, int clientPortNumber, String workerUsername, Socket clientSocket) throws IOException { this.label = label; this.sharedObject = sharedObject; this.HOST = HOST; this.centralServerPort = centralServerPort; this.MulticastIP = MulticastIP; this.clientPortNumber = clientPortNumber; this.workerUsername = workerUsername; this.clientSocket = clientSocket; this.messageToClient = new PrintWriter(this.clientSocket.getOutputStream(), true); this.messageFromClient = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream())); } /** * Método run que irá ler a mensagem do cliente, e que dependendo desta, irá * reencaminhar para os diferentes métodos desta classe. */ @Override public void run() { try { this.clientMessage = this.messageFromClient.readLine(); if (this.clientMessage.startsWith("Listener of")) { this.sharedObject.newListener(this.clientSocket, this.clientMessage.replace("Listener of ", "")); } else if (this.clientMessage.equalsIgnoreCase("newClient")) { this.newClient(); } else if (this.clientMessage.equalsIgnoreCase("Eventos ativos")) { this.getEvents(); } else if (this.clientMessage.equalsIgnoreCase("Reportar")) { this.reportNewEvent(); } else if (this.clientMessage.equalsIgnoreCase("Logout")) { this.clientLogout(); } } catch (IOException e) { System.err.println("IOException at ClientHandler!"); } } /** * Método que representa o menu inicial do cliente, onde é questionado se o * utilizador pretende realizar o login ou o registo. * * @throws IOException */ private void newClient() throws IOException { boolean goNext = false; while (!goNext) { this.messageToClient.println("[WORKER] Pretende realizar o login, o registo ou sair: "); this.clientMessage = this.messageFromClient.readLine(); if (this.clientMessage != null) { if (this.clientMessage.equalsIgnoreCase("login") || this.clientMessage.equalsIgnoreCase("registo") || this.clientMessage.equalsIgnoreCase("sair")) { goNext = true; } else { this.messageToClient.println("[WORKER] Inseriu uma resposta inválida!"); } } } if (this.clientMessage.equalsIgnoreCase("login")) { this.clientLogin(); } else { if (this.clientMessage.equalsIgnoreCase("registo")) { this.clientRegistration(); } else { this.messageToClient.println("[WORKER] Saiu da aplicação!"); } } } /** * Método responsável pelo login de um cliente, utilizando o protocolo de * ClientLoginProtocol. * * @throws IOException */ private void clientLogin() throws IOException { ClientLoginProtocol loginHandler = new ClientLoginProtocol(); String clientUsername = "undefined"; String protocolAnswer = "undefined"; this.messageToClient.println(loginHandler.welcomeMessage()); while (!protocolAnswer.equalsIgnoreCase("[WORKER] Sucesso na autenticação!")) { protocolAnswer = loginHandler.processInput(this.clientMessage); this.messageToClient.println(protocolAnswer); if (protocolAnswer.equalsIgnoreCase("[WORKER] Erro na autenticação!")) { this.newClient(); } if (protocolAnswer.equalsIgnoreCase("[WORKER] Sucesso na autenticação!")) { if (this.notifyClientLoginToServer(clientUsername, this.workerUsername) && this.sharedObject.clientLogin(loginHandler.getClient())) { this.messageToClient.println("[WORKER] Done!"); this.messageToClient.println("[WORKER] IP: " + this.MulticastIP); this.messageToClient.println("[WORKER] ClientPortNumber: " + this.clientPortNumber); } else { this.messageToClient.println("[WORKER] Esta conta já se encontra autenticada!"); this.newClient(); } } else { this.clientMessage = this.messageFromClient.readLine(); if (protocolAnswer.equalsIgnoreCase("[WORKER] Indique o seu username: ")) { clientUsername = this.clientMessage; } } } } /** * Método responsável pelo logout de um cliente. * * @throws IOException */ private void clientLogout() throws IOException { String clientUsername = this.messageFromClient.readLine(); if (this.sharedObject.clientLogout(clientUsername) && this.notifyClientLogoutToServer(clientUsername)) { this.messageToClient.println("[WORKER] Logout realizado com sucesso!"); } else { this.messageToClient.println("[WORKER] Erro no logout!"); } } /** * Método responsável pelo registo de um cliente, utilizando o protocolo * ClientRegistrationProtocol. * * @throws IOException */ private void clientRegistration() throws IOException { ClientRegistrationProtocol registrationHandler = new ClientRegistrationProtocol(); String protocolAnswer = "undefined"; this.messageToClient.println(registrationHandler.welcomeMessage()); while (!protocolAnswer.equalsIgnoreCase("[WORKER] Sucesso ao realizar o registo!")) { protocolAnswer = registrationHandler.processInput(this.clientMessage); this.messageToClient.println(protocolAnswer); if (protocolAnswer.equalsIgnoreCase("[WORKER] Erro no registo!") || protocolAnswer.equalsIgnoreCase("[WORKER] Sucesso ao realizar o registo!")) { this.newClient(); } else { if (!protocolAnswer.equalsIgnoreCase("[WORKER] Esse username já se encontra a ser utilizado!")) { this.clientMessage = this.messageFromClient.readLine(); } } } this.newClient(); } /** * Método responsável por notificar ao servidor central que um novo cliente * realizou o login. * * @param clientUsername - username do Cliente * @param workerUsername - username do Worker * @return - se foi notificado com sucesso * @throws IOException */ private boolean notifyClientLoginToServer(String clientUsername, String workerUsername) throws IOException { Socket workerSocket = new Socket(HOST, centralServerPort); PrintWriter messageToServer = new PrintWriter(workerSocket.getOutputStream(), true); BufferedReader messageFromServer = new BufferedReader(new InputStreamReader(workerSocket.getInputStream())); messageToServer.println("Client Login"); messageToServer.println(clientUsername); messageToServer.println(workerUsername); this.serverMessage = messageFromServer.readLine(); messageFromServer.close(); messageToServer.close(); workerSocket.close(); if (this.serverMessage.equalsIgnoreCase("[SERVER] Cliente válido!")) { return true; } return false; } /** * Método responsável por notificar ao servidor central que um cliente * realizou o logou. * * @param clientUsername - username do Cliente * @param workerUsername - username do Worker * @return - se foi notificado com sucesso * @throws IOException */ private boolean notifyClientLogoutToServer(String clientUsername) throws IOException { Socket workerSocket = new Socket(HOST, centralServerPort); PrintWriter messageToServer = new PrintWriter(workerSocket.getOutputStream(), true); BufferedReader messageFromServer = new BufferedReader(new InputStreamReader(workerSocket.getInputStream())); messageToServer.println("Client Logout"); messageToServer.println(clientUsername); this.serverMessage = messageFromServer.readLine(); messageFromServer.close(); messageToServer.close(); workerSocket.close(); if (this.serverMessage.equalsIgnoreCase("[SERVER] Realizado o logout do cliente!")) { return true; } return false; } /** * Método responsável por processar o pedido de "Eventos ativos" do cliente. * É enviado ao cliente os eventos que se encontram ativos na sua zona. */ private void getEvents() { ArrayList<Event> events = this.sharedObject.getEvents(); if (events.isEmpty()) { this.messageToClient.println("[WORKER] Não existem eventos ativos!"); } else { this.messageToClient.println("------------------------------------------------------------"); for (int i = 0; i < events.size(); i++) { this.messageToClient.println("[EVENTO] " + events.get(i).getEvent()); this.messageToClient.println("[DANGERLEVEL] " + events.get(i).getDangerLevel()); this.messageToClient.println("[LOCAL] " + events.get(i).getLocal()); this.messageToClient.println("------------------------------------------------------------"); } } this.messageToClient.println("[WORKER] Done!"); } /** * Método responsável por processar o pedido de "Reportar" do cliente. É * utilizado o ClientEventReportProtocol para a realização do reporte. * * @throws IOException */ private void reportNewEvent() throws IOException { String clientUsername = this.messageFromClient.readLine(); ClientEventReportProtocol reportHandler = new ClientEventReportProtocol(); String protocolAnswer = "undefined"; this.messageToClient.println(reportHandler.welcomeMessage()); while (!protocolAnswer.equalsIgnoreCase("[WORKER] Sucesso no reporte!")) { protocolAnswer = reportHandler.processInput(this.clientMessage); this.messageToClient.println(protocolAnswer); if (!protocolAnswer.equalsIgnoreCase("[WORKER] Sucesso no reporte!")) { this.clientMessage = this.messageFromClient.readLine(); } } String labelText = this.sharedObject.getClientsReportsString().replace("</html>", "") + "<br>[CLIENT] Novo evento reportado pelo cliente: [" + clientUsername + "]" + "<br>[CLIENT][EVENT] " + reportHandler.getEvent() + "<br>[CLIENT][DANGERLEVEL] " + reportHandler.getDangerlevel() + "<br>[CLIENT][DESCRIPTION] " + reportHandler.getDescription() + "<br></html>"; this.sharedObject.setClientsReportsString(labelText); this.label.setText(this.sharedObject.getClientsReportsString()); /*System.out.println("[CLIENT] Novo evento reportado pelo cliente: [" + clientUsername + "]"); System.out.println("[CLIENT][EVENT] " + reportHandler.getEvent()); System.out.println("[CLIENT][DANGERLEVEL] " + reportHandler.getDangerlevel()); System.out.println("[CLIENT][DESCRIPTION] " + reportHandler.getDescription());*/ } }
// ********************************************************** // 1. 제 목: 강사 질문방 // 2. 프로그램명: AdminQnaBean.java // 3. 개 요: 강사 질문방 // 4. 환 경: JDK 1.4 // 5. 버 젼: 1.0 // 6. 작 성: 강성욱 2005. 9. 20 // 7. 수 정: // ********************************************************** package com.ziaan.tutor; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.Statement; import java.util.ArrayList; import java.util.Vector; import com.ziaan.common.BoardBean; import com.ziaan.library.ConfigSet; import com.ziaan.library.DBConnectionManager; import com.ziaan.library.DataBox; import com.ziaan.library.ErrorManager; import com.ziaan.library.FileManager; import com.ziaan.library.FormatDate; import com.ziaan.library.ListSet; import com.ziaan.library.RequestBox; import com.ziaan.library.SQLString; import com.ziaan.library.StringManager; /** * 자료실 관리(ADMIN) * * @date : 2005. 9 * @author : S.W.Kang */ public class AdminQnaBean { private static final String FILE_TYPE = "p_file"; // 파일업로드되는 tag name private static final int FILE_LIMIT = 5; // 페이지에 세팅된 파일첨부 갯수 private ConfigSet config; private int row; public AdminQnaBean() { try { config = new ConfigSet(); row = Integer.parseInt(config.getProperty("page.bulletin.row") ); // 이 모듈의 페이지당 row 수를 셋팅한다 } catch(Exception e) { e.printStackTrace(); } } /** * 자료실 리스트화면 select * @param box receive from the form object and session * @return ArrayList 자료실 리스트 * @throws Exception */ public ArrayList selectQnaList(RequestBox box) throws Exception { DBConnectionManager connMgr = null; Connection conn = null; ListSet ls = null; ArrayList list = null; String sql = ""; // PdsData data = null; DataBox dbox = null; int v_tabseq = box.getInt("p_tabseq"); int v_pageno = box.getInt("p_pageno"); String v_searchtext = box.getString("p_searchtext"); String v_search = box.getString("p_search"); String s_userid = box.getSession("userid"); String s_gadmin = box.getSession("gadmin"); try { connMgr = new DBConnectionManager(); list = new ArrayList(); sql = "select a.seq, a.userid, a.name, a.title, count(b.realfile) filecnt, a.indate, a.cnt, a.refseq, a.levels, a.position "; sql += " from TZ_BOARD a, TZ_BOARDFILE b "; sql += " where a.tabseq = b.tabseq( +) "; sql += " and a.seq = b.seq( +) "; sql += " and a.tabseq = " + v_tabseq; if ( s_gadmin.equals("P1") ) { sql += " and a.refseq in (select seq from tz_board where levels=1 and tabseq=" + v_tabseq + " and userid =" +SQLString.Format(s_userid) + ") "; } if ( !v_searchtext.equals("") ) { // 검색어가 있으면 if ( v_search.equals("name") ) { // 이름으로 검색할때 sql += " and lower(a.name) like lower(" + StringManager.makeSQL("%" + v_searchtext + "%") + ")"; } else if (v_search.equals("title") ) { // 제목으로 검색할때 sql += " and lower(a.title) like lower(" + StringManager.makeSQL("%" + v_searchtext + "%") + ")"; } else if (v_search.equals("content") ) { // 내용으로 검색할때 sql += " and a.content like " + StringManager.makeSQL("%" + v_searchtext + "%"); } } sql += " group by a.seq, a.userid, a.name, a.title, a.indate, a.cnt, a.refseq, a.levels, a.position "; sql += " order by a.refseq desc, a.position asc "; ls = connMgr.executeQuery(sql); ls.setPageSize(row); // 페이지당 row 갯수를 세팅한다 ls.setCurrentPage(v_pageno); // 현재페이지번호를 세팅한다. int totalpagecount = ls.getTotalPage(); // 전체 페이지 수를 반환한다 int totalrowcount = ls.getTotalCount(); // 전체 row 수를 반환한다 while ( ls.next() ) { dbox = ls.getDataBox(); list.add(dbox); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e10 ) { } } } return list; } /** * 선택된 자료실 게시물 상세내용 select * @param box receive from the form object and session * @return ArrayList 조회한 상세정보 * @throws Exception */ public DataBox selectQna(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; String sql = ""; DataBox dbox = null; int v_tabseq = box.getInt("p_tabseq"); int v_seq = box.getInt("p_seq"); int v_upfilecnt = (box.getInt("p_upfilecnt") > 0?box.getInt("p_upfilecnt"):1); Vector realfileVector = new Vector(); Vector savefileVector = new Vector(); Vector fileseqVector = new Vector(); int [] fileseq = new int [v_upfilecnt]; try { connMgr = new DBConnectionManager(); sql = "select a.seq, a.userid, a.name, a.title, a.content, b.fileseq, b.realfile, b.savefile, a.indate, a.cnt "; sql += " from TZ_BOARD a, TZ_BOARDFILE b "; sql += " where a.tabseq = b.tabseq( +) "; sql += " and a.seq = b.seq( +) "; sql += " and a.tabseq = " + v_tabseq; sql += " and a.seq = " + v_seq; ls = connMgr.executeQuery(sql); while ( ls.next() ) { // ------------------- 2004.12.25 변경 ------------------------------------------------------------------- dbox = ls.getDataBox(); realfileVector.addElement( ls.getString("realfile") ); savefileVector.addElement( ls.getString("savefile") ); fileseqVector.addElement(String.valueOf( ls.getInt("fileseq"))); } if ( realfileVector != null ) dbox.put("d_realfile", realfileVector); if ( savefileVector != null ) dbox.put("d_savefile", savefileVector); if ( fileseqVector != null ) dbox.put("d_fileseq", fileseqVector); connMgr.executeUpdate("update TZ_BOARD set cnt = cnt + 1 where tabseq = " + v_tabseq + " and seq = " +v_seq); } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { }} if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e10 ) { } } } return dbox; } /** * 새로운 자료실 내용 등록 * @param box receive from the form object and session * @return isOk 1:insert success,0:insert fail * @throws Exception */ public int insertQna(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; PreparedStatement pstmt1 = null; String sql = ""; String sql1 = "",sql2 = ""; int isOk1 = 1; int isOk2 = 1; int v_tabseq = box.getInt("p_tabseq"); String v_title = box.getString("p_title"); String v_content = box.getString("p_content"); String v_content1 = ""; String s_userid = box.getSession("userid"); String s_usernm = box.getSession("name"); try { connMgr = new DBConnectionManager(); connMgr.setAutoCommit(false); // ---------------------- 게시판 번호 가져온다 ---------------------------- sql = "select nvl(max(seq), 0) from TZ_BOARD where tabseq = " + v_tabseq; ls = connMgr.executeQuery(sql); ls.next(); int v_seq = ls.getInt(1) + 1; ls.close(); // ------------------------------------------------------------------------------------ /*********************************************************************************************/ // 나모에디터 본문 처리 (Mime Document Parsing 및 이미지 업로드) /* ConfigSet conf = new ConfigSet(); SmeNamoMime namo = new SmeNamoMime(v_content); // 객체생성 boolean result = namo.parse(); // 실제 파싱 수행 if ( !result ) { // 파싱 실패시 System.out.println( namo.getDebugMsg() ); // 디버깅 메시지 출력 return 0; } if ( namo.isMultipart() ) { // 문서가 멀티파트인지 판단 String v_server = conf.getProperty("autoever.url.value"); String fPath = conf.getProperty("dir.namo"); // 파일 저장 경로 지정 String refUrl = conf.getProperty("url.namo");; // 웹에서 저장된 파일을 접근하기 위한 경로 String prefix = "cpCompany" + v_seq; // 파일명 접두어 result = namo.saveFile(fPath, v_server +refUrl, prefix); // 실제 파일 저장 } if ( !result ) { // 파일저장 실패시 System.out.println( namo.getDebugMsg() ); // 디버깅 메시지 출력 return 0; } v_content1 = namo.getContent(); // 최종 컨텐트 얻기 */ /*********************************************************************************************/ //// //// //// //// //// //// //// //// // 게시판 table 에 입력 //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// /// sql1 = "insert into TZ_BOARD(tabseq, seq, userid, name, indate, title, content, cnt, refseq, levels, position, luserid, ldate) "; sql1 += " values (?, ?, ?, ?, to_char(sysdate, 'YYYYMMDDHH24MISS'), ?, ?, ?, ?, ?, ?, ?, to_char(sysdate, 'YYYYMMDDHH24MISS')) "; // sql1 += " values (?, ?, ?, ?, to_char(sysdate, 'YYYYMMDDHH24MISS'), ?, empty_clob(), ?, ?, ?, ?, ?, to_char(sysdate, 'YYYYMMDDHH24MISS')) "; pstmt1 = connMgr.prepareStatement(sql1); pstmt1.setInt(1, v_tabseq); pstmt1.setInt(2, v_seq); pstmt1.setString(3, s_userid); pstmt1.setString(4, s_usernm); pstmt1.setString(5, v_title); pstmt1.setString(6, v_content); pstmt1.setInt(7, 0); pstmt1.setInt(8, v_seq); pstmt1.setInt(9, 1); pstmt1.setInt(10, 1); pstmt1.setString(11, s_userid); isOk1 = pstmt1.executeUpdate(); sql2 = "select content from tz_board where tabseq = " + v_tabseq + " and seq = " + v_seq ; // connMgr.setOracleCLOB(sql2, v_content); // (기타 서버 경우) isOk2 = this.insertUpFile(connMgr,v_tabseq, v_seq, box); if ( isOk1 > 0 && isOk2 > 0) connMgr.commit(); else connMgr.rollback(); } catch ( Exception ex ) { connMgr.rollback(); ErrorManager.getErrorStackTrace(ex, box, sql1); throw new Exception("sql = " + sql1 + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( pstmt1 != null ) { try { pstmt1.close(); } catch ( Exception e1 ) { } } if ( connMgr != null ) try { connMgr.setAutoCommit(true); } catch ( Exception e ) { } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e10 ) { } } } return isOk1*isOk2; } /** * 선택된 자료 상세내용 수정 * @param box receive from the form object and session * @return isOk 1:update success,0:update fail * @throws Exception */ public int updateQna(RequestBox box) throws Exception { DBConnectionManager connMgr = null; Connection conn = null; PreparedStatement pstmt1 = null; String sql1 = "",sql2= ""; int isOk1 = 1; int isOk2 = 1; int isOk3 = 1; int v_tabseq = box.getInt("p_tabseq"); int v_seq = box.getInt("p_seq"); int v_upfilecnt = box.getInt("p_upfilecnt"); // 서버에 저장되있는 파일수 String v_title = box.getString("p_title"); String v_content = box.getString("p_content"); Vector v_savefile = new Vector(); Vector v_filesequence = new Vector(); System.out.println("upfilecnt == == == == == == == == == == == == == == == == == = > " +v_upfilecnt); for ( int i = 0; i < v_upfilecnt; i++ ) { if ( !box.getString("p_fileseq" + i).equals("")) { v_savefile.addElement(box.getString("p_savefile" + i)); // 서버에 저장되있는 파일명 중에서 삭제할 파일들 v_filesequence.addElement(box.getString("p_fileseq" + i)); // 서버에 저장되있는 파일번호 중에서 삭제할 파일들 } } String s_userid = box.getSession("userid"); String s_usernm = box.getSession("name"); /*********************************************************************************************/ // 나모에디터 본문 처리 (Mime Document Parsing 및 이미지 업로드) /* ConfigSet conf = new ConfigSet(); SmeNamoMime namo = new SmeNamoMime(v_content); // 객체생성 boolean result = namo.parse(); // 실제 파싱 수행 System.out.println(result); if ( !result ) { // 파싱 실패시 System.out.println( namo.getDebugMsg() ); // 디버깅 메시지 출력 return 0; } if ( namo.isMultipart() ) { // 문서가 멀티파트인지 판단 String v_server = conf.getProperty("autoever.url.value"); String fPath = conf.getProperty("dir.namo"); // 파일 저장 경로 지정 String refUrl = conf.getProperty("url.namo");; // 웹에서 저장된 파일을 접근하기 위한 경로 String prefix = "cpCompany" + v_seq; // 파일명 접두어 result = namo.saveFile(fPath, v_server +refUrl, prefix); // 실제 파일 저장 System.out.println(result); } if ( !result ) { // 파일저장 실패시 System.out.println( namo.getDebugMsg() ); // 디버깅 메시지 출력 return 0; } v_content = namo.getContent(); // 최종 컨텐트 얻기 */ /*********************************************************************************************/ try { connMgr = new DBConnectionManager(); connMgr.setAutoCommit(false); sql1 = "update TZ_BOARD set title = ?, content = ?, userid = ?, name = ?, luserid = ?, indate = to_char(sysdate, 'YYYYMMDDHH24MISS')"; // sql1 = "update TZ_BOARD set title = ?, content = empty_clob(), userid = ?, name = ?, luserid = ?, indate = to_char(sysdate, 'YYYYMMDDHH24MISS')"; sql1 += " where tabseq = ? and seq = ?"; pstmt1 = connMgr.prepareStatement(sql1); pstmt1.setString(1, v_title); pstmt1.setString(2, v_content); pstmt1.setString(3, s_userid); pstmt1.setString(4, s_usernm); pstmt1.setString(5, s_userid); pstmt1.setInt(6, v_tabseq); pstmt1.setInt(7, v_seq); isOk1 = pstmt1.executeUpdate(); sql2 = "select content from tz_board where tabseq = " + v_tabseq + " and seq = " + v_seq; // connMgr.setOracleCLOB(sql2, v_content); // (기타 서버 경우) isOk2 = this.insertUpFile(connMgr, v_tabseq, v_seq, box); // 파일첨부했다면 파일table에 insert isOk3 = this.deleteUpFile(connMgr, box, v_filesequence); // 삭제할 파일이 있다면 파일table에서 삭제 if ( isOk1 > 0 && isOk2 > 0 && isOk3 > 0) { connMgr.commit(); if ( v_savefile != null ) { FileManager.deleteFile(v_savefile); // DB 에서 모든처리가 완료되면 해당 첨부파일 삭제 } } else connMgr.rollback(); } catch(Exception ex) { connMgr.rollback(); ErrorManager.getErrorStackTrace(ex, box, sql1); throw new Exception("sql = " + sql1 + "\r\n" + ex.getMessage() ); } finally { if ( pstmt1 != null ) { try { pstmt1.close(); } catch ( Exception e ) { } } if ( connMgr != null ) try { connMgr.setAutoCommit(true); } catch ( Exception e ) { } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e10 ) { } } } return isOk1*isOk2*isOk3; } /** * 선택된 게시물 삭제 * @param box receive from the form object and session * @return isOk 1:delete success,0:delete fail * @throws Exception */ public int deleteQna(RequestBox box) throws Exception { DBConnectionManager connMgr = null; Connection conn = null; PreparedStatement pstmt1 = null; PreparedStatement pstmt2 = null; String sql1 = ""; String sql2 = ""; int isOk1 = 0; int isOk2 = 0; int v_tabseq = box.getInt("p_tabseq"); int v_seq = box.getInt("p_seq"); int v_upfilecnt = box.getInt("p_upfilecnt"); // 서버에 저장되있는 파일수 Vector v_savefile = box.getVector("p_savefile"); // 답변 유무 체크(답변 있을시 삭제불가) if ( this.selectBoard(v_tabseq, v_seq) == 0 ) { try { connMgr = new DBConnectionManager(); connMgr.setAutoCommit(false); sql1 = "delete from TZ_BOARD where tabseq = ? and seq = ? "; pstmt1 = connMgr.prepareStatement(sql1); pstmt1.setInt(1, v_tabseq); pstmt1.setInt(2, v_seq); isOk1 = pstmt1.executeUpdate(); if ( v_upfilecnt > 0 ) { sql2 = "delete from TZ_BOARDFILE where tabseq = ? and seq = ?"; pstmt2 = connMgr.prepareStatement(sql2); pstmt2.setInt(1, v_tabseq); pstmt2.setInt(2, v_seq); isOk2 = pstmt2.executeUpdate(); } else { isOk2 = 1; } if ( isOk1 > 0 && isOk2 > 0) { connMgr.commit(); if ( v_savefile != null ) { FileManager.deleteFile(v_savefile); // 첨부파일 삭제 } } else connMgr.rollback(); } catch ( Exception ex ) { connMgr.rollback(); ErrorManager.getErrorStackTrace(ex, box, sql1); throw new Exception("sql = " + sql1 + "\r\n" + ex.getMessage() ); } finally { if ( pstmt1 != null ) { try { pstmt1.close(); } catch ( Exception e ) { } } if ( pstmt2 != null ) { try { pstmt2.close(); } catch ( Exception e ) { } } if ( connMgr != null ) try { connMgr.setAutoCommit(true); } catch ( Exception e ) { } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e10 ) { } } } } return isOk1*isOk2; } /** * 질문 답변 등록 * @param box receive from the form object and session * @return isOk 1:reply success,0:reply fail * @throws Exception */ public int replyQna(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; Statement stmt = null; PreparedStatement pstmt = null; PreparedStatement pstmt1 = null; String sql = ""; String sql1 = "",sql2 = "", sql3 = ""; int isOk = 1; int isOk1 = 1; int isOk2 = 1; int v_tabseq = box.getInt("p_tabseq"); String v_title = box.getString("p_title"); String v_content = box.getString("p_content"); String v_content1 = ""; String s_userid = box.getSession("userid"); String s_usernm = box.getSession("name"); int v_refseq = box.getInt("p_refseq"); int v_levels = box.getInt("p_levels"); int v_position = box.getInt("p_position"); try { connMgr = new DBConnectionManager(); connMgr.setAutoCommit(false); // 기존 답변글 위치 한칸밑으로 변경 sql = "update TZ_BOARD "; sql += " set position = position + 1 "; sql += " where tabseq = ? "; sql += " and refseq = ? "; sql += " and position > ? "; pstmt = connMgr.prepareStatement(sql); pstmt.setInt(1, v_tabseq); pstmt.setInt(2, v_refseq); pstmt.setInt(3, v_position); isOk = pstmt.executeUpdate(); stmt = connMgr.createStatement(); // ---------------------- 게시판 번호 가져온다 ---------------------------- sql1 = "select nvl(max(seq), 0) from TZ_BOARD where tabseq = " + v_tabseq; ls = connMgr.executeQuery(sql1); ls.next(); int v_seq = ls.getInt(1) + 1; ls.close(); // ------------------------------------------------------------------------------------ /*********************************************************************************************/ // 나모에디터 본문 처리 (Mime Document Parsing 및 이미지 업로드) /* ConfigSet conf = new ConfigSet(); SmeNamoMime namo = new SmeNamoMime(v_content); // 객체생성 boolean result = namo.parse(); // 실제 파싱 수행 if ( !result ) { // 파싱 실패시 System.out.println( namo.getDebugMsg() ); // 디버깅 메시지 출력 return 0; } if ( namo.isMultipart() ) { // 문서가 멀티파트인지 판단 String v_server = conf.getProperty("autoever.url.value"); String fPath = conf.getProperty("dir.namo"); // 파일 저장 경로 지정 String refUrl = conf.getProperty("url.namo");; // 웹에서 저장된 파일을 접근하기 위한 경로 String prefix = "cpCompany" + v_seq; // 파일명 접두어 result = namo.saveFile(fPath, v_server +refUrl, prefix); // 실제 파일 저장 } if ( !result ) { // 파일저장 실패시 System.out.println( namo.getDebugMsg() ); // 디버깅 메시지 출력 return 0; } v_content = namo.getContent(); // 최종 컨텐트 얻기 */ /*********************************************************************************************/ //// //// //// //// //// //// //// //// // 게시판 table 에 입력 //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// /// sql2 = "insert into TZ_BOARD(tabseq, seq, userid, name, indate, title, content, cnt, refseq, levels, position, luserid, ldate) "; sql2 += " values (?, ?, ?, ?, to_char(sysdate, 'YYYYMMDDHH24MISS'), ?, ?, ?, ?, ?, ?, ?, to_char(sysdate, 'YYYYMMDDHH24MISS')) "; // sql2 += " values (?, ?, ?, ?, to_char(sysdate, 'YYYYMMDDHH24MISS'), ?, empty_clob(), ?, ?, ?, ?, ?, to_char(sysdate, 'YYYYMMDDHH24MISS')) "; pstmt1 = connMgr.prepareStatement(sql2); pstmt1.setInt(1, v_tabseq); pstmt1.setInt(2, v_seq); pstmt1.setString(3, s_userid); pstmt1.setString(4, s_usernm); pstmt1.setString(5, v_title); pstmt1.setString(6, v_content); pstmt1.setInt(7, 0); pstmt1.setInt(8, v_refseq); pstmt1.setInt(9, v_levels + 1); pstmt1.setInt(10, v_position + 1); pstmt1.setString(11, s_userid); isOk1 = pstmt1.executeUpdate(); sql3 = "select content from tz_board where tabseq = " + v_tabseq + " and seq = " + v_seq ; // connMgr.setOracleCLOB(sql3, v_content); // (기타 서버 경우) isOk2 = this.insertUpFile(connMgr,v_tabseq, v_seq, box); if ( isOk1 > 0 && isOk2 > 0) connMgr.commit(); else connMgr.rollback(); } catch ( Exception ex ) { connMgr.rollback(); ErrorManager.getErrorStackTrace(ex, box, sql1); throw new Exception("sql = " + sql1 + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e1 ) { } } if ( pstmt1 != null ) { try { pstmt1.close(); } catch ( Exception e1 ) { } } if ( connMgr != null ) try { connMgr.setAutoCommit(true); } catch ( Exception e ) { } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e10 ) { } } } return isOk1*isOk2; } //// //// //// //// //// //// //// //// //// //// //// //// //// /// 파일 테이블 //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// / /** * 새로운 자료파일 등록 * @param connMgr DB Connection Manager * @param p_tabseq 게시판 일련번호 * @param p_seq 게시물 일련번호 * @param box receive from the form object and session * @return isOk 1:insert success,0:insert fail * @throws Exception */ public int insertUpFile(DBConnectionManager connMgr, int p_tabseq, int p_seq, RequestBox box) throws Exception { ListSet ls = null; PreparedStatement pstmt2 = null; String sql = ""; String sql2 = ""; int isOk2 = 1; // ---------------------- 업로드되는 파일의 형식을 알고 코딩해야한다 -------------------------------- String [] v_realFileName = new String [FILE_LIMIT]; String [] v_newFileName = new String [FILE_LIMIT]; for ( int i = 0; i < FILE_LIMIT; i++ ) { v_realFileName [i] = box.getRealFileName(FILE_TYPE + (i +1)); v_newFileName [i] = box.getNewFileName(FILE_TYPE + (i +1)); } // ---------------------------------------------------------------------------------------------------------------------------- String s_userid = box.getSession("userid"); try { // ---------------------- 자료 번호 가져온다 ---------------------------- sql = "select nvl(max(fileseq), 0) from TZ_BOARDFILE where tabseq = " + p_tabseq + " and seq = " + p_seq; ls = connMgr.executeQuery(sql); ls.next(); int v_fileseq = ls.getInt(1) + 1; ls.close(); // ------------------------------------------------------------------------------------ //// //// //// //// //// //// //// //// // 파일 table 에 입력 //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// /// sql2 = "insert into TZ_BOARDFILE(tabseq, seq, fileseq, realfile, savefile, luserid, ldate)"; sql2 += " values (?, ?, ?, ?, ?, ?, to_char(sysdate, 'YYYYMMDDHH24MISS'))"; pstmt2 = connMgr.prepareStatement(sql2); for ( int i = 0; i < FILE_LIMIT; i++ ) { if ( !v_realFileName [i].equals("")) { // 실제 업로드 되는 파일만 체크해서 db에 입력한다 pstmt2.setInt(1, p_tabseq); pstmt2.setInt(2, p_seq); pstmt2.setInt(3, v_fileseq); pstmt2.setString(4, v_realFileName[i]); pstmt2.setString(5, v_newFileName[i]); pstmt2.setString(6, s_userid); isOk2 = pstmt2.executeUpdate(); v_fileseq++; } } } catch ( Exception ex ) { FileManager.deleteFile(v_newFileName, FILE_LIMIT); // 일반파일, 첨부파일 있으면 삭제.. ErrorManager.getErrorStackTrace(ex, box, sql2); throw new Exception("sql = " + sql2 + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( pstmt2 != null ) { try { pstmt2.close(); } catch ( Exception e1 ) { } } } return isOk2; } /** * 선택된 자료파일 DB에서 삭제 * @param connMgr DB Connection Manager * @param box receive from the form object and session * @param p_filesequence 선택 파일 갯수 * @return * @throws Exception */ public int deleteUpFile(DBConnectionManager connMgr, RequestBox box, Vector p_filesequence) throws Exception { PreparedStatement pstmt3 = null; String sql3 = ""; int isOk3 = 1; int v_tabseq = box.getInt("p_tabseq"); int v_seq = box.getInt("p_seq"); try { sql3 = "delete from TZ_BOARDFILE where tabseq = ? and seq =? and fileseq = ?"; pstmt3 = connMgr.prepareStatement(sql3); for ( int i = 0; i < p_filesequence.size(); i++ ) { int v_fileseq = Integer.parseInt((String)p_filesequence.elementAt(i)); pstmt3.setInt(1, v_tabseq); pstmt3.setInt(2, v_seq); pstmt3.setInt(3, v_fileseq); isOk3 = pstmt3.executeUpdate(); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql3); throw new Exception("sql = " + sql3 + "\r\n" + ex.getMessage() ); } finally { if ( pstmt3 != null ) { try { pstmt3.close(); } catch ( Exception e ) { } } } return isOk3; } /** * 삭제시 하위 답변 유무 체크 * @param seq 게시판 번호 * @return result 0 : 답변 없음, 1 : 답변 있음 * @throws Exception */ public int selectBoard(int tabseq, int seq) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; String sql = ""; int result = 0; try { connMgr = new DBConnectionManager(); sql = " select count(*) cnt "; sql += " from "; sql += " (select tabseq, refseq, levels, position "; sql += " from TZ_BOARD "; sql += " where tabseq = " + tabseq; sql += " and seq = " + seq; sql += " ) a, TZ_BOARD b "; sql += " where a.tabseq = b.tabseq "; sql += " and a.refseq = b.refseq "; sql += " and b.levels = (a.levels +1) "; sql += " and b.position = (a.position +1) "; ls = connMgr.executeQuery(sql); if ( ls.next() ) { result = ls.getInt("cnt"); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { }} if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return result; } }
package com.arthur.leetcode; /** * @title: No76 * @Author ArthurJi * @Date: 2021/4/12 10:04 * @Version 1.0 */ public class No76 { public String minWindow(String s, String t) { if (s == null || t == null || s.length() == 0 || t.length() == 0) { return ""; } int left = 0; int right = 0; int start = 0; int size = Integer.MAX_VALUE; int sSize = s.length(); int tSize = t.length(); int count = tSize; int[] freq = new int[128]; for (int i = 0; i < tSize; i++) { freq[t.charAt(i)]++; } while (right < sSize) { if (freq[s.charAt(right)] > 0) { count--; } freq[s.charAt(right)]--; if (count == 0) { while (freq[s.charAt(left)] < 0) { freq[s.charAt(left)]++; left++; } if (right - left + 1 < size) { size = right - left + 1; start = left; } count++; freq[s.charAt(left)]++; left++; } right++; } return size == Integer.MAX_VALUE ? "" : s.substring(start, start + size); } } /* 76. 最小覆盖子串 给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 "" 。 注意:如果 s 中存在这样的子串,我们保证它是唯一的答案。 示例 1: 输入:s = "ADOBECODEBANC", t = "ABC" 输出:"BANC" 示例 2: 输入:s = "a", t = "a" 输出:"a" */ /*简简单单,非常容易理解的滑动窗口思想 Mcdull 发布于 2020-05-23 31.8k 题解 滑动窗口的思想: 用i,j表示滑动窗口的左边界和右边界,通过改变i,j来扩展和收缩滑动窗口,可以想象成一个窗口在字符串上游走,当这个窗口包含的元素满足条件,即包含字符串T的所有元素,记录下这个滑动窗口的长度j-i+1,这些长度中的最小值就是要求的结果。 步骤一 不断增加j使滑动窗口增大,直到窗口包含了T的所有元素 步骤二 不断增加i使滑动窗口缩小,因为是要求最小字串,所以将不必要的元素排除在外,使长度减小,直到碰到一个必须包含的元素,这个时候不能再扔了,再扔就不满足条件了,记录此时滑动窗口的长度,并保存最小值 步骤三 让i再增加一个位置,这个时候滑动窗口肯定不满足条件了,那么继续从步骤一开始执行,寻找新的满足条件的滑动窗口,如此反复,直到j超出了字符串S范围。 面临的问题: 如何判断滑动窗口包含了T的所有元素? 我们用一个字典need来表示当前滑动窗口中需要的各元素的数量,一开始滑动窗口为空,用T中各元素来初始化这个need,当滑动窗口扩展或者收缩的时候,去维护这个need字典,例如当滑动窗口包含某个元素,我们就让need中这个元素的数量减1,代表所需元素减少了1个;当滑动窗口移除某个元素,就让need中这个元素的数量加1。 记住一点:need始终记录着当前滑动窗口下,我们还需要的元素数量,我们在改变i,j时,需同步维护need。 值得注意的是,只要某个元素包含在滑动窗口中,我们就会在need中存储这个元素的数量,如果某个元素存储的是负数代表这个元素是多余的。比如当need等于{'A':-2,'C':1}时,表示当前滑动窗口中,我们有2个A是多余的,同时还需要1个C。这么做的目的就是为了步骤二中,排除不必要的元素,数量为负的就是不必要的元素,而数量为0表示刚刚好。 回到问题中来,那么如何判断滑动窗口包含了T的所有元素?结论就是当need中所有元素的数量都小于等于0时,表示当前滑动窗口不再需要任何元素。 优化 如果每次判断滑动窗口是否包含了T的所有元素,都去遍历need看是否所有元素数量都小于等于0,这个会耗费O(k)O(k)的时间复杂度,k代表字典长度,最坏情况下,k可能等于len(S)。 其实这个是可以避免的,我们可以维护一个额外的变量needCnt来记录所需元素的总数量,当我们碰到一个所需元素c,不仅need[c]的数量减少1,同时needCnt也要减少1,这样我们通过needCnt就可以知道是否满足条件,而无需遍历字典了。 前面也提到过,need记录了遍历到的所有元素,而只有need[c]>0大于0时,代表c就是所需元素 图示 以S="DOABECODEBANC",T="ABC"为例 初始状态: image.png 步骤一:不断增加j使滑动窗口增大,直到窗口包含了T的所有元素,need中所有元素的数量都小于等于0,同时needCnt也是0 image.png 步骤二:不断增加i使滑动窗口缩小,直到碰到一个必须包含的元素A,此时记录长度更新结果 image.png 步骤三:让i再增加一个位置,开始寻找下一个满足条件的滑动窗口 image.png 代码 def minWindow(self, s: str, t: str) -> str: need=collections.defaultdict(int) for c in t: need[c]+=1 needCnt=len(t) i=0 res=(0,float('inf')) for j,c in enumerate(s): if need[c]>0: needCnt-=1 need[c]-=1 if needCnt==0: #步骤一:滑动窗口包含了所有T元素 while True: #步骤二:增加i,排除多余元素 c=s[i] if need[c]==0: break need[c]+=1 i+=1 if j-i<res[1]-res[0]: #记录结果 res=(i,j) need[s[i]]+=1 #步骤三:i增加一个位置,寻找新的满足条件滑动窗口 needCnt+=1 i+=1 return '' if res[1]>len(s) else s[res[0]:res[1]+1] #如果res始终没被更新过,代表无满足条件的结果 我们会用j扫描一遍S,也会用i扫描一遍S,最多扫描2次S,所以时间复杂度是O(n)O(n),空间复杂度为O(k)O(k),k为S和T中的字符集合。 下一篇:最小覆盖子串(双指针:滑动窗口 + HashMap 存字符出现的次数☀)(再看+) © 著作权归作者所有 36 条评论 精选评论(3) nu-li-fen-dou-huo-huo-huo 努力奋斗火火火 2020-09-06 点赞楼主思路!根据楼主思路写的Java版本 class Solution { public String minWindow(String s, String t) { if (s == null || s.length() == 0 || t == null || t.length() == 0){ return ""; } int[] need = new int[128]; //记录需要的字符的个数 for (int i = 0; i < t.length(); i++) { need[t.charAt(i)]++; } //l是当前左边界,r是当前右边界,size记录窗口大小,count是需求的字符个数,start是最小覆盖串开始的index int l = 0, r = 0, size = Integer.MAX_VALUE, count = t.length(), start = 0; //遍历所有字符 while (r < s.length()) { char c = s.charAt(r); if (need[c] > 0) {//需要字符c count--; } need[c]--;//把右边的字符加入窗口 if (count == 0) {//窗口中已经包含所有字符 while (l < r && need[s.charAt(l)] < 0) { need[s.charAt(l)]++;//释放右边移动出窗口的字符 l++;//指针右移 } if (r - l + 1 < size) {//不能右移时候挑战最小窗口大小,更新最小窗口开始的start size = r - l + 1; start = l;//记录下最小值时候的开始位置,最后返回覆盖串时候会用到 } //l向右移动后窗口肯定不能满足了 重新开始循环 //应该是释放左边移动出窗口的字符 need[s.charAt(l)]++; l++; count++; } r++; } return size == Integer.MAX_VALUE ? "" : s.substring(start, start + size); } }*/
/* * 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 chessPackage.board; import chessPackage.pieces.Piece; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * * @author tonip */ public abstract class Tile { protected static int tileCoordenate; private static final Map<Integer, EmptyTile> EMPTY_TILES_CACHE = createAllPossibleEmptyTiles(); private static Map<Integer, EmptyTile> createAllPossibleEmptyTiles() { final Map<Integer, EmptyTile> emptyTileMap = new HashMap<>(); for (int i = 0; i < BoardUtilities.NUM_TILES; i++){ emptyTileMap.put(i, new EmptyTile(i)); } return Collections.unmodifiableMap(emptyTileMap); } public static Tile createTile(final int tileCoordinate, final Piece piece){ return piece != null ? new OccupiedTile(tileCoordenate, piece) : EMPTY_TILES_CACHE.get(tileCoordinate); } protected Tile(final int tileCoordinate) { this.tileCoordenate = tileCoordinate; } public abstract boolean isTileOccupied(); public abstract Piece getPiece(); }
package com.example.agustinuswidiantoro.icp_mobile.activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import com.example.agustinuswidiantoro.icp_mobile.R; import com.example.agustinuswidiantoro.icp_mobile.adapter.BookAdapter; import com.example.agustinuswidiantoro.icp_mobile.model.DataBook; import com.example.agustinuswidiantoro.icp_mobile.util.HttpHandler; import com.example.agustinuswidiantoro.icp_mobile.util.SessionUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; public class BookActivity extends AppCompatActivity { ArrayList<DataBook> dataBooks; ListView listView; private String TAG = BookActivity.class.getSimpleName(); private ProgressDialog pDialog; // URL to get books JSON String url = "http://test.incenplus.com:5000/books?token="; SessionUtils session; Button input_book; RecyclerView mBook; BookAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.content_main); input_book = (Button) findViewById(R.id.btninput_book); input_book.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getApplicationContext(), InsertBookActivity.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK)); finish(); } }); // Session class instance session = new SessionUtils(getApplicationContext()); // get user data from session HashMap<String, String> user = session.getUserDetails(); String token = user.get(SessionUtils.KEY_TOKEN); Log.e(TAG, "Session token: " + token); dataBooks = new ArrayList<>(); new GetBooks().execute(); } /** * Async task class to get json by making HTTP call */ private class GetBooks extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); // Showing progress dialog pDialog = new ProgressDialog(BookActivity.this); pDialog.setMessage("Please wait..."); pDialog.setCancelable(false); pDialog.show(); } @Override protected Void doInBackground(Void... arg0) { HttpHandler sh = new HttpHandler(); // get user data from session HashMap<String, String> user = session.getUserDetails(); String token = user.get(SessionUtils.KEY_TOKEN); // Making a request to url and getting response String jsonStr = sh.makeServiceCall(url + token); Log.e(TAG, "Response from url book : " + jsonStr); if (jsonStr != null) { try { JSONObject jsonObj = new JSONObject(jsonStr); JSONObject data = jsonObj.getJSONObject("data"); // Getting JSON Array node JSONArray books = data.getJSONArray("books"); // looping through All Contacts for (int i = 0; i < books.length(); i++) { JSONObject c = books.getJSONObject(i); String createdAt = c.getString("createdAt"); String description = c.getString("description"); String name_book = c.getString("name"); String id_book = c.getString("id"); JSONObject by = c.getJSONObject("createdBy"); String fullname = by.getString("fullname"); Log.e(TAG, "Book list : " + createdAt + " , " + description + " , " + name_book + " , " + fullname + " , " + id_book); // tmp hash map for single contact // HashMap<String, String> book = new HashMap<>(); DataBook book = new DataBook(id_book, createdAt, fullname, name_book, description); // adding each child node to HashMap key => value //// book.put("id", id_book); // book.put("fullname", fullname); // book.put("id", id_book); // book.put("description", description); // book.put("name", name_book); // adding book to book list dataBooks.add(book); } } catch (final JSONException e) { Log.e(TAG, "Json parsing error 1: " + e.getMessage()); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Json parsing error 2: " + e.getMessage(), Toast.LENGTH_LONG) .show(); } }); } } else { Log.e(TAG, "Couldn't get json from server."); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG) .show(); } }); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); // Dismiss the progress dialog if (pDialog.isShowing()) pDialog.dismiss(); // Setup and Handover data to recyclerview mBook = (RecyclerView) findViewById(R.id.recyclerBook); mAdapter = new BookAdapter(BookActivity.this, dataBooks); mBook.setAdapter(mAdapter); mBook.setLayoutManager(new LinearLayoutManager(BookActivity.this)); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Membaca file menu dan menambahkan isinya ke action bar jika ada. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on the action bar items switch (item.getItemId()) { case R.id.miProfile: startActivity(new Intent(getApplicationContext(), UserProfileActivity.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK)); finish(); return true; default: return super.onOptionsItemSelected(item); } } }
/* * 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. */ import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; /** * * @author hillaryomondi * */ public class Reservation extends javax.swing.JFrame { /** * Creates new form Reservation */ public Reservation() { 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">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jTextField3 = new javax.swing.JTextField(); jTextField4 = new javax.swing.JTextField(); jComboBox1 = new javax.swing.JComboBox<>(); jComboBox2 = new javax.swing.JComboBox<>(); jComboBox3 = new javax.swing.JComboBox<>(); jButtonexit = new javax.swing.JButton(); jButtonDelete = new javax.swing.JButton(); jLabel11 = new javax.swing.JLabel(); jDateChooser1 = new com.toedter.calendar.JDateChooser(); jDateChooser2 = new com.toedter.calendar.JDateChooser(); jComboBox4 = new javax.swing.JComboBox<>(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jButton2 = new javax.swing.JButton(); jLabel14 = new javax.swing.JLabel(); jTextField5 = new javax.swing.JTextField(); jButton3 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); setPreferredSize(new java.awt.Dimension(925, 495)); setResizable(false); getContentPane().setLayout(null); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel1.setText("GUEST RESERVATION"); getContentPane().add(jLabel1); jLabel1.setBounds(190, 10, 195, 30); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel2.setText("FIRST NAME"); getContentPane().add(jLabel2); jLabel2.setBounds(10, 50, 110, 20); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel3.setText("LAST NAME"); getContentPane().add(jLabel3); jLabel3.setBounds(10, 80, 110, 20); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel4.setText("PHONE NO."); getContentPane().add(jLabel4); jLabel4.setBounds(10, 110, 120, 17); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel5.setText("E-MAIL"); getContentPane().add(jLabel5); jLabel5.setBounds(10, 140, 120, 17); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel6.setText("HOTEL BRANCH"); getContentPane().add(jLabel6); jLabel6.setBounds(10, 170, 130, 17); jLabel7.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel7.setText("ROOM TYPE"); getContentPane().add(jLabel7); jLabel7.setBounds(10, 200, 140, 20); jLabel8.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel8.setText("ROOM NO."); getContentPane().add(jLabel8); jLabel8.setBounds(10, 230, 120, 17); jLabel9.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel9.setText("ARRIVAL DATE"); getContentPane().add(jLabel9); jLabel9.setBounds(10, 260, 130, 17); jLabel10.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel10.setText("DEPARTURE DATE"); getContentPane().add(jLabel10); jLabel10.setBounds(10, 290, 130, 20); getContentPane().add(jTextField1); jTextField1.setBounds(190, 50, 160, 20); jTextField2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField2ActionPerformed(evt); } }); getContentPane().add(jTextField2); jTextField2.setBounds(190, 80, 160, 20); jTextField3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField3ActionPerformed(evt); } }); getContentPane().add(jTextField3); jTextField3.setBounds(190, 110, 160, 20); jTextField4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField4ActionPerformed(evt); } }); getContentPane().add(jTextField4); jTextField4.setBounds(190, 140, 160, 20); jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Ole Sarani", "Comfy", "Maya", "Cicada", "Sarova", "Villa Rosa" })); getContentPane().add(jComboBox1); jComboBox1.setBounds(190, 170, 160, 20); jComboBox2.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Presidential suite", "Deluxe room", "Double room", "Single room", "interconnecting room" })); getContentPane().add(jComboBox2); jComboBox2.setBounds(190, 200, 160, 20); jComboBox3.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "001", "002", "003", "004", "005", "006", "007", "008", "009", "010", "011", "012", "013", "014", "015", "016" })); jComboBox3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox3ActionPerformed(evt); } }); getContentPane().add(jComboBox3); jComboBox3.setBounds(190, 230, 160, 20); jButtonexit.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButtonexit.setText("EXIT"); jButtonexit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonexitActionPerformed(evt); } }); getContentPane().add(jButtonexit); jButtonexit.setBounds(660, 450, 70, 25); jButtonDelete.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButtonDelete.setText("DELETE"); jButtonDelete.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonDeleteActionPerformed(evt); } }); getContentPane().add(jButtonDelete); jButtonDelete.setBounds(540, 450, 90, 25); jLabel11.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel11.setText("MEALS"); getContentPane().add(jLabel11); jLabel11.setBounds(10, 320, 50, 17); getContentPane().add(jDateChooser1); jDateChooser1.setBounds(190, 260, 160, 20); getContentPane().add(jDateChooser2); jDateChooser2.setBounds(190, 290, 160, 20); jComboBox4.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "1", "2", "3" })); getContentPane().add(jComboBox4); jComboBox4.setBounds(190, 320, 160, 20); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "FIRST NAME", "LAST NAME", "PHONE NO.", "E-MAIL", "HOTEL BRANCH", "ROOM TYPE", "ROOM NO.", "ARRIVAL DATE", "DEPARTURE DATE", "MEALS" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class, java.lang.Integer.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); jScrollPane1.setViewportView(jTable1); getContentPane().add(jScrollPane1); jScrollPane1.setBounds(410, 30, 452, 340); jButton2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jButton2.setText("TOTAL COST"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); getContentPane().add(jButton2); jButton2.setBounds(270, 450, 120, 23); jLabel14.setText("TOTAL"); getContentPane().add(jLabel14); jLabel14.setBounds(30, 454, 32, 10); getContentPane().add(jTextField5); jTextField5.setBounds(80, 450, 110, 20); jButton3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jButton3.setText("UPDATE"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); getContentPane().add(jButton3); jButton3.setBounds(450, 450, 80, 23); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField3ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField3ActionPerformed private JFrame frame; private void jButtonexitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonexitActionPerformed frame= new JFrame("Exit"); if(JOptionPane.showConfirmDialog(frame,"Confirm if you want to exit","Hilbit Hotels", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_NO_OPTION) System.exit(0); }//GEN-LAST:event_jButtonexitActionPerformed private void jComboBox3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox3ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jComboBox3ActionPerformed private void jButtonDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDeleteActionPerformed DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); if(jTable1.getSelectedRow()==-1){ if(jTable1.getRowCount()==0){ JOptionPane.showMessageDialog(null, "Hotel reservation confirmed","Hilbit Group Of Hotels", JOptionPane.OK_OPTION); } }else{ model.removeRow(jTable1.getSelectedRow()); } }//GEN-LAST:event_jButtonDeleteActionPerformed private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField2ActionPerformed private void jTextField4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField4ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField4ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed DefaultTableModel model=(DefaultTableModel) jTable1.getModel(); model.addRow(new Object[]{ jtxtfirsttName.getText(), jtxtlastName.getText(), jtxtphoneNo.getText(), jtxtemail.getText(), jtxthotelBranch(), jtxtroomType.getText(), jtxtroomNo.getText(), jtxtarrivalDate.getText(), jtxtdepartureDate.getText(), jtxtmeals.getText(), }); }//GEN-LAST:event_jButton2ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed if() } }//GEN-LAST:event_jButton3ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Reservation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Reservation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Reservation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Reservation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Reservation().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButtonDelete; private javax.swing.JButton jButtonexit; private javax.swing.JComboBox<String> jComboBox1; private javax.swing.JComboBox<String> jComboBox2; private javax.swing.JComboBox<String> jComboBox3; private javax.swing.JComboBox<String> jComboBox4; private com.toedter.calendar.JDateChooser jDateChooser1; private com.toedter.calendar.JDateChooser jDateChooser2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel14; 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.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField4; private javax.swing.JTextField jTextField5; // End of variables declaration//GEN-END:variables private long Departure_Date() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
package ua.siemens.dbtool.model.enums; /** * Created by Pavel on 5/23/2017. */ public enum UserRole { USER, ADMIN }
package property; public abstract class AbstractItem { public abstract boolean disposable(); public void hello(){ System.out.println("hello"); } public static void main(String[] main){ AbstractItem i1 = new AbstractItem() {//匿名类 @Override public boolean disposable() { System.out.println("233"); return false; } }; i1.disposable(); } }
package com.example.q7; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.RadioGroup; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio_group); radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { String coach = ""; if(checkedId == R.id.real_madrid) coach = "Zinedine Zidane"; else if(checkedId == R.id.barcelona) coach = "Ernesto Valverde"; else if(checkedId == R.id.liverpool) coach = "Jurgen Klop"; Toast.makeText(MainActivity.this,coach,Toast.LENGTH_LONG).show(); } }); } }
import java.util.ArrayList; import java.util.List; import java.util.Scanner; enum Label {CHEAP, OK, EXPENSIVE}; public class exB2 { public static void main(String[] args) { String courseTitle; int nbrDays = 0; double pricePerDay = 0; boolean priorKnowledgeRequired = true; List<String> instructors = new ArrayList<String>(); double totalPriceToPay = 0; Label courseLabel; instructors.add("Sandy"); instructors.add("Guy"); Scanner sc = new Scanner(System.in); System.out.println("Please enter course title"); courseTitle = sc.nextLine(); System.out.println("Please enter number of days"); nbrDays = Integer.parseInt(sc.nextLine()); System.out.println("Please enter price per day"); pricePerDay = Double.parseDouble(sc.nextLine()); double totalPriceWithoutTVA = nbrDays * pricePerDay; double totalPriceWithTVA = totalPriceWithoutTVA + (totalPriceWithoutTVA * 21/100); System.out.println("\nCourse title: " +courseTitle+ "\nNumber of days: " +nbrDays+ "\nPrice per day: " +pricePerDay+ "\nPrior knowledge requested : " +priorKnowledgeRequired); System.out.println("Number of instructors: " +instructors.size()); if (nbrDays > 3 && priorKnowledgeRequired) { System.out.println("\nTotal price (no taxes to pay) : " +totalPriceWithoutTVA); totalPriceToPay = totalPriceWithoutTVA; } else { System.out.println("\nTotal price : " +totalPriceWithTVA); totalPriceToPay = totalPriceWithTVA; } if (totalPriceToPay < 500) { courseLabel = Label.CHEAP; } else if (totalPriceToPay >= 500 && totalPriceToPay <= 1500) { courseLabel = Label.OK; } else { courseLabel = Label.EXPENSIVE; } System.out.println("\nThis price for this course is " +courseLabel); } }
package fr.pumpmyblock.commands; import java.io.File; import java.io.IOException; import java.util.Map; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import fr.pumpmyblock.utils.IslandUtils; import fr.pumpmyblock.utils.TeamsUtils; public class IslandDispatcherCmd implements CommandExecutor { String[] HELP_ISLAND = {"-----------------------", "/island create", "/island team help", "/island help", "-----------------------"}; String NOT_A_PLAYER = "Joueur introuvable."; String NO_TEAM = "Créez une team avant de créer votre île !"; private boolean onCreateCmd(Player p, Command cmd , String... args) { File userdata = new File("plugins/PumpMyBlock"); File f = new File(userdata + "/" + p.getName() + ".yml"); FileConfiguration playerData = YamlConfiguration.loadConfiguration(f); File[] files = new File("plugins/PumpMyblock").listFiles(); int x = 0; for (int i = 0 ; i < files.length ; i++) { if (files[i].isFile()) { x = x*1000; } } Location islandcreate = new Location(Bukkit.getWorld("pumpmyblockmap"), x , 120, 0); if(userdata.exists()) { IslandUtils.pasteIsland(islandcreate); p.teleport(islandcreate.add(0, 2, 2)); playerData.createSection("islandLoc", (Map<?, ?>) islandcreate); try { playerData.save(f); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else { TeamsUtils.createTeam(p); IslandUtils.pasteIsland(islandcreate); } return true; } private boolean onHelpCmd(Player p, Command cmd , String... args) { p.sendMessage(HELP_ISLAND); return true; } private boolean onTpWorldCmd(Player p, Command cmd , String... args) { p.teleport(new Location(Bukkit.getWorld("pumpmyblockmap"), 0, 150, 0)); p.getLocation().getBlock().getLocation().subtract(0, 3, 0).getBlock().setType(Material.DIRT);; return true; } @Override public boolean onCommand(CommandSender sender, Command cmd, String arg, String[] args) { if(sender instanceof Player) { Player p = (Player) sender; if(cmd.getName().equalsIgnoreCase("island")) { if(args.length >= 1) { if(args[0].equalsIgnoreCase("create")) { return onCreateCmd(p, cmd, args); }else if(args[0].equalsIgnoreCase("tpworld")) { return onTpWorldCmd(p, cmd, args); }else if(args[0].equalsIgnoreCase("help")) { return onHelpCmd(p, cmd, args); } return false; }else { return onHelpCmd(p, cmd, args); } } } return false; } }
package com.changhongit.config; import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; public class Initializer extends AbstractHttpSessionApplicationInitializer{ public Initializer() { super(RedisConfig.class); } }
/** * */ package test; import java.io.File; import java.io.FileNotFoundException; import java.lang.reflect.Method; import java.util.Scanner; import metier.IMetier; import metier.MetierImpl; import dao.DaoImpl; import dao.IDao; /** * @author BALDE Baba-Abdoulaye * * 30 nov. 2016 */ public class Test { /** * @param args */ public static void main(String[] args) { /* * Developpement par reflexion */ // TODO Auto-generated method stub /* * Methode classique */ // IDao dao = new DaoImpl(); // MetierImpl metier= new MetierImpl(); // metier.setDao(dao); // System.out.println(metier.calcul()); Scanner scanner; try { scanner = new Scanner(new File("config.text")); String classDao= scanner.next(); String classMetier=scanner.next(); Class cdao = Class.forName(classDao); IDao objetDao =(IDao)cdao.newInstance(); /* * Utilisation de l'intanciation dynamique */ Class cmetier = Class.forName(classMetier); IMetier objetMetier = (IMetier) cmetier.newInstance(); /* * Invocation de la methode de la classe metierImpl. */ Method method= cmetier.getMethod("setDao" ,new Class[]{IDao.class}); method.invoke(objetMetier, new Object[]{objetDao}); System.out.println(objetMetier.calcul()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.xixiwan.platform.face.feign.order.service.impl; import com.xixiwan.platform.face.feign.order.service.CommonService; import io.shardingsphere.core.keygen.KeyGenerator; import org.apache.commons.lang3.RandomUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; @Service @Transactional public class CommonServiceImpl implements CommonService { @Resource private KeyGenerator keyGenerator; @Override public Long generateKey() { Number key = keyGenerator.generateKey(); return Long.parseLong(String.valueOf(key) + RandomUtils.nextInt(0, 10)); } @Override public Long generateOrderKey() { RandomUtils.nextLong(); return Long.parseLong(String.valueOf(System.currentTimeMillis()) + RandomUtils.nextInt(10000, 100000)); } }
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.sql.*; import javax.swing.*; public class mech extends JFrame implements ActionListener { Connection con; Statement st; ResultSet rs; JLabel l1=new JLabel("MECH DEPARTMENT ISSUES "); JLabel l2=new JLabel("TYPE ISSUE"); JComboBox c1=new JComboBox (); JLabel l3=new JLabel("Teacher Related"); JLabel l4=new JLabel(" Complainted before"); JLabel l5=new JLabel("Give Here Details"); JLabel l6=new JLabel("USER ID"); JTextArea a1=new JTextArea(); JTextField f1=new JTextField(); JComboBox cb=new JComboBox(); JButton b1=new JButton("submit"); JTextField f2=new JTextField(); JLabel background=new JLabel(new ImageIcon("C:\\Users\\Ramandeep Singh\\Pictures\\foto-garage-ag-161525-unsplash (4123).jpg")); public mech() { this.setVisible(true); this.setSize(500,500); add(background); background.add(l1); background.add(l2); background.add(l4); background.add(a1); background.add(f1); background.add(l3); background.add(c1); background.add(l5); background.add(cb); background.add(b1); background.add(l6); background.add(f2); l1.setFont(new Font("Arial",Font.BOLD,50)); l2.setFont(new Font("Arial",Font.BOLD,15)); l3.setFont(new Font("Arial",Font.BOLD,15)); l4.setFont(new Font("Arial",Font.BOLD,15)); l6.setFont(new Font("Arial",Font.BOLD,15)); l5.setFont(new Font("Arial",Font.BOLD,15)); l1.setForeground(Color.CYAN); l1.setBounds(400,0,900,50); l6.setBounds(30,80,140,30); f2.setBounds(200,80,100,30); l2.setBounds(30,120,140,30); l3.setBounds(30,170,140,30); c1.setBounds(200,120,150,30); l4.setBounds(30,570,340,30); l5.setBounds(30,220,140,30); a1.setBounds(200,220,500,300); b1.setBounds(200,620,100,30); f1.setBounds(200,170,100,30); cb.setBounds(200,570,80,30); cb.addItem("Yes"); cb.addItem("No"); c1.addItem("class"); c1.addItem("timetable"); c1.addItem("teacher"); c1.addItem("lab"); c1.addItem("class representer"); c1.addItem("other"); b1.addActionListener(this); c1.setFont(new Font("Arial",Font.BOLD,15)); cb.setFont(new Font("Arial",Font.BOLD,15)); f1.setFont(new Font("Arial",Font.BOLD,15)); f2.setFont(new Font("Arial",Font.BOLD,15)); a1.setFont(new Font("Arial",Font.BOLD,15)); l4.setForeground(Color.CYAN); l5.setForeground(Color.CYAN); l6.setForeground(Color.CYAN); l3.setForeground(Color.CYAN); l2.setForeground(Color.CYAN); l1.setForeground(Color.CYAN); b1.setForeground(Color.CYAN); b1.setForeground(Color.CYAN); b1.setBackground(Color.BLUE); b1.setForeground(Color.cyan); // l6.setBorder(BorderFactory.createLineBorder(Color.WHITE)); //background.setLayout(new FlowLayout()); b1.setBorder(BorderFactory.createLineBorder(Color.WHITE)); try { Class.forName("com.mysql.jdbc.Driver"); con=DriverManager.getConnection("jdbc:mysql://Localhost/project","root","1234"); st=con.createStatement(); } catch(Exception ex) { JOptionPane.showMessageDialog(null,ex.getMessage()); } } public static void main(String[] args) { new mech(); } public void actionPerformed(ActionEvent arg) { if(arg.getSource().equals(b1)) { try { st.executeUpdate("insert into mech values(' "+f2.getText()+" ' ,' "+c1.getSelectedItem()+" ', ' "+cb.getSelectedItem()+" ' ,' "+a1.getText()+" ',' "+f1.getText()+" ' )" ); JOptionPane.showMessageDialog(null, "one complaint added"); } catch(Exception ex) { JOptionPane.showMessageDialog(null, ex.getMessage()); } } } }
package com.muyh.zouzou.utils; import org.apache.commons.lang3.StringUtils; import sun.misc.BASE64Encoder; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StringUtil extends StringUtils { private StringUtil() { } /** 7位ASCII字符,也叫作ISO646-US、Unicode字符集的基本拉丁块 */ public static final String US_ASCII = "US-ASCII"; /** ISO 拉丁字母表 No.1,也叫作 ISO-LATIN-1 */ public static final String ISO_8859_1 = "ISO-8859-1"; /** 8位 UCS 转换格式 */ public static final String UTF_8 = "UTF-8"; /** 16 位 UCS 转换格式,Big Endian(最低地址存放高位字节)字节顺序 */ public static final String UTF_16BE = "UTF-16BE"; /** 16 位 UCS 转换格式,Little-endian(最高地址存放低位字节)字节顺序 */ public static final String UTF_16LE = "UTF-16LE"; /** 16 位 UCS 转换格式,字节顺序由可选的字节顺序标记来标识 */ public static final String UTF_16 = "UTF-16"; /** 中文超大字符集 */ public static final String GBK = "GBK"; /** * Md5加密 * @param string 字符串 * @return 加密后字符串 */ public static final String getMd5(String string) { char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; String s = null; if (isNotBlank(string)) { try { byte[] strTemp = string.getBytes(); MessageDigest mdTemp = MessageDigest.getInstance("MD5"); mdTemp.update(strTemp); byte[] md = mdTemp.digest(); int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } s = new String(str); } catch (NoSuchAlgorithmException e) { s = null; } } return s; } /** * Md5加密 * @param string 字符串 * @return 加密后字符串 */ public static final String getMd5Low(String string) { char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; String s = null; if (isNotBlank(string)) { try { byte[] strTemp = string.getBytes(); MessageDigest mdTemp = MessageDigest.getInstance("MD5"); mdTemp.update(strTemp); byte[] md = mdTemp.digest(); int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } s = new String(str); } catch (NoSuchAlgorithmException e) { s = null; } } return s; } /** * 填充左边字符 * @param source 源字符串 * @param fill 填充字符 * @param len 填充到的长度 * @return 填充后的字符串 */ public static final String fillLeft(String source, char fill, int len) { StringBuffer ret = new StringBuffer(); if (null == source) { ret.append(""); } if (source.length() > len) { ret.append(source); } else { int slen = source.length(); while (ret.toString().length() + slen < len) { ret.append(fill); } ret.append(source); } return ret.toString(); } /** * 填充右边字符 * @param source 源字符串 * @param fill 填充字符 * @param len 填充到的长度 * @return 填充后的字符串 */ public static final String filRight(String source, char fill, int len) { StringBuffer ret = new StringBuffer(); if (null == source) { ret.append(""); } if (source.length() > len) { ret.append(source); } else { ret.append(source); while (ret.toString().length() < len) { ret.append(fill); } } return ret.toString(); } /** * 检测是否特殊字符 * @param str 字符串 * @return 错误提示 */ public static final String check(String str) { StringBuffer error = new StringBuffer(); if (null != str && !"".equals(str.trim())) { char c; for (int i = 0; i < str.length(); i++) { c = str.charAt(i); if (c == '"') { error.append(" 特殊字符[\"]"); } if (c == '\'') { error.append(" 特殊字符[']"); } if (c == '<') { error.append(" 特殊字符[<]"); } if (c == '>') { error.append(" 特殊字符[>]"); } if (c == '&') { error.append(" 特殊字符[&]"); } if (c == '%') { error.append(" 特殊字符[%]"); } if (c == ':' || c == ':') { error.append(" 特殊字符[:]"); } if (c == '*') { error.append(" 特殊字符[*]"); } if (c == '|') { error.append(" 特殊字符[|]"); } } } return error.toString(); } /** * 修改编码 * @param str 字符串 * @param oldCharset 老编码 * @param newCharset 新编码 * @return 修改后的字符串 */ public static final String changeCharset(String str, String oldCharset, String newCharset) { String s = ""; if (str != null) { // 用默认字符编码解码字符串。 byte[] bs = null; try { if (isNotBlank(oldCharset)) { bs = str.getBytes(oldCharset); } else { bs = str.getBytes(); } } catch (UnsupportedEncodingException e) { s = null; } // 用新的字符编码生成字符串 try { s = new String(bs, newCharset); } catch (Exception e) { s = null; } } return s; } /** * 检测是否是中文字符 * @param str * @return */ public static final boolean isChinese(String str) { char[] ch = str.toCharArray(); for (int i = 0; i < ch.length; i++) { char c = ch[i]; if (isChinese(c)) { return true; } } return false; } private static boolean isChinese(char c) { Character.UnicodeBlock ub = Character.UnicodeBlock.of(c); if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) { return true; } return false; } /** * 检测输入数字 * @param str * @return */ public static final boolean isNum(String str) { Pattern pattern = Pattern.compile("^[0-9]*$"); Matcher matcher = pattern.matcher(str); return matcher.matches(); } /** * 检测输入字母 * @param str * @return */ public static final boolean isChar(String str) { Pattern pattern = Pattern.compile("^[A-Za-z]+$"); Matcher matcher = pattern.matcher(str); return matcher.matches(); } /** * 检测输入字母数字 * @param str * @return */ public static final boolean isCharAndNum(String str) { Pattern pattern = Pattern.compile("^[A-Za-z0-9]+$"); Matcher matcher = pattern.matcher(str); return matcher.matches(); } /** * 验证邮箱地址 * @param email * @return */ public static boolean isEmail(String email) { Pattern pattern = Pattern.compile("^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$"); Matcher matcher = pattern.matcher(email); return matcher.matches(); } /** * 验证手机号码 * @param mobile * @return */ public static boolean isMobileNO(String mobile) { Pattern p = Pattern.compile("^1[3|4|5|7|8]\\d{9}$"); Matcher m = p.matcher(mobile); return m.matches(); } /** * IP是否合法 * @param ip * @return */ public static final boolean isIp(String ip) { Pattern p = Pattern.compile("^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$"); Matcher m = p.matcher(ip); return m.matches(); } /** * 邮编是否合法 * @param postcode * @return */ public static final boolean isPostCode(String postcode) { Pattern p = Pattern.compile("[1-9]\\d{5}(?!\\d)"); Matcher m = p.matcher(postcode); return m.matches(); } /** * 密码是否合法 * @param password * @return */ public static final boolean isPassword(String password) { Pattern p = Pattern.compile("^[0-9a-zA-Z_]{6,20}$"); Matcher m = p.matcher(password); return m.matches(); } /** * 身份证是否合法 * @param idcard * @return */ public static final boolean isIdCard(String idcard) { Pattern p = Pattern.compile("^((11|12|13|14|15|21|22|23|31|32|33|34|35|36|37|41|42|43|44|45|46|50|51|52|53|54|61|62|63|64|65|71|81|82|91)\\d{4})((((19|20)(([02468][048])|([13579][26]))0229))|((20[0-9][0-9])|(19[0-9][0-9]))((((0[1-9])|(1[0-2]))((0[1-9])|(1\\d)|(2[0-8])))|((((0[1,3-9])|(1[0-2]))(29|30))|(((0[13578])|(1[02]))31))))((\\d{3}(x|X))|(\\d{4}))$"); Matcher m = p.matcher(idcard); // 身份证第18位校验 boolean flag = getLength(idcard) == 18 && CalculateIdentityUtil.calculate(idcard).equals(idcard.substring(17)); return m.matches() && flag; } /** * 护照是否合法 * @param passport * @return */ public static final boolean isPassport(String passport) { Pattern p1 = Pattern.compile("^[a-zA-Z]{5,17}$"); Pattern p2 = Pattern.compile("^[a-zA-Z0-9]{5,17}$"); Matcher m1 = p1.matcher(passport); Matcher m2 = p2.matcher(passport); return m1.matches() || m2.matches(); } /** * 日期是否合法(严格验证,包括闰年、32号等,只支持1999-1-1或1999/1/1形式的) * @param dateStr * @return */ public static final boolean isDate(String dateStr) { if(StringUtil.isBlank(dateStr)) { return false; } Pattern p = Pattern.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-/]{1}((((0?[13578])|(1[02]))[\\-/]{1}((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-/]{1}((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-/]{1}((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-/]{1}((((0?[13578])|(1[02]))[\\-/]{1}((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-/]{1}((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-/]{1}((0?[1-9])|(1[0-9])|(2[0-8]))))))"); Matcher m = p.matcher(dateStr); // 正则支持形如2016/1-1的,所以要再做一次判断 boolean flag = false; if(dateStr.split("-").length == 3 || dateStr.split("/").length == 3) { flag = true; } return m.matches() && flag; } /** * 获得含有中文字符串长度 * @param str * @return */ public static final int getLength(String str) { int length = 0; /* 获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1 */ if (isNotBlank(str)) { char[] chars = str.toCharArray(); for (int i = 0; i < chars.length; i++) { /* 获取一个字符 */ char temp = chars[i]; /* 判断是否为中文字符 */ if (isChinese(String.valueOf(temp))) { /* 中文字符长度为2 */ length += 2; } else { /* 其他字符长度为1 */ length += 1; } } } return length; } /** * 检查整数 * @param num 被检测数 * @param type "0+":非负整数 "+":正整数 "-0":非正整数 "-":负整数 "":整数 * @return true:是 false:否 */ public static boolean checkNumber(String num, String type) { String eL = ""; if (type.equals("0+")) { eL = "^\\d+$";// 非负整数 } else if (type.equals("+")) { eL = "^\\d*[1-9]\\d*$";// 正整数 } else if (type.equals("-0")) { eL = "^((-\\d+)|(0+))$";// 非正整数 } else if (type.equals("-")) { eL = "^-\\d*[1-9]\\d*$";// 负整数 } else { eL = "^-?\\d+$";// 整数 } Pattern p = Pattern.compile(eL); Matcher m = p.matcher(num); boolean b = m.matches(); return b; } /** * 检查整数 * @param d 被检测数 * @return true:是 false:否 */ public static boolean checkNumber(Double d) { if (0 == d - (int) d.doubleValue()) { return true; } return false; } /** * 检验价格 * @param price 价格 * @param min 最小价格 * @param max 最大价格 * @return */ public static boolean checkPrice(String price,Float min,Float max) { String el = "^(([1-9][0-9]*)|(([0]\\.\\d{1,2}|[1-9][0-9]*\\.\\d{1,2})))$";//两位小数 Pattern p = Pattern.compile(el); Matcher m = p.matcher(price); boolean b = m.matches(); Float fPrice = Float.parseFloat(price); if(b) { if(fPrice >= min && fPrice <= max) { return true; } } return false; } /** * 判断是否为金额 形如1.00 是必须带小数点的 像数字12不认为是金额 * @param str 被检测字符串 * @return */ public static boolean isMoney(String str) { Pattern pattern = Pattern.compile("^(\\-?(0|[1-9]\\d{0,})((\\.[0-9]{1,2}){1}))$"); // 判断小数点后2位的数字的正则表达式 Matcher match = pattern.matcher(str); return match.matches(); } /** * 以"UTF-8"的形式编码 * @param str 待编码的字符串 * @return 编码后的二进制数据 */ public static byte[] getBytes(String str) { byte[] data = null; try { data = str.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { } return data; } /** * 以"UTF-8"的形式解码 * @param data 待解码的二进制数据 * @return 解码后的字符串 */ public static String newString(byte[] data) { String str = null; try { str = new String(data, "UTF-8"); } catch (UnsupportedEncodingException e) { } return str; } public static String urlDecode(String old, String charset) { if (old == null) { return ""; } if (isNotBlank(charset)) { try { return URLDecoder.decode(old, charset); } catch (UnsupportedEncodingException e) { } } return URLDecoder.decode(old); } /** * 格式化银行卡号 如 **** **** **** 4245 * @param bankCardNum 银行卡号 * @return 格式化后的银行卡号 */ public static String formatBankCardNum1(String bankCardNum) { String after4 = ""; if(bankCardNum.length() > 4) { after4 = bankCardNum.substring(bankCardNum.length() - 4); } else { after4 = bankCardNum; } return "**** **** **** " + after4; } /** * 格式化银行卡号 如 **6543 * @param bankCardNum 银行卡号 * @return 格式化后的银行卡号 */ public static String formatBankCardNum2(String bankCardNum) { String after4 = ""; if(bankCardNum.length() > 6) { after4 = bankCardNum.substring(bankCardNum.length() - 4); } else { after4 = bankCardNum; } //后6位的前2位带星 return "**" + after4; } /** * 格式化银行名称 如 邮政储蓄银行... * @param bankName 银行名称 * @return 格式化后的银行名称 */ public static String formatBankName(String bankName) { if(bankName.length() > 6) { return bankName.substring(0, 6) + "..."; } return bankName; } /** * 防止跨站脚本 * @param value * @return */ public static String cleanXSS(String value) { value = value.replaceAll("<", "&lt;").replaceAll(">", "&gt;"); /*value = value.replaceAll("\\(", "&#40;").replaceAll("\\)", "&#41;"); value = value.replaceAll("'", "&#39;"); value = value.replaceAll("eval\\((.*)\\)", ""); value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\""); value = value.replaceAll("script", "");*/ return value; } /** * 抽取数字 * @param value * @return */ public static String extractNumber(String value) { if (isBlank(value)) { return null; } String regEx="[^0-9]"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(value); return m.replaceAll("").trim(); } /** * string转base64 * @return */ public static final String getBase64(String str) { String base64 = null; if (StringUtil.isNotBlank(str)) { BASE64Encoder encode = new BASE64Encoder(); try { base64 = encode.encode(str.getBytes("GB2312")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return base64; } }
package com.flyusoft.apps.jointoil.entity; import java.util.Date; import javax.persistence.MappedSuperclass; import com.flyusoft.common.entity.IdEntity; /**. * 压缩机监控数据的基类 * * @author helin */ @MappedSuperclass public class CompressorMD extends IdEntity { private Date time;// 监控时间, public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } }
package org.apache.hadoop.hdfs; import java.io.IOException; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Random; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.fs.permission.PermissionStatus; import org.apache.hadoop.hdfs.server.blockmanagement.BlockInfo; import org.apache.hadoop.hdfs.server.blockmanagement.IndexedReplica; import org.apache.hadoop.hdfs.server.datanode.Replica; import org.apache.hadoop.hdfs.server.namenode.INode; import org.apache.hadoop.hdfs.server.namenode.INodeFile; import org.apache.hadoop.hdfs.server.namenode.INodeFile; import org.apache.hadoop.hdfs.server.namenode.persistance.EntityManager; import org.apache.hadoop.hdfs.server.namenode.persistance.data_access.entity.BlockInfoDataAccess; import org.apache.hadoop.hdfs.server.namenode.persistance.data_access.entity.InodeDataAccess; import org.apache.hadoop.hdfs.server.namenode.persistance.data_access.entity.ReplicaDataAccess; import org.apache.hadoop.hdfs.server.namenode.persistance.storage.StorageConnector; import org.apache.hadoop.hdfs.server.namenode.persistance.storage.StorageException; import org.apache.hadoop.hdfs.server.namenode.persistance.storage.StorageFactory; import org.apache.hadoop.io.IOUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Salman <salman@sics.se> */ public class TestLongTransactions { public static final Log LOG = LogFactory.getLog(TestLongTransactions.class); HdfsConfiguration conf = null; boolean test_status = true; // means test has passed. in case of error threads will set it to false int wait_time = 10 * 1000; long start_time = 0; boolean test_started = false; // first thread will set it to true. @Before public void initialize() throws Exception { conf = new HdfsConfiguration(); StorageFactory.setConfiguration(conf); StorageFactory.getConnector().formatStorage(); } @After public void close() { } @Test public void testDeleteOnExit() { try { start_time = System.currentTimeMillis(); // just put on row in a table and make two transactins // wait on it insertData(); int waitTime; Runnable w1 = new worker("T1"); Runnable w2 = new worker("T2"); Thread t1 = new Thread(w1); Thread t2 = new Thread(w2); t1.start(); //Thread.sleep(1000); t2.start(); t2.join(); t1.join(); if (!test_status) { fail("Test failed. Two transactions got the write lock at the same time"); } } catch (Exception e) // all exceptions are bad { e.printStackTrace(); fail("Test Failed"); } } private void insertData() throws StorageException { System.out.println("Building the data..."); List<INode> newFiles = new LinkedList<INode>(); INodeFile root; root = new INodeFile(false, new PermissionStatus("salman", "usr", new FsPermission((short) 0777)), (short) 3, 0l, 0l, 0l); root.setId(0); root.setName("/"); root.setParentId(-1); INodeFile dir; dir = new INodeFile(false, new PermissionStatus("salman", "usr", new FsPermission((short) 0777)), (short) 3, 0l, 0l, 0l); dir.setId(1); dir.setName("test_dir"); dir.setParentId(0); INodeFile file; file = new INodeFile(false, new PermissionStatus("salman", "usr", new FsPermission((short) 0777)), (short) 3, 0l, 0l, 0l); file.setId(2); file.setName("file1"); file.setParentId(1); newFiles.add(root); newFiles.add(dir); newFiles.add(file); StorageFactory.getConnector().beginTransaction(); InodeDataAccess da = (InodeDataAccess) StorageFactory.getDataAccess(InodeDataAccess.class); da.prepare(new LinkedList<INode>(), newFiles, new LinkedList<INode>()); StorageFactory.getConnector().commit(); } private class worker implements Runnable { private String name; public worker(String name) { this.name = name; } @Override public void run() { beginTx(); InodeDataAccess da = (InodeDataAccess) StorageFactory.getDataAccess(InodeDataAccess.class); readRowWithRCLock(da, "/", -1); readRowWithRCLock(da, "test_dir", 0); readRowWithRCLock(da, "file1", 1); readRowWithRCLock(da, "/", -1); readRowWithWriteLock(da, "test_dir", 0); commitTx(); } private void beginTx() { try { printMsg("Tx Start"); StorageFactory.getConnector().beginTransaction(); } catch (StorageException e) { test_status = false; System.err.println("Test Failed Begin Tx "); e.printStackTrace(); fail("Test Failed"); } } private void commitTx() { try { printMsg("Commiting"); StorageFactory.getConnector().commit(); } catch (StorageException e) { test_status = false; System.err.println("Test Failed Commit Tx "); e.printStackTrace(); fail("Test Failed"); } } private void readRowWithWriteLock(InodeDataAccess da, String name, long parent_id) { try { StorageFactory.getConnector().writeLock(); INode file = (INodeFile) da.findInodeByNameAndParentId(name, parent_id); printMsg("ReadC Lock " + "pid: " + file.getParentId() + ", id:" + file.getId() + ", name:" + file.getName()); } catch (StorageException e) { test_status = false; System.err.println("Test Failed ReadRowWithWriteLock. name "+name+" paretn_id "+parent_id); e.printStackTrace(); fail("Test Failed"); } } private void readRowWithRCLock(InodeDataAccess da, String name, long parent_id) { try { StorageFactory.getConnector().readCommitted(); INode file = (INodeFile) da.findInodeByNameAndParentId(name, parent_id); printMsg("ReadC Lock " + "pid: " + file.getParentId() + ", id:" + file.getId() + ", name:" + file.getName()); } catch (StorageException e) { test_status = false; System.err.println("Test Failed ReadRowWithRCLock. name "+name+" paretn_id "+parent_id+" exception " ); e.printStackTrace(); fail("Test Failed"); } } private void printReplicas(List<IndexedReplica> replicas) { for (int i = 0; i < replicas.size(); i++) { IndexedReplica replica = replicas.get(i); printMsg(name + " " + replica.toString()); } } private void printMsg(String msg) { System.out.println((System.currentTimeMillis() - start_time) + " " + " " + name + " " + msg); } } }
package com.itobuz.android.awesomechat.navigation; /** * Created by Debasis on 28/12/16. */ public interface RegistrationNavigator extends Navigator { void toLogin(); void attach(RegistrationResultListener registrationResultListener); void detach(RegistrationResultListener registrationResultListener); interface RegistrationResultListener { void onRegistrationSuccess(String statusMessage); void onRegistrationFailed(String statusMessage); } }
package com.lovers.java.domain; public class WorkflowNode { /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column workflow_node.node_id * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ private Integer nodeId; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column workflow_node.node_key * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ private String nodeKey; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column workflow_node.workflow_id * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ private Integer workflowId; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column workflow_node.node_name * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ private String nodeName; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column workflow_node.node_id * * @return the value of workflow_node.node_id * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public Integer getNodeId() { return nodeId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column workflow_node.node_id * * @param nodeId the value for workflow_node.node_id * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public void setNodeId(Integer nodeId) { this.nodeId = nodeId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column workflow_node.node_key * * @return the value of workflow_node.node_key * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public String getNodeKey() { return nodeKey; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column workflow_node.node_key * * @param nodeKey the value for workflow_node.node_key * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public void setNodeKey(String nodeKey) { this.nodeKey = nodeKey == null ? null : nodeKey.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column workflow_node.workflow_id * * @return the value of workflow_node.workflow_id * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public Integer getWorkflowId() { return workflowId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column workflow_node.workflow_id * * @param workflowId the value for workflow_node.workflow_id * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public void setWorkflowId(Integer workflowId) { this.workflowId = workflowId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column workflow_node.node_name * * @return the value of workflow_node.node_name * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public String getNodeName() { return nodeName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column workflow_node.node_name * * @param nodeName the value for workflow_node.node_name * * @mbg.generated Wed Sep 25 10:59:33 CST 2019 */ public void setNodeName(String nodeName) { this.nodeName = nodeName == null ? null : nodeName.trim(); } }
package ru.forpda.example.an21utools.widget; import android.content.Context; import ru.forpda.example.an21utools.R; import ru.forpda.example.an21utools.model.ModelFactory; import ru.forpda.example.an21utools.util.LogHelper; /** * Created by max on 12.11.2014. */ public class MusicWidgetPlay extends MusicWidgetBase { private static LogHelper Log = new LogHelper(MusicWidgetPlay.class); @Override protected int getWidgetId() { return R.layout.widgetmusic_play; } @Override protected int getWidgetCleckabelViewId() { return R.id.widgetMusicImageView; } @Override protected void onClick(Context context) { ModelFactory.getAutoRunModel().getMusicOperation().play(); Log.d("onClick"); } }
package core.event.handlers; import core.event.Event; import core.player.PlayerCompleteServer; import core.server.game.GameDriver; import exceptions.server.game.GameFlowInterruptedException; public interface EventHandler<T extends Event> { public void handle(T event, GameDriver game) throws GameFlowInterruptedException; public Class<T> getEventClass(); public PlayerCompleteServer getPlayerSource(); public void deactivate(/* reactivate callback? */); }
package oops; public class Wrappperclass { public static void main(String[] args) { /* int i=23; Integer iw=new Integer(i);//boxing Integer j=++i;//auto-boxing(internally~Integer j=new Integer(++i); System.out.println(iw); String s="a"; System.out.println(j); int f=Integer.valueOf(j);//unboxing int k=f++;//auto-unboxing */ Add ad=new Add(); ad.print(); } } class Add { Integer i=new Integer(12); Integer j=13; void print() { System.out.println("i is "+i); System.out.println("j is "+j); System.out.println("print sum :"); Integer sum=i+j; System.out.println("sum of "+i+" and "+j+"="+sum); Integer v=Integer.valueOf(sum); System.out.println("value of v="+v); } }
package com.worldchip.bbp.ect.view; import com.worldchip.bbp.ect.R; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.ImageButton; public class MyDialog extends Dialog implements android.view.View.OnClickListener { public interface onCheckListener { public void onYes(); public void onNo(); } private ImageButton mImgBtnYes; private ImageButton mImgBtnNO; public onCheckListener mOnCheckListener; public MyDialog(Context context, onCheckListener mOnCheckListener) { super(context,R.style.Dialog_global); this.mOnCheckListener = mOnCheckListener; } @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.mydialog_content); Window dialogWindow = this.getWindow(); WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); lp.x =20; lp.width = 380; lp.height = 200; dialogWindow.setAttributes(lp); mImgBtnYes = (ImageButton) findViewById(R.id.yes); mImgBtnNO = (ImageButton) findViewById(R.id.no); mImgBtnYes.setOnClickListener(this); mImgBtnNO.setOnClickListener(this); } private void ondraw() { // TODO Auto-generated method stub } @Override public void onClick(View arg0) { // TODO Auto-generated method stub if (arg0.getId() == R.id.yes) { mOnCheckListener.onYes(); } else if (arg0.getId() == R.id.no) { mOnCheckListener.onNo(); } MyDialog.this.dismiss(); } }
package com.java.smm.controller; import com.github.pagehelper.PageInfo; import com.java.domain.Permission; import com.java.service.permission.IPermissionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import java.util.List; /** * @program: ssm_system * @description: 资源控制器 * @author: Gakki * @create: 2020-11-04 13:45 **/ @Controller @RequestMapping("/permission") public class PermissionController { @Autowired private IPermissionService permissionService; @RequestMapping("/findAll.do") public ModelAndView findAll( @RequestParam(name = "page",required = true, defaultValue = "1") Integer page, @RequestParam(name = "page",required = true, defaultValue = "3" ) Integer size ) throws Exception { List<Permission> list = permissionService.findAll(page, size); ModelAndView mv = new ModelAndView(); PageInfo<Permission> pageInfo = new PageInfo<>(list); mv.addObject("pageInfo",pageInfo); mv.setViewName("permission-list"); return mv; } @RequestMapping("/save.do") public String savePermission(Permission permission) throws Exception { permissionService.savePermission(permission); return "redirect:findAll.do"; } }
package by.academy.classwork.lesson4.arrays; import java.util.Arrays; public class Task4class { public static void main(String[] args) { // // 3. Создать двумерный массив типа char размером 4х2. // И записать туда значения с помощью блока для инициализации. // Распечатать значения массива. char [][] array = {{'a','b','c','d'},{'e','f','g','h'}}; System.out.println(Arrays.deepToString (array)); } }
package org.tum.project.callback; import org.tum.project.bean.FifoInfo; import org.tum.project.bean.FlitsInfo; import org.tum.project.bean.PacketTimingInfo; import java.util.HashMap; import java.util.List; import java.util.TreeMap; /** * adapter for data call back * Created by heylbly on 17-6-5. */ public class DataUpdateCallbackAdapter implements DataUpdateCallback { @Override public void updateFLowLatency(HashMap<Long, String> flowChartDataMap, StringBuffer analyzeResult) { } @Override public void updateFifoSizeAnalyze(HashMap<String, List<FifoInfo>> fifoMap, TreeMap<String, List<String>> processData) { } @Override public void updateFlowPacketLatency(HashMap<Integer, List<PacketTimingInfo>> flow_id_to_packetInfo_map) { } @Override public void updateFlitsTraceData(HashMap<Integer, List<HashMap<Integer, List<FlitsInfo>>>> flow_id_to_flits_map) { } }
package listener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import model.Staff; import view.MainWindow; public class OutputListener implements ActionListener { MainWindow mw; @Override public void actionPerformed(ActionEvent e) { if(e.getActionCommand().equals("导出")) { JFileChooser chooser=new JFileChooser(); chooser.showSaveDialog(null); File file=chooser.getSelectedFile(); if (file==null) { return; } ArrayList<Staff> al=new ArrayList<Staff>(); for (int row=0;row<mw.table.getRowCount();row++) { int id=Integer.parseInt(String.valueOf(mw.table.getValueAt(row, 0))); String name=String.valueOf(mw.table.getValueAt(row, 1)); int sex=0; if(mw.table.getValueAt(row, 2).equals("女")) { sex=0; } else { sex=1; } String department=String.valueOf(mw.table.getValueAt(row, 3)); int salary=Integer.parseInt(String.valueOf(mw.table.getValueAt(row, 4))); al.add(new Staff(id,name,sex,department,salary)); } Document document=DocumentHelper.createDocument(); Element root=document.addElement("company"); // File file=new File("src/company.xml"); for (Staff s:al) { Element staff=root.addElement("staff"); Element id=staff.addElement("id"); id.setText(String.valueOf(s.getId())); Element name=staff.addElement("name"); name.setText(s.getName()); Element sex=staff.addElement("sex"); sex.setText(String.valueOf(s.getSex())); Element department=staff.addElement("department"); department.setText(String.valueOf(s.getDepartment())); Element salary=staff.addElement("salary"); salary.setText(String.valueOf(s.getSalary())); } try { BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))); document.write(bw); bw.flush(); bw.close(); JOptionPane.showMessageDialog(null, "导出成功","提示", JOptionPane.INFORMATION_MESSAGE); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } } public OutputListener(MainWindow mw) { super(); this.mw = mw; } }
/* * Copyright © 2020-2022 ForgeRock AS (obst@forgerock.com) * * 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.forgerock.sapi.gateway.uk.common.shared.api.meta.share; import com.forgerock.sapi.gateway.uk.common.shared.api.meta.obie.OBGroupName; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import static com.forgerock.sapi.gateway.uk.common.shared.api.meta.obie.OBGroupName.*; public enum IntentType { ACCOUNT_REQUEST("AR_", AISP), ACCOUNT_ACCESS_CONSENT("AAC_", AISP), PAYMENT_DOMESTIC_CONSENT("PDC_", PISP), PAYMENT_DOMESTIC_SCHEDULED_CONSENT("PDSC_", PISP), PAYMENT_DOMESTIC_STANDING_ORDERS_CONSENT("PDSOC_", PISP), PAYMENT_INTERNATIONAL_CONSENT("PIC_", PISP), PAYMENT_INTERNATIONAL_SCHEDULED_CONSENT("PISC_", PISP), PAYMENT_INTERNATIONAL_STANDING_ORDERS_CONSENT("PISOC_", PISP), PAYMENT_FILE_CONSENT("PFC_", PISP), FUNDS_CONFIRMATION_CONSENT("FCC_", CBPII), DOMESTIC_VRP_PAYMENT_CONSENT("DVRP_", PISP); private String intentIdPrefix; private OBGroupName obGroupName; IntentType(String intentIdPrefix, OBGroupName obGroupName) { this.intentIdPrefix = intentIdPrefix; this.obGroupName = obGroupName; } public static IntentType identify(String intentId) { for (IntentType type : IntentType.values()) { if (intentId.startsWith(type.intentIdPrefix)) { return type; } } return null; } public OBGroupName getObGroupName() { return obGroupName; } public String generateIntentId() { String intentId = intentIdPrefix + UUID.randomUUID().toString(); return intentId.substring(0, Math.min(intentId.length(), 40)); } public static List<IntentType> byOBGroupeName(OBGroupName obGroupName) { return Arrays.asList(IntentType.values()).stream().filter(i -> i.obGroupName == obGroupName).collect(Collectors.toList()); } }
package userRules.cellularMarketModel.math; public class Histogram { public static double[] createHistogram(double[] data) { // find the number of bins using k = 1 + log2N int k = (int) (1 + Math.log(data.length)); // create the bins double[] bins = new double[k]; // find the maximum range double max = findMax(data); // the minimum range double min = findMin(data); // find the range double range = max - min; double binRange = range / ((double)k); int count = 0; // We need a N^2 run time to iterate over // all of the data AND iterate through the bins. for (int i = 0; i < data.length; i++) { for (int j = 0; j < bins.length; j++) { // If the data value is greater than the minimum binRange // and less than the maximum bin range for each bin. if (((data[i]) >= (min + (binRange * (double)j))) && ((data[i]) <= (min + (binRange * ((double)(j + 1)))))) { // Increment the bin count. bins[j]++; count++; } } } double numObservations = data.length; for (int i = 0; i < bins.length; i++) { bins[i] = (((double)bins[i]) / ((double)(numObservations))); } return bins; } private static double findMax(double[] data) { double max = 0; for (double x : data) { if (x > max) { max = x; } } return max; } private static double findMin(double[] data) { double min = data[0]; for (double x : data) { if (x < min) { min = x; } } return min; } }
package de.uulm.in.vs.grn.a2; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.util.Scanner; public class UrlFetcherBin { public static void main(String[] args) { while(true) { System.out.println("URL eingeben:"); Scanner sc = new Scanner(System.in); String adress = sc.nextLine(); System.out.println("Enter Filename"); String filename = sc.nextLine(); URL url; InputStream is = null; String[] parts = adress.split("\\."); System.out.println(parts[parts.length-1]); if(parts[parts.length-1].equals("png") || parts[parts.length-1].equals("jpg") || parts[parts.length-1].equals("pdf")) { filename += "." + parts[parts.length-1]; } else { filename += ".html"; } System.out.println(filename); try { url = new URL(adress); is = url.openStream(); FileOutputStream out = new FileOutputStream(new File(filename)); System.out.println("Downloading ..."); int c = -1; byte[] buffer = new byte[512]; while ((c = is.read(buffer)) > -1) { out.write(buffer, 0, c); } out.close(); is.close(); System.out.println("Download completed"); } catch (MalformedURLException mue) { System.out.println("Ungültige URL"); } catch (IOException ioe) { } } } public static String formate(String adress) { String result = ""; String [] arr = adress.split("\\."); if(!adress.contains("www")){ result = "https://www"; for(int i =0; i<arr.length; i++) { result += "." + arr[i]; } } else { arr[0] = "https://www"; for(int i =0; i<arr.length; i++) { result += arr[i] + "."; } result = result.substring(0,result.length()-1); } return result; } }
package com.activequant.clientsample.utils; import com.activequant.domainmodel.TimeFrame; import com.activequant.domainmodel.TimeStamp; import com.activequant.timeseries.TSContainer2; /** * * @author GhostRider * */ public class EMACalculator { private int period = 0; private TSContainer2 d; private double lambda = 1.0; private double lastEma = 0.0; public double getLastEma() { return lastEma; } // public EMACalculator(int period, TimeFrame timeFrame) { d = new TSContainer2(""); lambda = 2.0 / ((double) period + 1.0); this.period = period; d.setResolutionInNanoseconds(timeFrame.getNanoseconds()); } public void update(TimeStamp ts, Double val) { boolean newVal = false; int cn = d.getNumRows(); d.setValue("VAL", ts, val); if (d.getNumRows() > period * 2) { d.delete(0); newVal = true; } if (cn != d.getNumRows()) newVal = true; // calculate ... if (d.getNumRows() <= period) { // let's calculate the moving average. // ... double sma = 0.0; for (int i = 0; i < d.getNumRows(); i++) { sma += (Double) d.getColumns().get(0).get(i); } sma /= d.getNumRows(); lastEma = sma; d.setValue("EMA", ts, sma); } else { // take the last EMA value and add the current weighted value ... double ema = lambda * val + (1 - lambda) * lastEma; d.setValue("EMA", ts, ema); if (newVal) lastEma = ema; } // if (newVal) // System.out.println(lastEma); } }
package com.esum.framework.queue; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.MessageProducer; import javax.jms.ObjectMessage; import javax.jms.Session; import javax.jms.TextMessage; import junit.framework.TestCase; import org.apache.commons.io.IOUtils; import com.esum.framework.FrameworkSystemVariables; import com.esum.framework.core.component.ComponentConstants; import com.esum.framework.core.config.Configurator; import com.esum.framework.core.management.ManagementConstants; import com.esum.framework.core.management.hornetq.HornetQManager; import com.esum.framework.core.management.mbean.queue.QueueControlMBean; import com.esum.framework.core.queue.QueueHandlerFactory; import com.esum.framework.core.queue.mq.JmsQueueMessageHandler; import com.esum.framework.core.queue.mq.ProducerCallback; import com.esum.framework.jmx.JmxClientTemplate; import com.esum.framework.net.queue.HornetQServer; public class HornetQPersistentTest extends TestCase { protected void setUp(){ System.setProperty("xtrus.home", "D:/test/xtrus-4.3"); try { Configurator.init(System.getProperty("xtrus.home")+"/conf/env.properties"); Configurator.init(Configurator.DEFAULT_DB_PROPERTIES_ID, System.getProperty("xtrus.home")+"/conf/db.properties"); System.setProperty(FrameworkSystemVariables.NODE_ID, Configurator.getInstance().getString("node.id")); System.setProperty(FrameworkSystemVariables.NODE_TYPE, ComponentConstants.LOCATION_TYPE_MAIN); System.setProperty(FrameworkSystemVariables.NODE_CODE, Configurator.getInstance().getString("node.code")); Configurator.init(QueueHandlerFactory.CONFIG_QUEUE_HANDLER_ID, Configurator.getInstance().getString("queue.properties")); HornetQServer.getInstance().start(); HornetQManager.getInstance().initializeMBeanList(); } catch (Exception e) { fail(e.getMessage()); } } protected void tearDown(){ try { HornetQServer.getInstance().stop(); } catch (Exception e) { } } public void testPersistent1() throws Exception{ JmxClientTemplate jmxClient = JmxClientTemplate.createJmxClient("localhost", 9026); QueueControlMBean mbean = jmxClient.query(ManagementConstants.OBJECT_NAME_QUEUE_CONTROL, QueueControlMBean.class); mbean.createQueue("IN_LOGGER_CHANNEL1", true); jmxClient.close(); JmsQueueMessageHandler queueHandler = (JmsQueueMessageHandler)QueueHandlerFactory.getInstance("IN_LOGGER_CHANNEL1"); String data = IOUtils.toString(getClass().getResourceAsStream("/data/test.xml")); // 1.send to queue for(int i=0;i<10;i++){ queueHandler.send(new com.esum.framework.queue.TextMessage("test".getBytes())); } // 2.message count System.out.println("=================================================="); System.out.println("Queue Message Count : "+queueHandler.count()); System.out.println("=================================================="); queueHandler.close(); } public void testPersistent2() throws Exception{ JmsQueueMessageHandler queueHandler = (JmsQueueMessageHandler)QueueHandlerFactory.getInstance("IN_LOGGER_CHANNEL1"); // 1.message count System.out.println("=================================================="); System.out.println("Queue Message Count : "+queueHandler.count()); System.out.println("=================================================="); queueHandler.close(); } public void testPersistent3() throws Exception{ JmsQueueMessageHandler queueHandler = (JmsQueueMessageHandler)QueueHandlerFactory.getInstance("IN_LOGGER_CHANNEL1"); // 1. get message queueHandler.setMessageListener(new MessageListener() { @Override public void onMessage(Message message) { try { if(message instanceof TextMessage) { TextMessage t = (TextMessage)message; System.out.println("TEXT : "+t.getText()); } else if(message instanceof ObjectMessage) { com.esum.framework.queue.TextMessage ot = (com.esum.framework.queue.TextMessage)((ObjectMessage)message).getObject(); System.out.println(new String(ot.getMessage())); } } catch (Exception e){ e.printStackTrace(); } finally { try { message.acknowledge(); } catch (JMSException e) { } } } }); Thread.sleep(5*1000); queueHandler.close(); } }