text
stringlengths
10
2.72M
package android.support.v4.widget; import android.view.animation.Animation; import android.view.animation.Transformation; class l$1 extends Animation { final /* synthetic */ l$a Ai; final /* synthetic */ l Aj; l$1(l lVar, l$a l_a) { this.Aj = lVar; this.Ai = l_a; } public final void applyTransformation(float f, Transformation transformation) { if (this.Aj.Ah) { l.b(f, this.Ai); return; } float b = l.b(this.Ai); float f2 = this.Ai.As; float f3 = this.Ai.Ar; float f4 = this.Ai.At; l.c(f, this.Ai); if (f <= 0.5f) { float f5 = 0.8f - b; this.Ai.D(f3 + (l.cJ().getInterpolation(f / 0.5f) * f5)); } if (f > 0.5f) { this.Ai.E(((0.8f - b) * l.cJ().getInterpolation((f - 0.5f) / 0.5f)) + f2); } this.Ai.setRotation((0.25f * f) + f4); this.Aj.setRotation((216.0f * f) + (1080.0f * (l.a(this.Aj) / 5.0f))); } }
package kodlama.io.hrms.api.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import kodlama.io.hrms.business.abstracts.CityService; import kodlama.io.hrms.core.utilities.results.DataResult; import kodlama.io.hrms.entities.concretes.City; @RestController @RequestMapping("/app/city") @CrossOrigin public class CitiesController { private CityService cityService; @Autowired public CitiesController(CityService cityService) { super(); this.cityService = cityService; } @GetMapping("getById") public DataResult<City> getById(@RequestParam int id){ return this.cityService.getById(id); } @GetMapping("getAll") public DataResult<List<City>> getAll(){ return this.cityService.getAll(); } }
import java.util.*; import java.io.*; public class cfedu46b{ public static void main(String [] args) throws IOException{ InputReader in = new InputReader("cfedu46b.in"); int n = in.nextInt(); int m = in.nextInt(); HashSet<Pair> set = new HashSet<Pair>(); int [] arr = new int[n]; Pair [] p = new Pair[n - 1]; for(int i = 0; i < arr.length; i++){ arr[i] = in.nextInt(); if(i > 0) p[i - 1] = new Pair(arr[i - 1], arr[i], 0); } if(p.length > 1) set.add(p[0]); if(arr[0] == 1 && arr.length > 1 && arr[1] != 2){ set.add(new Pair(arr[0], arr[1], 1)); } else if(arr[0] != 1){ set.add(new Pair(arr[0] - 1, arr[0], 1)); } while(!set.isEmpty()){ HashSet<Pair> } } static class Pair{ public int x, y; public int s; public Pair(int x, int y, int i){ this.x = x; this.y = y; s = i; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(String s) { try{ reader = new BufferedReader(new FileReader(s), 32768); } catch (Exception e){ reader = new BufferedReader(new InputStreamReader(System.in), 32768); } tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
package com.team_linne.digimov.mapper; import com.team_linne.digimov.dto.MovieSessionResponse; import com.team_linne.digimov.dto.OrderRequest; import com.team_linne.digimov.dto.OrderResponse; import com.team_linne.digimov.model.Order; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Component; @Component public class OrderMapper { public Order toEntity(OrderRequest orderRequest) { Order order = new Order(); BeanUtils.copyProperties(orderRequest,order); order.setCreditCardNumber(orderRequest.getCreditCardInfo().getNumber()); return order; } public OrderResponse toResponse(Order order, MovieSessionResponse movieSession) { OrderResponse orderResponse = new OrderResponse(); BeanUtils.copyProperties(order,orderResponse); orderResponse.setMovieSession(movieSession); return orderResponse; } }
package UnitTests; import java.awt.Color; import org.junit.Test; import Elements.*; import Geometries.*; import Primitives.*; import Renderer.*; import Scene.*; public class RenderTest { @Test public void renderingTest1(){ Scene scene = new Scene(); scene.addGeometry(new Sphere(50, new Point3D(new Coordinate(0), new Coordinate(0), new Coordinate(-149)))); Triangle triangle = new Triangle(new Point3D( new Coordinate(100), new Coordinate(0), new Coordinate(-149)), new Point3D(new Coordinate(0), new Coordinate(100), new Coordinate(-149)), new Point3D( new Coordinate(100), new Coordinate(100), new Coordinate(-149))); Triangle triangle2 = new Triangle(new Point3D( new Coordinate(100), new Coordinate(0), new Coordinate(-149)), new Point3D(new Coordinate(0), new Coordinate(-100), new Coordinate(-149)), new Point3D( new Coordinate(100), new Coordinate(-100), new Coordinate(-149))); Triangle triangle3 = new Triangle(new Point3D(new Coordinate(-100), new Coordinate(0), new Coordinate(-149)), new Point3D( new Coordinate(0), new Coordinate(100), new Coordinate(-149)), new Point3D(new Coordinate(-100), new Coordinate(100), new Coordinate(-149))); Triangle triangle4 = new Triangle(new Point3D(new Coordinate(-100), new Coordinate(0), new Coordinate(-149)), new Point3D( new Coordinate(0), new Coordinate(-100), new Coordinate(-149)), new Point3D(new Coordinate(-100), new Coordinate(-100), new Coordinate(-149))); scene.addGeometry(triangle); scene.addGeometry(triangle2); scene.addGeometry(triangle3); scene.addGeometry(triangle4); ImageWriter imageWriter = new ImageWriter("RenderTest_1", 500, 500, 500, 500); Render render = new Render(scene, imageWriter); render.renderImage(); render.printGrid(50); render.get_imageWriter().writeToImage(); } @Test public void renderingTest2(){ Scene scene = new Scene(); scene.set_ambientLight(new AmbientLight(Color.blue,0.8)); scene.addGeometry(new Sphere(100, new Point3D(new Coordinate(0), new Coordinate(0), new Coordinate(-149)))); Triangle triangle = new Triangle(new Point3D( new Coordinate(100), new Coordinate(0), new Coordinate(-149)), new Point3D(new Coordinate(0), new Coordinate(100), new Coordinate(-149)), new Point3D( new Coordinate(100), new Coordinate(100), new Coordinate(-149))); Triangle triangle2 = new Triangle(new Point3D( new Coordinate(100), new Coordinate(0), new Coordinate(-149)), new Point3D(new Coordinate(0), new Coordinate(-100), new Coordinate(-149)), new Point3D( new Coordinate(100), new Coordinate(-100), new Coordinate(-149))); Triangle triangle3 = new Triangle(new Point3D(new Coordinate(-100), new Coordinate(0), new Coordinate(-149)), new Point3D( new Coordinate(0), new Coordinate(100), new Coordinate(-149)), new Point3D(new Coordinate(-100), new Coordinate(100), new Coordinate(-149))); Triangle triangle4 = new Triangle(new Point3D(new Coordinate(-100), new Coordinate(0), new Coordinate(-149)), new Point3D( new Coordinate(0), new Coordinate(-100), new Coordinate(-149)), new Point3D(new Coordinate(-100), new Coordinate(-100), new Coordinate(-149))); scene.addGeometry(triangle); scene.addGeometry(triangle2); scene.addGeometry(triangle3); scene.addGeometry(triangle4); ImageWriter imageWriter = new ImageWriter("RenderTest_2", 500, 500, 500, 500); Render render = new Render(scene, imageWriter); render.renderImage(); render.printGrid(10); render.get_imageWriter().writeToImage(); } @Test public void renderingTest3(){ Scene scene = new Scene(); scene.set_ambientLight(new AmbientLight(Color.white,0.1)); scene.addGeometry(new Sphere(50, new Point3D(new Coordinate(0), new Coordinate(0), new Coordinate(-150)))); Triangle triangle = new Triangle(Color.red,new Point3D( new Coordinate(100), new Coordinate(0), new Coordinate(-149)), new Point3D(new Coordinate(0), new Coordinate(100), new Coordinate(-149)), new Point3D( new Coordinate(100), new Coordinate(100), new Coordinate(-149))); Triangle triangle2 = new Triangle(Color.green,new Point3D( new Coordinate(100), new Coordinate(0), new Coordinate(-149)), new Point3D(new Coordinate(0), new Coordinate(-100), new Coordinate(-149)), new Point3D( new Coordinate(100), new Coordinate(-100), new Coordinate(-149))); Triangle triangle3 = new Triangle(Color.orange,new Point3D(new Coordinate(-100), new Coordinate(0), new Coordinate(-149)), new Point3D( new Coordinate(0), new Coordinate(100), new Coordinate(-149)), new Point3D(new Coordinate(-100), new Coordinate(100), new Coordinate(-149))); Triangle triangle4 = new Triangle(Color.pink,new Point3D(new Coordinate(-100), new Coordinate(0), new Coordinate(-149)), new Point3D( new Coordinate(0), new Coordinate(-100), new Coordinate(-149)), new Point3D(new Coordinate(-100), new Coordinate(-100), new Coordinate(-149))); scene.addGeometry(triangle); scene.addGeometry(triangle2); scene.addGeometry(triangle3); scene.addGeometry(triangle4); ImageWriter imageWriter = new ImageWriter("RenderTest_3", 500, 500, 500, 500); Render render = new Render(scene, imageWriter); render.renderImage(); render.printGrid(55); render.get_imageWriter().writeToImage(); } @Test public void renderingTest4(){ Scene scene = new Scene(); scene.set_ambientLight(new AmbientLight(Color.red,0.3)); scene.addGeometry(new Sphere(50, new Point3D(new Coordinate(0), new Coordinate(0), new Coordinate(-150)))); Triangle triangle = new Triangle(new Point3D( new Coordinate(100), new Coordinate(0), new Coordinate(-149)), new Point3D(new Coordinate(0), new Coordinate(100), new Coordinate(-149)), new Point3D( new Coordinate(100), new Coordinate(100), new Coordinate(-149))); Triangle triangle2 = new Triangle(Color.green,new Point3D( new Coordinate(100), new Coordinate(0), new Coordinate(-149)), new Point3D(new Coordinate(0), new Coordinate(-100), new Coordinate(-149)), new Point3D( new Coordinate(100), new Coordinate(-100), new Coordinate(-149))); Triangle triangle3 = new Triangle(Color.orange,new Point3D(new Coordinate(-100), new Coordinate(0), new Coordinate(-149)), new Point3D( new Coordinate(0), new Coordinate(100), new Coordinate(-149)), new Point3D(new Coordinate(-100), new Coordinate(100), new Coordinate(-149))); Triangle triangle4 = new Triangle(Color.pink,new Point3D(new Coordinate(-100), new Coordinate(0), new Coordinate(-149)), new Point3D( new Coordinate(0), new Coordinate(-100), new Coordinate(-149)), new Point3D(new Coordinate(-100), new Coordinate(-100), new Coordinate(-149))); scene.addGeometry(triangle); scene.addGeometry(triangle2); scene.addGeometry(triangle3); scene.addGeometry(triangle4); ImageWriter imageWriter = new ImageWriter("RenderTest_4", 500, 500, 500, 500); Render render = new Render(scene, imageWriter); render.renderImage(); render.printGrid(55); render.get_imageWriter().writeToImage(); } @Test public void testAddingLightSources(){ PointLight pl = new PointLight(new PointLight(new Color(255,100,100), new Point3D(new Coordinate(-200), new Coordinate(-200), new Coordinate(-100)), 0, 0.000001, 0.0000005)); SpotLight sl = new SpotLight(new SpotLight(new Color(255, 100, 100), new Point3D(new Coordinate(-200), new Coordinate(-200), new Coordinate(-100)), 0, 0.00001, 0.000005, new Vector())); DirectionalLight dl = new DirectionalLight(new Color(255, 100, 100),new Vector()); } }
package com.legalzoom.api.test.dto; /** * */ public class CreateOrderIdDTO implements DTO { private String orderId; //pkOrder from Order private boolean showOrderItemTree; public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public boolean isShowOrderItemTree() { return showOrderItemTree; } public void setShowOrderItemTree(boolean showOrderItemTree) { this.showOrderItemTree = showOrderItemTree; } }
package oicq.wlogin_sdk.a; public final class f extends a { int vJe; public f() { this.vJe = 0; this.vIl = 260; } public final byte[] bY(byte[] bArr) { this.vJe = bArr.length; Object obj = new byte[this.vJe]; System.arraycopy(bArr, 0, obj, 0, bArr.length); super.IE(this.vIl); super.Z(obj, this.vJe); super.cKe(); return super.cKa(); } }
package com.sanchezquality.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.sanchezquality.entity.Pais; import com.sanchezquality.repository.PaisRepository; @Service @Transactional(readOnly = true) public class PaisService { @Autowired PaisRepository paisRepository; public List<Pais> findAll(){ return paisRepository.findAll(); } }
package uo.sdi.business.impl.task.command; import uo.sdi.business.exception.BusinessException; import uo.sdi.infrastructure.Factories; public class DeleteCategoryCommand{ private Long catId; public DeleteCategoryCommand(Long catId) { this.catId = catId; } public Void execute() throws BusinessException { Factories.persistence.getTaskDao().deleteAllFromCategory( catId ); Factories.persistence.getCategoryDao().delete( catId ); return null; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package mvirtual.catalog.heritage; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ActionContext; import org.mvirtual.persistence.entity.Heritage; import org.hibernate.Session; import org.hibernate.Transaction; import mvirtual.catalog.SessionNames; import java.util.Map; /** * * @author fabricio */ public class SaveHeritage extends ActionSupport { @Override public String execute () { Map <String, Object> httpSession = ActionContext.getContext().getSession(); Heritage heritage = (Heritage) httpSession.get (SessionNames.HERITAGE); Session dbSession = (Session) httpSession.get (SessionNames.HERITAGE_DB_SESSION); Transaction dbTransaction = (Transaction) httpSession.get (SessionNames.HERITAGE_DB_TRANSACTION); dbSession.save (heritage); dbTransaction.commit (); dbSession.close (); httpSession.put (SessionNames.HERITAGE, null); httpSession.put (SessionNames.HERITAGE_DB_SESSION, null); httpSession.put (SessionNames.HERITAGE_DB_TRANSACTION, null); httpSession.put (SessionNames.HERITAGE_OPERATION, null); return SUCCESS; } }
package com.mathpar.students.ukma.Morenets.MPI_3; import java.util.Arrays; import mpi.MPI; import mpi.MPIException; public class MPI_3_13 { public static void main(String[] args) throws MPIException { MPI.Init(args); int myrank = MPI.COMM_WORLD.getRank(); int n = Integer.parseInt(args[0]); int[] a = new int[n]; int size = MPI.COMM_WORLD.getSize(); for (int i = 0; i < n; i++) a[i] = i; System.out.println("myrank = " + myrank + ": a = " + Arrays.toString(a)); int[] q = new int[n]; int[] recvSizes = new int[size]; Arrays.fill(recvSizes, 1); MPI.COMM_WORLD.reduceScatter(a, q, recvSizes, MPI.INT, MPI.SUM); if (myrank == 0) System.out.println("myrank = " + myrank + ": q = " + Arrays.toString(q)); MPI.Finalize(); } } /* Command: mpirun -np 4 java -cp out/production/MPI_3_13 MPI_3_13 4 Output: myrank = 2: a = [0, 1, 2, 3] myrank = 3: a = [0, 1, 2, 3] myrank = 0: a = [0, 1, 2, 3] myrank = 1: a = [0, 1, 2, 3] myrank = 0: q = [0, 0, 0, 0] */
package assemAssist.model.factoryline.assemblyLine; import java.util.Collection; import org.joda.time.Duration; import assemAssist.model.clock.clock.Clock; import assemAssist.model.company.VehicleModel; import assemAssist.model.operations.task.Task; import assemAssist.model.order.order.Order; /** * A virtual assembly line to calculate the estimated completion date for * {@link Order}s. It does not finish the {@link Task}s of the orders. * * @author SWOP Group 3 * @version 3.0 */ public final class VirtualAssemblyLine extends ModifiableAssemblyLine { /** * Initialises this virtual assembly line with the given {@link Clock}. * * @param clock * @throws IllegalArgumentException * @see AssemblyLine */ public VirtualAssemblyLine(Clock clock, Collection<VehicleModel> producableModels) throws IllegalArgumentException { super(clock, producableModels); } /** * The virtual assembly line can always move because the tasks need not to * be completed. * * @return True */ @Override protected boolean canMove() { return true; } /** * Sets the estimation date of the given order to the current time. */ @Override protected void setDate(Order order) { order.getModifiableOrder().setEstDate(getClock().getTime()); } /** * Returns the worked time. */ @Override public Duration getWorkedTime() { return getExpectedTimeOfStep(); } }
package com.tencent.mm.plugin.mmsight.segment.a; import android.os.Looper; import android.view.Surface; import com.tencent.mm.plugin.mmsight.segment.a.a.a; import com.tencent.mm.plugin.mmsight.segment.a.a.c; import com.tencent.mm.plugin.mmsight.segment.a.a.d; import com.tencent.mm.plugin.u.i; import com.tencent.mm.plugin.u.j; import com.tencent.mm.sdk.platformtools.x; public final class b implements a { boolean Fd = false; boolean bTv = false; boolean dGv = false; int lnA; int lnB = 0; private int lnC = 0; a lnD; d lnE; com.tencent.mm.plugin.mmsight.segment.a.a.b lnF; c lnG; i lnz = new i(Looper.getMainLooper()); public b() { i iVar = this.lnz; if (iVar.ldy != null) { j jVar = iVar.ldy; if (jVar.ldg != null) { jVar.ldg.lda = false; } } this.lnz.setNeedResetExtractor(false); this.lnz.ldz = new 1(this); } public final void setSurface(Surface surface) { this.lnz.setSurface(surface); } public final void setDataSource(String str) { this.lnz.setPath(str); } public final void prepareAsync() { this.lnz.bdz(); } public final void start() { if (this.Fd) { this.lnz.start(); } this.bTv = true; } public final void stop() { this.lnz.ldy.stop(); this.bTv = false; } public final void pause() { this.lnz.pause(); } public final boolean isPlaying() { return this.lnz.isPlaying(); } public final void seekTo(int i) { if (this.lnz != null) { x.i("MicroMsg.MMSegmentVideoPlayer", "seekTo: %s", new Object[]{Integer.valueOf(i)}); this.lnz.sG(i); } } public final int getCurrentPosition() { return this.lnz.bdA(); } public final int getDuration() { return (int) this.lnz.ldy.aqC; } public final void release() { this.lnz.release(); } public final void setAudioStreamType(int i) { } public final void setLooping(boolean z) { this.dGv = z; } public final void setLoop(int i, int i2) { this.lnB = i; this.lnC = i2; } public final void a(com.tencent.mm.plugin.mmsight.segment.a.a.b bVar) { this.lnF = bVar; } public final void a(c cVar) { this.lnG = cVar; } public final void a(d dVar) { this.lnE = dVar; } public final void a(a aVar) { this.lnD = aVar; } }
package com.epam.bar.command.impl; import com.epam.bar.command.*; import com.epam.bar.command.marker.UserCommandMarker; import com.epam.bar.entity.Cocktail; import com.epam.bar.entity.Review; import com.epam.bar.entity.User; import com.epam.bar.exception.ServiceException; import com.epam.bar.service.ReviewService; import com.epam.bar.util.LocalizationMessage; import com.epam.bar.validator.ChainValidator; import com.epam.bar.validator.impl.FeedbackValidator; import com.epam.bar.validator.impl.NumberValidator; import com.epam.bar.validator.impl.RateValidator; import lombok.extern.log4j.Log4j2; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * Review of the {@link Cocktail} from the {@link User} * * @author Kirill Karalionak * @version 1.0.0 */ @Log4j2 public class RestAddReviewCommand implements Command, UserCommandMarker { private final ReviewService service; /** * @param service the service */ public RestAddReviewCommand(ReviewService service) { this.service = service; } @Override public CommandResult execute(RequestContext requestContext) { CommandResult commandResult; String feedback = requestContext.getRequestParameters().get(RequestParameter.FEEDBACK); String rate = requestContext.getRequestParameters().get(RequestParameter.RATE); ChainValidator validator = new NumberValidator(rate, new RateValidator(Integer.parseInt(rate), new FeedbackValidator(feedback))); Optional<String> serverMessage = validator.validate(); if (serverMessage.isEmpty()) { User user = (User) requestContext.getSessionAttributes().get(RequestParameter.USER); Cocktail cocktail = (Cocktail) requestContext.getSessionAttributes().get(RequestParameter.COCKTAIL); Review review = Review.builder() .withFeedback(feedback) .withCocktail(cocktail) .withRate(Integer.parseInt(rate)) .withAuthor(user) .build(); try { service.addReview(review); commandResult = new CommandResult(Map.of(RequestAttribute.REDIRECT_COMMAND, CommandType.TO_COCKTAIL_VIEW.getCommandName(), RequestAttribute.COCKTAIL_ID, cocktail.getId()), new HashMap<>()); } catch (ServiceException e) { log.error("Review add failed" + e); commandResult = new CommandResult(Map.of(RequestAttribute.REDIRECT_COMMAND, CommandType.ERROR.getCommandName()), new HashMap<>()); } } else { commandResult = new CommandResult(Map.of(RequestAttribute.SERVER_MESSAGE, LocalizationMessage.localize(requestContext.getLocale(), serverMessage.get())), new HashMap<>()); } return commandResult; } }
package edu.luc.cs271.wordcount; import java.util.Collections; import java.util.Iterator; import java.util.Map; /** A map-based class for counting word frequencies from an iterator. */ public class WordCounter { /** The map for storing the word counts. */ private final Map<String, Integer> theMap; /** Creates a word counter instance based on the given map. */ public WordCounter(final Map<String, Integer> theMap) { // TODO // DONE this.theMap = theMap; } /** Counts the frequencies of all words in the given iterator. */ public void countWords(final Iterator<String> words) { // TODO for each word in the iterator, update the corresponding frequency in the map // HINT to do this without a conditional, use the getOrDefault method // DONE, but check later int counter = 0; while (words.hasNext()) { String str = words.next(); str.toLowerCase(); if (theMap.containsKey(str)) { counter = theMap.get(str); theMap.put(str, counter + 1); } else theMap.put(str, 1); // Didn't work VVVV //while (words.hasNext()) { // String str = words.next(); // str = str.toLowerCase(); // Integer someInt = this.theMap.getOrDefault(str, 0); // this.theMap.put(str, someInt++); } } /** Retrieve the frequency of a particular word. */ public int getCount(final String word) { // TODO // DONE int count = 0; if (theMap.containsKey(word)) { count = theMap.get(word); theMap.put(word, count); } else { theMap.put(word, 0); } return count; } /** Retrieve the map representing all word frequencies. */ public Map<String, Integer> getCounts() { return Collections.unmodifiableMap(theMap); } }
/** * @author André Pinto * * Esta classe faz a conexão com o Banco de Dados, e tem método para fechar a conexão, insere usuário no Banco de Dados, * pesquisa todos os usuários, pesquisa os administradores, pesquisa por email um único usuário, altera o status de administrador * de um único usuário, e também faz o login do usuário cadastrado */ package br.com.fiap.ston.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import br.com.fiap.ston.beans.Usuario; import br.com.fiap.ston.conexao.ConexaoFactory; public class UsuarioDAO { private Connection conexao; public UsuarioDAO() { try { this.conexao = new ConexaoFactory().getConnection(); } catch (Exception e) { e.printStackTrace(); System.out.println("Erro de conexão com o BD"); } } public void fechar() { try { conexao.close(); } catch(Exception e) { e.printStackTrace(); System.out.println("Erro ao fechar a Conexão da UsuarioDAO"); } } public void inserir(Usuario user) { try { if(this.pesquisarPorEmail(user.getEmail()) != null) { throw new IllegalArgumentException(); } String sql = "INSERT INTO USUARIO VALUES (?,?,?,?,?,?)"; PreparedStatement estrutura = conexao.prepareStatement(sql); estrutura.setString(1, user.getEmail()); estrutura.setString(2, user.getNome()); estrutura.setString(3, user.getTelefone()); estrutura.setString(4, user.getCelular()); estrutura.setString(5, String.valueOf(user.getAdmin())); estrutura.setString(6, user.getSenha()); estrutura.execute(); } catch(Exception e) { e.printStackTrace(); System.out.println("Erro ao inserir PerguntaNaoRespondida no BD"); } } public ResultSet pesquisarTodas() { try { String sql = "SELECT * FROM USUARIO"; PreparedStatement estrutura = conexao.prepareStatement(sql); ResultSet resultado = estrutura.executeQuery(); return resultado; } catch(Exception e) { e.printStackTrace(); System.out.println("Erro ao pesquisar todos Usuários"); } return null; } public ResultSet pesquisarPorAdmin() { try { String sql = "SELECT * FROM USUARIO WHERE ST_ADMIN = '1'"; PreparedStatement estrutura = conexao.prepareStatement(sql); ResultSet resultado = estrutura.executeQuery(); return resultado; } catch(Exception e) { e.printStackTrace(); System.out.println("Erro ao pesquisar todos os Admins"); } return null; } public void mudarAdmin(String email, char status) { try { String sql = "UPDATE USUARIO SET ST_ADMIN = ? WHERE NM_EMAIL = ?"; PreparedStatement estrutura = conexao.prepareStatement(sql); estrutura.setString(1, String.valueOf(status)); estrutura.setString(2, email); estrutura.executeUpdate(); } catch (Exception e) { e.printStackTrace(); System.out.println("Erro ao alterar o Status Admin do Usuário"); } } public Usuario pesquisarPorEmail(String email) { try { if(email == null) { return null; } Usuario user = new Usuario(); String sql = "SELECT * FROM USUARIO WHERE NM_EMAIL = ?"; PreparedStatement estrutura = conexao.prepareStatement(sql); estrutura.setString(1, email); ResultSet resultado = estrutura.executeQuery(); if(resultado.next()) { user.setNome(resultado.getString("NM_USUARIO")); user.setEmail(resultado.getString("NM_EMAIL")); user.setSenha(resultado.getString("NM_SENHA")); user.setAdmin(resultado.getString("ST_ADMIN").charAt(0)); return user; } return null; } catch(Exception e) { e.printStackTrace(); System.out.println("Erro ao pesquisar por email de usuário"); } return null; } public boolean login(String email, String senha) { Usuario user = this.pesquisarPorEmail(email); if(user != null && user.getSenha().equals(senha)) { return true; } return false; } }
package pe.gob.trabajo.repository.search; import pe.gob.trabajo.domain.Discap; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; /** * Spring Data Elasticsearch repository for the Discap entity. */ public interface DiscapSearchRepository extends ElasticsearchRepository<Discap, Long> { }
package com.example.myapplication2.Helper; import android.app.Activity; import android.content.Context; import android.speech.tts.TextToSpeech; import android.widget.TextView; import com.example.myapplication2.DataModel.TestModel; import com.example.myapplication2.R; import org.json.JSONObject; import java.io.IOException; import java.util.Locale; import okhttp3.Call; import okhttp3.Callback; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class APICall { private String url, location, facility; private Context context; private TextView textView; private TestModel tmodel; OkHttpClient client; Request request; private TextToSpeech tts; public APICall(String url, String location, String facility, Context context) { this.context = context; this.location = location; this.facility = facility; textView = ((Activity)context).findViewById(R.id.textView); textView.setText("Changed!"); client = new OkHttpClient(); this.url = url; HttpUrl.Builder urlBuilder = HttpUrl.parse(this.url).newBuilder(); urlBuilder.addQueryParameter("offset", "0"); urlBuilder.addQueryParameter("limit", "10"); if (location != null && location.length() > 0) { urlBuilder.addQueryParameter("sort", "near:" + location); //location buzzword } if (facility != null && facility.length() > 0) { urlBuilder.addQueryParameter("facilities", facility); //access buzzword } String uri = urlBuilder.build().toString(); request = new Request.Builder() .url(uri) .addHeader("Ocp-Apim-Subscription-Key","47db0bfc5032433cbf31ab78415fe4b1") .build(); } //TODO: GET THIS TO RETURN THE RESULT public void execute(){ final Object result; client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()){ String resStr = response.body().string().toString(); try { final JSONObject json = new JSONObject(resStr); final String myResponse = response.body().toString(); textView.post(new Runnable() { @Override public void run() { final TestModel tmodel = (TestModel) GsonHelper.deserialize(json.toString(), TestModel.class); textView.setText(tmodel.results[0].location.name); tts = new TextToSpeech(context, new TextToSpeech.OnInitListener() { @Override public void onInit(int i) { tts.setLanguage(Locale.US); tts.speak(tmodel.results[0].location.name, TextToSpeech.QUEUE_ADD, null); } }); } }); } catch (Exception e){ } } } }); } }
package filmarchiv.model; import java.util.List; public class Marketing { private int id; private List<String> bewertungen; private List<String> rezensionen; private List<Zeit> werbepausen; public int getId() { return id; } public void setId(int id) { this.id = id; } public List<String> getBewertungen() { return bewertungen; } public void setBewertungen(List<String> bewertungen) { this.bewertungen = bewertungen; } public List<String> getRezensionen() { return rezensionen; } public void setRezensionen(List<String> rezensionen) { this.rezensionen = rezensionen; } public List<Zeit> getWerbepausen() { return werbepausen; } public void setWerbepausen(List<Zeit> werbepausen) { this.werbepausen = werbepausen; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((rezensionen == null) ? 0 : rezensionen.hashCode()); result = prime * result + id; result = prime * result + ((bewertungen == null) ? 0 : bewertungen.hashCode()); result = prime * result + ((werbepausen == null) ? 0 : werbepausen.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Marketing other = (Marketing) obj; if (rezensionen == null) { if (other.rezensionen != null) return false; } else if (!rezensionen.equals(other.rezensionen)) return false; if (id != other.id) return false; if (bewertungen == null) { if (other.bewertungen != null) return false; } else if (!bewertungen.equals(other.bewertungen)) return false; if (werbepausen == null) { if (other.werbepausen != null) return false; } else if (!werbepausen.equals(other.werbepausen)) return false; return true; } @Override public String toString() { return "Mitwirkende [id=" + id + ", bewertungen=" + bewertungen + ", rezensionen=" + rezensionen + ", werbepausen=" + werbepausen + "]"; } }
package com.facebook.react.uimanager; import android.util.TypedValue; public class PixelUtil { public static float toDIPFromPixel(float paramFloat) { return paramFloat / (DisplayMetricsHolder.getWindowDisplayMetrics()).density; } public static float toPixelFromDIP(double paramDouble) { return toPixelFromDIP((float)paramDouble); } public static float toPixelFromDIP(float paramFloat) { return TypedValue.applyDimension(1, paramFloat, DisplayMetricsHolder.getWindowDisplayMetrics()); } public static float toPixelFromSP(double paramDouble) { return toPixelFromSP((float)paramDouble); } public static float toPixelFromSP(float paramFloat) { return TypedValue.applyDimension(2, paramFloat, DisplayMetricsHolder.getWindowDisplayMetrics()); } } /* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\reac\\uimanager\PixelUtil.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.alodiga.wallet.ejb; import java.util.List; import javax.ejb.Stateless; import javax.ejb.TransactionManagement; import javax.ejb.TransactionManagementType; import javax.interceptor.Interceptors; import org.apache.log4j.Logger; import com.alodiga.wallet.common.ejb.ReportEJB; import com.alodiga.wallet.common.ejb.ReportEJBLocal; import com.alodiga.wallet.common.exception.EmptyListException; import com.alodiga.wallet.common.exception.GeneralException; import com.alodiga.wallet.common.exception.NullParameterException; import com.alodiga.wallet.common.exception.RegisterNotFoundException; import com.alodiga.wallet.common.genericEJB.AbstractWalletEJB; import com.alodiga.wallet.common.genericEJB.EJBRequest; import com.alodiga.wallet.common.genericEJB.WalletContextInterceptor; import com.alodiga.wallet.common.genericEJB.WalletLoggerInterceptor; import com.alodiga.wallet.common.model.ParameterType; import com.alodiga.wallet.common.model.Report; import com.alodiga.wallet.common.model.Enterprise; import com.alodiga.wallet.common.model.ReportHasProfile; import com.alodiga.wallet.common.model.ReportParameter; import com.alodiga.wallet.common.model.ReportType; import com.alodiga.wallet.common.model.Transaction; import com.alodiga.wallet.common.model.User; import com.alodiga.wallet.common.utils.EjbConstants; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.persistence.Query; import com.alodiga.wallet.common.utils.QueryConstants; @Interceptors({WalletLoggerInterceptor.class, WalletContextInterceptor.class}) @Stateless(name = EjbConstants.REPORT_EJB, mappedName = EjbConstants.REPORT_EJB) @TransactionManagement(TransactionManagementType.BEAN) public class ReportEJBImp extends AbstractWalletEJB implements ReportEJB, ReportEJBLocal { private static final Logger logger = Logger.getLogger(ReportEJBImp.class); //Report public void deleteProfileReports(EJBRequest request) throws NullParameterException, GeneralException { Object param = request.getParam(); if (param == null || !(param instanceof Long)) { throw new NullParameterException( sysError.format(EjbConstants.ERR_NULL_PARAMETER, this.getClass(), getMethodName(), "profileId"), null); } Map<String, Object> map = new HashMap<String, Object>(); map.put("reportId", (Long) param); try { executeNameQuery(ReportHasProfile.class, QueryConstants.DELETE_REPORT_PROFILE, map, getMethodName(), logger, "ReportProfile", null, null); } catch (Exception e) { throw new GeneralException(logger, sysError.format(EjbConstants.ERR_GENERAL_EXCEPTION, this.getClass(), getMethodName(), e.getMessage()), null); } } public void deleteReportParameter(EJBRequest request) throws NullParameterException, GeneralException { Object param = request.getParam(); if (param == null || !(param instanceof Long)) { throw new NullParameterException( sysError.format(EjbConstants.ERR_NULL_PARAMETER, this.getClass(), getMethodName(), "reportId"), null); } Map<String, Object> map = new HashMap<String, Object>(); map.put("reportId", (Long) param); try { executeNameQuery(ReportParameter.class, QueryConstants.DELETE_REPORT_PARAMETER, map, getMethodName(), logger, "ReportParameter", null, null); } catch (Exception e) { throw new GeneralException(logger, sysError.format(EjbConstants.ERR_GENERAL_EXCEPTION, this.getClass(), getMethodName(), e.getMessage()), null); } } public Report enableProduct(EJBRequest request) throws GeneralException, NullParameterException, RegisterNotFoundException { return (Report) saveEntity(request, logger, getMethodName()); } public List<ParameterType> getParameterType(EJBRequest request) throws EmptyListException, GeneralException, NullParameterException { List<ParameterType> parameterType = (List<ParameterType>) listEntities(ParameterType.class, request, logger, getMethodName()); return parameterType; } public List<Report> getReport(EJBRequest request) throws EmptyListException, GeneralException, NullParameterException { List<Report> reports = (List<Report>) listEntities(Report.class, request, logger, getMethodName()); return reports; } public List<ReportHasProfile> getReportByProfile(EJBRequest request) throws EmptyListException, GeneralException, NullParameterException { List<ReportHasProfile> reportHasProfiles = null; Map<String, Object> params = request.getParams(); if (!params.containsKey("profileId")) { throw new NullParameterException( sysError.format(EjbConstants.ERR_NULL_PARAMETER, this.getClass(), getMethodName(), "profileId"), null); } reportHasProfiles = (List<ReportHasProfile>) getNamedQueryResult(ReportEJB.class, QueryConstants.REPORT_BY_PROFILE, request, getMethodName(), logger, "reports"); return reportHasProfiles; } public List<Report> getReportByReportTypeId(Long reportTypeId, User currentUser) throws NullParameterException, GeneralException, EmptyListException { Long profileId = currentUser.getCurrentProfile().getId(); if (reportTypeId == null) { throw new NullParameterException( sysError.format(EjbConstants.ERR_NULL_PARAMETER, this.getClass(), getMethodName(), "reportTypeId"), null); } else if (currentUser == null) { throw new NullParameterException( sysError.format(EjbConstants.ERR_NULL_PARAMETER, this.getClass(), getMethodName(), "currentUser"), null); } List<Report> reports = new ArrayList<Report>(); String sql = "SELECT rhp.reportId FROM ReportHasProfile rhp WHERE rhp.profileId.id= ?1 AND rhp.reportId.reportTypeId.id= ?2"; try { Query query = createQuery(sql); query.setParameter("1", profileId); query.setParameter("2", reportTypeId); reports = query.setHint("toplink.refresh", "true").getResultList(); } catch (Exception ex) { throw new GeneralException(logger, sysError.format(EjbConstants.ERR_GENERAL_EXCEPTION, this.getClass(), getMethodName(), ex.getMessage()), null); } if (reports.isEmpty()) { throw new EmptyListException(logger, sysError.format(EjbConstants.ERR_EMPTY_LIST_EXCEPTION, this.getClass(), getMethodName()), null); } return reports; } public List<ReportParameter> getReportParameter(EJBRequest request) throws EmptyListException, GeneralException, NullParameterException { List<ReportParameter> reportParameters = (List<ReportParameter>) listEntities(ReportParameter.class, request, logger, getMethodName()); return reportParameters; } public List<ReportType> getReportTypes(EJBRequest request) throws EmptyListException, GeneralException, NullParameterException { List<ReportType> reportTypes = (List<ReportType>) listEntities(ReportType.class, request, logger, getMethodName()); return reportTypes; } public ParameterType loadParameterType(EJBRequest request) throws RegisterNotFoundException, NullParameterException, GeneralException { ParameterType parameterType = (ParameterType) loadEntity(ParameterType.class, request, logger, getMethodName()); return parameterType; } public Report loadReport(EJBRequest request) throws RegisterNotFoundException, NullParameterException, GeneralException { Report report = (Report) loadEntity(Report.class, request, logger, getMethodName()); return report; } public ReportParameter loadReportParameter(EJBRequest request) throws RegisterNotFoundException, NullParameterException, GeneralException { ReportParameter reportParameter = (ReportParameter) loadEntity(ReportParameter.class, request, logger, getMethodName()); return reportParameter; } public List<String> runReport(EJBRequest request) throws NullParameterException, GeneralException, EmptyListException { List<String> reports = new ArrayList<String>(); Map<String, Object> params = request.getParams(); String sql = (String) params.get(QueryConstants.PARAM_SQL); if (!params.containsKey(QueryConstants.PARAM_SQL)) { throw new NullParameterException( sysError.format(EjbConstants.ERR_NULL_PARAMETER, this.getClass(), getMethodName(), QueryConstants.PARAM_PROFILE_ID), null); } try { reports = entityManager.createNativeQuery(sql).setHint("toplink.refresh", "true").getResultList(); } catch (Exception e) { throw new GeneralException(logger, sysError.format(EjbConstants.ERR_GENERAL_EXCEPTION, this.getClass(), getMethodName(), e.getMessage()), null); } if (reports.isEmpty()) { throw new EmptyListException(logger, sysError.format(EjbConstants.ERR_EMPTY_LIST_EXCEPTION, this.getClass(), getMethodName()), null); } return reports; } public Report saveReport(EJBRequest request) throws NullParameterException, GeneralException { return (Report) saveEntity(request, logger, getMethodName()); } }
package ru.hse.performance; public class PerformanceUtil { private static long beginTime; private static long stepTime; private static long endTime; private static boolean initialized=false; /** * Инициализирет счётчики. Должен вызываться в начала программы. */ public static void initialize(){ beginTime = System.currentTimeMillis(); stepTime = beginTime; endTime = beginTime; initialized=true; } /** * Печатает время, которое было затрачено на выполнение части кода от предыдущего вызова этого метода до текущего. * Если счётчики не были инициализированы, то инициализирует их * @param stepName */ public static void printTimeForStep(String stepName){ if(!initialized){ initialize(); } endTime = System.currentTimeMillis(); System.out.println(stepName+" finished in: " + ((float) (endTime - stepTime) / 1000) + " seconds"); stepTime=endTime; } /** * Выводит общее время выполнения, рассчитанное как разность между временем инициализации счётчиков и текущим временем. * Если счётчики не были инициализированы, то инициализирует их */ public static void printTotalTime(){ if(!initialized){ initialize(); } endTime = System.currentTimeMillis(); System.out.println("Total time: " + ((float) (endTime - beginTime) / 1000) + " seconds"); } }
////1번 class Apple { // 필드 int num; // 생성자 : 객제가 생성될 때 단 한번 불러짐 // 목적 : 필드 변수 초기화 Apple() { System.out.println("나는야 사과"); System.out.println(this.hashCode()); // this는 a BUT this가 b가 될 수 있음 num = 0; // 필드 초기화 } // 생성자 함수 재정의 Apple(int a, int b) { System.out.println(a); System.out.println(b); } Apple(int num) { this.num = num; } // 함수 void func01() { System.out.println("나는야 함수 1번"); } void func02(int a, int b) { System.out.println(a); System.out.println(b); } int func03() { return 100; } int func04(int a, int b) { return a + b; } Apple func05() { System.out.println("나는야 함수 5번"); return this; //체이닝 기법 } void func06() { System.out.println("나는야 함수 6번"); } int func06(int a) { return a; } char func06(char a) { // 함수 테스팅! return 'a'; } } public class ClassEx { public static void main(String[] args) { Apple a = new Apple(); // 객체 생성 System.out.println(a.hashCode()); // 객체의 민증번호 a.func01(); // 함수 호출 System.out.println(a.num); a.func02(1, 2); System.out.println(a.func03()); System.out.println(a.func04(10, 20)); a.func05(); // 체이닝 방식 : 함수가 자기 자신을 리턴 a.func05().func05().func06(); a.func05().func05().func06(); } }
package nl.rug.oop.flaps.aircraft_editor.controller.listeners.infopanel_listeners; import lombok.extern.java.Log; import nl.rug.oop.flaps.aircraft_editor.util.AddEdit; import nl.rug.oop.flaps.aircraft_editor.view.panels.aircraft_info.InfoPanel; import nl.rug.oop.flaps.aircraft_editor.view.panels.aircraft_info.interaction_panels.CargoConfigPanel; import nl.rug.oop.flaps.aircraft_editor.view.panels.aircraft_info.interaction_panels.FuelConfigPanel; import nl.rug.oop.flaps.aircraft_editor.view.panels.aircraft_info.interaction_panels.PassengersConfigPanel; import nl.rug.oop.flaps.simulation.model.aircraft.Aircraft; import nl.rug.oop.flaps.simulation.model.cargo.CargoUnit; import javax.swing.undo.UndoableEditSupport; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashMap; /** * this class uses {@link ActionListener} to listen to an action for the confirm button to confirm a change made by the user\ * either for {@link PassengersConfigPanel} or {@link CargoConfigPanel} and {@link FuelConfigPanel} * */ @Log public class ConfirmChangeButtonListener implements ActionListener { private FuelConfigPanel fuelConfigPanel; private CargoConfigPanel cargoConfigPanel; private PassengersConfigPanel passengersConfigPanel; private final Aircraft aircraft; private final UndoableEditSupport undoSupport; public ConfirmChangeButtonListener(FuelConfigPanel fuelConfigPanel, Aircraft aircraft) { this.fuelConfigPanel = fuelConfigPanel; this.aircraft = aircraft; this.undoSupport = aircraft.getEditMenu().getUndoSupport(); } public ConfirmChangeButtonListener(CargoConfigPanel cargoConfigPanel, Aircraft aircraft) { this.cargoConfigPanel = cargoConfigPanel; this.aircraft = aircraft; this.undoSupport = aircraft.getEditMenu().getUndoSupport(); } public ConfirmChangeButtonListener(PassengersConfigPanel passengersConfigPanel, Aircraft aircraft) { this.passengersConfigPanel = passengersConfigPanel; this.aircraft = aircraft; this.undoSupport = aircraft.getEditMenu().getUndoSupport(); } /** * updates the panels for fuel, cargo or passenger when the confirm button is pressed * */ @Override public void actionPerformed(ActionEvent e) { updateFuel(e); updateCargo(e); updatePassengers(e); } /** * Creates a backup of the undo/redo data and updates the the passengers * @param e the button event, check if its from the cargoConfigPanel */ private void updatePassengers(ActionEvent e) { if (passengersConfigPanel != null && e.getSource() == passengersConfigPanel.getConfirmButton()) { HashMap<String, Integer> undoPassengers = new HashMap<>(passengersConfigPanel.getModel().getPassengers()); passengersConfigPanel.updateConfig(); HashMap<String, Integer> redoPassengers = new HashMap<>(passengersConfigPanel.getModel().getPassengers()); undoSupport.postEdit(new AddEdit(passengersConfigPanel, undoPassengers, redoPassengers)); InfoPanel.updateResultInfo(); log.info("Updated Passengers"); } } /** * Creates a backup of the undo/redo data and updates the the cargoArea * @param e the button event, check if its from the cargoConfigPanel */ private void updateCargo(ActionEvent e) { if (cargoConfigPanel != null && e.getSource() == cargoConfigPanel.getConfirmButton()) { CargoUnit undoCargoUnit = new CargoUnit(cargoConfigPanel.getSelectedCargoUnit().getCargoType(), cargoConfigPanel.getSelectedCargoUnit().getWeight()); cargoConfigPanel.getSelectedCargoUnit().setWeight(cargoConfigPanel.getInfoSlider().getValue()); CargoUnit redoCargoUnit = new CargoUnit(cargoConfigPanel.getSelectedCargoUnit().getCargoType(), cargoConfigPanel.getSelectedCargoUnit().getWeight()); undoSupport.postEdit(new AddEdit(cargoConfigPanel, undoCargoUnit, redoCargoUnit)); aircraft.addToCargoArea(cargoConfigPanel.getSelectedCargoArea(), cargoConfigPanel.getSelectedCargoUnit()); cargoConfigPanel.updateCargoAreaWeightLabel(); cargoConfigPanel.getBluePrintModel().getBluePrintPanel().repaint(); InfoPanel.updateResultInfo(); log.info("Updated Cargo"); } } /** * Creates a backup of the undo/redo data and updates the the fuelTank * @param e the button event, check if its from the fuelConfigPanel */ private void updateFuel(ActionEvent e) { if (fuelConfigPanel != null && e.getSource() == fuelConfigPanel.getConfirmButton()) { double undoFuelTankAmount = fuelConfigPanel.getAircraft().getFuelAmountForFuelTank(fuelConfigPanel.getSelectedTank()); double redoFuelTankAmount = fuelConfigPanel.getInfoSlider().getValue(); undoSupport.postEdit(new AddEdit(fuelConfigPanel,undoFuelTankAmount, redoFuelTankAmount)); aircraft.setFuelAmountForFuelTank(fuelConfigPanel.getSelectedTank(), fuelConfigPanel.getInfoSlider().getValue()); fuelConfigPanel.getDisplayPanel().removeAll(); fuelConfigPanel.initConfigPanelFuel(); fuelConfigPanel.getBluePrintModel().getBluePrintPanel().repaint(); InfoPanel.updateResultInfo(); log.info("Updated Fuel"); } } }
package com.example.cafey; import android.app.Activity; public class cafeHouse extends Activity { }
package pl.finsys.jms; /** * Place description here. * * @author jarek@finsys.pl */ import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.MapMessage; import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.support.JmsUtils; public class MessageConsumerBean{ private JmsTemplate jmsTemplate; private Destination destination; public void setJmsTemplate(JmsTemplate jmsTemplate) { this.jmsTemplate = jmsTemplate; } public void setDestination(Destination destination) { this.destination = destination; } public EmailObject receiveMessage() { MapMessage message = (MapMessage) jmsTemplate.receive(destination); try { EmailObject messageObj = new EmailObject(); messageObj.setFrom(message.getString("from")); messageObj.setMessage(message.getString("message")); return messageObj; } catch (JMSException e) { throw JmsUtils.convertJmsAccessException(e); } } }
import javax.swing.JFrame; import javax.swing.JOptionPane; import images.APImage; import images.Pixel; public class Project5_8 { public static void main(String[] args) { int resize = Integer.parseInt(JOptionPane.showInputDialog("Enter the resize value: " )); APImage image = new APImage("res/smokey.jpg"); int x = image.getWidth() / resize; int y = image.getHeight() / resize; image.setSize(image.getWidth(),image.getHeight()); image.setTitle("Big cat"); image.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); APImage newImage = new APImage(x,y); for(int runY = 0; runY < y-1; runY++) { for(int runX = 0; runX < x; runX++) { Pixel getPixel = image.getPixel(runX * resize, runY * resize); newImage.setPixel(runX, runY, getPixel); } } image.draw(); newImage.setSize(x,y); newImage.draw(); } }
package feedback.faces.rest.service; import java.util.ArrayList; import feedback.faces.rest.service.dao.Path; public class Paths { private static Paths instance = null; private static ArrayList<Path> paths = new ArrayList<Path>(); private Paths() { paths.add(new Path("/answers/{id}", "GET", "Returns a Specific Answer Object")); paths.add(new Path("/answers", "POST", "Adds a New Answer")); paths.add(new Path("/feedback/{id}", "GET", "Returns a Specific Feedback Object")); paths.add(new Path("/feedback", "POST", "Adds a New Feedback Response")); paths.add(new Path("/questions/{id}", "GET", "Returns a Specific Question Object")); paths.add(new Path("/questions/{id}/answers", "GET", "Returns a List of All Answers Associated with this Question")); paths.add(new Path("/questions", "POST", "Adds a New Question")); paths.add(new Path("/surveys/{id}", "GET", "Returns a Specific Survey Object")); paths.add(new Path("/surveys/{id}/feedback", "GET", "All Feedback for the Specified Survey")); paths.add(new Path("/surveys/{id}/users", "GET", "All Users with Access to the Specified Survey")); paths.add(new Path("/surveys/{id}/questions", "GET", "All Questions Associated with this Survey")); paths.add(new Path("/surveys", "POST", "Adds a New Survey")); paths.add(new Path("/users/{id}", "GET", "Returns a Specific User Object")); paths.add(new Path("/users", "POST", "Adds a New User")); paths.add(new Path("/admin/shutdown", "GET", "Shutsdown the Feedback Faces REST Service")); } public static ArrayList<Path> getPaths() { if (instance == null) { instance = new Paths(); } return paths; } }
package com.tencent.mm.modelvideo; import com.tencent.mm.modelcdntran.i.a; import com.tencent.mm.modelcdntran.keep_ProgressInfo; import com.tencent.mm.modelcdntran.keep_SceneResult; import com.tencent.mm.sdk.platformtools.x; import java.io.ByteArrayOutputStream; class f$1 implements a { final /* synthetic */ f emq; f$1(f fVar) { this.emq = fVar; } public final int a(String str, int i, keep_ProgressInfo keep_progressinfo, keep_SceneResult keep_sceneresult, boolean z) { if (i != 0) { x.w("MicroMsg.NetScenePreloadVideoFake", "%d preload video error startRet[%d]", new Object[]{Integer.valueOf(this.emq.hashCode()), Integer.valueOf(i)}); if (this.emq.emp != null) { this.emq.emp.a(this.emq, false, 0, 0); } } if (keep_progressinfo != null) { x.d("MicroMsg.NetScenePreloadVideoFake", "%d preload video[%d %d] mediaId[%s]", new Object[]{Integer.valueOf(this.emq.hashCode()), Integer.valueOf(keep_progressinfo.field_finishedLength), Integer.valueOf(keep_progressinfo.field_toltalLength), str}); } if (keep_sceneresult != null) { x.i("MicroMsg.NetScenePreloadVideoFake", "%d preload video error [%d]", new Object[]{Integer.valueOf(this.emq.hashCode()), Integer.valueOf(keep_sceneresult.field_retCode)}); if (keep_sceneresult.field_retCode == 0) { x.i("MicroMsg.NetScenePreloadVideoFake", "%d preload video download all video file", new Object[]{Integer.valueOf(this.emq.hashCode())}); this.emq.f(this.emq.emj, keep_sceneresult.field_fileLength, this.emq.dQk); } else if (this.emq.emp != null) { this.emq.emp.a(this.emq, false, 0, 0); } } return 0; } public final void a(String str, ByteArrayOutputStream byteArrayOutputStream) { } public final byte[] i(String str, byte[] bArr) { return new byte[0]; } }
package com.workorder.ticket.service.impl; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Resource; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import com.alibaba.fastjson.JSON; import com.sowing.common.exception.ParamException; import com.sowing.common.exception.ServiceException; import com.workorder.ticket.common.ConstantsValue; import com.workorder.ticket.common.TemplateKeys; import com.workorder.ticket.common.enums.DeployOp; import com.workorder.ticket.common.enums.DeployStatus; import com.workorder.ticket.common.enums.DeployType; import com.workorder.ticket.common.utils.DateUtils; import com.workorder.ticket.controller.vo.common.FlowStepItem; import com.workorder.ticket.controller.vo.common.HistogramItem; import com.workorder.ticket.controller.vo.common.TicketOpLog; import com.workorder.ticket.model.ActivityStart; import com.workorder.ticket.model.TaskInfo; import com.workorder.ticket.persistence.dao.BizLogDao; import com.workorder.ticket.persistence.dao.DeployDao; import com.workorder.ticket.persistence.dao.DeployProjectDao; import com.workorder.ticket.persistence.dao.DeployStepDao; import com.workorder.ticket.persistence.dao.FlowTemplateDao; import com.workorder.ticket.persistence.dao.GroupDao; import com.workorder.ticket.persistence.dao.ProjectDao; import com.workorder.ticket.persistence.dao.UserDao; import com.workorder.ticket.persistence.dto.UserInfoDto; import com.workorder.ticket.persistence.dto.UserQueryDto; import com.workorder.ticket.persistence.dto.deploy.DeployProjectDto; import com.workorder.ticket.persistence.dto.deploy.DeployQueryDto; import com.workorder.ticket.persistence.dto.deploy.DeployWithCreatorDto; import com.workorder.ticket.persistence.entity.Deploy; import com.workorder.ticket.persistence.entity.DeployProject; import com.workorder.ticket.persistence.entity.DeployStep; import com.workorder.ticket.persistence.entity.FlowTemplate; import com.workorder.ticket.persistence.entity.Group; import com.workorder.ticket.persistence.entity.Project; import com.workorder.ticket.persistence.entity.User; import com.workorder.ticket.remote.ActivityServiceRpc; import com.workorder.ticket.service.BizLogService; import com.workorder.ticket.service.DeployService; import com.workorder.ticket.service.bo.deploy.DeployBo; import com.workorder.ticket.service.bo.deploy.DeployEditBo; import com.workorder.ticket.service.bo.deploy.DeployQueryBo; import com.workorder.ticket.service.bo.user.UserInfoBo; import com.workorder.ticket.service.common.SessionService; import com.workorder.ticket.service.common.SmsService; import com.workorder.ticket.service.convertor.DeployServiceConvertor; /** * 部署申请服务 * * @author wzdong * @Date 2019年3月25日 * @version 1.0 */ @Service public class DeployServiceImpl implements DeployService { private static final Logger LOGGER = LoggerFactory .getLogger(DeployServiceImpl.class); @Resource private DeployDao deployDao; @Resource private DeployStepDao deployStepDao; @Resource private DeployProjectDao deployProjectDao; @Resource private ProjectDao projectDao; @Resource private FlowTemplateDao flowTemplateDao; @Resource private UserDao userDao; @Resource private GroupDao groupDao; @Resource private BizLogDao bizLogDao; @Resource private SmsService smsService; @Resource private SessionService sessionService; @Resource private BizLogService bizLogService; @Resource private ActivityServiceRpc activityServiceRpc; /** * 新建部署申请 * * @param initVo * @return */ @Override @Transactional public void create(DeployEditBo initBo) { LOGGER.info("用户[{}]新建部署申请!", sessionService.getCurrentUser() .getUsername()); // 1.插入申请表 Deploy deploy = DeployServiceConvertor.buildDeploy(initBo); deploy.setCreateId(sessionService.getCurrentUser().getUserId()); deploy.setCreateTime(new Date()); deploy.setStatus(DeployStatus.NEW.getType()); deploy.setFlowEngineDefinitionId(getDeployFlowDefinitId(initBo .getType())); deployDao.insert(deploy); initBo.setId(deploy.getId()); // 2.插入申请项目表 List<DeployProject> deployProjectList = DeployServiceConvertor .buildDeployProjects(initBo); if (CollectionUtils.isEmpty(deployProjectList)) { throw ParamException.paramException("参数异常!"); } deployProjectDao.insertBatch(deployProjectList); // 3.插入申请步骤表 List<DeployStep> deployStepList = DeployServiceConvertor .buildDeploySteps(initBo); AtomicInteger stepOrder = new AtomicInteger(1); deployStepList.forEach(item -> { item.setStepOrder(stepOrder.addAndGet(1)); }); if (CollectionUtils.isEmpty(deployStepList)) { throw ParamException.paramException("参数异常!"); } deployStepDao.insertBatch(deployStepList); // 日志 updateStatusAndLog(deploy, DeployOp.NEW, ""); LOGGER.info("用户[{}]新建部署申请[{}]成功!", sessionService.getCurrentUser() .getUsername(), deploy.getId()); } /** * 编辑部署申请 * * @param editVo * @return */ @Override @Transactional public void edit(DeployEditBo editBo) { Deploy deploy = getAndCheckDataAuth(editBo.getId()); // 新建或拒绝才能编辑 if (deploy == null || (DeployStatus.NEW.getType() != deploy.getStatus() && DeployStatus.REFUSED .getType() != deploy.getStatus())) { LOGGER.info("Deploy:{}", JSON.toJSONString(deploy)); throw ServiceException.commonException("不合法请求!"); } LOGGER.info("用户[{}]编辑部署申请[{}]!", sessionService.getCurrentUser() .getUsername(), editBo.getId()); // 1.编辑申请表 Deploy updateDeploy = DeployServiceConvertor.buildDeploy(editBo); deployDao.updateByPrimaryKeySelective(updateDeploy); // 2.编辑申请项目表 List<DeployProject> deployProjectList = DeployServiceConvertor .buildDeployProjects(editBo); if (CollectionUtils.isEmpty(deployProjectList)) { throw ParamException.paramException("参数异常!"); } deployProjectDao.deleteByDeployId(editBo.getId()); deployProjectDao.insertBatch(deployProjectList); // 3.编辑申请步骤表 List<DeployStep> deployStepList = DeployServiceConvertor .buildDeploySteps(editBo); AtomicInteger stepOrder = new AtomicInteger(1); deployStepList.forEach(item -> { item.setStepOrder(stepOrder.addAndGet(1)); }); if (CollectionUtils.isEmpty(deployStepList)) { throw ParamException.paramException("参数异常!"); } deployStepDao.deleteByDeployId(editBo.getId()); deployStepDao.insertBatch(deployStepList); updateStatusAndLog(deploy, DeployOp.EDIT, ""); LOGGER.info("用户[{}]编辑部署申请[{}]成功!", sessionService.getCurrentUser() .getUsername(), editBo.getId()); } /** * 删除部署申请 * * @param editVo * @return */ @Override @Transactional public void delete(Long deployId) { Deploy deploy = getAndCheckDataAuth(deployId); if (DeployStatus.NEW.getType() != deploy.getStatus()) { throw ServiceException.commonException("不可删除!"); } deployProjectDao.deleteByDeployId(deployId); deployDao.deleteByPrimaryKey(deployId); deployProjectDao.deleteByDeployId(deployId); LOGGER.info("用户[{}]删除部署申请[{}]成功!", sessionService.getCurrentUser() .getUsername(), deployId); } /** * 撤销部署申请 * * @param editVo * @return */ @Override public void revoke(Long deployId) { Deploy deploy = getAndCheckDataAuth(deployId); LOGGER.info("用户[{}]撤销部署申请[{}]!", sessionService.getCurrentUser() .getUsername(), deployId); if (deploy.getFlowEngineInstanceId() != null) { LOGGER.info("用户[{}]撤销部署申请[{}],删除流程引擎实例[{}]!", sessionService .getCurrentUser().getUsername(), deployId, deploy .getFlowEngineInstanceId()); activityServiceRpc.deleteTask(deploy.getFlowEngineInstanceId()); } updateStatusAndLog(deploy, DeployOp.REVOKE, ""); LOGGER.info("用户[{}]撤销部署申请[{}]成功!", sessionService.getCurrentUser() .getUsername(), deployId); } /** * 提交部署申请 * * @param deployId * @return */ @Override @Transactional public void submit(Long deployId) { Deploy deploy = getAndCheckDataAuth(deployId); // 第一次提交 if (DeployStatus.NEW.getType() == deploy.getStatus()) { LOGGER.info("用户[{}]提交部署申请[{}]!", sessionService.getCurrentUser() .getUsername(), deployId); submit(deploy); } else if (DeployStatus.REFUSED.getType() == deploy.getStatus()) { // 拒绝、修改后提交 LOGGER.info("用户[{}]重新提交部署申请[{}]!", sessionService.getCurrentUser() .getUsername(), deployId); resubmit(deploy); } else { // 异常请求 LOGGER.warn("用户[{}]提交部署申请[{}],部署申请状态不合法,status:{}!", sessionService .getCurrentUser().getUsername(), deployId, deploy .getStatus()); throw ServiceException.commonException("不合法请求!"); } LOGGER.info("用户[{}]提交部署申请[{}]成功!", sessionService.getCurrentUser() .getUsername(), deployId); } /** * 处理任务 * * @return */ @Override public void completeTask(Long deployId, Boolean result, String comment) { Deploy deploy = deployDao.getByPrimaryKey(deployId); // 部署申请状态校验 if (deploy == null || (deploy.getStatus() != DeployStatus.PROCESSING.getType() && deploy .getStatus() != DeployStatus.REFUSED.getType())) { throw ServiceException.commonException("非法请求!"); } LOGGER.info("用户[{}]处理部署申请[{}],instanceId:[{}]!", sessionService .getCurrentUser().getUsername(), deployId, deploy .getFlowEngineInstanceId()); // 流程引擎处理部署申请 TaskInfo taskInfo = activityServiceRpc.getCurrentTask(deploy .getFlowEngineInstanceId()); if (taskInfo == null) { throw ServiceException.commonException("没有任务需要处理!"); } String processor = String.valueOf(sessionService.getCurrentUser() .getUserId()); activityServiceRpc.completeTask(taskInfo.getTaskId(), processor, result, comment); // 处理结果 【同意】 OR 【拒绝】 if (result != null) { if (result == false) { LOGGER.info("用户[{}]审核拒绝部署申请[{}]!", sessionService .getCurrentUser().getUsername(), deployId); updateStatusAndLog(deploy, DeployOp.REFUSED, comment); noticeResult(deploy, deploy.getCreateId(), "拒绝处理"); } else { LOGGER.info("用户[{}]审核通过部署申请[{}]!", sessionService .getCurrentUser().getUsername(), deployId); updateStatusAndLog(deploy, DeployOp.AGREE, comment); } } LOGGER.info("用户[{}]处理部署申请[{}]成功!", sessionService.getCurrentUser() .getUsername(), deployId); // 判断流程是否结束 TaskInfo nextTask = activityServiceRpc.getCurrentTask(deploy .getFlowEngineInstanceId()); if (nextTask == null) { LOGGER.info("部署申请[{}]处理结束!", deployId); updateStatusAndLog(deploy, DeployOp.COMPLETE, ""); noticeResult(deploy, deploy.getCreateId(), "处理完成"); } else { // 通知 noticeProcess(deploy, Long.valueOf(nextTask.getAssigee())); } } /** * 查询部署申请详情 * * @return */ @Override public DeployBo getById(Long deployId) { DeployWithCreatorDto deployWithCreator = deployDao .getWithCreator(deployId); // 查询部署申请当前处理人 User currentProcessor = getCurrentProcessor(deployWithCreator .getFlowEngineInstanceId()); List<Project> projects = projectDao.getByDeployId(deployId); List<DeployStep> deploySteps = deployStepDao.getByDeployId(deployId); return DeployServiceConvertor.buildDeployBo(deployWithCreator, currentProcessor, projects, deploySteps); } /** * 查询部署申请操作日志 * * @return */ @Override public List<TicketOpLog> getOpLogs(Long deployId) { return bizLogService.getOpLogs(deployId, ConstantsValue.BIZ_TYPE_DEPLOYMENT); } /** * 查询部署申请处理步骤 * * @return */ @Override public List<FlowStepItem> getFlowSteps(Long deployId) { Deploy deploy = getAndCheckDataAuth(deployId); if (deploy.getFlowEngineInstanceId() == null) { return Collections.emptyList(); } List<TaskInfo> histortyTaskList = activityServiceRpc .findHistoryTasks(deploy.getFlowEngineInstanceId()); if (deploy.getFlowEngineInstanceId() == null) { return Collections.emptyList(); } UserQueryDto userQueryBo = new UserQueryDto(); List<Long> userIds = new ArrayList<Long>(); histortyTaskList.forEach(item -> { if (item.getAssigee() != null) { userIds.add(Long.valueOf(item.getAssigee())); } }); userQueryBo.setUserIds(userIds); List<UserInfoDto> opUsers = userDao.getUserList(userQueryBo); List<FlowStepItem> steps = new ArrayList<FlowStepItem>(); histortyTaskList.forEach(item -> { String assigneer = getUserRealName(item.getAssigee(), opUsers); steps.add(new FlowStepItem(item.getTaskName(), assigneer, item .getComment())); }); return steps; } /** * 查询所有部署申请 * * @param queryVo * @return */ @Override public List<DeployBo> queryAllList(DeployQueryBo queryBo) { DeployQueryDto queryDto = DeployServiceConvertor .buildDeployQueryDto(queryBo); return queryByParam(queryDto); } /** * 查询所有部署申请Count * * @param queryVo * @return */ @Override public int queryAllListCount(DeployQueryBo queryBo) { DeployQueryDto queryDto = DeployServiceConvertor .buildDeployQueryDto(queryBo); return deployDao.getCountByParam(queryDto); } /** * 查询所有待处理的部署申请 * * @param queryVo * @return */ @Override public List<DeployBo> queryWaitingList() { List<String> definitIds = getDeployFlowDefinitIds(); if (CollectionUtils.isEmpty(definitIds)) { return Collections.emptyList(); } // 查询待处理任务 List<TaskInfo> taskInfoList = new ArrayList<TaskInfo>(); definitIds.forEach(item -> { taskInfoList.addAll(activityServiceRpc.findTasksByUserId(item, sessionService.getCurrentUser().getUserId().toString())); }); if (CollectionUtils.isEmpty(taskInfoList)) { return Collections.emptyList(); } // 根据任务查询部署申请 List<String> instanceIds = new ArrayList<String>(); taskInfoList.forEach(item -> instanceIds.add(item.getInstanceId())); DeployQueryDto queryDto = new DeployQueryDto(); queryDto.setInstanceIds(instanceIds); List<DeployBo> result = queryByParam(queryDto); if (CollectionUtils.isEmpty(result)) { return Collections.emptyList(); } // 过滤非处理中的请求 Iterator<DeployBo> itr = result.iterator(); while (itr.hasNext()) { DeployBo deployBo = itr.next(); if (DeployStatus.PROCESSING.getType() != deployBo.getStatus()) { itr.remove(); } } return result; } /** * 查询所有待处理的部署申请Count * * @param queryVo * @return */ @Override public int queryWaitingListCount() { return queryWaitingList().size(); } /** * 查询用户处理的部署申请历史 * * @param queryVo */ @Override public List<DeployBo> queryHistoryList(DeployQueryBo queryBo) { // TODO: return null; } /** * 查询用户处理的部署申请历史Count * * @param queryVo */ @Override public int queryHistoryListCount(DeployQueryBo queryBo) { // TODO: return 0; } /** * 按天统计部署申请 * * @param start * @param end * @return */ @Override public List<HistogramItem> statisticByDay(Date start, Date end) { List<HistogramItem> list = deployDao.statisticByDay(start, end); List<HistogramItem> result = new ArrayList<HistogramItem>(); Map<String, HistogramItem> map = new HashMap<String, HistogramItem>(); list.forEach(item -> map.put(item.getItem(), item)); // 日期补全 int between = DateUtils.differentDaysByMillisecond(start, end); int offset = 0; do { String day = DateUtils.format( DateUtils.getAddedDate(start, offset), DateUtils.DATE_FORMAT_YYYY_MM_DD); offset++; HistogramItem histogramItem = map.get(day); if (histogramItem == null) { result.add(new HistogramItem(day)); } else { result.add(histogramItem); } } while (offset <= between); return result; } /** * 首次提交 * * @param deploy */ private void submit(Deploy deploy) { // 开启部署申请流程 Map<String, Object> variables = getActivitInitVariables(); LOGGER.info("用户[{}]提交部署申请[{}],处理人:{}!", sessionService.getCurrentUser() .getUserId(), deploy.getId(), variables); String instanceId = activityServiceRpc .startProcesses(new ActivityStart(deploy .getFlowEngineDefinitionId(), variables)); instanceId = instanceId.replaceAll("\"", ""); LOGGER.info("用户[{}]提交部署申请[{}],启动流程,instanceId:{}!", sessionService .getCurrentUser().getUserId(), deploy.getId(), instanceId); // 保存部署申请流程实例ID deploy.setSubmitTime(new Date()); deploy.setFlowEngineInstanceId(instanceId); updateStatusAndLog(deploy, DeployOp.SUBMIT, ""); // 提交部署申请 completeTask(deploy.getId(), null, ""); } /** * 重新提交部署申请 * * @param DeployId * @return */ private void resubmit(Deploy deploy) { // 重新提交部署申请 completeTask(deploy.getId(), null, ""); deploy.setSubmitTime(new Date()); updateStatusAndLog(deploy, DeployOp.RESUBMIT, ""); } /** * 校验部署申请数据编辑权限 * * @param deployId */ private Deploy getAndCheckDataAuth(Long deployId) { Deploy deploy = deployDao.getByPrimaryKey(deployId); if (deploy == null || sessionService.getCurrentUser().getUserId() != deploy .getCreateId()) { LOGGER.warn("数据操作权限不合法:{},操作人ID:{}", JSON.toJSONString(deploy), deployId); throw ServiceException.commonException("非法请求!"); } return deploy; } /** * 获取当前处理人 * * @param flowEngineInstanceId * @return */ private User getCurrentProcessor(String flowEngineInstanceId) { if (flowEngineInstanceId == null) { return null; } TaskInfo taskInfo = activityServiceRpc .getCurrentTask(flowEngineInstanceId); User currentProcessor = null; if (taskInfo != null) { currentProcessor = userDao.selectByPrimaryKey(Long.valueOf(taskInfo .getAssigee())); } return currentProcessor; } /** * 查询部署申请流程引擎模板ID * * @return */ private String getDeployFlowDefinitId(Byte type) { FlowTemplate flow = null; if (DeployType.BUGFIX.getType() == type) { flow = flowTemplateDao.getOneByCode(TemplateKeys.RELEASE_FIXBUG .getKey()); } else if (DeployType.CODE_OPTIMIZE.getType() == type) { flow = flowTemplateDao.getOneByCode(TemplateKeys.RELEASE_OPTIMIZE .getKey()); } else if (DeployType.VERSION_RELEASE.getType() == type) { flow = flowTemplateDao.getOneByCode(TemplateKeys.RELEASE_VERSION .getKey()); } if (flow == null) { throw ServiceException.commonException("流程模板为空!"); } return flow.getFlowEngineDefinitionId(); } /** * 查询所有审批模板ID * * @return */ private List<String> getDeployFlowDefinitIds() { List<String> types = new ArrayList<String>(); FlowTemplate flow = null; flow = flowTemplateDao.getOneByCode(TemplateKeys.RELEASE_FIXBUG .getKey()); if (flow != null) { types.add(flow.getFlowEngineDefinitionId()); } flow = flowTemplateDao.getOneByCode(TemplateKeys.RELEASE_OPTIMIZE .getKey()); if (flow != null) { types.add(flow.getFlowEngineDefinitionId()); } flow = flowTemplateDao.getOneByCode(TemplateKeys.RELEASE_VERSION .getKey()); if (flow != null) { types.add(flow.getFlowEngineDefinitionId()); } return types; } private List<DeployBo> queryByParam(DeployQueryDto workQueryDto) { // 查询部署申请主表 List<DeployWithCreatorDto> list = deployDao .getListByParam(workQueryDto); if (CollectionUtils.isEmpty(list)) { return Collections.emptyList(); } List<Long> deployIds = new ArrayList<Long>(); list.forEach(item -> deployIds.add(item.getId())); List<DeployBo> result = new ArrayList<DeployBo>(); // 查询部署申请步骤 Map<Long, List<DeployStep>> deployStepMap = getDeployStepsByDeployIds(deployIds); // 查询部署申请项目 Map<Long, List<Project>> deployProjectMap = getProjectByDeployIds(deployIds); list.forEach(item -> result.add(DeployServiceConvertor.buildDeployBo( item, getCurrentProcessor(item.getFlowEngineInstanceId()), deployProjectMap.get(item.getId()), deployStepMap.get(item.getId())))); return result; } private Map<Long, List<DeployStep>> getDeployStepsByDeployIds( List<Long> deployIds) { Map<Long, List<DeployStep>> result = new HashMap<Long, List<DeployStep>>(); List<DeployStep> stepList = deployStepDao.getByDeployIds(deployIds); if (CollectionUtils.isEmpty(stepList)) { return Collections.emptyMap(); } stepList.forEach(item -> { List<DeployStep> tmpSteps = result.get(item.getDeployId()); if (tmpSteps == null) { tmpSteps = new ArrayList<DeployStep>(); result.put(item.getDeployId(), tmpSteps); } tmpSteps.add(item); }); return result; } private Map<Long, List<Project>> getProjectByDeployIds(List<Long> deployIds) { Map<Long, List<Project>> result = new HashMap<Long, List<Project>>(); List<DeployProjectDto> projectList = projectDao .getByDeployIds(deployIds); if (CollectionUtils.isEmpty(projectList)) { return Collections.emptyMap(); } projectList.forEach(item -> { List<Project> tmpSteps = result.get(item.getDeployId()); if (tmpSteps == null) { tmpSteps = new ArrayList<Project>(); result.put(item.getDeployId(), tmpSteps); } tmpSteps.add(item); }); return result; } /** * 记录日志以及更改状态 * * @param deploy * @param op */ private void updateStatusAndLog(Deploy deploy, DeployOp op, String comment) { // 更新数据状态 if (op.getTargetStatus() != null) { deploy.setStatus(op.getTargetStatus().getType()); deployDao.updateByPrimaryKeySelective(deploy); } // 日志 bizLogService.saveDeployLog(deploy.getId(), deploy.getTitle(), op .getValue(), comment, sessionService.getCurrentUser() .getUserId()); } private String getUserRealName(String userId, List<UserInfoDto> opUsers) { if (StringUtils.isEmpty(userId)) { return null; } String realname = null; for (UserInfoDto userDto : opUsers) { if (userDto.getId().equals(Long.valueOf(userId))) { realname = userDto.getRealname(); break; } } return realname; } /** * 获取短信通知处理模板 * * @param deployId * @param title * @param submitor * @return */ private String getNoticeProcessMessage(Long deployId, String title, String submitor) { String messageTemplet = "【部署申请系统】提示您有一个待处理部署申请,请前往系统处理。部署申请编号:[number],部署申请标题:[title],提交人:[sumitor]"; messageTemplet = messageTemplet.replaceAll("number", deployId.toString()); messageTemplet = messageTemplet.replaceAll("title", title); messageTemplet = messageTemplet.replaceAll("sumitor", submitor); return messageTemplet; } /** * 获取短信通知处理结果模板 * * @param DeployId * @param title * @param submitor * @return */ private String getNoticeResultMessage(String deployTitle, String result) { String messageTemplet = "【部署申请系统】提示您,您提交的部署申请[title],已处理,处理结果[result]。"; messageTemplet = messageTemplet.replaceAll("title", deployTitle); messageTemplet = messageTemplet.replaceAll("result", result); return messageTemplet; } /** * 通知处理 * * @param DeployWithProjectDto * @param noticeUserId */ private void noticeProcess(Deploy deploy, Long noticeUserId) { User nextProcessor = userDao.selectByPrimaryKey(Long .valueOf(noticeUserId)); User submitor = userDao.selectByPrimaryKey(deploy.getCreateId()); if (nextProcessor == null) { LOGGER.info("通知用户[{}]处理部署申请[{}]失败,用户不存在!", noticeUserId, deploy.getId()); } // TODO:邮件短信息通知 try { smsService.send( nextProcessor.getMobile(), getNoticeProcessMessage(deploy.getId(), deploy.getTitle(), submitor.getRealname())); } catch (Exception e) { LOGGER.error("通知用户处理部署申请失败,excption:{}", e); e.printStackTrace(); } LOGGER.info("通知用户[{}]处理部署申请[{}]!", nextProcessor.getUsername(), deploy.getId()); } /** * 通知处理结果 * * @param DeployWithProjectDto * @param noticeUserId */ private void noticeResult(Deploy deploy, Long noticeUserId, String result) { User nextProcessor = userDao.selectByPrimaryKey(Long .valueOf(noticeUserId)); if (nextProcessor == null) { LOGGER.info("通知用户[{}]部署申请处理结果[{}]失败,用户不存在!", noticeUserId, result); } // TODO:邮件短信息通知 try { smsService.send(nextProcessor.getMobile(), getNoticeResultMessage(deploy.getTitle(), result)); } catch (Exception e) { LOGGER.error("通知用户部署申请处理结果失败,excption:{}", e); e.printStackTrace(); } LOGGER.info("通知用户[{}]部署申请处理结果[{}]成功!", nextProcessor.getUsername(), result); } /** * activiti初始化参数 * * @return */ private Map<String, Object> getActivitInitVariables() { // 开启部署申请流程 Map<String, Object> variables = new HashMap<String, Object>(); UserInfoBo proposer = sessionService.getCurrentUser(); Group proposeGroup = groupDao.selectByPrimaryKey(proposer.getGroup() .getId()); User groupLeader = userDao.selectByPrimaryKey(proposeGroup.getUserId()); User operatorUser = userDao.getLeaderByGroupCode(OPERATOR_GROUP_CODE); User productUser = userDao.getLeaderByGroupCode(PROD_GROUP_CODE); User testUser = userDao.getLeaderByGroupCode(TEST_GROUP_CODE); User leaderUser = userDao.getLeaderByGroupCode(LEADER_GROUP_CODE); if (groupLeader == null || operatorUser == null || productUser == null || testUser == null || leaderUser == null) { throw ServiceException.commonException("配置异常!"); } variables.put("groupLeader", groupLeader.getId()); variables.put("proposer", proposer.getUserId()); variables.put("tester", testUser.getId()); variables.put("proder", productUser.getId()); variables.put("leader", leaderUser.getId()); variables.put("operator", operatorUser.getId()); return variables; } private static String OPERATOR_GROUP_CODE = "operator";// 运维 private static String PROD_GROUP_CODE = "product";// 产品 private static String TEST_GROUP_CODE = "test";// 测试 private static String LEADER_GROUP_CODE = "leader";// 领导 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mapred.gridmix; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.Log; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.test.system.MRCluster; import org.apache.hadoop.mapreduce.test.system.JTClient; import org.apache.hadoop.mapreduce.test.system.JTProtocol; import org.apache.hadoop.mapred.gridmix.FilePool; import org.apache.hadoop.mapred.gridmix.test.system.UtilsForGridmix; import org.apache.hadoop.mapred.gridmix.test.system.GridMixRunMode; import org.apache.hadoop.mapred.gridmix.test.system.GridMixConfig; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.FileStatus; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.AfterClass; import org.junit.Test; import java.io.IOException; import java.util.ArrayList; public class TestGridMixFilePool { private static final Log LOG = LogFactory.getLog(TestGridMixFilePool.class); private static Configuration conf = new Configuration(); private static MRCluster cluster; private static JTProtocol remoteClient; private static JTClient jtClient; private static Path gridmixDir; private static int clusterSize; @BeforeClass public static void before() throws Exception { String [] excludeExpList = {"java.net.ConnectException", "java.io.IOException"}; cluster = MRCluster.createCluster(conf); cluster.setExcludeExpList(excludeExpList); cluster.setUp(); jtClient = cluster.getJTClient(); remoteClient = jtClient.getProxy(); clusterSize = cluster.getTTClients().size(); gridmixDir = new Path("herriot-gridmix"); UtilsForGridmix.createDirs(gridmixDir, remoteClient.getDaemonConf()); } @AfterClass public static void after() throws Exception { UtilsForGridmix.cleanup(gridmixDir, conf); cluster.tearDown(); } @Test public void testFilesCountAndSizesForSpecifiedFilePool() throws Exception { conf = remoteClient.getDaemonConf(); final long inputSizeInMB = clusterSize * 200; int [] fileSizesInMB = {50, 100, 400, 50, 300, 10, 60, 40, 20 ,10 , 500}; long targetSize = Long.MAX_VALUE; final int expFileCount = clusterSize + 4; String [] runtimeValues ={"LOADJOB", SubmitterUserResolver.class.getName(), "STRESS", inputSizeInMB + "m", "file:///dev/null"}; String [] otherArgs = { "-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=false", "-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=false" }; // Generate the input data by using gridmix framework. int exitCode = UtilsForGridmix.runGridmixJob(gridmixDir, conf, GridMixRunMode.DATA_GENERATION.getValue(), runtimeValues, otherArgs); Assert.assertEquals("Data generation has failed.", 0 , exitCode); // Create the files without using gridmix input generation with // above mentioned sizes in a array. createFiles(new Path(gridmixDir, "input"), fileSizesInMB); conf.setLong(FilePool.GRIDMIX_MIN_FILE, 100 * 1024 * 1024); FilePool fpool = new FilePool(conf, new Path(gridmixDir, "input")); fpool.refresh(); verifyFilesSizeAndCountForSpecifiedPool(expFileCount, targetSize, fpool); } private void createFiles(Path inputDir, int [] fileSizes) throws Exception { for (int size : fileSizes) { UtilsForGridmix.createFile(size, inputDir, conf); } } private void verifyFilesSizeAndCountForSpecifiedPool(int expFileCount, long minFileSize, FilePool pool) throws IOException { final ArrayList<FileStatus> files = new ArrayList<FileStatus>(); long filesSizeInBytes = pool.getInputFiles(minFileSize, files); long actFilesSizeInMB = filesSizeInBytes / (1024 * 1024); long expFilesSizeInMB = (clusterSize * 200) + 1300; Assert.assertEquals("Files Size has not matched for specified pool.", expFilesSizeInMB, actFilesSizeInMB); int actFileCount = files.size(); Assert.assertEquals("File count has not matched.", expFileCount, actFileCount); int count = 0; for (FileStatus fstat : files) { String fp = fstat.getPath().toString(); count = count + ((fp.indexOf("datafile_") > 0)? 0 : 1); } Assert.assertEquals("Total folders are not matched with cluster size", clusterSize, count); } }
/* * 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 edu.ucla.cs.scai.canali.core.experiment.qald6; import java.util.ArrayList; public class ExperimenterTest { public static void main(String[] args) throws Exception { //String path = "/home/lucia/data/nlp2sparql_data/"; String path = ""; QASystem qas = new CanaliW2VQASystem(path + "/home/lucia/data/w2v/abstract_200_20.w2v.bin", path + "/home/lucia/data/seodwarf/index/supportFiles/property_labels"); //System.setProperty("kb.index.dir", "/home/lucia/nlp2sparql-data/dbpedia-processed/2015-10/dbpedia-processed_onlydbo_mini_e/index/"); //!!! System.setProperty("kb.index.dir", path + "/home/lucia/data/seodwarf/index/processed/"); String query = "What is the online resource of Cretan Sea ?"; //String query = "Show me the Image having hasOnlineResource aaa"; ArrayList<String> systAns = new ArrayList<String>(); systAns = qas.getAnswer(query, null); for (String a : systAns) { System.out.println("System = " + a); } } }
/* Author - Saira Akram * Creation Date - May 2018 * Last Modified Date - August 2018 */ package com.sdc.automation.stepdefinitions; import com.sdc.automation.backend.HDCAConnector; import cucumber.api.java.en.And; import cucumber.api.java.en.Given; public class HDCAstepDefinition { @And("the HDCA NULL check begins") public void hasNullValues() throws Exception { HDCAConnector.checkNull(); } @Given("^I am connected to HDCA: \"([^\"]*)\"$") public void iAmConnectedToHDCA(String HDCAconnectionURl) { HDCAConnector.setConnectionURl(HDCAconnectionURl); } @And("^I use the HDCA Authorisation: \"([^\"]*)\"$") public void iSpecifyHDCAauthorisation(String HDCAauthorisation) { HDCAConnector.setAuthorisation(HDCAauthorisation); } @And("I use the HDCA END_TIME: \"([^\"]*)\"$") public void iSpecifyHDCAendTime(String HDCAendTime) { HDCAConnector.setEndTime(HDCAendTime); } @And("the HDCA data is extracted at: \"([^\"]*)\"$") public void iSpecifyHDCAfilePath(String filePath) throws Exception { HDCAConnector.setFilePath(filePath); } @And("I use the HDCA Query: \"([^\"]*)\"$") public void iSpecifyHDCAquery(String HDCAquery) { HDCAConnector.setQuery(HDCAquery); } @And("I use the HDCA Resource: \"([^\"]*)\"$") public void iSpecifyHDCAresource(String HDCAresource) { HDCAConnector.setResource(HDCAresource); } @And("I use the HDCA START_TIME: \"([^\"]*)\"$") public void iSpecifyHDCAstartTime(String HDCAstartTime) { HDCAConnector.setStartTime(HDCAstartTime); } @And("the HDCA connection is established") public void theHDCAconnection() throws Exception { HDCAConnector.connect(); } }
package com.yixin.dsc.dto; import java.io.Serializable; import java.math.BigDecimal; import java.util.List; /** * 试算DTO * Package : com.yixin.dsc.dto * * @author YixinCapital -- wangwenlong * 2018年7月4日 下午7:42:11 * */ public class DscComputerResultDto implements Serializable{ /** * */ private static final long serialVersionUID = 5249451569455534322L; /** * 申请编号/订单编号 */ private String applyNo; /** * FRZE 客户融资额 */ private BigDecimal frze; /** * 试算明细 */ private List<DscFeeScheduleDto> schedules; public String getApplyNo() { return applyNo; } public void setApplyNo(String applyNo) { this.applyNo = applyNo; } public BigDecimal getFrze() { return frze; } public void setFrze(BigDecimal frze) { this.frze = frze; } public List<DscFeeScheduleDto> getSchedules() { return schedules; } public void setSchedules(List<DscFeeScheduleDto> schedules) { this.schedules = schedules; } }
package leecode.dfs; import java.util.LinkedList; import java.util.Queue; //https://leetcode-cn.com/problems/check-completeness-of-a-binary-tree/solution/hen-jian-dan-de-si-lu-dai-ma-hen-jian-ji-by-yuanyb/ public class 二叉树的完全性检验_958 { // //LinkedList做队列的话支持添加null元素,而ArrayDeque不支持添加null,这个题要添加空 public boolean isCompleteTree(TreeNode root) { Queue<TreeNode> queue=new LinkedList<>(); queue.offer(root); TreeNode pre=root; while (!queue.isEmpty()){ TreeNode cur=queue.poll(); if(pre==null&&cur!=null){ return false; } if(cur!=null){ queue.offer(cur.left); queue.offer(cur.right); } pre=cur; } return true; } }
package org.gardella.security.service; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang.time.DateUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.gardella.common.jdbc.ZeroRowsAffectedException; import org.gardella.security.LoginCode; import org.gardella.security.LoginState; import org.gardella.security.MyUserAuthentication; import org.gardella.security.dao.UserDAO; import org.gardella.security.model.LoginSession; import org.gardella.security.model.User; import org.gardella.security.model.UserStatus; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.CredentialsExpiredException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.GrantedAuthorityImpl; import org.springframework.security.core.context.SecurityContextHolder; import com.google.common.base.Preconditions; public class LoginService{ protected final Log logger = LogFactory.getLog(getClass()); private UserDAO userDAO; public LoginState checkLogin( String email, String password ){ User user = userDAO.getUser(email); LoginState state = new LoginState( user ); if( user == null ){ state.setCode(LoginCode.INVALID_EMAIL); } else if( !user.getPassword().equals( DigestUtils.md5Hex(password) ) ){ state.setCode(LoginCode.INVALID_PASSWORD); } else if (user.getUserStatus()!=UserStatus.ACTIVE) { if(user.getUserStatus() == UserStatus.PENDING){ state.setCode(LoginCode.PENDING_USER); }else{ state.setCode(LoginCode.INACTIVE_USER); } }else { state.setCode(LoginCode.SUCCESS); } return state; } public LoginState checkSessionKey( String sessionKey ){ long userId = getUserIdFromValidSession( sessionKey ); LoginState state; if(userId > 0 ){ User user = userDAO.getUser(userId); state = new LoginState(user); state.setCode(LoginCode.HEADER_AUTH); }else{ state = new LoginState(null); state.setCode(LoginCode.PERMISSION_DENIED); } return state; } public void setUserDAO(UserDAO userDAO) { this.userDAO = userDAO; } private Authentication success(LoginState state, String sessionId) { List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); authorities.add(new GrantedAuthorityImpl("ROLE_USER")); if(state.getCode() == LoginCode.PENDING_USER){ authorities.add(new GrantedAuthorityImpl("ROLE_NEEDS_EMAIL_AUTH")); } if(state.getUser().admin()){ authorities.add(new GrantedAuthorityImpl("ROLE_ADMIN")); } //save a simple bean that is a subset of our User model object MyUserAuthentication user = new MyUserAuthentication(state.getUser()); user.setCountryCode(LocaleContextHolder.getLocale().getCountry()); // Longest. Class name. EVAR UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user, state.getUser().getPassword(), authorities); if(state.getCode() != LoginCode.HEADER_AUTH){ //save it in the DB (user_session) saveSessionId( sessionId, user.getUserId() ); } SecurityContextHolder.getContext().setAuthentication(token); return token; } public Authentication login(String user, String pass, String sessionKey) { Preconditions.checkNotNull(user); Preconditions.checkNotNull(pass); Preconditions.checkNotNull(sessionKey); LoginState state = this.checkLogin(user, pass); return login2(state, sessionKey); } public Authentication loginWithSessionKey(String sessionKey, String email) { Preconditions.checkNotNull(sessionKey); LoginState state = this.checkSessionKey(sessionKey); if(state.getUser() != null && state.getUser().getEmail().equalsIgnoreCase(email)){ return login2(state, sessionKey); } throw new BadCredentialsException("email does not match sessionkey"); } private Authentication login2(LoginState state, String session) { LoginCode code = state.getCode(); switch (code) { case SUCCESS: case HEADER_AUTH: case PENDING_USER: return success(state, session); case INACTIVE_USER: throw new CredentialsExpiredException(code.toString()); default: throw new BadCredentialsException(code.toString()); } } private void saveSessionId( String sessionId, long userId ){ if(getUserIdFromValidSession(sessionId) != userId){ //if the session is still valid, leave it alone try{ userDAO.deleteLoginSession(sessionId); // clear out any old sessions w/ this id }catch(ZeroRowsAffectedException e){ //catch exception if the sessionId is already gone //noop } LoginSession loginSession = new LoginSession(); loginSession.setSessionKey(sessionId); loginSession.setUserId(userId); long now = System.currentTimeMillis(); loginSession.setCreatedOn(new Date(now)); loginSession.setModifiedOn(new Date(now)); long endTime = now + (DateUtils.MILLIS_PER_HOUR * 2); //session expires in 2 hours loginSession.setExpiredOn(new Date(endTime)); userDAO.createLoginSession(loginSession); } } private long getUserIdFromValidSession( String sessionId ){ LoginSession sess = userDAO.getLoginSession(sessionId); if(sess != null && sess.getExpiredOn().after(new Date())){ return sess.getUserId(); } //logger.error("session id [" + sessionId + "] is invalid or null in the db."); if(sess == null){ logger.error("session row is null for id: [" + sessionId + "]"); }else{ logger.error("session row invalid for id: [" + sessionId + "] expire stamp: [" + sess.getExpiredOn().toString() + "]"); } return -1L; } }
package webservices; import entity.Article; import org.codehaus.jackson.map.ObjectMapper; import service.Service; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.*; import javax.ws.rs.core.Context; import java.io.IOException; import java.util.Collection; /** * Created by F on 11/07/2015. */ @RequestScoped @Named @Path("/article") @Produces("application/json; charset=UTF-8") public class ArticleService { @Inject Service service; @GET @Path("get/{articleId}") public Article getArticle(@PathParam("articleId") final Integer articleId) { return service.find(Article.class, articleId); } @POST @Path("/add") @Consumes("application/json") public Article addArticle(String value) throws IOException { Article article = new ObjectMapper().readValue(value, Article.class); return service.create(article); } @POST @Path("/update") @Consumes("application/json") public Article updateArticle(String value) throws IOException { Article article = new ObjectMapper().readValue(value, Article.class); return service.update(article); } @POST @Path("/delete") @Consumes("application/json") public String deleteArticle(String value) throws IOException { Article article = new ObjectMapper().readValue(value, Article.class); service.delete(article); return "OK"; } public Collection<Article> getAllArticles(@Context final HttpServletRequest request) { return service.findAll(Article.class); } }
/* * This file is part of SMG, a symbolic memory graph Java library * Originally developed as part of CPAChecker, the configurable software verification platform * * Copyright (C) 2011-2015 Petr Muller * Copyright (C) 2007-2014 Dirk Beyer * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package cz.afri.smg.objects; import java.util.Set; import com.google.common.collect.Sets; import cz.afri.smg.abstraction.SMGConcretisation; import cz.afri.smg.graphs.ReadableSMG; public abstract class SMGAbstractObject extends SMGObject { protected SMGAbstractObject(final int pSize, final String pLabel) { super(pSize, pLabel); } protected SMGAbstractObject(final SMGObject pPrototype) { super(pPrototype); } @Override public final boolean isAbstract() { return true; } public abstract boolean matchGenericShape(SMGAbstractObject pOther); public abstract boolean matchSpecificShape(SMGAbstractObject pOther); public final Set<ReadableSMG> concretise(final ReadableSMG pSmg) { SMGConcretisation concretisation = createConcretisation(); if (concretisation == null) { return Sets.newHashSet(pSmg); } return concretisation.execute(pSmg); } protected abstract SMGConcretisation createConcretisation(); }
package ba.bitcamp.LabS03D04; public class FunkProsjekNiza { public static int[] unosUNiz(int brojA) { /** * */ int[] noviNiz = new int [brojA]; for(int i = 0; i<noviNiz.length; i++) { System.out.print("Unesite broj u niz: "); int brojNiz = TextIO.getlnInt(); noviNiz[i] = brojNiz; } return noviNiz; } /** * * @param niz * @return */ public static double sum(int [] niz) { double sum = 0; for (int i = 0; i < niz.length; i++) { sum = sum + niz[i]; } return sum; } /** * * @param suma * @param broj * @return */ public static double prosjek (double suma, int broj) { double prosjek = (double)(suma / broj); return prosjek; } public static void main(String[] args) { System.out.print("Unesite broj elemenata u nizu: "); int broj = TextIO.getlnInt(); int [] niz = unosUNiz(broj); double suma = sum(niz); System.out.println("Suma niza je: " + suma); double prosjek = prosjek(suma, broj); System.out.println("Prosjek niza je: " + prosjek); } }
package 문제풀이; public class 정리문제 { public static void main(String[] args) { String food = "떡볶이"; switch (food) { case "떡볶이": System.out.println("분식집으로"); break; //우동: 일식집, 짜장: 중국집, 아니면: 집에서 case "우동": System.out.println("일식집으로"); break; case "짜장": System.out.println("중국집으로"); break; default: System.out.println("집에서"); break; } String sn = "980201-1037514"; //위치값 index char gender = sn.charAt(7); // '1' //switch //if~else : char는 기본데이터이기 때문에 비교연산자 사용 가능 switch (gender) { case '1': case '3': System.out.println("남자"); break; case '2': case '4': System.out.println("여자"); break; default: System.out.println("잘못 입력했음"); break; } if (gender == '1' || gender == '3') { System.out.println("남자"); } else if (gender == '2' || gender == '4'){ System.out.println("여자"); } else { System.out.println("잘못입력"); } } }
package memory; public class _ParsableTest { }
package com.hban.common.view; import android.app.Dialog; import android.app.DialogFragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import com.hban.common.R; /** * Created by zhuchuntao on 16-12-5. */ public class CommonDialog extends DialogFragment { public CommonDialog() { super(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //下边这段代码会将布局中所有的组件按照这个样式显示 //setStyle(DialogFragment.STYLE_NO_TITLE,R.style.load_dialog); } @Override public void onStart() { super.onStart(); Dialog dialog = getDialog(); if (dialog != null) { DisplayMetrics dm = new DisplayMetrics(); getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm); //宽度是屏幕宽度的3/4 dialog.getWindow().setLayout((int) (dm.widthPixels * 0.75), ViewGroup.LayoutParams.WRAP_CONTENT); } } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return super.onCreateDialog(savedInstanceState); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE); View view = inflater.inflate(R.layout.common_dialog, null); return view; } }
package com.tencent.mm.plugin.backup.e; public class k$a { public String gWj = ""; public String gWk = ""; public String gWl = ""; public String gWm = ""; public k$a(String str, String str2, String str3, String str4) { this.gWj = str; this.gWk = str2; this.gWl = str3; this.gWm = str4; } public final String toString() { return this.gWj + " " + this.gWk + " " + this.gWl + " " + this.gWm; } }
package ba.bitcamp.LabS13D01.vjezbe.server; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import ba.bitcamp.LabS13D01.vjezbe.gui.ChatGUI; public class Server { private static final int port = 1717; public static void serverStart() throws IOException { ServerSocket server = new ServerSocket(port); while (true) { System.out.println("Waiting"); Socket client = server.accept(); ChatGUI chat = new ChatGUI(client); new Thread(chat).start(); } } public static void main(String[] args) { try { serverStart(); } catch (IOException e) { System.err.println(e.getMessage()); } } }
/* * 2012-3 Red Hat Inc. and/or its affiliates and other contributors. * * 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 org.overlord.rtgov.active.collection; import org.overlord.rtgov.active.collection.predicate.Predicate; /** * This class defines the query specification that can be used to define * the active collection that is required. If a name and no predicate/parent * is specified, then a lookup on the name will be returned. If the query * spec defines a name, predicate and parent collection, then initially * a check will be made for the collection name. If it does not exist, then * a derived collection of that name will be created based on the parent * collection name and predicate. * */ @org.codehaus.enunciate.json.JsonRootType public class QuerySpec { private String _collection=null; private Predicate _predicate=null; private String _parent=null; private int _maxItems=0; private Truncate _truncate=Truncate.Start; private Style _style=Style.Normal; private java.util.Map<String,Object> _properties=new java.util.HashMap<String, Object>(); /** * The default constructor. */ public QuerySpec() { } /** * This method returns the name of the collection. * * @return The collection name */ public String getCollection() { return (_collection); } /** * This method sets the name of the collection. * * @param name The collection name */ public void setCollection(String name) { _collection = name; } /** * This method returns the optional predicate. If specified, * along with the parent collection name, it can * be used to derive a sub-collection. * * @return The predicate */ public Predicate getPredicate() { return (_predicate); } /** * This method sets the optional predicate. If specified, * along with the parent collection name, it can * be used to derive a sub-collection. * * @param pred The predicate */ public void setPredicate(Predicate pred) { _predicate = pred; } /** * This method returns the name of the parent collection. * * @return The parent collection name */ public String getParent() { return (_parent); } /** * This method sets the name of the parent collection. * * @param name The parent collection name */ public void setParent(String name) { _parent = name; } /** * This method returns the maximum number of items * that should be included in the query result, * or 0 if unrestricted. * * @return The maximum number of items, or 0 if unrestricted */ public int getMaxItems() { return (_maxItems); } /** * This method sets the maximum number of items * that should be included in the query result, * or 0 if unrestricted. * * @param maxItems The maximum number of items, or 0 if unrestricted */ public void setMaxItems(int maxItems) { _maxItems = maxItems; } /** * This method returns which part of the collection * should be truncated if the collection contains * more items than can be returned in the query result. * * @return The truncation location */ public Truncate getTruncate() { return (_truncate); } /** * This method sets which part of the collection * should be truncated if the collection contains * more items than can be returned in the query result. * * @param truncate The truncation location */ public void setTruncate(Truncate truncate) { _truncate = truncate; } /** * This method returns the style that should be used * for returning the result. * * @return The style */ public Style getStyle() { return (_style); } /** * This method sets the style that should be used * for returning the result. * * @param style The style */ public void setStyle(Style style) { _style = style; } /** * This method returns the additional properties. * * @return The properties */ public java.util.Map<String,Object> getProperties() { return (_properties); } /** * This method sets the additional properties. * * @param props The properties */ public void setProperties(java.util.Map<String,Object> props) { _properties = props; } /** * {@inheritDoc} */ public String toString() { return ("Query[collection="+_collection+" parent=" +_parent+" predicate="+_predicate +" maxItems="+_maxItems+" truncate=" +_truncate+" style="+_style+"]"); } /** * This enumerated type defines where truncation should * occur if the collection size is greater than the * maximum number of items specified. */ public enum Truncate { /** * This value indicates that the last portion of the * collection should be returned. */ Start, /** * This value indicates that the first portion of the * collection should be returned. */ End } /** * This enumerated type defines the style used for returning * the results. */ public enum Style { /** * This value indicates that the results should be returned * as normal. */ Normal, /** * This value indicates that the results should be returned * in reverse order. */ Reversed } }
package temakereso.helper; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; @Data @NoArgsConstructor public class ReportFilters { private static ReportFilters EMPTY = new ReportFilters(); @DateTimeFormat(pattern = "yy.MM.dd") private Date startDate; @DateTimeFormat(pattern = "yy.MM.dd") private Date endDate; public boolean isEmpty() { return this.equals(EMPTY); } }
package com.tt.a; import android.app.Application; import com.bytedance.d.a.b.a; import com.bytedance.d.a.c.b.a; import d.f.b.l; public final class b implements a { public static final b a = new b(); public final com.bytedance.d.a.b.b a() { return com.bytedance.d.a.b.b.a.a("BDLog"); } public final void a(Application paramApplication) { l.b(paramApplication, "app"); l.b(paramApplication, "app"); a.a.a((a)this, paramApplication); } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\a\b.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package marche.traitement.Marche; import marche.traitement.Acteurs.Acteur; import marche.traitement.Acteurs.ChoixAcheteur.StrategyChoixAcheteur; import marche.traitement.Acteurs.VendeurAcheteur; import marche.traitement.Produit.Produit; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; /** * */ public class Offre { private boolean valider = false; private int prix; private Produit produit; private List<Acteur> acheteurPotentiel = new ArrayList<Acteur>(); private VendeurAcheteur vendeur; private LivreDuMarche marche; private StrategyChoixAcheteur strategyChoixAcheteur; public VendeurAcheteur getVendeur() { return vendeur; } /** * Permet d'instancier une offre * @param prix int correspondant au prix de l'offre * @param produit Produit correspondant à la marchandise à venre * @param vendeurAcheteur Acteur correspondant au vendeur de la marchandise * @param strategyChoixAcheteur Strategie permettant de choisisr la manière de selectionner l'acheteur * @param marche Correspond au marche dans lequel l'offre sera disponible */ public Offre(int prix, Produit produit, VendeurAcheteur vendeurAcheteur,StrategyChoixAcheteur strategyChoixAcheteur, LivreDuMarche marche) { this.prix = prix; this.produit = produit; this.vendeur = vendeurAcheteur; this.strategyChoixAcheteur = strategyChoixAcheteur; this.marche = marche; } /** * methode permettant de retirer l'offre elle-même dumarché où elle se trouve */ public void retirerOffre() { marche.getLivre().remove(this); } /** * méthode permettant d'obtenir La strategie de vente souhaité par le vendeur * @return strategie de choix d'acheteur */ public StrategyChoixAcheteur getStrategyChoixAcheteur() { return strategyChoixAcheteur; } public LivreDuMarche getMarche() { return marche; } /** * Ajoute a la liste des archives une archive avec l'offre et la date du jour */ public void archiver() { HistoriqueOffre.addOffresArchives( new Archive(null, this, LocalDate.now())); retirerOffre(); } /** * Retourne le prix de l'offre * @return int */ public int getPrix() { return prix; } /** * Retourne la valider de l'offre Oui/Non * @return boolean */ public boolean isValider() { return valider; } /** * Valider une offre */ public void validerOffre() { this.valider = true; } /** * Retourne le produit de l'offre * @return produit */ public Produit getProduit() { return produit; } /** * Retourne la liste des acheteurs potentiels * @return acheteurPotentiel */ public List<Acteur> getAcheteurPotentiel() { return acheteurPotentiel; } /** * Ajoute un acheteur a la liste des acheteurs potentiels * @param acheteurPotentiel Acteur correspondant à l'acheteur potentiel */ public void addAcheteurPotentiel(Acteur acheteurPotentiel) { this.acheteurPotentiel.add(acheteurPotentiel); } /** * Retourne tout le detail d'une offre avec le nom du produit le prix et la date de peremption * @return toString */ @Override public String toString() { StringBuilder s = new StringBuilder(" Offre : " + produit.getQuantite() + " " + produit.getUnite() + " "); s.append(produit.getNom()); s.append(" à "); s.append(prix + "€"); s.append(" et qui périme le "); s.append(produit.getDateDePeremption()); s.append('\n'); return s.toString(); } }
package com.tkb.elearning.action.admin; import java.io.IOException; import java.util.List; import com.tkb.elearning.model.MeetingMinutes; import com.tkb.elearning.service.MeetingMinutesService; import com.tkb.elearning.util.VerifyBaseAction; public class MeetingMinutesAction extends VerifyBaseAction { private static final long serialVersionUID = 1L; private MeetingMinutesService meetingMinutesService; //會議記錄服務 private List<MeetingMinutes> meetingMinutesList; //會議記錄清單 private MeetingMinutes meetingMinutes; //會議記錄資料 private int pageNo; //頁碼 private int[] deleteList; //刪除的ID清單 /** * 清單頁面 * @return */ public String index() { if(meetingMinutes == null) { meetingMinutes = new MeetingMinutes(); } pageTotalCount = meetingMinutesService.getCount(meetingMinutes); pageNo = super.pageSetting(pageNo); meetingMinutesList = meetingMinutesService.getList(pageCount, pageStart, meetingMinutes); return "list"; } /** * 新增頁面 * @return */ public String add() { meetingMinutes = new MeetingMinutes(); return "form"; } /** * 新增資料 * @return * @throws IOException */ public String addSubmit() throws IOException { meetingMinutesService.add(meetingMinutes); return "index"; } /** * 修改頁面 * @return */ public String update() { meetingMinutes = meetingMinutesService.getData(meetingMinutes); return "form"; } /** * 修改最新消息 * @return * @throws IOException */ public String updateSubmit() throws IOException { meetingMinutesService.update(meetingMinutes); return "index"; } /** * 刪除最新消息 * @return */ public String delete() throws IOException { for(int id : deleteList) { meetingMinutes.setId(id); meetingMinutes = meetingMinutesService.getData(meetingMinutes); meetingMinutesService.delete(id); } return "index"; } /** * 瀏覽頁面 * @return */ public String view(){ meetingMinutes=meetingMinutesService.getData(meetingMinutes); System.out.println(meetingMinutes.getId()); return "view"; } public MeetingMinutesService getMeetingMinutesService() { return meetingMinutesService; } public void setMeetingMinutesService(MeetingMinutesService meetingMinutesService) { this.meetingMinutesService = meetingMinutesService; } public List<MeetingMinutes> getMeetingMinutesList() { return meetingMinutesList; } public void setMeetingMinutesList(List<MeetingMinutes> meetingMinutesList) { this.meetingMinutesList = meetingMinutesList; } public MeetingMinutes getMeetingMinutes() { return meetingMinutes; } public void setMeetingMinutes(MeetingMinutes meetingMinutes) { this.meetingMinutes = meetingMinutes; } public int getPageNo() { return pageNo; } public void setPageNo(int pageNo) { this.pageNo = pageNo; } public int[] getDeleteList() { return deleteList; } public void setDeleteList(int[] deleteList) { this.deleteList = deleteList; } }
package com.example.leosauvaget.channelmessaging.model; import java.util.List; public class MessagesModel { private List<MessageModel> messages; public MessagesModel () {} public List<MessageModel> getMessages() { return this.messages; } public void setMessages(List<MessageModel> messages) { this.messages = messages; } @Override public String toString() { return "MessagesModel{" + "messages=" + messages + '}'; } }
/* * MIT License * * Copyright (c) 2020 Odai Mohammad * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. */ package com.cloud_native.hateoas_x.models; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import org.springframework.lang.NonNull; import javax.persistence.*; import javax.validation.constraints.Future; import javax.validation.constraints.FutureOrPresent; import javax.validation.constraints.Size; import java.util.Date; /** * A task entity. Model's a task's attributes. */ @Entity @Data @NoArgsConstructor @EntityListeners(AuditingEntityListener.class) public class Task { /** * Task ID. */ @Id @GeneratedValue private Long id; /** * Task name. * The tasks's name is required and must at least be 5 characters long. */ @NonNull @Size(min = 5) private String name; /** * Task description. */ private String description; /** * Task start date. * A task's start date must not be null or blank, and must be a future or present date. */ @Column(name = "start_date") @FutureOrPresent private Date startDate; /** * Task end date. * A task's end date must not be null or blank, and must be a future date. */ @Column(name = "end_date") @Future private Date endDate; /** * Project tasks. * Each project has many tasks that are unique. * When a project is delete, its tasks are also deleted. */ @ManyToOne @JoinColumn(name = "project_id") @NonNull private Project project; /** * Task creation date. */ @Column(name = "created_date") @CreatedDate @Temporal(TemporalType.TIMESTAMP) private Date createdDate; }
package jc.sugar.JiaHui.jmeter.exceptions; /** * @Code 谢良基 2021/6/28 */ public class JMeterExecutionException extends Exception{ public JMeterExecutionException(String message){ super(message); } public JMeterExecutionException(Throwable cause){ super(cause); } public JMeterExecutionException(){ } public JMeterExecutionException(String message, Throwable cause){ super(message, cause); } public JMeterExecutionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace){ super(message, cause, enableSuppression, writableStackTrace); } }
package com.trey.fitnesstools; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import java.util.ArrayList; import java.util.List; public class FragmentPlateCalculator extends Fragment { //weight that has been entered into the EditText private double enteredWeight; //weight of the bar alone private double barWeight; //true if the user wants full weight, false if they want one sided private boolean fullWeightEntered; private EditText txtFullWeight; private EditText txtBarWeight; private TextView lblBarWeight; private Button btnCalculateWeight; private RadioGroup radioGroup; private RadioButton radioFullWeight; private RadioButton radioOneSide; //list of Plates used to calculate the user's weight (will be different from the list of ALL types of weights) public static PlateList calculationPlates; //list of doubles displayed in the RecyclerView public static ResultAdapter plateAdapter; public static final String KEY_ADAPTER_PLATELIST = "key_adapter_platelist"; public static final String KEY_SHARED_PREF_PLATES = "key_shared_pref_plates"; public static final String DialogFragmentID = "settings_button_dialog"; public static final String KEY_SHARED_PREF_PLATE_LENGTH = "plate_length"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); //if a weight is passed to the parent activity, retrieve it. Otherwise use the default value of 0. enteredWeight = getActivity().getIntent().getIntExtra(ActivityPlateCalculator.KEY_WEIGHT,0); //if the screen just rotated, creates a new adapter that had the same list as before rotation. if(savedInstanceState != null) { ArrayList<Double> list = (ArrayList<Double>)savedInstanceState.getSerializable(KEY_ADAPTER_PLATELIST); //list would only be null if the user rotates before an adapter is created (i.e. before actually generating any output) if(list != null) { plateAdapter = new ResultAdapter(list); } //the calculation plates must be loaded in from the shared preferences file on each rotation // ****(maybe save in onSaveInstanceState to improve performance?)**** loadPlatesFromSharedPreferences(); } //if the screen hasn't just rotated (i.e. first time activity is created (before any recreation)) else { //try to load the plates from the shared preferences. returns true if the list has elemnts and returns false if the list is empty boolean hasPlates = loadPlatesFromSharedPreferences(); //if the list is empty, the plates have never been saved, so create a new list. if(!hasPlates) { //initialize the calculationPlates with the default plate list. calculationPlates = new PlateList(); calculationPlates.setStandardPlates(); } } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_plate_calculator,container,false); txtFullWeight = v.findViewById(R.id.editTextEnterFullWeight); //enteredWeight will only be greater than 0 if the user has passed it from another activity. if(enteredWeight > 0) { txtFullWeight.setText(LiftingCalculations.desiredFormat(enteredWeight)); } txtBarWeight = v.findViewById(R.id.editTextEnterBarWeight); lblBarWeight = v.findViewById(R.id.lblBarWeight); btnCalculateWeight = v.findViewById(R.id.btnCalculateWeight); btnCalculateWeight.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { configureOutputRecyclerView(); } }); radioFullWeight = (RadioButton)v.findViewById(R.id.radioFullWeight) ; radioOneSide = (RadioButton)v.findViewById(R.id.radioOneSide) ; radioGroup = (RadioGroup)v.findViewById(R.id.radioGroup); radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, int checkedId) { if(checkedId == radioFullWeight.getId()) { fullWeightEntered = true; txtBarWeight.setVisibility(View.VISIBLE); lblBarWeight.setVisibility(View.VISIBLE); } else if(checkedId == radioOneSide.getId()) { fullWeightEntered = false; txtBarWeight.setVisibility(View.INVISIBLE); lblBarWeight.setVisibility(View.INVISIBLE); } } }); radioFullWeight.setChecked(true); return v; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.fragment_plate_calculator_menu,menu); inflater.inflate(R.menu.menu_question_mark,menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId() == R.id.actionItem_plateCalcSettings) { DialogFragmentPlates dialog = DialogFragmentPlates.newInstance(); dialog.show(getFragmentManager(),DialogFragmentID); return true; } else if(item.getItemId() == R.id.question_item) { String message = getString(R.string.long_message_plate_calculator); DialogFragmentQuestionMark dialog = DialogFragmentQuestionMark.newInstance(message); dialog.show(getFragmentManager(),"question_tag"); } return super.onOptionsItemSelected(item); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if(plateAdapter != null) { ArrayList<Double> adapterList = (ArrayList<Double>) plateAdapter.getList(); outState.putSerializable(KEY_ADAPTER_PLATELIST, adapterList); } else { outState.putSerializable(KEY_ADAPTER_PLATELIST,null); } } @Override public void onStop() { super.onStop(); saveCalculationPlatesToSharedPreferences(); } //HACKY way of writing the calculationPlates list to the activity's shared preferences. public void saveCalculationPlatesToSharedPreferences() { SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.clear(); //Gson object allows you to convert custom objects (like plate) to string Gson gson = new Gson(); //go through the entire array list, converting each element to a string with the Gson, and storing it in the sharedPreferences. int listLength = calculationPlates.size(); for(int i = 0; i < listLength; i++) { String stringRepresentation = gson.toJson(calculationPlates.get(i)); editor.putString(KEY_SHARED_PREF_PLATES + Integer.toString(i),stringRepresentation); } //the size of the list needs to be saved into the SharedPreferences object so that the plates can be retrieved later. editor.putInt(KEY_SHARED_PREF_PLATE_LENGTH,listLength); editor.commit(); } //retrieve the calculation plates from the shared preferences file. //returns true if the list is not empty //returns false if list is empty public boolean loadPlatesFromSharedPreferences() { SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); Gson gson = new Gson(); calculationPlates = new PlateList(); int listLength = sharedPref.getInt(KEY_SHARED_PREF_PLATE_LENGTH,0); for(int i = 0; i < listLength; i++) { String stringRepresentation = sharedPref.getString(KEY_SHARED_PREF_PLATES + Integer.toString(i),""); Plate plate = gson.fromJson(stringRepresentation,Plate.class); calculationPlates.add(plate); } return listLength > 0; } //get input from the text boxes and store in fields private void getInput() { try { enteredWeight = Double.parseDouble(txtFullWeight.getText().toString()); //only need to get the bar weight if the user enters their full weight if(fullWeightEntered) barWeight = Double.parseDouble(txtBarWeight.getText().toString()); } catch(Exception e) { Toast.makeText(FragmentPlateCalculator.this.getActivity(),"enter a valid number",Toast.LENGTH_SHORT).show(); } } //generates the plates for the user's input and passes them to the adapter for the recyclerView to display private void configureOutputRecyclerView() { //get input from text boxes getInput(); //used to store intermediate results from method calls MutableDouble ret = new MutableDouble(-1); if(fullWeightEntered) { plateAdapter = new ResultAdapter(findRequiredPlatesFullWeight(enteredWeight,barWeight,ret)); } else { plateAdapter = new ResultAdapter(findRequiredPlatesOneSideWeight(enteredWeight,ret)); } //show the output plates DialogFragmentOutput dialog = DialogFragmentOutput.newInstance(); dialog.show(getFragmentManager(),"output"); if(ret.getValue() > -1) { notifyInexactWeight(ret.getValue()); } } //given the amount of weight on one side of the bar, determine which plates are required to represent that weight private ArrayList<Double> findRequiredPlatesOneSideWeight(double oneSideWeight, MutableDouble ret) { ArrayList<Double> resultList = new ArrayList<>(); //store the leftover amount after the plate list is generated double remainingWeight = generateResultPlateList(resultList, oneSideWeight); //if the user's weight cannot be exactly represented, notify them. determineWeightExactRepresentation(remainingWeight,true, ret); return resultList; } //given the total amount of weight (including the bar), determine which plates are required to represent that weight private ArrayList<Double> findRequiredPlatesFullWeight(double fullWeight, double pBarWeight, MutableDouble ret) { ArrayList<Double> resultList = new ArrayList<>(); double oneSideWeight = (fullWeight - pBarWeight) / 2; double remainingWeight = generateResultPlateList(resultList,oneSideWeight); determineWeightExactRepresentation(remainingWeight,false,ret); return resultList; } //tells the user if their weight can be exactly represented with the plates from calculationPlates //params: remainingWeight -> weight left over after calculationPlates is iterated through // oneSide -> true if the weight is for one side and false for full weight private void determineWeightExactRepresentation(double remainingWeight, boolean oneSide, MutableDouble ret) { if (remainingWeight > 0) { //program's approximation of the entered weight double approximateWeight; if (oneSide) { approximateWeight = enteredWeight - remainingWeight; } else { double totalRemainingWeight = remainingWeight * 2; approximateWeight = enteredWeight - totalRemainingWeight; } //notifyInexactWeight(approximateWeight); ret.setValue(approximateWeight); } else { //if weight is exact, then the returned double will have a default value of -1 ret.setValue(-1); } } //tell the user that the weight cannot be exactly represented private void notifyInexactWeight(double approximateWeight) { //create a dialog to notify the user and display the approximate weight. DialogFragmentInexactWeight dialog = DialogFragmentInexactWeight.newInstance(approximateWeight); dialog.show(getFragmentManager(), "random tag"); } //generates the arrayList of plates from the amount of weight on one side of the bar. //make sure the input arrayList is an empty arrayList private double generateResultPlateList(ArrayList<Double> resultList, double oneSideWeight) { //loop through each of the possible plates, starting at the largest //subtract the current type of plate, until the remaining size is less than that plate, then go to the next plate type. for(int i = 0; i < calculationPlates.size(); i++) { Plate currentPlate = calculationPlates.get(i); //only use the current plate in the calcultion if it is enabled(can be disabled from the checkBoxes in DialogFragmentPlates. if(currentPlate.isEnabled()) { double currentPlateValue = currentPlate.getWeight(); while (oneSideWeight >= currentPlateValue) { resultList.add(currentPlateValue); oneSideWeight = oneSideWeight - currentPlateValue; } } } //return remaining weight after looping through all possible plates. return oneSideWeight; } //use this to instantiate a new fragment public static FragmentPlateCalculator newInstance() { FragmentPlateCalculator fragment = new FragmentPlateCalculator(); return fragment; } //CLASSES FOR CONFIGURING THE RECYCLER-VIEW (ViewHolder and Adapter required) // ********************************************************************************************** private class ResultHolder extends RecyclerView.ViewHolder { private TextView resultText; public ResultHolder(View v) { super(v); resultText = v.findViewById(R.id.weight_text_plate_holder); } public void bind(double p) { resultText.setText(LiftingCalculations.desiredFormat(p)); } } public class ResultAdapter extends RecyclerView.Adapter<ResultHolder> { private List<Double> results; public ResultAdapter(List<Double> results) { this.results = results; } @Override public ResultHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(getActivity()); View view = inflater.inflate(R.layout.view_holder_result,parent,false); ResultHolder holder = new ResultHolder(view); return holder; } @Override public void onBindViewHolder(ResultHolder holder, int position) { holder.bind(results.get(position)); } @Override public int getItemCount() { return results.size(); } public List<Double> getList() { return results; } } //********************************************************************************************** }
package dev.schoenberg.kicker_stats; import static com.dumbster.smtp.SimpleSmtpServer.*; import static java.lang.System.*; import static java.nio.file.Files.*; import static javax.ws.rs.core.HttpHeaders.*; import static javax.ws.rs.core.MediaType.*; import static org.assertj.core.api.Assertions.*; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; import com.dumbster.smtp.SimpleSmtpServer; import dev.schoenberg.kicker_stats.core.helper.mail.MailerConfiguration; import dev.schoenberg.kicker_stats.rest.HookedServer; import dev.schoenberg.kicker_stats.rest.ServerService; import kong.unirest.GetRequest; import kong.unirest.HttpResponse; import kong.unirest.RequestBodyEntity; import kong.unirest.Unirest; @Category({ ServerTest.class, PersistenceTest.class }) public class AcceptanceTest { private static HookedServer server; private static String baseUrl = "http://localhost:" + Main.PORT; private static Path tempDb; private static SimpleSmtpServer smtp; @BeforeClass public static void setUp() throws Exception { int smtpPort = 17385; smtp = start(smtpPort); Main.mailerConfig = new MailerConfiguration("localhost", smtpPort, "", ""); Main.serverFactory = AcceptanceTest::createHooked; tempDb = createTempDatabase(); Main.url = "jdbc:sqlite:" + tempDb.toString().replace("\\", "/"); Main.main(new String[0]); } private static Path createTempDatabase() throws IOException { Path tempDb = Files.createTempFile("kickerStats", ".db"); // Also cleaning remaining files from previous runs list(tempDb.getParent()).filter(AcceptanceTest::isDbFile).map(Path::toFile).forEach(File::deleteOnExit); return tempDb; } private static boolean isDbFile(Path filePath) { String fileName = filePath.getFileName().toString(); return fileName.startsWith("kickerStats") && fileName.endsWith(".db"); } private static HookedServer createHooked(int p, List<ServerService> s) { server = new HookedServer(p, s); server.closeServer = false; return server; } @AfterClass public static void tearDown() throws IOException { server.closeServer = true; server.close(); smtp.stop(); } @Test public void versionEndpointIsAvailable() { String content = get("/version"); assertThat(content).isNotBlank(); } @Test public void resourceCanBeRequested() throws IOException, URISyntaxException { String expected = loadResourceFile("subfolder/fileInSubfolder.css"); String content = get("/resources/subfolder/fileInSubfolder.css"); assertThat(content).isEqualTo(expected); } @Test public void playerIsCreated() { String loginBody = "{\"mail\":\"admin@schoenberg.dev\", \"password\":\"pwd\"}"; String authValue = post("/login", loginBody); String body = "{\"name\":\"Aaron Rodgers\", \"mail\":\"houdini@packers.com\", \"hashedPassword\":\"12345\"}"; post("/players", body, authValue); String response = get("/players", authValue); assertThat(response).contains("{\"name\":\"Aaron Rodgers\",\"mail\":\"houdini@packers.com\"}"); } private String loadResourceFile(String resourcePath) throws URISyntaxException, IOException { Path path = Paths.get(getClass().getClassLoader().getResource(resourcePath).toURI()); return String.join(lineSeparator(), Files.readAllLines(path)); } private String get(String subUrl) { return get(subUrl, null); } private String get(String subUrl, String authValue) { GetRequest request = Unirest.get(baseUrl + subUrl); if (authValue != null) { request = request.header(AUTHORIZATION, authValue); } HttpResponse<String> response = request.asString(); assertThat(response.getStatus()).isEqualTo(200); return response.getBody(); } private String post(String subUrl, String body) { return post(subUrl, body, null); } private String post(String subUrl, String body, String authValue) { RequestBodyEntity request = Unirest.post(baseUrl + subUrl).body(body).header(CONTENT_TYPE, APPLICATION_JSON); if (authValue != null) { request = request.header(AUTHORIZATION, authValue); } HttpResponse<String> response = request.asString(); assertThat(response.getStatus()).isLessThan(300); return response.getBody(); } }
package emp.application.model; import java.io.Serializable; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import org.hibernate.envers.Audited; @Entity //@Audited @Table(name = "RIGHTS") public class Right implements Serializable{ private static final long serialVersionUID = 1L; @Id @SequenceGenerator(name = "permissionlevelSeq", sequenceName = "P_LEVEL_SEQ") // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "permissionlevelSeq") @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "LEVEL_ID", unique = true, nullable = false) private int id; @Column(name = "NAME", unique = true, nullable = false) private String name; @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "PERMISSION_RIGHT", joinColumns = { @JoinColumn(name = "PERMISSIONLEVELS_LEVEL_ID", referencedColumnName = "LEVEL_ID") }, inverseJoinColumns = { @JoinColumn(name = "PERMISSIONS_PERMISSION_ID", referencedColumnName = "PERMISSION_ID") }) private Set<Permission> permissions; public Right() { } public Right(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Permission> getPermissions() { return permissions; } public void setPermissions(Set<Permission> permissions) { this.permissions = permissions; } }
package com.example.shree.wlug; import android.content.Intent; import android.support.annotation.NonNull; import android.support.design.widget.TextInputLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; public class Register extends AppCompatActivity { public FirebaseAuth mAuth; EditText emailEdit; EditText passwordEdit; String email,password; Button register; TextInputLayout errorEmail; TextInputLayout errorPassword; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); mAuth = FirebaseAuth.getInstance(); emailEdit = (EditText) findViewById(R.id.email); passwordEdit = (EditText) findViewById(R.id.password); register= (Button) findViewById(R.id.register); errorEmail= (TextInputLayout) findViewById(R.id.errorEmail); errorPassword= (TextInputLayout) findViewById(R.id.errorPassword); } @Override public void onBackPressed() { super.onBackPressed(); Register.this.finish(); startActivity(new Intent(getApplicationContext(),MainActivity.class)); } public void register(View view) { email = emailEdit.getText().toString(); password = passwordEdit.getText().toString(); if(email.isEmpty() || password.isEmpty()) { if(email.isEmpty()) { // Toast.makeText(MainActivity.this, "All Fields Are Required", Toast.LENGTH_SHORT).show(); errorEmail.setError("Email is required."); } if(password.isEmpty()) { //Toast.makeText(MainActivity.this, "All Fields Are Required", Toast.LENGTH_SHORT).show(); errorPassword.setError("Password is required."); } } else { mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { Toast.makeText(getApplicationContext(), "Successfully Registered.", Toast.LENGTH_SHORT).show(); FirebaseUser user = mAuth.getCurrentUser(); boolean verified = user.isEmailVerified(); if (verified) { Toast.makeText(getApplicationContext(), "Email Verified", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Email not Verified", Toast.LENGTH_LONG).show(); user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { Toast.makeText(getApplicationContext(), "Email sent to your Gmail Account. Please verify your Email", Toast.LENGTH_LONG).show(); startActivity(new Intent(getApplicationContext(), MainActivity.class)); } }); } } else { Toast.makeText(getApplicationContext(), "Something went wrong.", Toast.LENGTH_SHORT).show(); } } }); } } }
// ______________________________________________________ // Generated by sql2java - http://sql2java.sourceforge.net/ // jdbc driver used at code generation time: com.mysql.jdbc.Driver // // Please help us improve this tool by reporting: // - problems and suggestions to // http://sourceforge.net/tracker/?group_id=54687 // - feedbacks and ideas on // http://sourceforge.net/forum/forum.php?forum_id=182208 // ______________________________________________________ package legaltime.model; import legaltime.model.exception.DAOException; /** * Listener that is notified of client_account_register table changes. * @author sql2java */ public interface ClientAccountRegisterListener { /** * Invoked just before inserting a ClientAccountRegisterBean record into the database. * * @param bean the ClientAccountRegisterBean that is about to be inserted */ public void beforeInsert(ClientAccountRegisterBean bean) throws DAOException; /** * Invoked just after a ClientAccountRegisterBean record is inserted in the database. * * @param bean the ClientAccountRegisterBean that was just inserted */ public void afterInsert(ClientAccountRegisterBean bean) throws DAOException; /** * Invoked just before updating a ClientAccountRegisterBean record in the database. * * @param bean the ClientAccountRegisterBean that is about to be updated */ public void beforeUpdate(ClientAccountRegisterBean bean) throws DAOException; /** * Invoked just after updating a ClientAccountRegisterBean record in the database. * * @param bean the ClientAccountRegisterBean that was just updated */ public void afterUpdate(ClientAccountRegisterBean bean) throws DAOException; /** * Invoked just before deleting a ClientAccountRegisterBean record in the database. * * @param bean the ClientAccountRegisterBean that is about to be deleted */ public void beforeDelete(ClientAccountRegisterBean bean) throws DAOException; /** * Invoked just after deleting a ClientAccountRegisterBean record in the database. * * @param bean the ClientAccountRegisterBean that was just deleted */ public void afterDelete(ClientAccountRegisterBean bean) throws DAOException; }
package com.gotkx.utils.io; import org.junit.Test; import java.io.*; import java.util.ArrayList; import java.util.List; public class CreateIO { /** * 在电脑D盘下创建一个文件为HelloWorld.txt文件,判断他是文件还是目录,在创建一个目 * 录IOTest,之后将HelloWorld.txt移动到IOTest目录下去;之后遍历IOTest这个目录下的文 * 件 */ @Test public void test_1() { String sourceString = "sourceString"; //待写入字符串 byte[] sourceByte = sourceString.getBytes(); File file = new File("G:\\Temp\\HelloWorld.txt"); file.delete(); try { if (file.createNewFile()) { FileOutputStream outStream = new FileOutputStream(file); //文件输出流用于将数据写入文件 outStream.write(sourceByte); outStream.close(); //关闭文件输出流 //outStream.flush(); System.out.println("这是" + (file.isDirectory() ? "文件夹" : "文件")); } } catch (IOException e) { e.printStackTrace(); } File file_2 = new File("G:\\Temp\\Test"); file_2.mkdirs(); System.out.println("移动" + (file.renameTo(new File(file_2 + File.separator + file.getName())) ? "成功" : "失败")); } void findFileAndFolder(List list, File file) { //写一个递归的方法,查询文件和文件夹 File[] listFiles = file.listFiles(); //如果是一个空的文件夹 //后面的不执行,直接返回 if (listFiles == null) { return; } //如果文件夹有内容,遍历里面的所有文件(包括文件夹和文件),都添加到集合里面 for (File file2 : listFiles) { //如果只是想要里面的文件或者文件夹或者某些固定格式的文件可以判断下再添加 list.add(file2); //添加到集合后,在来判断是否是文件夹,再遍历里面的所有文件 //方法的递归 findFileAndFolder(list, file2); } } /** * 递归实现输入任意目录,列出文件以及文件夹 */ @Test public void test_2() throws IOException { //比如输入D盘 File file = new File("G:\\Soft\\Nox\\bin\\video"); if (file.exists() && file.isDirectory()) { List<File> list = new ArrayList<File>(); findFileAndFolder(list, file); //System.out.println(list.size()); //将相关信息接入到硬盘 FileOutputStream outputStream = new FileOutputStream(new File("G:\\Temp\\Test\\2.txt")); for (File xxx : list) { outputStream.write((xxx.toString() + "\n").getBytes()); } outputStream.close(); } } @Test /** * 从指定文件里面读取数据 */ public void test_3() throws IOException { File file = new File("G:\\Temp\\Test\\2.txt"); FileInputStream inputStream = new FileInputStream(file); //InputStreamReader streamReader = new InputStreamReader(inputStream, "utf-8"); byte[] bytes = new byte[1024]; // int read = inputStream.read(bytes); // inputStream.close(); // System.out.println(new String(bytes)); while (true) { int read = inputStream.read(bytes); if (read <= 0) { break; } //从哪开始,到哪结束 System.out.println(new String(bytes, 0, read)); } } @Test /** * 输入一个文件名和一个字符串,统计这个字符串在这个文件中出现的次数 * 逻辑是 一边读,先找到第一个匹配的字符比如我 m * 然后再进入for循环 用 mp4的 length属性 为条件,再逐个匹配 接下来,是不是 为 p呢 */ public void test_4() throws IOException { File file = new File("G:\\Temp\\Test\\2.txt"); FileReader fileReader = new FileReader(file); String s = new String("mp4"); int count = 0, c; while ((c = fileReader.read()) != -1) { while (c == s.charAt(0)) { //System.out.println(s.charAt(0)); for (int i = 1; i < s.length(); i++) { c = fileReader.read(); //System.out.println(s.charAt(i)); if (c != s.charAt(i)) { break; } if (i == s.length() - 1) { count++; } } } } System.out.println(count); } @Test /** * 两个文件,从第一个读取 写入到第二个 */ public void test_5() throws Exception { FileInputStream fileInputStream = new FileInputStream(new File("G:\\Temp\\Test\\2.txt")); File file = new File("G:\\Temp\\Test\\3.txt"); if(!file.exists()){ file.createNewFile(); } FileOutputStream outputStream = new FileOutputStream(file); byte[] bytes = new byte[1024]; int read = fileInputStream.read(bytes); if(read > 0){ outputStream.write(bytes); } } }
/* * @version 1.0 * @author PSE group */ package kit.edu.pse.goapp.server.servlets; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import kit.edu.pse.goapp.server.authentication.Authentication; import kit.edu.pse.goapp.server.converter.daos.GpsDaoConverter; import kit.edu.pse.goapp.server.converter.objects.ObjectConverter; import kit.edu.pse.goapp.server.daos.GpsDaoImpl; import kit.edu.pse.goapp.server.datamodels.GPS; import kit.edu.pse.goapp.server.exceptions.CustomServerException; /** * Servlet implementation class GpsServlet */ @WebServlet("/Gps") public class GpsServlet extends HttpServlet { private static final long serialVersionUID = 1L; private Authentication authentication = new Authentication(); /** * constructor of the class GpsServlet * * @see HttpServlet#HttpServlet() */ public GpsServlet() { super(); } /** * updates the GPS data * * @see HttpServlet#doPut(HttpServletRequest, HttpServletResponse) */ @Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { int userId = authentication.authenticateUser(request); String jsonString = request.getReader().readLine(); GpsDaoImpl dao = (GpsDaoImpl) new GpsDaoConverter().parse(jsonString); dao.setUserId(userId); dao.setUserId(userId); dao.userSetGPS(); GPS gps = dao.userGetGPS(); response.getWriter().write(new ObjectConverter<GPS>().serialize(gps, GPS.class)); } catch (CustomServerException e) { response.setStatus(e.getStatusCode()); response.getWriter().write(e.toString()); } } }
package queryBuilders; import org.hamcrest.CoreMatchers; import org.junit.After; import org.junit.Assert; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; /** * Created by cenk on 03/01/15. */ public class SqliteQueryBuilderTest { private Map<String, String> fields = null; private String modelName = ""; @After public void tearDown() { fields = null; modelName = ""; } @Test public void testCreateTable() throws ClassNotFoundException { System.out.println("@Test Starts : TestCreateTable"); fields = new HashMap<String, String>(); fields.put("Name", "String"); fields.put("Name1", "boolean"); fields.put("Name2", "int"); fields.put("Name3", "char"); fields.put("Name4", "long"); modelName = "TestModel4"; String str = new SqliteQueryBuilder().createTable(modelName, fields); String expectedSql = "create table if not exists TESTMODEL4 (id wibblewibble primary key, NAME4 long, NAME String, NAME3 char, NAME2 int, NAME1 boolean);"; assertEquals(expectedSql, str); System.out.println("@Test Ends : TestCreateTable"); } @Test public void testDropTable() { System.out.println("@Test Starts : TestDropTable"); modelName = "TestModel4"; String str = new SqliteQueryBuilder().dropTable(modelName); String expectedSql = String.format("Drop table if exists %s", modelName); assertEquals(expectedSql, str); System.out.println("@Test Ends : TestDropTable"); } @Test public void testInsertOne() { System.out.println("@Test Starts : TestInsertOne"); Map<String, String> fieldAndValues = new HashMap<String, String>(); fieldAndValues.put("name", "Name"); modelName = "people"; String str = new SqliteQueryBuilder().insert(modelName, fieldAndValues); String expectedSqlStarts = "insert into PEOPLE (id , NAME) values ("; String expectedSqlEnds = "'Name');"; Assert.assertThat(str, CoreMatchers.containsString(expectedSqlStarts)); Assert.assertThat(str, CoreMatchers.containsString(expectedSqlEnds)); System.out.println("@Test Ends : TestInsertOne"); } @Test public void testCheckTableExists() { System.out.println("@Test Ends : TestCheckTableExists"); modelName = "TestModel4"; String str = new SqliteQueryBuilder().checkTableExists(modelName); String expectedSql = String.format("select name from sqlite_master master where type='table' AND name='%s';", modelName.toUpperCase()); assertEquals(expectedSql, str); System.out.println("@Test Ends : TestCheckTableExists"); } @Test public void testUpdateOne() { System.out.println("@Test Ends : TestUpdateOne"); Map<String, String> fieldAndValues = new HashMap<String, String>(); fieldAndValues.put("name", "Name"); modelName = "people"; Map<String, String> filters = new HashMap<String, String>(); filters.put("name", "Name1"); String str = new SqliteQueryBuilder().update(modelName, fieldAndValues, filters); String expectedSql = "update PEOPLE set NAME='Name' where NAME='Name1';"; assertEquals(expectedSql, str); System.out.println("@Test Ends : TestUpdateOne"); } @Test public void testDeleteOne() { System.out.println("@Test Ends : TestDeleteOne"); modelName = "people"; Map<String, String> filters = new HashMap<String, String>(); filters.put("name", "Name1"); String str = new SqliteQueryBuilder().delete(modelName, filters); String expectedSql = "delete from PEOPLE where NAME='Name1';"; assertEquals(expectedSql, str); System.out.println("@Test Ends : TestDeleteOne"); } @Test public void testSelect() { System.out.println("@Test Starts : TestSelect"); modelName = "people"; Map<String, String> fieldAndValues = new HashMap<String, String>(); fieldAndValues.put("name", "Name"); int limit = 10; String str = new SqliteQueryBuilder().select(modelName); String expectedSql = "select * from PEOPLE;"; assertEquals(expectedSql, str); System.out.println("@Test Ends : TestSelect1"); String str1 = new SqliteQueryBuilder().select(modelName, fieldAndValues); String expectedSql1 = "select * from PEOPLE where NAME='Name';"; assertEquals(expectedSql1, str1); System.out.println("@Test Ends : TestSelect2"); String str2 = new SqliteQueryBuilder().select(modelName, limit); String expectedSql2 = "select * from PEOPLE limit 10;"; assertEquals(expectedSql2, str2); System.out.println("@Test Ends : TestSelect3"); String str3 = new SqliteQueryBuilder().select(modelName, fieldAndValues, limit); String expectedSql3 = "select * from PEOPLE where NAME='Name' limit 10;"; assertEquals(expectedSql3, str3); System.out.println("@Test Ends : TestSelect4"); } public String selectAll() { return null; } public String count() { return null; } }
package com.jiw.dudu.constants; /** * @Description RabbitMQ队列及交换机相关定义 * @Author pangh * @Date 2022年09月27日 * @Version v1.0.0 */ public class RabbitMQ { /** * 用户队列 */ public static final String USER_QUEUE = "msg.user"; /** * 用户死信队列 */ public static final String DLX_USER_QUEUE = "dlx.msg.user"; /** * 组织队列 */ public static final String ORG_QUEUE = "msg.org"; /** * 组织死信队列 */ public static final String DLX_ORG_QUEUE = "dlx.msg.org"; /** * 组织架构备份队列 */ public static final String BAK_ORG_QUEUE = "bak.msg.org"; /** * 交换机名称 */ public static final String ORG_USER_EXCHANGE = "dudu.direct.org.user"; /** * 死信交换机名称 */ public static final String DLX_ORG_USER_EXCHANGE = "dlx.dudu.direct.org.user"; /** * 备份交换机名称 */ public static final String BAK_ORG_USER_EXCHANGE = "bak.dudu.fanout.org.user"; /** * 用户路由KEY */ public static final String USER_ROUTING_KEY = "userRouting"; /** * 用户死信路由KEY */ public static final String DLX_USER_ROUTING_KEY = "dlxUserRouting"; /** * 组织机构路由KEY */ public static final String ORG_ROUTING_KEY = "orgRouting"; /** * 组织机构死信路由KEY */ public static final String DLX_ORG_ROUTING_KEY = "dlxOrgRouting"; }
package cn.hui.javapro.design.decorator; public class Employer implements Project{ public void doCoding() { System.out.println("代码工人在编写代码............"); } }
package com.amoraesdev.mobify; import java.io.Console; import java.io.PrintStream; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import com.amoraesdev.mobify.valueobjects.Notification; import com.fasterxml.jackson.databind.ObjectMapper; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; @SpringBootApplication public class ClientApplication { @Autowired private ClientOAuth clientOAuth; @Value("${mobify-server-url}") private String mobifyServerUrl; private String accessToken; private Console console = System.console(); private PrintStream out = System.out; public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(ClientApplication.class, args); ClientApplication app = context.getBean(ClientApplication.class); app.start(); } public void start(){ //get an access token from the oauth server this.accessToken = clientOAuth.getAccessToken(); //show some basic console interface to type the message out.println("Mobify Sample Client"); out.println("Notification type:"); String type = console.readLine(); out.println("Notification text:"); String message = console.readLine(); out.println("Users (use comma to separate them):"); String users = console.readLine(); String[] usersArray = users.split(","); sendNotification(usersArray, type, message); out.println("---------------"); } public void sendNotification(String[] users, String type, String message){ String url = mobifyServerUrl.concat("/applications/%s/notifications"); try { ObjectMapper mapper = new ObjectMapper(); Notification notification = new Notification(users, type, message); HttpResponse<String> response = Unirest.post(String.format(url, clientOAuth.getClientId())) .header("Authorization", "Bearer ".concat(accessToken)) .header("Content-Type", "application/json") .body(mapper.writeValueAsString(notification)) .asString(); if(response.getStatus() == 200){ out.println("Notification successfully sent."); }else{ throw new RuntimeException("Error sending notification. Error code: "+response.getStatus()); } } catch (Exception e) { throw new RuntimeException("Error sending notification", e); } } }
package VSMTests; import java.io.IOException; import java.util.ArrayList; import Jama.Matrix; import VSMUtilityClasses.VSMUtil; import cern.colt.matrix.tdouble.impl.DenseDoubleMatrix2D; import com.jmatio.io.MatFileWriter; import com.jmatio.types.MLDouble; public class TestMATFile { public static void main(String... args) throws ClassNotFoundException, IOException { VSMUtil.createMatFileProjections("JJ"); VSMUtil.createMatFileProjections("NNP"); VSMUtil.createMatFileProjections("IN"); VSMUtil.createMatFileProjections("S"); VSMUtil.createMatFileProjections("VBN"); VSMUtil.createMatFileProjections("NNS"); } }
package com.ebupt.portal.shiro.Service; import com.ebupt.portal.common.Results.JSONResult; import javax.servlet.http.HttpServletRequest; public interface AuthService { JSONResult checkLogin(String username, String password, HttpServletRequest request); }
/** (Sum the digits in an integer) Write a method that computes the sum of the digits in an integer. Use the following method header: public static int sumDigits(long n) For example, sumDigits(234) returns 9(2 + 3 + 4). (Hint: Use the % operator to extract digits, and the / operator to remove the extracted digit. For instance, to extract 4 from 234, use 234 % 10 (= 4). To remove 4 from 234, use 234 / 10 (= 23). Use a loop to repeatedly extract and remove the digit until all the digits are extracted. Write a test program that prompts the user to enter an integer and displays the sum of all its digits. */ import java.util.*; public class Exercise6_2 { /** Main method */ public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter an integer System.out.print("Enter an integer : "); long number = input.nextLong(); // Display the sum of all its digits in the integer System.out.println("The sum of its digits in the integer" + number + " is " + sumDigits(number)); } public static int sumDigits(long number) { int sum = 0; while (sum > 0) { sum += number % 10; number /= 10; } return sum; } }
package de.zarncke.lib.err; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.concurrent.TimeoutException; import org.junit.Assert; import org.junit.runner.Description; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; import org.junit.runner.notification.RunNotifier; import org.junit.runner.notification.StoppedByUserException; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.RunnerBuilder; import com.google.common.base.Supplier; import de.zarncke.lib.block.Running; import de.zarncke.lib.coll.L; import de.zarncke.lib.ctx.Context; import de.zarncke.lib.log.BufferedLog; import de.zarncke.lib.log.Log; import de.zarncke.lib.test.Tests; import de.zarncke.lib.time.Times; import de.zarncke.lib.util.Chars; import de.zarncke.lib.value.Default; /** * JUnit 4 variant of {@link GuardedTest}. * To be used like this: <code> * <pre> * * @RunWith(Guarded.class) * @MaxTestTimeMillis(2*Times.MILLIS_PER_SECOND) // applies to all methods (optional) * @Scope(THREAD) // THREAD is default * public class MyTest { * @MaxTestTimeMillis(10*Times.MILLIS_PER_SECOND) // applies to this method * @Test * public void testMe() throws Exception { * } * ... * } * </pre></code> * @author Gunnar Zarncke <gunnar@zarncke.de> */ public class Guarded extends BlockJUnit4ClassRunner { /** * Allows to access the unbuffered Log (the default log outside of the test - usually StdOut). */ public static final Context<Log> UNBUFFERED = Context.of(Default.of((Log) null, Log.class, "unbuffered")); public static final class DelegateNotifier extends RunNotifier { private final RunNotifier notifier; private final boolean[] inError; RunNotifier delegate; public DelegateNotifier(final RunNotifier notifier, final boolean[] inError) { this.notifier = notifier; this.inError = inError; this.delegate = this.notifier; } @Override public void addListener(final RunListener listener) { this.delegate.addListener(listener); } @Override public void removeListener(final RunListener listener) { this.delegate.removeListener(listener); } @Override public void fireTestRunStarted(final Description description) { this.delegate.fireTestRunStarted(description); } @Override public void fireTestRunFinished(final Result result) { this.delegate.fireTestRunFinished(result); } @Override public void fireTestStarted(final Description description) throws StoppedByUserException { this.delegate.fireTestStarted(description); } @Override public void fireTestFailure(final Failure failure) { this.inError[0] = true; this.delegate.fireTestFailure(failure); } @Override public void fireTestAssumptionFailed(final Failure failure) { this.delegate.fireTestAssumptionFailed(failure); } @Override public void fireTestIgnored(final Description description) { this.delegate.fireTestIgnored(description); } @Override public void fireTestFinished(final Description description) { this.delegate.fireTestFinished(description); } @Override public void pleaseStop() { this.delegate.pleaseStop(); } @Override public void addFirstListener(final RunListener listener) { this.delegate.addFirstListener(listener); } } /** * Time-out for tests. Defaults to some sensible default time-out. * Can be set on class and method. */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD }) @Inherited public @interface MaxTestTimeMillis { long value() default Times.MILLIS_PER_SECOND; } /** * The scope of the test-{@link Log} established for the test. * Default is {@link #THREAD} which makes the Log available in the current thread only. */ public enum ScopeType { THREAD(Context.THREAD), INHERITED(Context.INHERITED), CLASS_LOADER(Context.CLASS_LOADER), GLOBAL(Context.GLOBAL); private Context.Scope scope; ScopeType(final Context.Scope scope) { this.scope = scope; } } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Inherited public @interface Scope { /** * @return ScopeType */ ScopeType value(); } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Inherited public @interface WithContext { Class<? extends Supplier<Default<?>[]>> value(); } static Default<?>[] getContext(final Class<?> klass) throws InitializationError { final WithContext annotation = klass.getAnnotation(WithContext.class); if (annotation == null) { return Default.many(); } try { return annotation.value().newInstance().get(); } catch (final IllegalAccessException e) { throw new InitializationError(e); } catch (final InstantiationException e) { throw new InitializationError(e); } } private static long getMaxTestTimeMillis(final Class<?> klass) { final MaxTestTimeMillis annotation = klass.getAnnotation(MaxTestTimeMillis.class); if (annotation == null) { return Long.MAX_VALUE; } return annotation.value(); } @SuppressWarnings("deprecation" /* for backward compatibility */) private long getMaxMethodTimeMillis(final FrameworkMethod method) { final MaxTestTimeMillis annotation = method.getAnnotation(MaxTestTimeMillis.class); if (annotation == null) { if (this.lastCreatedFixture instanceof GuardedTest4) { return ((GuardedTest4) this.lastCreatedFixture).getMaximumTestMillis(); } return this.maxTestTimeMillis; } return annotation.value(); } private static Context.Scope getScope(final Class<?> klass) { final Scope annotation = klass.getAnnotation(Scope.class); if (annotation == null) { return Context.THREAD; } return annotation.value().scope; } private final long maxTestTimeMillis; private final Context.Scope scope; private Object lastCreatedFixture; private final Class<?>[] categories; private final Default<?>[] context; public Guarded(final Class<?> klass) throws InitializationError { this(klass, null); } /** * @param klass to run * @param categories to filter by; null means run all tests, empty means run only tests without category * @throws InitializationError */ public Guarded(final Class<?> klass, final Class<?>[] categories) throws InitializationError { super(klass); this.maxTestTimeMillis = getMaxTestTimeMillis(klass); this.scope = getScope(klass); this.categories = categories; this.context = getContext(klass); } /** * Called reflectively on classes annotated with <code>@RunWith(Suite.class)</code> * * @param klass the root class * @param builder builds runners for classes in the suite * @param categories (optional) to use for filtering executed tests * @throws InitializationError */ public Guarded(final Class<?> klass, final RunnerBuilder builder, final Class<?>[] categories) throws InitializationError { this(klass, categories); } @Override protected void runChild(final FrameworkMethod method, final RunNotifier notifier) { final Description methodDescription = Description.createTestDescription(getTestClass().getJavaClass(), testName(method), method.getAnnotations()); if (this.categories != null && !(Tests.hasMethodMatchingCategory(method.getMethod(), this.categories) || Tests.hasClassMatchingCategory( method.getMethod().getDeclaringClass(), this.categories))) { notifier.fireTestIgnored(methodDescription); return; } final Default<?>[] originalContext = Context.bundleCurrentContext(); // set up Warden testWarden = Warden.appointWarden(); BufferedLog bufferLog = new BufferedLog(); final Log defLog = Log.LOG.get(); Default<Log> previousLog = Context.setFromNowOn(Default.of(bufferLog, Log.class), this.scope); final Log delegateLog = previousLog.getValue() == null ? defLog : previousLog.getValue(); bufferLog.setDelegate(delegateLog); Context.setFromNowOn(UNBUFFERED.getOtherDefault(delegateLog), this.scope); // execute guarded final boolean[] inError = new boolean[1]; final RunNotifier xnotifier = new DelegateNotifier(notifier, inError); final long start = System.currentTimeMillis(); Warden.guard(new Running() { @Override public void run() { if (Guarded.this.context != null && Guarded.this.context.length > 0) { Context.runWith(new Running() { @Override public void run() { superRunChild(method, xnotifier); } }, Guarded.this.context); } else { superRunChild(method, xnotifier); } } }); // check timing final long dur = System.currentTimeMillis() - start; if (isTimeExceeded(method, dur)) { final String msg = "test took too long " + dur + "ms, allowed is only " + getMaxMethodTimeMillis(method) + "ms"; if (isTimingFailureEnabled()) { notifier.fireTestFailure(new Failure(methodDescription, new TimeoutException(msg))); } else { delegateLog.report(msg); } } // clean up testWarden.finish(); Context.setFromNowOn(previousLog, this.scope); Context.setFromNowOn(UNBUFFERED.getOtherDefault(null), this.scope); if (inError[0]) { bufferLog.flush(); } else { if (bufferLog.getNumberOfBufferedIssues() > 0 || bufferLog.getNumberOfBufferedThrowables() > 0) { final StringBuilder msg = new StringBuilder("Test ").append(getClass().getName()).append(" successful. "); if (bufferLog.getNumberOfBufferedIssues() > 0) { msg.append(" Didn't print ").append(bufferLog.getNumberOfBufferedIssues()).append(" issues."); } if (bufferLog.getNumberOfBufferedThrowables() > 0) { msg.append(" Didn't report ").append(bufferLog.getNumberOfBufferedThrowables()).append(" exceptions."); } Log.LOG.get().report(msg); bufferLog.clear(); } } assertAndCorrectRemainingContext(originalContext); testWarden = null; inError[0] = false; previousLog = null; bufferLog = null; } static void assertAndCorrectRemainingContext(final Default<?>[] originalContext) { final Default<?>[] remainingContext = Context.bundleCurrentContext(); if (remainingContext.length != originalContext.length) { // correct Context for (final Default<?> remaining : remainingContext) { boolean exists = false; for (final Default<?> orig : originalContext) { if (orig.getType().equals(remaining.getType())) { exists = true; break; } } if (!exists) { Context.setFromNowOn(remaining.withOtherValue(null), Context.GLOBAL); } } Assert.assertEquals("Context after execution of test differs from Context before - missing cleanup", Chars.join(L.l(originalContext), "\n").toString(), Chars.join(L.l(remainingContext), "\n").toString()); } } protected void superRunChild(final FrameworkMethod method, final RunNotifier notifier) { super.runChild(method, notifier); } @Override protected Object createTest() throws Exception { final Object fixture = super.createTest(); this.lastCreatedFixture = fixture; return fixture; } public static Log getUnbufferedLog() { return UNBUFFERED.get(); } private boolean isTimeExceeded(final FrameworkMethod method, final long dur) { double scale = 1.0; String scaleStr = System.getProperty(GuardedTest.SCALE_TEST_TIMEOUT_PROPERTY); if (scaleStr == null) { scaleStr = System.getenv(GuardedTest.SCALE_TEST_TIMEOUT_PROPERTY); } if (scaleStr != null) { try { scale = Double.parseDouble(scaleStr); } catch (final NumberFormatException e) { Warden.report(e); } } final long maxMethodTimeMillis = getMaxMethodTimeMillis(method); return dur > maxMethodTimeMillis * scale; } private boolean isTimingFailureEnabled() { return System.getProperty(GuardedTest.IGNORE_TEST_TIMEOUT_PROPERTY) == null && System.getenv(GuardedTest.IGNORE_TEST_TIMEOUT_PROPERTY) == null; } }
package com.smartwerkz.bytecode; import static org.junit.Assert.assertEquals; import java.util.concurrent.Callable; import javassist.ClassPool; import javassist.CtClass; import javassist.CtNewConstructor; import javassist.CtNewMethod; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import org.junit.Test; import com.smartwerkz.bytecode.controlflow.FrameExit; import com.smartwerkz.bytecode.primitives.JavaInteger; import com.smartwerkz.bytecode.primitives.JavaObject; import com.smartwerkz.bytecode.vm.ByteArrayResourceLoader; import com.smartwerkz.bytecode.vm.Classpath; import com.smartwerkz.bytecode.vm.HostVMResourceLoader; import com.smartwerkz.bytecode.vm.OptimizingResourceLoader; import com.smartwerkz.bytecode.vm.VirtualMachine; public class PerformanceTest { private static final int COUNT = 1000; @Test public void testJavaBytecodeInterpreter() throws Exception { ClassPool cp = new ClassPool(false); CtClass objClazz = cp.makeClass("java.lang.Object"); objClazz.addConstructor(CtNewConstructor.defaultConstructor(objClazz)); CtClass cc = cp.makeClass("org.example.Foo"); cc.addMethod(CtNewMethod.make("public static int add(int a, int b){ return a+b;};", cc)); byte[] b = cc.toBytecode(); VirtualMachine vm = new VirtualMachine(); vm.start(); Classpath classpath = new Classpath(); classpath.addLoader(new OptimizingResourceLoader(new ByteArrayResourceLoader(b))); classpath.addLoader(new HostVMResourceLoader()); vm.setClasspath(classpath); for (int i = 0; i < COUNT; i++) { FrameExit result = vm.execute("org/example/Foo", "add", new JavaObject[] { new JavaInteger(1), new JavaInteger(2) }); assertEquals(new JavaInteger(3), result.getResult()); } } @Test public void testECMAScriptViaScriptEngine() throws Exception { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("ECMAScript"); String script = "function add(a,b) { return a+b; }"; engine.eval(script); Invocable inv = (Invocable) engine; for (int i = 0; i < COUNT; i++) { Double result = (Double) inv.invokeFunction("add", 1, 2); assertEquals(3, result.intValue()); } } @Test public void testDirectJava() throws Exception { for (int i = 0; i < COUNT; i++) { int x = add(1, 2); assertEquals(3, x); } } private int add(final int i, final int j) { return new Callable<Integer>() { @Override public Integer call() { return i + j; } }.call().intValue(); } }
/** * */ package com.example.originalaso_2014_002; import android.content.Context; import android.database.SQLException; import android.database.sqlite.SQLiteCursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; /** * @author student * */ public class MySQLiteOpenHelper extends SQLiteOpenHelper { public MySQLiteOpenHelper(Context context) { super(context, "20140021201733", null, 1); // TODO 自動生成されたコンストラクター・スタブ } /* * (非 Javadoc) * * @see * android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite * .SQLiteDatabase) */ @Override public void onCreate(SQLiteDatabase db) { // TODO 自動生成されたメソッド・スタブ db.execSQL("CREATE TABLE IF NOT EXISTS Hitokoto(_id INTEGER PRIMARY KEY " + "AUTOINCREMENT NOT NULL,phrase TEXT);"); } /* * (非 Javadoc) * * @see * android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite * .SQLiteDatabase, int, int) */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO 自動生成されたメソッド・スタブ db.execSQL("drop table Hitokoto"); onCreate(db); } public void insertHitokoto(SQLiteDatabase db, String inputMsg) { String sqlstr = "INSERT INTO Hitokoto(phrase) values('" + inputMsg + "');"; try { db.beginTransaction(); db.execSQL(sqlstr); db.setTransactionSuccessful(); } catch (SQLException e) { Log.e("えらー1", e.toString()); } finally { db.endTransaction(); } return; } public void deleteHitokoto(SQLiteDatabase db, int id) { String sqlstr = "DELETE FROM Hitokoto WHERE _id = " + id + ";"; try { db.beginTransaction(); db.execSQL(sqlstr); db.setTransactionSuccessful(); } catch (SQLException e) { Log.e("でりーとえらー", e.toString()); } finally { db.endTransaction(); } } public String selectRamdomHitokoto(SQLiteDatabase db) { String rtString = null; String sqlstr = "SELECT _id, phrase FROM Hitokoto ORDER BY RANDOM();"; try { SQLiteCursor cursor = (SQLiteCursor) db.rawQuery(sqlstr, null); if (cursor.getCount() != 0) { cursor.moveToFirst(); rtString = cursor.getString(1); } cursor.close(); } catch (SQLException e) { Log.e("えらー2", e.toString()); } finally { } return rtString; } public SQLiteCursor selectHitokotoList(SQLiteDatabase db) { SQLiteCursor cursor = null; String sqlstr = "SELECT _id,phrase FROM Hitokoto ORDER BY _id;"; try { cursor = (SQLiteCursor)db.rawQuery(sqlstr,null); if(cursor.getCount()!=0){ cursor.moveToFirst(); } } catch (SQLException e) { Log.e("カーソル取得えらー", e.toString()); } finally { } return cursor; } }
package com.ericlam.mc.minigames.core.exception; import com.ericlam.mc.minigames.core.exception.arena.create.ArenaCreateException; public class NoMoreElementException extends ArenaCreateException { public NoMoreElementException(String arena) { super(arena); } }
package ru.krasview.kvlib.widget.lists; import java.util.Map; import ru.krasview.secret.ApiConst; import android.content.Context; public class OneSeasonSeriesList extends AllSeriesList { public OneSeasonSeriesList(Context context, Map<String, Object> map) { super(context, map); } @Override protected String getApiAddress() { return ApiConst.SEASON + "?id=" + getMap().get("id"); } }
package com.pay.payo.model; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import androidx.annotation.NonNull; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.PrimaryKey; import lombok.Getter; import lombok.Setter; @Entity(tableName = "payment_info") public class NetworksResponseModel implements Parcelable { @SerializedName("resultCode") @Expose @PrimaryKey @NonNull @Setter @Getter public String resultCode; @SerializedName("networks") @Expose @ColumnInfo(name = "networks") @Getter @Setter public Networks networks; @SerializedName("resultInfo") @Expose @ColumnInfo(name = "resultInfo") @Getter @Setter public String resultInfo; @SerializedName("returnCode") @Expose @ColumnInfo(name = "returnCode") @Getter @Setter public ReturnCode returnCode; @SerializedName("identification") @Expose @ColumnInfo(name = "identification") @Getter @Setter public Identification identification; @SerializedName("integrationType") @Expose @ColumnInfo(name = "integrationType") @Getter @Setter public String integrationType; @SerializedName("interaction") @Expose @ColumnInfo(name = "interaction") @Getter @Setter public Interaction interaction; @SerializedName("links") @Expose @ColumnInfo(name = "links") @Getter @Setter public Links links; @SerializedName("operationType") @Expose @ColumnInfo(name = "operationType") @Getter @Setter public String operationType; @SerializedName("style") @Expose @ColumnInfo(name = "style") @Getter @Setter public Style style; @SerializedName("payment") @Expose @ColumnInfo(name = "payment") @Getter @Setter public Payment payment; @SerializedName("operation") @Expose @ColumnInfo(name = "operation") @Getter @Setter public String operation; @SerializedName("timestamp") @Expose @ColumnInfo(name = "timestamp") @Getter @Setter public String timestamp; @SerializedName("status") @Expose @ColumnInfo(name = "status") @Getter @Setter public Status status; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.resultCode); dest.writeParcelable(this.networks, flags); dest.writeString(this.resultInfo); dest.writeParcelable(this.returnCode, flags); dest.writeParcelable(this.identification, flags); dest.writeString(this.integrationType); dest.writeParcelable(this.interaction, flags); dest.writeParcelable(this.links, flags); dest.writeString(this.operationType); dest.writeParcelable(this.style, flags); dest.writeParcelable(this.payment, flags); dest.writeString(this.operation); dest.writeString(this.timestamp); dest.writeParcelable(this.status, flags); } public void readFromParcel(Parcel source) { this.resultCode = source.readString(); this.networks = source.readParcelable(Networks.class.getClassLoader()); this.resultInfo = source.readString(); this.returnCode = source.readParcelable(ReturnCode.class.getClassLoader()); this.identification = source.readParcelable(Identification.class.getClassLoader()); this.integrationType = source.readString(); this.interaction = source.readParcelable(Interaction.class.getClassLoader()); this.links = source.readParcelable(Links.class.getClassLoader()); this.operationType = source.readString(); this.style = source.readParcelable(Style.class.getClassLoader()); this.payment = source.readParcelable(Payment.class.getClassLoader()); this.operation = source.readString(); this.timestamp = source.readString(); this.status = source.readParcelable(Status.class.getClassLoader()); } public NetworksResponseModel() { } protected NetworksResponseModel(Parcel in) { this.resultCode = in.readString(); this.networks = in.readParcelable(Networks.class.getClassLoader()); this.resultInfo = in.readString(); this.returnCode = in.readParcelable(ReturnCode.class.getClassLoader()); this.identification = in.readParcelable(Identification.class.getClassLoader()); this.integrationType = in.readString(); this.interaction = in.readParcelable(Interaction.class.getClassLoader()); this.links = in.readParcelable(Links.class.getClassLoader()); this.operationType = in.readString(); this.style = in.readParcelable(Style.class.getClassLoader()); this.payment = in.readParcelable(Payment.class.getClassLoader()); this.operation = in.readString(); this.timestamp = in.readString(); this.status = in.readParcelable(Status.class.getClassLoader()); } public static final Parcelable.Creator<NetworksResponseModel> CREATOR = new Parcelable.Creator<NetworksResponseModel>() { @Override public NetworksResponseModel createFromParcel(Parcel source) { return new NetworksResponseModel(source); } @Override public NetworksResponseModel[] newArray(int size) { return new NetworksResponseModel[size]; } }; }
package com.tencent.mm.plugin.profile.ui.newbizinfo; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Build.VERSION; import android.os.Bundle; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.tencent.mm.R; import com.tencent.mm.aa.k; import com.tencent.mm.ac.d; import com.tencent.mm.ac.d$a; import com.tencent.mm.ac.d$b; import com.tencent.mm.ac.g; import com.tencent.mm.ac.h.a; import com.tencent.mm.ac.i; import com.tencent.mm.ac.z; import com.tencent.mm.model.am; import com.tencent.mm.model.au; import com.tencent.mm.model.c; import com.tencent.mm.model.q; import com.tencent.mm.plugin.game.f$k; import com.tencent.mm.plugin.profile.ui.BizInfoPayInfoIconPreference; import com.tencent.mm.plugin.profile.ui.IconWidgetPreference; import com.tencent.mm.pluginsdk.ui.d.j; import com.tencent.mm.protocal.c.cgc; import com.tencent.mm.protocal.c.qt; import com.tencent.mm.sdk.platformtools.BackwardSupportUtil.b; import com.tencent.mm.sdk.platformtools.ah; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.ab; import com.tencent.mm.ui.base.h; import com.tencent.mm.ui.base.preference.KeyValuePreference; import com.tencent.mm.ui.base.preference.Preference; import com.tencent.mm.ui.base.preference.PreferenceSmallCategory; import com.tencent.mm.ui.base.preference.f; import com.tencent.mm.ui.s; import com.tencent.mm.ui.statusbar.DrawStatusBarPreference; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class NewBizInfoMoreInofUI extends DrawStatusBarPreference implements a { private List<d$a> dKO; private d$b dKP; private boolean dKW = false; private int eLK; private f eOE; private ab guS; private d lUs; private qt lVI; private String lVN; private boolean lVO; private Bundle lVQ; public void onCreate(Bundle bundle) { super.onCreate(bundle); this.eOE = this.tCL; lF(a.lYr); if (VERSION.SDK_INT >= 21) { com.tencent.mm.ui.statusbar.a.c(this.mController.contentView, getWindow().getStatusBarColor(), com.tencent.mm.ui.statusbar.d.c(getWindow())); } setMMTitle(R.l.contact_info_biz_more); nS(-16777216); s.cqp(); cqh(); lC(false); setBackBtn(new 1(this), R.k.actionbar_icon_dark_back); String oV = bi.oV(getIntent().getStringExtra("Contact_User")); String oV2 = bi.oV(getIntent().getStringExtra("Contact_Alias")); int intExtra = getIntent().getIntExtra("Contact_VUser_Info_Flag", 0); int intExtra2 = getIntent().getIntExtra("Contact_KWeibo_flag", 0); String stringExtra = getIntent().getStringExtra("Contact_KWeibo"); String stringExtra2 = getIntent().getStringExtra("Contact_KWeiboNick"); au.HU(); this.guS = c.FR().Yg(oV); if (this.guS == null || ((int) this.guS.dhP) == 0 || bi.oV(this.guS.field_username).length() <= 0) { this.guS = new ab(); this.guS.setUsername(oV); this.guS.du(oV2); this.guS.eF(intExtra); this.guS.dQ(stringExtra); this.guS.eE(intExtra2); this.guS.dA(stringExtra2); } else if (intExtra != 0) { this.guS.eF(intExtra); } this.lUs = com.tencent.mm.ac.f.kH(this.guS.field_username); byte[] byteArrayExtra = getIntent().getByteArrayExtra("Contact_customInfo"); try { this.lVI = byteArrayExtra == null ? null : (qt) new qt().aG(byteArrayExtra); } catch (Throwable e) { x.printErrStackTrace("MicroMsg.NewBizInfoMoreInofUI", e, "", new Object[0]); } this.eLK = getIntent().getIntExtra("Contact_Scene", 9); this.lVQ = getIntent().getBundleExtra("Contact_Ext_Args"); initView(); } protected final void initView() { String string; IndexOutOfBoundsException e; int indexOf; this.eOE.bw("biz_placed_to_the_top", true); d kH = com.tencent.mm.ac.f.kH(this.guS.field_username); this.dKO = null; this.dKP = null; if ((kH == null || kH.bG(false) == null) && this.lVI != null) { kH = new d(); kH.field_username = this.guS.field_username; kH.field_brandFlag = this.lVI.eJV; kH.field_brandIconURL = this.lVI.eJY; kH.field_brandInfo = this.lVI.eJX; kH.field_extInfo = this.lVI.eJW; kH.field_type = kH.bG(false).Mw(); } if (kH != null && kH.field_brandInfo == null && kH.field_extInfo == null && this.lVI != null) { kH.field_username = this.guS.field_username; kH.field_brandFlag = this.lVI.eJV; kH.field_brandIconURL = this.lVI.eJY; kH.field_brandInfo = this.lVI.eJX; kH.field_extInfo = this.lVI.eJW; kH.field_type = kH.bG(false).Mw(); } if (kH != null) { this.lUs = kH; this.dKO = kH.Mh(); this.dKP = kH.bG(false); this.dKW = this.dKP.Mj(); } if (com.tencent.mm.l.a.gd(this.guS.field_type)) { if (this.lUs == null ? true : this.lUs.Me()) { Bitmap e2; Drawable bitmapDrawable; String str; boolean z; CharSequence charSequence; KeyValuePreference keyValuePreference = (KeyValuePreference) this.eOE.ZZ("contact_info_wechat_account"); if (!bi.oW(this.guS.wM())) { this.eOE.bw("contact_info_wechat_account", false); keyValuePreference.setSummary(j.a(this, this.guS.wM())); } else if (ab.XT(this.guS.field_username) || com.tencent.mm.model.s.hd(this.guS.field_username)) { this.eOE.bw("contact_info_wechat_account", true); } else { this.eOE.bw("contact_info_wechat_account", false); keyValuePreference.setSummary(this.mController.tml.getString(R.l.app_field_username) + bi.oV(this.guS.BM())); } if (this.dKP == null && this.dKP.Mt() != null && !bi.oW(this.dKP.Mt().dLJ)) { d$b.d Mt = this.dKP.Mt(); keyValuePreference = (KeyValuePreference) this.eOE.ZZ("contact_info_verifyuser"); if (keyValuePreference != null) { keyValuePreference.csl(); keyValuePreference.tCA = false; if (bi.oW(Mt.dLK)) { switch (Mt.dLI) { case 0: string = getResources().getString(R.l.contact_info_verify_user_title); break; case 1: string = getResources().getString(R.l.contact_info_biz_new_sweibo_verify); break; case 2: string = getResources().getString(R.l.contact_info_biz_new_tweibo_verify); break; default: x.w("MicroMsg.NewBizInfoMoreInofUI", "getVerifyStr, error type %d", new Object[]{Integer.valueOf(Mt.dLI)}); string = getResources().getString(R.l.contact_info_isnot_verify_user_title); break; } keyValuePreference.tmc = string; } else { keyValuePreference.tmc = Mt.dLK; } if (am.a.dBt != null) { e2 = b.e(am.a.dBt.gX(this.guS.field_verifyFlag), 2.0f); } else { Object e22 = null; } if (e22 != null) { bitmapDrawable = new BitmapDrawable(getResources(), com.tencent.mm.sdk.platformtools.c.CV(R.k.new_biz_certified)); } else { bitmapDrawable = null; } str = "MicroMsg.NewBizInfoMoreInofUI"; String str2 = "verify bmp is null ? %B"; Object[] objArr = new Object[1]; if (e22 == null) { z = true; } else { z = false; } objArr[0] = Boolean.valueOf(z); x.i(str, str2, objArr); keyValuePreference.tCI = bitmapDrawable; if (Mt.dLJ != null) { str = Mt.dLM; CharSequence a = j.a(this, Mt.dLJ.trim()); if (bi.oW(str)) { charSequence = a; } else { try { charSequence = new SpannableString(str + " " + a); try { charSequence.setSpan(new ForegroundColorSpan(-36352), 0, str.length(), 17); } catch (IndexOutOfBoundsException e3) { e = e3; x.e("MicroMsg.NewBizInfoMoreInofUI", "verifySummary setSpan error: %s", new Object[]{e.getMessage()}); keyValuePreference.setSummary(charSequence); if (this.dKP != null) { } x.w("MicroMsg.NewBizInfoMoreInofUI", "has not trademark info"); this.eOE.bw("contact_info_trademark", true); if (this.dKP != null) { } this.eOE.bw("contact_info_privilege", true); string = getIntent().getStringExtra("Contact_BIZ_KF_WORKER_ID"); x.d("MicroMsg.NewBizInfoMoreInofUI", "updateKF %s, %b", new Object[]{string, Boolean.valueOf(this.lVO)}); if (!this.lVO) { this.lVN = string; g kR; IconWidgetPreference iconWidgetPreference; if (this.dKP == null || !this.dKP.MA() || this.guS == null) { this.eOE.bw("contact_info_kf_worker", true); } else if (bi.oW(string)) { kR = z.MX().kR(this.guS.field_username); if (kR == null) { this.eOE.bw("contact_info_kf_worker", true); z.MZ().a(this); z.MZ().ag(this.guS.field_username, q.GF()); this.lVO = true; } else { x.d("MicroMsg.NewBizInfoMoreInofUI", "has default kf %s", new Object[]{kR.field_openId}); this.eOE.bw("contact_info_kf_worker", false); iconWidgetPreference = (IconWidgetPreference) this.eOE.ZZ("contact_info_kf_worker"); iconWidgetPreference.setSummary(kR.field_nickname); e22 = com.tencent.mm.aa.c.a(kR.field_openId, false, -1); if (e22 == null) { c(kR); JF(kR.field_openId); } else { iconWidgetPreference.C(e22); } } } else { i MX = z.MX(); g kQ = MX.kQ(string); if (kQ == null || i.a(kQ)) { z.MZ().a(this); z.MZ().ah(this.guS.field_username, string); this.lVO = true; } if (kQ == null) { x.d("MicroMsg.NewBizInfoMoreInofUI", "no such kf, get default kf"); kR = MX.kR(this.guS.field_username); } else { kR = kQ; } if (kR == null) { this.eOE.bw("contact_info_kf_worker", true); } else { this.eOE.bw("contact_info_kf_worker", false); iconWidgetPreference = (IconWidgetPreference) this.eOE.ZZ("contact_info_kf_worker"); iconWidgetPreference.setSummary(kR.field_nickname); e22 = com.tencent.mm.aa.c.a(kR.field_openId, false, -1); if (e22 == null) { c(kR); JF(kR.field_openId); } else { iconWidgetPreference.C(e22); } x.d("MicroMsg.NewBizInfoMoreInofUI", "kf worker %s, %s", new Object[]{kR.field_openId, kR.field_nickname}); } } } if (this.dKP != null) { } this.eOE.bw("contact_info_service_phone", true); if (this.dKP != null) { } this.eOE.bw("contact_info_reputation", true); this.eOE.bw("contact_info_guarantee_info", true); this.eOE.bw("contact_info_scope_of_business", true); if (com.tencent.mm.model.s.v(this.guS)) { } this.eOE.bw("contact_info_verifyuser_weibo", true); if (this.dKP == null) { } this.eOE.bw("near_field_service", true); if (bnL() == null) { this.eOE.bw("contact_info_see_locate", false); } else { this.eOE.bw("contact_info_see_locate", true); } indexOf = this.eOE.indexOf("contact_info_category2"); if (indexOf >= 0) { } x.d("MicroMsg.NewBizInfoMoreInofUI", "pos no more"); } } catch (IndexOutOfBoundsException e4) { e = e4; charSequence = a; x.e("MicroMsg.NewBizInfoMoreInofUI", "verifySummary setSpan error: %s", new Object[]{e.getMessage()}); keyValuePreference.setSummary(charSequence); if (this.dKP != null) { } x.w("MicroMsg.NewBizInfoMoreInofUI", "has not trademark info"); this.eOE.bw("contact_info_trademark", true); if (this.dKP != null) { } this.eOE.bw("contact_info_privilege", true); string = getIntent().getStringExtra("Contact_BIZ_KF_WORKER_ID"); x.d("MicroMsg.NewBizInfoMoreInofUI", "updateKF %s, %b", new Object[]{string, Boolean.valueOf(this.lVO)}); if (this.lVO) { this.lVN = string; g kR2; IconWidgetPreference iconWidgetPreference2; if (this.dKP == null || !this.dKP.MA() || this.guS == null) { this.eOE.bw("contact_info_kf_worker", true); } else if (bi.oW(string)) { kR2 = z.MX().kR(this.guS.field_username); if (kR2 == null) { this.eOE.bw("contact_info_kf_worker", true); z.MZ().a(this); z.MZ().ag(this.guS.field_username, q.GF()); this.lVO = true; } else { x.d("MicroMsg.NewBizInfoMoreInofUI", "has default kf %s", new Object[]{kR2.field_openId}); this.eOE.bw("contact_info_kf_worker", false); iconWidgetPreference2 = (IconWidgetPreference) this.eOE.ZZ("contact_info_kf_worker"); iconWidgetPreference2.setSummary(kR2.field_nickname); e22 = com.tencent.mm.aa.c.a(kR2.field_openId, false, -1); if (e22 == null) { c(kR2); JF(kR2.field_openId); } else { iconWidgetPreference2.C(e22); } } } else { i MX2 = z.MX(); g kQ2 = MX2.kQ(string); if (kQ2 == null || i.a(kQ2)) { z.MZ().a(this); z.MZ().ah(this.guS.field_username, string); this.lVO = true; } if (kQ2 == null) { x.d("MicroMsg.NewBizInfoMoreInofUI", "no such kf, get default kf"); kR2 = MX2.kR(this.guS.field_username); } else { kR2 = kQ2; } if (kR2 == null) { this.eOE.bw("contact_info_kf_worker", true); } else { this.eOE.bw("contact_info_kf_worker", false); iconWidgetPreference2 = (IconWidgetPreference) this.eOE.ZZ("contact_info_kf_worker"); iconWidgetPreference2.setSummary(kR2.field_nickname); e22 = com.tencent.mm.aa.c.a(kR2.field_openId, false, -1); if (e22 == null) { c(kR2); JF(kR2.field_openId); } else { iconWidgetPreference2.C(e22); } x.d("MicroMsg.NewBizInfoMoreInofUI", "kf worker %s, %s", new Object[]{kR2.field_openId, kR2.field_nickname}); } } } if (this.dKP != null) { } this.eOE.bw("contact_info_service_phone", true); if (this.dKP != null) { } this.eOE.bw("contact_info_reputation", true); this.eOE.bw("contact_info_guarantee_info", true); this.eOE.bw("contact_info_scope_of_business", true); if (com.tencent.mm.model.s.v(this.guS)) { } this.eOE.bw("contact_info_verifyuser_weibo", true); if (this.dKP == null) { } this.eOE.bw("near_field_service", true); if (bnL() == null) { this.eOE.bw("contact_info_see_locate", true); } else { this.eOE.bw("contact_info_see_locate", false); } indexOf = this.eOE.indexOf("contact_info_category2"); if (indexOf >= 0) { } x.d("MicroMsg.NewBizInfoMoreInofUI", "pos no more"); } } keyValuePreference.setSummary(charSequence); } else { x.e("MicroMsg.NewBizInfoMoreInofUI", "[arthurdan.emojiSpan] Notice!!!! extInfo.verifyInfo.verifySourceDescription is null"); } } else { this.eOE.bw("contact_info_verifyuser", true); } } else if (this.dKP != null || this.dKP.Mu() == null || bi.oW(this.dKP.Mu().dLS)) { x.w("MicroMsg.NewBizInfoMoreInofUI", "has not verify info"); this.eOE.bw("contact_info_verifyuser", true); } else { keyValuePreference = (KeyValuePreference) this.eOE.ZZ("contact_info_verifyuser"); if (keyValuePreference != null) { keyValuePreference.setSummary(this.dKP.Mu().dLS); } } if (this.dKP != null || bi.oW(this.dKP.Mn())) { x.w("MicroMsg.NewBizInfoMoreInofUI", "has not trademark info"); this.eOE.bw("contact_info_trademark", true); } else { keyValuePreference = (KeyValuePreference) this.eOE.ZZ("contact_info_trademark"); if (keyValuePreference != null) { Bitmap CV; keyValuePreference.csl(); keyValuePreference.tCA = false; if (am.a.dBt != null) { CV = com.tencent.mm.sdk.platformtools.c.CV(R.k.new_biz_trademark_protection); } else { CV = null; } String str3 = "MicroMsg.NewBizInfoMoreInofUI"; str = "trademark bmp is null ? %B"; Object[] objArr2 = new Object[1]; if (CV == null) { z = true; } else { z = false; } objArr2[0] = Boolean.valueOf(z); x.i(str3, str, objArr2); if (CV != null) { bitmapDrawable = new BitmapDrawable(getResources(), CV); } else { bitmapDrawable = null; } keyValuePreference.tCI = bitmapDrawable; keyValuePreference.setSummary(this.dKP.Mn()); x.d("MicroMsg.NewBizInfoMoreInofUI", "trademark name : %s, url : %s.", new Object[]{this.dKP.Mn(), this.dKP.Mm()}); } } if (this.dKP != null || this.dKP.Mp() == null || this.dKP.Mp().size() <= 0) { this.eOE.bw("contact_info_privilege", true); } else { keyValuePreference = (KeyValuePreference) this.eOE.ZZ("contact_info_privilege"); keyValuePreference.csl(); keyValuePreference.lO(false); keyValuePreference.csk(); for (d$b.f fVar : this.dKP.Mp()) { LinearLayout linearLayout = (LinearLayout) View.inflate(this, R.i.keyvalue_pref_item, null); ((ImageView) linearLayout.findViewById(R.h.image_iv)).setImageDrawable(new com.tencent.mm.plugin.profile.ui.b.a(getResources(), fVar.iconUrl)); CharSequence charSequence2 = fVar.description; getResources().getIdentifier(fVar.dLR, "string", getPackageName()); ((TextView) linearLayout.findViewById(R.h.summary)).setText(charSequence2); keyValuePreference.dp(linearLayout); } } string = getIntent().getStringExtra("Contact_BIZ_KF_WORKER_ID"); x.d("MicroMsg.NewBizInfoMoreInofUI", "updateKF %s, %b", new Object[]{string, Boolean.valueOf(this.lVO)}); if (this.lVO) { this.lVN = string; g kR22; IconWidgetPreference iconWidgetPreference22; if (this.dKP == null || !this.dKP.MA() || this.guS == null) { this.eOE.bw("contact_info_kf_worker", true); } else if (bi.oW(string)) { kR22 = z.MX().kR(this.guS.field_username); if (kR22 == null) { this.eOE.bw("contact_info_kf_worker", true); z.MZ().a(this); z.MZ().ag(this.guS.field_username, q.GF()); this.lVO = true; } else { x.d("MicroMsg.NewBizInfoMoreInofUI", "has default kf %s", new Object[]{kR22.field_openId}); this.eOE.bw("contact_info_kf_worker", false); iconWidgetPreference22 = (IconWidgetPreference) this.eOE.ZZ("contact_info_kf_worker"); iconWidgetPreference22.setSummary(kR22.field_nickname); e22 = com.tencent.mm.aa.c.a(kR22.field_openId, false, -1); if (e22 == null) { c(kR22); JF(kR22.field_openId); } else { iconWidgetPreference22.C(e22); } } } else { i MX22 = z.MX(); g kQ22 = MX22.kQ(string); if (kQ22 == null || i.a(kQ22)) { z.MZ().a(this); z.MZ().ah(this.guS.field_username, string); this.lVO = true; } if (kQ22 == null) { x.d("MicroMsg.NewBizInfoMoreInofUI", "no such kf, get default kf"); kR22 = MX22.kR(this.guS.field_username); } else { kR22 = kQ22; } if (kR22 == null) { this.eOE.bw("contact_info_kf_worker", true); } else { this.eOE.bw("contact_info_kf_worker", false); iconWidgetPreference22 = (IconWidgetPreference) this.eOE.ZZ("contact_info_kf_worker"); iconWidgetPreference22.setSummary(kR22.field_nickname); e22 = com.tencent.mm.aa.c.a(kR22.field_openId, false, -1); if (e22 == null) { c(kR22); JF(kR22.field_openId); } else { iconWidgetPreference22.C(e22); } x.d("MicroMsg.NewBizInfoMoreInofUI", "kf worker %s, %s", new Object[]{kR22.field_openId, kR22.field_nickname}); } } } if (this.dKP != null || bi.oW(this.dKP.Mz())) { this.eOE.bw("contact_info_service_phone", true); } else { this.eOE.bw("contact_info_service_phone", false); Preference ZZ = this.eOE.ZZ("contact_info_service_phone"); if (ZZ != null) { ZZ.setSummary(this.dKP.Mz()); ZZ.hIZ = getResources().getColor(R.e.link_color); } } if (this.dKP != null || this.dKP.Mr() == null) { this.eOE.bw("contact_info_reputation", true); this.eOE.bw("contact_info_guarantee_info", true); this.eOE.bw("contact_info_scope_of_business", true); } else { BizInfoPayInfoIconPreference bizInfoPayInfoIconPreference = (BizInfoPayInfoIconPreference) this.eOE.ZZ("contact_info_reputation"); if (this.dKP.Mr().dLN > 0) { bizInfoPayInfoIconPreference.uD(this.dKP.Mr().dLN); } else { this.eOE.bw("contact_info_reputation", true); } bizInfoPayInfoIconPreference = (BizInfoPayInfoIconPreference) this.eOE.ZZ("contact_info_guarantee_info"); if (this.dKP.Mr().dLP == null || this.dKP.Mr().dLP.size() <= 0) { this.eOE.bw("contact_info_guarantee_info", true); } else { bizInfoPayInfoIconPreference.bH(this.dKP.Mr().dLP); } keyValuePreference = (KeyValuePreference) this.eOE.ZZ("contact_info_scope_of_business"); if (bi.oW(this.dKP.Mr().dLO)) { this.eOE.bw("contact_info_scope_of_business", true); } else { keyValuePreference.setSummary(this.dKP.Mr().dLO); keyValuePreference.tCG = 4; keyValuePreference.lO(false); } } if (com.tencent.mm.model.s.v(this.guS) || this.guS.csO == null || this.guS.csO.equals("")) { this.eOE.bw("contact_info_verifyuser_weibo", true); } else { keyValuePreference = (KeyValuePreference) this.eOE.ZZ("contact_info_verifyuser_weibo"); if (keyValuePreference != null) { keyValuePreference.setSummary(bi.aG(this.guS.field_weiboNickname, "") + getString(R.l.settings_show_weibo_field, new Object[]{com.tencent.mm.model.s.hV(this.guS.csO)})); keyValuePreference.hIZ = com.tencent.mm.bp.a.g(this, R.e.link_color); keyValuePreference.lO(false); } } if (this.dKP == null && this.dKP.Mi()) { this.eOE.ZZ("near_field_service").setSummary(R.l.weixin_connect_wifi); } else { this.eOE.bw("near_field_service", true); } if (bnL() == null) { this.eOE.bw("contact_info_see_locate", false); } else { this.eOE.bw("contact_info_see_locate", true); } indexOf = this.eOE.indexOf("contact_info_category2"); if (indexOf >= 0 || this.dKO == null || this.dKO.size() <= 0) { x.d("MicroMsg.NewBizInfoMoreInofUI", "pos no more"); } int size = this.dKO.size() - 1; while (size >= 0) { if (this.dKO.get(size) != null && ((!getString(R.l.contact_info_biz_participants).equals(((d$a) this.dKO.get(size)).title) || this.dKW) && !((bi.oW(((d$a) this.dKO.get(size)).title) && bi.oW(((d$a) this.dKO.get(size)).dKS)) || ((d$a) this.dKO.get(size)).dKS.equals("__mp_wording__brandinfo_location") || getString(R.l.contact_info_biz_see_location).equals(((d$a) this.dKO.get(size)).title) || ((d$a) this.dKO.get(size)).dKS.equals("__mp_wording__brandinfo_history_massmsg")))) { int i; Preference preference = new Preference(this); preference.setKey("contact_info_bizinfo_external#" + size); charSequence = ((d$a) this.dKO.get(size)).title; int identifier = getResources().getIdentifier(((d$a) this.dKO.get(size)).dKS, "string", getPackageName()); if (identifier > 0) { charSequence = getString(identifier); } if (this.lUs.LX() && ("__mp_wording__brandinfo_history_massmsg".equals(((d$a) this.dKO.get(size)).dKS) || r1.equals(getString(R.l.__mp_wording__brandinfo_history_massmsg)))) { charSequence = getString(R.l.enterprise_brand_history); } preference.setTitle(charSequence); if (!bi.oW(((d$a) this.dKO.get(size)).description)) { preference.setSummary(((d$a) this.dKO.get(size)).description); } if (bi.oV(((d$a) this.dKO.get(size)).dKS).equals("__mp_wording__brandinfo_feedback")) { identifier = this.eOE.indexOf("contact_info_scope_of_business"); if (identifier > 0) { i = identifier + 1; this.eOE.a(preference, i); if (bi.oV(((d$a) this.dKO.get(size)).dKS).equals("__mp_wording__brandinfo_biz_detail")) { this.eOE.a(new PreferenceSmallCategory(this), i); } } } i = indexOf; this.eOE.a(preference, i); if (bi.oV(((d$a) this.dKO.get(size)).dKS).equals("__mp_wording__brandinfo_biz_detail")) { this.eOE.a(new PreferenceSmallCategory(this), i); } } size--; } return; } } this.eOE.bw("contact_info_wechat_account", true); if (this.dKP == null) { } if (this.dKP != null) { } x.w("MicroMsg.NewBizInfoMoreInofUI", "has not verify info"); this.eOE.bw("contact_info_verifyuser", true); if (this.dKP != null) { } x.w("MicroMsg.NewBizInfoMoreInofUI", "has not trademark info"); this.eOE.bw("contact_info_trademark", true); if (this.dKP != null) { } this.eOE.bw("contact_info_privilege", true); string = getIntent().getStringExtra("Contact_BIZ_KF_WORKER_ID"); x.d("MicroMsg.NewBizInfoMoreInofUI", "updateKF %s, %b", new Object[]{string, Boolean.valueOf(this.lVO)}); if (this.lVO) { this.lVN = string; g kR222; IconWidgetPreference iconWidgetPreference222; if (this.dKP == null || !this.dKP.MA() || this.guS == null) { this.eOE.bw("contact_info_kf_worker", true); } else if (bi.oW(string)) { kR222 = z.MX().kR(this.guS.field_username); if (kR222 == null) { this.eOE.bw("contact_info_kf_worker", true); z.MZ().a(this); z.MZ().ag(this.guS.field_username, q.GF()); this.lVO = true; } else { x.d("MicroMsg.NewBizInfoMoreInofUI", "has default kf %s", new Object[]{kR222.field_openId}); this.eOE.bw("contact_info_kf_worker", false); iconWidgetPreference222 = (IconWidgetPreference) this.eOE.ZZ("contact_info_kf_worker"); iconWidgetPreference222.setSummary(kR222.field_nickname); e22 = com.tencent.mm.aa.c.a(kR222.field_openId, false, -1); if (e22 == null) { c(kR222); JF(kR222.field_openId); } else { iconWidgetPreference222.C(e22); } } } else { i MX222 = z.MX(); g kQ222 = MX222.kQ(string); if (kQ222 == null || i.a(kQ222)) { z.MZ().a(this); z.MZ().ah(this.guS.field_username, string); this.lVO = true; } if (kQ222 == null) { x.d("MicroMsg.NewBizInfoMoreInofUI", "no such kf, get default kf"); kR222 = MX222.kR(this.guS.field_username); } else { kR222 = kQ222; } if (kR222 == null) { this.eOE.bw("contact_info_kf_worker", true); } else { this.eOE.bw("contact_info_kf_worker", false); iconWidgetPreference222 = (IconWidgetPreference) this.eOE.ZZ("contact_info_kf_worker"); iconWidgetPreference222.setSummary(kR222.field_nickname); e22 = com.tencent.mm.aa.c.a(kR222.field_openId, false, -1); if (e22 == null) { c(kR222); JF(kR222.field_openId); } else { iconWidgetPreference222.C(e22); } x.d("MicroMsg.NewBizInfoMoreInofUI", "kf worker %s, %s", new Object[]{kR222.field_openId, kR222.field_nickname}); } } } if (this.dKP != null) { } this.eOE.bw("contact_info_service_phone", true); if (this.dKP != null) { } this.eOE.bw("contact_info_reputation", true); this.eOE.bw("contact_info_guarantee_info", true); this.eOE.bw("contact_info_scope_of_business", true); if (com.tencent.mm.model.s.v(this.guS)) { } this.eOE.bw("contact_info_verifyuser_weibo", true); if (this.dKP == null) { } this.eOE.bw("near_field_service", true); if (bnL() == null) { this.eOE.bw("contact_info_see_locate", true); } else { this.eOE.bw("contact_info_see_locate", false); } indexOf = this.eOE.indexOf("contact_info_category2"); if (indexOf >= 0) { } x.d("MicroMsg.NewBizInfoMoreInofUI", "pos no more"); } private d$a bnL() { if (this.dKO == null || this.dKO.size() < 0) { x.w("MicroMsg.NewBizInfoMoreInofUI", "brandInfoList is null not show location"); return null; } for (d$a d_a : this.dKO) { if (d_a.dKS.equals("__mp_wording__brandinfo_location")) { return d_a; } if (getString(R.l.contact_info_biz_see_location).equals(d_a.title)) { return d_a; } } x.w("MicroMsg.NewBizInfoMoreInofUI", "brandInfoList is null not show location"); return null; } private static void c(g gVar) { long currentTimeMillis = System.currentTimeMillis(); k KH = com.tencent.mm.aa.q.KH(); if (KH.kc(gVar.field_openId) == null) { com.tencent.mm.aa.j jVar = new com.tencent.mm.aa.j(); jVar.username = gVar.field_openId; jVar.dHQ = gVar.field_headImgUrl; jVar.by(false); jVar.csA = 3; KH.a(jVar); } com.tencent.mm.aa.q.KJ().jP(gVar.field_openId); x.d("MicroMsg.NewBizInfoMoreInofUI", "downloadKFAvatar, %d", new Object[]{Long.valueOf(System.currentTimeMillis() - currentTimeMillis)}); } private void JF(String str) { ah.i(new 2(this, str), 2000); } public final String MQ() { return "MicroMsg.NewBizInfoMoreInofUI"; } public final void d(LinkedList<cgc> linkedList) { z.MZ().b(this); if (this.eOE == null) { x.e("MicroMsg.NewBizInfoMoreInofUI", "onKFSceneEnd, screen is null"); } else if (this.guS == null) { x.e("MicroMsg.NewBizInfoMoreInofUI", "onKFSceneEnd, contact is null"); } else if (linkedList == null || linkedList.size() <= 0) { x.w("MicroMsg.NewBizInfoMoreInofUI", "onKFSceneEnd, worker is null"); } else { if (!bi.oW(this.lVN)) { Iterator it = linkedList.iterator(); while (it.hasNext()) { cgc cgc = (cgc) it.next(); if (cgc.sAB != null && cgc.sAB.equals(this.lVN)) { this.eOE.bw("contact_info_kf_worker", false); this.eOE.ZZ("contact_info_kf_worker").setSummary(cgc.rTW); return; } } } this.eOE.bw("contact_info_kf_worker", false); this.eOE.ZZ("contact_info_kf_worker").setSummary(((cgc) linkedList.get(0)).rTW); } } public final int Ys() { return R.o.newbizinfo_more_info_pref; } public final boolean a(f fVar, Preference preference) { int i = 7; String str = preference.mKey; x.i("MicroMsg.NewBizInfoMoreInofUI", str + " item has been clicked!"); String str2; Intent intent; int i2; String str3; d dVar; Intent intent2; if ("contact_info_see_locate".endsWith(str)) { d$a bnL = bnL(); str2 = bnL.url; intent = new Intent(); intent.putExtra("rawUrl", str2); intent.putExtra("useJs", true); intent.putExtra("vertical_scroll", true); intent.putExtra("geta8key_scene", 3); intent.putExtra("KPublisherId", "brand_profile"); intent.putExtra("prePublishId", "brand_profile"); if ((this.lVQ != null && (this.eLK == 39 || this.eLK == 56 || this.eLK == 35)) || this.eLK == 87 || this.eLK == 89 || this.eLK == 85 || this.eLK == 88) { x.d("MicroMsg.NewBizInfoMoreInofUI", "from biz search."); Bundle bundle = new Bundle(); bundle.putBoolean("KFromBizSearch", true); bundle.putBundle("KBizSearchExtArgs", this.lVQ); intent.putExtra("jsapiargs", bundle); i2 = com.tencent.mm.l.a.gd(this.guS.field_type) ? 7 : 6; int identifier = getResources().getIdentifier(bnL.dKS, "string", getPackageName()); str3 = bnL.title; if (identifier > 0) { str3 = getString(identifier); } ay(i2, str3); } com.tencent.mm.bg.d.b(this, "webview", ".ui.tools.WebViewUI", intent); return true; } else if ("contact_info_verifyuser".endsWith(str)) { dVar = this.lUs; if (dVar == null) { return true; } d$b bG = dVar.bG(false); if (bG == null) { return true; } str2 = null; if (bG.Mt() != null && !bi.oW(bG.Mt().dLL)) { str2 = bG.Mt().dLL; } else if (!(bG.Mu() == null || bi.oW(bG.Mu().dLT))) { str2 = bG.Mu().dLT; } if (!bi.oW(str2)) { intent2 = new Intent(); intent2.putExtra("rawUrl", str2); intent2.putExtra("useJs", true); intent2.putExtra("vertical_scroll", true); intent2.putExtra("geta8key_scene", 3); com.tencent.mm.bg.d.b(this, "webview", ".ui.tools.WebViewUI", intent2); } com.tencent.mm.plugin.profile.ui.newbizinfo.c.c.bT(this.guS.field_username, 1200); return true; } else if ("contact_info_trademark".endsWith(str)) { dVar = this.lUs; if (dVar == null || dVar.bG(false) == null || bi.oW(dVar.bG(false).Mm())) { return true; } intent2 = new Intent(); intent2.putExtra("rawUrl", dVar.bG(false).Mm()); intent2.putExtra("useJs", true); intent2.putExtra("vertical_scroll", true); intent2.putExtra("geta8key_scene", 3); com.tencent.mm.bg.d.b(this, "webview", ".ui.tools.WebViewUI", intent2); return true; } else { if ("contact_info_service_phone".equals(str)) { Preference ZZ = fVar.ZZ("contact_info_service_phone"); if (!(ZZ == null || ZZ.getSummary() == null || bi.oW(ZZ.getSummary().toString()))) { str3 = ZZ.getSummary().toString(); h.a(this, true, str3, "", getString(R.l.contact_info_dial), getString(R.l.app_cancel), new 3(this, str3), null); } } if (str.startsWith("contact_info_bizinfo_external#")) { i2 = bi.getInt(str.replace("contact_info_bizinfo_external#", ""), -1); if (i2 >= 0 && i2 < this.dKO.size()) { d$a d_a = (d$a) this.dKO.get(i2); str3 = d_a.url; intent = new Intent(); intent.putExtra("rawUrl", str3); intent.putExtra("useJs", true); intent.putExtra("vertical_scroll", true); intent.putExtra("geta8key_scene", 3); intent.putExtra("KPublisherId", "brand_profile"); intent.putExtra("prePublishId", "brand_profile"); if ((this.lVQ != null && (this.eLK == 39 || this.eLK == 56 || this.eLK == 35)) || this.eLK == 87 || this.eLK == 89 || this.eLK == 85 || this.eLK == 88) { x.d("MicroMsg.NewBizInfoMoreInofUI", "from biz search."); Bundle bundle2 = new Bundle(); bundle2.putBoolean("KFromBizSearch", true); bundle2.putBundle("KBizSearchExtArgs", this.lVQ); intent.putExtra("jsapiargs", bundle2); if (!com.tencent.mm.l.a.gd(this.guS.field_type)) { i = 6; } int identifier2 = getResources().getIdentifier(d_a.dKS, "string", getPackageName()); str2 = d_a.title; if (identifier2 > 0) { str2 = getString(identifier2); } ay(i, str2); } com.tencent.mm.bg.d.b(this, "webview", ".ui.tools.WebViewUI", intent); return true; } } if (str.equals("contact_info_verifyuser_weibo")) { new com.tencent.mm.plugin.profile.ui.a.a(this).ef(this.guS.csO, this.guS.field_username); return true; } Intent intent3; if (!(!"contact_info_guarantee_info".equals(str) || this.dKP.Mr() == null || bi.oW(this.dKP.Mr().dLQ))) { intent3 = new Intent(); intent3.putExtra("rawUrl", this.dKP.Mr().dLQ); intent3.putExtra("useJs", true); intent3.putExtra("vertical_scroll", true); intent3.putExtra("geta8key_scene", 3); com.tencent.mm.bg.d.b(this, "webview", ".ui.tools.WebViewUI", intent3); } if (!(!"contact_info_expose_btn".equals(str) || this.guS == null || bi.oW(this.guS.field_username))) { intent3 = new Intent(); intent3.putExtra("rawUrl", String.format("https://mp.weixin.qq.com/mp/infringement?username=%s&from=1#wechat_redirect", new Object[]{this.guS.field_username})); intent3.putExtra("showShare", false); com.tencent.mm.bg.d.b(this, "webview", ".ui.tools.WebViewUI", intent3); } return false; } } private void ay(int i, String str) { if (this.lVQ == null || !(this.eLK == 39 || this.eLK == 56 || this.eLK == 35 || this.eLK == 87 || this.eLK == 88 || this.eLK == 89 || this.eLK == 85)) { x.d("MicroMsg.NewBizInfoMoreInofUI", "mExtArgs is null or the add contact action is not from biz search."); } else if (this.guS == null) { x.i("MicroMsg.NewBizInfoMoreInofUI", "contact is null."); } else { int i2; String string = this.lVQ.getString("Contact_Ext_Args_Search_Id"); String oV = bi.oV(this.lVQ.getString("Contact_Ext_Args_Query_String")); int i3 = this.lVQ.getInt("Contact_Ext_Args_Index"); switch (this.eLK) { case 35: i2 = 1; break; case 85: i2 = 5; break; case f$k.AppCompatTheme_colorControlHighlight /*87*/: i2 = 2; break; case f$k.AppCompatTheme_colorButtonNormal /*88*/: i2 = 3; break; case f$k.AppCompatTheme_colorSwitchThumbNormal /*89*/: i2 = 4; break; default: i2 = 0; break; } String oV2 = bi.oV(this.lVQ.getString("Contact_Ext_Extra_Params")); String str2 = oV + "," + i + "," + bi.oV(this.guS.field_username) + "," + i3 + "," + (System.currentTimeMillis() / 1000) + "," + string + "," + i2; if (bi.oW(str)) { str2 = str2 + ",," + oV2; } else { str2 = str2 + "," + str + "," + oV2; } x.v("MicroMsg.NewBizInfoMoreInofUI", "report 10866: %s", new Object[]{str2}); com.tencent.mm.plugin.report.service.h.mEJ.k(10866, str2); } } }
package com.gtfs.service.impl; import java.io.Serializable; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import com.gtfs.bean.BranchMst; import com.gtfs.bean.LicHubMst; import com.gtfs.bean.LicMarkingToQcDtls; import com.gtfs.bean.LicOblApplicationMst; import com.gtfs.bean.LicPolicyDtls; import com.gtfs.bean.LicRequirementDtls; import com.gtfs.dao.interfaces.LicMarkingToQcDtlsDao; import com.gtfs.service.interfaces.LicMarkingToQcDtlsService; @Service public class LicMarkingToQcDtlsServiceImpl implements LicMarkingToQcDtlsService,Serializable{ @Autowired private LicMarkingToQcDtlsDao licMarkingToQcDtlsDao; public Boolean saveForConsolidateMarking(LicMarkingToQcDtls licMarkingToQcDtls){ return licMarkingToQcDtlsDao.saveForConsolidateMarking(licMarkingToQcDtls); } public List<LicOblApplicationMst> findIndividualMarkingDtlsByDate(String applicationNo,Date fromDate,Date toDate, List<LicHubMst> licHubMsts, BranchMst branchMst, Long branchId){ return licMarkingToQcDtlsDao.findIndividualMarkingDtlsByDate(applicationNo,fromDate, toDate, licHubMsts, branchMst, branchId); } public Boolean updateForIndividualMarking(List<LicOblApplicationMst> licHubMsts){ return licMarkingToQcDtlsDao.updateForIndividualMarking(licHubMsts); } @Override public List<LicRequirementDtls> findIndividualMArkingDtlsByDateForReq(Date fromDate, Date toDate, List<LicHubMst> licHubMsts, BranchMst branchMst) { return licMarkingToQcDtlsDao.findIndividualMArkingDtlsByDateForReq(fromDate, toDate, licHubMsts, branchMst); } @Override public Boolean updateForIndividualMarkingForReq(List<LicRequirementDtls> licHubMsts) { return licMarkingToQcDtlsDao.updateForIndividualMarkingForReq(licHubMsts); } @Override public Boolean updateForIndividualMarkingForRenewal(List<LicPolicyDtls> licPolicyDtlsList){ return licMarkingToQcDtlsDao.updateForIndividualMarkingForRenewal(licPolicyDtlsList); } @Override public Boolean saveForConsolidateMarkingForPos(LicMarkingToQcDtls licMarkingToQcDtls) { return licMarkingToQcDtlsDao.saveForConsolidateMarkingForPos(licMarkingToQcDtls); } @Override public Boolean updateForIndividualMarkingForPos(List<LicRequirementDtls> licRequirementDtlsList) { return licMarkingToQcDtlsDao.updateForIndividualMarkingForPos(licRequirementDtlsList); } @Override public List<LicOblApplicationMst> findIndividualMarkingDtlsReport(Date businessFromDate, Date businessToDate, List<LicHubMst> findHubForProcess, Long branchId) { return licMarkingToQcDtlsDao.findIndividualMarkingDtlsReport(businessFromDate, businessToDate, findHubForProcess, branchId); } }
package com.tfsis.server; import java.io.IOException; import java.util.HashMap; import java.util.Map.Entry; import java.util.logging.Level; import org.bigtesting.routd.Route; import org.bigtesting.routd.Router; import org.bigtesting.routd.TreeRouter; import com.tfsis.server.handlers.HttpHandlerBase; import com.tfsis.server.responses.NotFoundResponse; import com.tfsis.server.responses.StatusResponse; import fi.iki.elonen.NanoHTTPD; import fi.iki.elonen.NanoHTTPD.Response.Status; public class AppServer extends NanoHTTPD { java.util.logging.Logger log = java.util.logging.Logger.getLogger("AppServer"); public AppServer(int port) throws IOException { super(port); } private Router router; private HashMap<Route, HttpHandlerBase> routers; public void registeRouters(HashMap<String, HttpHandlerBase> r) { router = new TreeRouter(); routers = new HashMap<>(); for (Entry<String, HttpHandlerBase> entry : r.entrySet()) { Route rt = new Route(entry.getKey()); router.add(rt); routers.put(rt, entry.getValue()); } } // private void initRoutersMap() { // routers.put(new Route("/"), new HomeHandler()); // routers.put(new Route("/page/:id<[0-9]+>"), new HomeHandler()); // routers.put(new Route("/post/:id<[0-9]+>"), new HomeHandler()); // routers.put(new Route("/scripts/:name"), new HomeHandler()); // routers.put(new Route("/styles/:name"), new HomeHandler()); // routers.put(new Route("/fonts/:name"), new HomeHandler()); // } @Override public Response serve(IHTTPSession session) { String urlPath = session.getUri(); Route route = router.route(urlPath); if (route == null) { return new NotFoundResponse(); } if (!routers.containsKey(route)) { return new NotFoundResponse(); } HttpHandlerBase handler = routers.get(route); handler.setSessionContext(session); handler.setSessionRoute(route); try { return handler.process(); } catch (Exception e) { log.log(Level.SEVERE, e.getMessage()); return new StatusResponse(Status.INTERNAL_ERROR); } } @Override public void start(int arg0, boolean arg1) throws IOException { log.log(Level.INFO, "starting..."); super.start(NanoHTTPD.SOCKET_READ_TIMEOUT, false); } }
package com.gamemoim.demo.account; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.validator.constraints.Length; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; @Data @AllArgsConstructor @NoArgsConstructor public class SignUpRequestDto { @NotBlank @Length(min = 3, max = 20) private String nickname; @Email @NotBlank private String email; @NotBlank @Length(min = 8, max = 20) private String password; }
package com.rishi.baldawa.iq; import com.rishi.baldawa.iq.model.ListNode; import org.junit.Test; import static com.rishi.baldawa.iq.model.ListNodeDataFactory.l; import static org.junit.Assert.assertEquals; public class SortedListRemoveDuplicatesTest { @Test public void solutionWithDuplicates() throws Exception { ListNode input = l(1, 1, 2); ListNode expected = l(1, 2); assertEquals(new SortedListRemoveDuplicates().solution(input), expected); } @Test public void solutionWithMoreDuplicates() throws Exception { ListNode input = l(1, 1, 2, 3, 3); ListNode expected = l(1, 2, 3); assertEquals(new SortedListRemoveDuplicates().solution(input), expected); } @Test public void solutionWithNoDuplicates() throws Exception { ListNode input = l(1, 2, 3); ListNode expected = l(1, 2, 3); assertEquals(new SortedListRemoveDuplicates().solution(input), expected); } }
package recursionAndBacktracking; public class PrintLeafNodes { public static void main(String[] args) { Node root = new Node(1); root.left = new Node(2); root.left.left = new Node(4); root.right = new Node(3); root.right.left = new Node(5); root.right.right = new Node(8); root.right.left.left = new Node(6); root.right.left.right = new Node(7); root.right.right.left = new Node(9); root.right.right.right = new Node(10); printLeafs(root); } static void printLeafs(Node root) { if (root == null) { return; } printLeafs(root.left); if (root.left == null && root.right == null) { System.out.print(root.data + " "); } printLeafs(root.right); } static class Node { int data; Node left; Node right; protected Node(int data) { this.data = data; left = right = null; } } }
package com.alejandrorg.wikihsdn.logic; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; /** * This class has been made to "fix" the freebase RDF content. * * It has been created for my necessities so it is possible that it could work for everyone. I will * update it based on the new fixes that I will need to make to the RDF brokes that I will eventually found. * * The fix is based on removing all the special characters that are making the RDF content not readable by parsers * such as the ones in Jena libraries. * * Current version of the fix implies a content loss. Please check and modify the code adapted to your needs. * @author Alejandro Rodríguez González [http://www.alejandrorg.com] * */ public class FreebaseFixer { /** * Same as the other method but converts the String into an InputStream needed by some libraries. * @param url Receives the URL. * @return Returns the input stream. * @throws Exception It can throws exceptions. */ public static InputStream getFreebaseRDFContentAsInputStream(String url) throws Exception { return new ByteArrayInputStream(getFreebaseRDFContent(url).getBytes()); } /** * Method to get the freebase RDF content from a given URL as a String. * It is needed to get the URL content as String to process it and fix it. * @param url Receives the URL as parameter. * @return Return the content in a String. * @throws Exception It can throws exceptions. */ public static String getFreebaseRDFContent(String url) throws Exception { String urlContent = getURLContentAsString(url); String urlContentParts[] = urlContent.split("\n"); String fixedWebContent = ""; for (int i = 0; i < urlContentParts.length; i++) { String part = urlContentParts[i]; /* * In this case I'm removing unicode representations.. other options can be adaptaed. */ Pattern classPattern = Pattern.compile("\\\\u[0-9a-fA-F]{4}"); Matcher classMatcher = classPattern.matcher(part); if (!classMatcher.find()) { part = part.replaceAll("\\\\x[0-9a-fA-F]{4}", ""); part = part.replaceAll("\\\\x[0-9a-fA-F]", ""); /* * This is a fix for some special characters. */ part = part.replaceAll("[\u0024]+", ""); /* * This fix is for those cases where we have a string like that: * * "Influenza is also known as "blabla" and blabla because "ble ble" and whatever"@en; * The quotes inside the quotes break the the content for the parser. */ if (part.split(Character.toString('"')).length > 2) { part = fixStringQuotations(part); } fixedWebContent += part + "\r\n"; // for debugging: allows to print line number // System.out.println(i + " - " + part); } } return fixedWebContent; } /** * We use Apache HTTP libraries to get the content. * @param urlToRead URL of the RDF data. * @return Return the string. * @throws Exception It can throws exceptions. */ private static String getURLContentAsString(String urlToRead) throws Exception { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(urlToRead); HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); String responseString = EntityUtils.toString(entity, "UTF-8"); return responseString; } /** * This method is in charge of fixing the problem of multiple quotes. * @param str Receive the original string. * @return Return the fixed string. */ private static String fixStringQuotations(String str) { String fixed = ""; int numberQuotes = str.split(Character.toString('"')).length; int quotesFound = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) != '"') { fixed += str.charAt(i); } else { quotesFound++; if ((quotesFound == 1) || (quotesFound == numberQuotes - 1)) { fixed += '"'; } else { fixed += "'"; } } } return fixed; } }
package reversi.view; import reversi.Core; import reversi.Main; import javafx.fxml.FXML; import javafx.scene.control.TextField; import javafx.stage.Stage; public class PlayerNamePaneController { private Stage stage; private Main main; public void setMain(Main main) { this.main = main; } public PlayerNamePaneController() { } public Stage getStage() { return this.stage; } public void setStage(Stage stage) { this.stage = stage; } Core c = new Core(); @FXML private TextField player1Field; @FXML private TextField player2Field; @FXML private void handleReady() { c.setBlackName(player1Field.getText()); c.setWhiteName(player2Field.getText()); // System.out.println(t.getBlackName()); // System.out.println(t.getWhiteName()); if(c.getBlackName().isEmpty()||c.getWhiteName().isEmpty()||c.getBlackName().equals(c.getWhiteName())){ String s=""; if(c.getBlackName().isEmpty()||c.getWhiteName().isEmpty()) { s="No player name field should be empty!"; } else{ s="Jet fuel can't melt steel beams!"; } this.main.Error(s); } else{ this.main.createTable(c); } } public void initData(Core core) { this.c = core; } }
package LC800_1000.LC900_950; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class LC932_Beautiful_Arrays { @Test public void test() { int[] res = beautifulArray(5); for (int i : res) System.out.print(i); } public int[] beautifulArray3(int N) { return null; } public int[] beautifulArray(int N) { List<int[]> res = new ArrayList<>(); res.add(new int[]{1}); res.add(new int[]{1}); for (int i = 1; i < N; ++i) { int[] tem = new int[i + 1]; res.add(tem); int t = 0; for (int l : res.get((i + 2) / 2)) tem[t++] = 2 * l - 1; for (int r : res.get((i + 1) / 2)) tem[t++] = 2 * r; } return res.get(N); } HashMap<Integer, int[]> memo; public int[] beautifulArray2(int N) { memo = new HashMap<>(); return f(N); } private int[] f(int n) { if (memo.containsKey(n)) return memo.get(n); int [] ans = new int[n]; if (n == 1) ans[0] = 1; else { int t = 0; for (int x : f((n + 1) / 2)) // odds ans[t++] = 2 * x - 1; for (int x : f(n / 2)) // even ans[t++] = 2 * x; } memo.put(n, ans); return ans; } }
package com.ahmetkizilay.yatlib4j.streaming; import com.ahmetkizilay.yatlib4j.oauthhelper.OAuthHolder; public class GetFilterStream { private static final String BASE_URL = "https://stream.twitter.com/1.1/statuses/filter.json"; private static final String HTTP_METHOD = "POST"; public static GetFilterStream.Response sendRequest(GetFilterStream.Parameters params, OAuthHolder oauthHolder) { throw new UnsupportedOperationException(); } public static class Response { } public static class Parameters { } }
package com.chan.demo.mapper; import com.chan.demo.vo.loginVO; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; import javax.servlet.http.HttpSession; @Repository("loginMapper") @Mapper public interface loginMapper { //1. 로그인 public loginVO login(loginVO mv) throws Exception; //3. 로그아웃 public void logout(HttpSession session); }
/* 1: */ package com.kaldin.test.executetest.action; /* 2: */ /* 3: */ import com.kaldin.test.executetest.dao.TemporaryExamDAO; /* 4: */ import com.kaldin.test.settest.dao.impl.QuestionPaperImplementor; /* 5: */ import com.kaldin.test.settest.dto.QuestionPaperDTO; /* 6: */ import javax.servlet.http.HttpServletRequest; /* 7: */ import javax.servlet.http.HttpServletResponse; /* 8: */ import javax.servlet.http.HttpSession; /* 9: */ import org.apache.commons.lang.StringUtils; /* 10: */ import org.apache.struts.action.Action; /* 11: */ import org.apache.struts.action.ActionForm; /* 12: */ import org.apache.struts.action.ActionForward; /* 13: */ import org.apache.struts.action.ActionMapping; /* 14: */ /* 15: */ public class ShowAdditionalInfoAction /* 16: */ extends Action /* 17: */ { /* 18: */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) /* 19: */ throws Exception /* 20: */ { /* 21:34 */ String result = "success"; /* 22:35 */ String testid = request.getParameter("testid"); /* 23:36 */ String examid = request.getParameter("examid"); /* 24:37 */ QuestionPaperImplementor qpImplemontor = new QuestionPaperImplementor(); /* 25:38 */ QuestionPaperDTO questpaperDTO = qpImplemontor.getTest(testid); /* 26: */ /* 27:40 */ String comments = ""; /* 28:41 */ String videoURL = ""; /* 29:42 */ String videoLongURL = ""; /* 30:43 */ String examInfoFile = ""; /* 31:44 */ boolean isComment = true; /* 32:45 */ boolean isVideo = true; /* 33:46 */ boolean isExamInfoFile = true; /* 34: */ /* 35:48 */ request.getSession().removeAttribute("examid"); /* 36: */ try /* 37: */ { /* 38:50 */ comments = questpaperDTO.getComments() == null ? "" : questpaperDTO.getComments(); /* 39:51 */ videoURL = questpaperDTO.getVideoURL() == null ? "" : questpaperDTO.getVideoURL(); /* 40:52 */ examInfoFile = questpaperDTO.getExamInfoFile() == null ? "" : questpaperDTO.getExamInfoFile(); /* 41: */ } /* 42: */ catch (Exception e) {} /* 43:55 */ if ((StringUtils.isEmpty(comments)) || (comments == null) || (comments.equals(null)) || ("".equals(comments)) || (comments == "")) { /* 44:56 */ isComment = false; /* 45: */ } /* 46:57 */ if ((StringUtils.isEmpty(videoURL)) || (videoURL == null) || (videoURL.equals(null)) || ("".equals(videoURL)) || (videoURL == "")) { /* 47:58 */ isVideo = false; /* 48: */ } /* 49:59 */ if ((StringUtils.isEmpty(examInfoFile)) || (examInfoFile == null) || (examInfoFile.equals(null)) || ("".equals(examInfoFile)) || (examInfoFile == "")) { /* 50:60 */ isExamInfoFile = false; /* 51: */ } /* 52:62 */ if ((isComment) || (isVideo) || (isExamInfoFile)) /* 53: */ { /* 54:63 */ result = "success"; /* 55:64 */ request.setAttribute("comments", comments); /* 56:65 */ if (videoURL.indexOf("youtu.be") > -1) /* 57: */ { /* 58:66 */ videoLongURL = TemporaryExamDAO.getYouTubeLongUrl(videoURL); /* 59:67 */ videoURL = videoLongURL != null ? videoLongURL : videoURL; /* 60: */ } /* 61:70 */ if (videoURL.indexOf("youtube.com") > -1) { /* 62:71 */ videoURL = videoURL + "&html5=1"; /* 63: */ } /* 64:73 */ request.setAttribute("videoURL", videoURL); /* 65:74 */ request.setAttribute("examInfoFile", examInfoFile); /* 66: */ } /* 67: */ else /* 68: */ { /* 69:76 */ result = "noinfo"; /* 70: */ } /* 71:79 */ request.setAttribute("testid", testid); /* 72:80 */ request.getSession().setAttribute("examid", examid); /* 73: */ /* 74:82 */ return mapping.findForward(result); /* 75: */ } /* 76: */ } /* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip * Qualified Name: kaldin.test.executetest.action.ShowAdditionalInfoAction * JD-Core Version: 0.7.0.1 */
import java.util.HashSet; public class particularelementset { public static void main(String[] args) { HashSet<Integer> hs = new HashSet<>(); Integer num=899; hs.add(199); hs.add(299); hs.add(399); hs.add(499); boolean flag = hs.contains(num); if(flag) { System.out.println("element exists"); } else { System.out.println("elememt does not exists"); } } }
import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class first { public static void main(){ WebDriver driver = new FirefoxDriver(); driver.get("https:www.google.com"); } }
package com.colingodsey.quic.packet.frame; import io.netty.buffer.ByteBuf; import com.colingodsey.quic.utils.VariableInt; //TODO: make high priority public class Ping implements Frame { public static final int PACKET_ID = 0x01; public static final Ping INSTANCE = new Ping(); public static final Ping read(ByteBuf in) { Frame.verifyPacketId(in, PACKET_ID); return INSTANCE; } private Ping() {} public int length() { return 1; } public void write(ByteBuf out) { VariableInt.write(PACKET_ID, out); } }
package com.ifli.mbcp.domain; import java.io.Serializable; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "tbl_lookup_plan_type") public class PlanType extends GenericLookup implements Serializable { private Set<InsurancePlan> insurancePlan; @Override @Id @Column(name = "planTypeId") @GeneratedValue(strategy = GenerationType.AUTO) public Long getId() { return super.getId(); } @Override @Column(name = "planTypeName", length = 20, nullable = false) public String getName() { return super.getName(); } @Override @Column(name = "planTypeDescription", length = 30, nullable = true) public String getDescription() { return super.getDescription(); } //Confirm if this is the sole owner or not, in order to choose between //@JoinTable vs @JoinColumn. @OneToMany(fetch = FetchType.LAZY) @JoinColumn(name = "planTypeId") public Set<InsurancePlan> getInsurancePlan() { return insurancePlan; } public void setInsurancePlan(Set<InsurancePlan> insurancePlan) { this.insurancePlan = insurancePlan; } private static final long serialVersionUID = -9151461232548558789L; }
package com.leafye.annotation; import android.view.View; /** * Created by leafye on 2020/4/18. */ public interface ViewFinder { View findView(Object object, int id); }
package odeSolver; import Exceptions.WrongCalculationException; import Exceptions.WrongExpressionException; import Exceptions.WrongInputException; import MathExpr.MathExpr; import MathToken.MathTokenSymbol; public class DifferentialEquation { /** Right hand equation's member */ private MathExpr func; /** Exact Solution (Null If None) */ private MathExpr exprExact; /** Initial Time */ private double t0; /** Initial Value */ private double y0; /** Difference Between Each Time Value*/ private double step; /** Maximum Time*/ private double tmax; /** Number Of Time Points*/ private int stepNumber; /** Time Interval */ private double[] timeInterval; /** Independent symbol: t */ private MathTokenSymbol t; /** Dependent symbol: y(t) */ private MathTokenSymbol y; /** Approximated Y Solution Interval */ private double[] yk; /** Tolerance */ private double tol; /** Method Name */ private String methodName; /** Method Type */ private String methodType; /** True If Already Solved */ private boolean solved; /** True If Errors Already Calculated */ private boolean err; /** True If The Differential Equations Has An Exact Solution */ private boolean hasExact; /** Errors Percentage Between Exact And Approximated Solution */ private double[] errorsPerc; /** Errors Percentage Average */ private double errorsPercAvg; /** Errors Percentage Variance */ private double errorsPercVar; /** Errors Percentage Standard Deviation */ private double errorsPercSd; /** * General Case (With Exact Solution) * * @param exact Exact Solution * @param func f(t, y(t)) * @param t0 Initial Time * @param y0 Initial Value y(t0) = y0 * @param step difference between each moment * @param tmax max time, end of calculation * @param t Independent Symbol t * @param y Dependent Symbol y(t) * @throws WrongInputException Null Input * @throws WrongCalculationException */ public DifferentialEquation (MathExpr exact, MathExpr func, double t0, double y0, double step, double tmax, MathTokenSymbol t, MathTokenSymbol y) throws WrongInputException, WrongCalculationException { if (func == null) { throw new WrongInputException ("DifferentialEquation- Null Function"); } if (t == null) { throw new WrongInputException ("DifferentialEquation- Null Input Symbol t"); } if (y == null) { throw new WrongInputException ("DifferentialEquation- Null Input Symbol y(t)"); } if (t0 >= tmax) { throw new WrongInputException ("DifferentialEquation- t0 (=" + t0 + ") Must Be Less Than maxTime (=" + tmax + ")"); } if (step <= 0) { throw new WrongInputException ("DifferentialEquation- Step (=" + step + ") Must Be A Positive Number"); } // Fields Initialization this.methodName = "Not Solved Yet"; this.methodType = "Not Solved Yet"; this.func = func; this.t0 = t0; this.y0 = y0; this.step = step; this.tmax = tmax; this.tol = 0.00000001; this.t = t; this.y = y; // Status Fields Initialization this.solved = false; this.err = false; // Time Interval Calculation this.stepNumber =((int) ( ( tmax - t0) / step)) + 1; this.timeInterval = new double[this.stepNumber]; for (int i = 0; i < this.stepNumber; i++) { // Computing Time Points this.timeInterval[i] = t0 + i*step; } // Approximated Y Solution Interval Initialization this.yk = new double[this.stepNumber]; this.yk[0] = y0; // First y Point for (int i = 1; i < this.stepNumber; i++) { // Setting To Zero Yks this.yk[i] = 0; } if (exact == null) { this.exprExact = null; this.hasExact = false; } else { this.exprExact = exact; this.hasExact = true; } } /** * General Case (Without Exact Solution) * * @param func f(t, y(t)) * @param t0 Initial Time * @param y0 Initial Value y(t0) = y0 * @param step difference between each moment * @param tmax max time, end of calculation * @param t Independent Symbol t * @param y Dependent Symbol y(t) * @throws WrongInputException Null Input * @throws WrongCalculationException */ public DifferentialEquation (MathExpr func, double t0, double y0, double step, double tmax, MathTokenSymbol t, MathTokenSymbol y) throws WrongInputException, WrongCalculationException { this (null, func, t0, y0, step, tmax,t, y); } /** * String Symbols (With Exact Solution) * * @param exact Exact Solution * @param func f(t, y(t)) * @param t0 Initial Time * @param y0 Initial Value y(t0) = y0 * @param step difference between each moment * @param tmax max time, end of calculation * @param t Independent Symbol String t * @param y Dependent Symbol String y(t) * @throws WrongInputException Null Input * @throws WrongCalculationException */ public DifferentialEquation (MathExpr exact, MathExpr func, double t0, double y0, double step, double tmax, String t, String y) throws WrongInputException, WrongCalculationException { this (exact, func, t0, y0, step, tmax, new MathTokenSymbol (t), new MathTokenSymbol (y)); } /** * String Symbols (Without Exact Solution) * * @param func f(t, y(t)) * @param t0 Initial Time * @param y0 Initial Value y(t0) = y0 * @param step difference between each moment * @param tmax max time, end of calculation * @param t Independent Symbol String t * @param y Dependent Symbol String y(t) * @throws WrongInputException Null Input * @throws WrongCalculationException */ public DifferentialEquation (MathExpr func, double t0, double y0, double step, double tmax, String t, String y) throws WrongInputException, WrongCalculationException { this (null, func, t0, y0, step, tmax, new MathTokenSymbol (t), new MathTokenSymbol (y)); } /** * Default t0 = 0, step = 0.1, tmax = 1 (With Exact Solution) * * @param exact Exact Solution * @param func f(t, y(t)) * @param y0 Initial Value y(t0) = y0 * @param t Independent Symbol t * @param y Dependent Symbol y(t) * @throws WrongInputException Null Input * @throws WrongCalculationException */ public DifferentialEquation (MathExpr exact, MathExpr func, double y0, MathTokenSymbol t, MathTokenSymbol y) throws WrongInputException, WrongCalculationException { this (exact, func, 0, y0, 0.1, 1, t, y); } /** * String Symbols, Default t0 = 0, step = 0.1, tmax = 1 (Without Exact Solution) * * @param exact Exact Solution * @param func f(t, y(t)) * @param y0 Initial Value y(t0) = y0 * @param t Independent Symbol String t * @param y Dependent Symbol String y(t) * @throws WrongInputException Null Input * @throws WrongCalculationException */ public DifferentialEquation (MathExpr exact, MathExpr func, double y0, String t, String y) throws WrongInputException, WrongCalculationException { this (exact, func, 0, y0, 0.1, 1, new MathTokenSymbol (t), new MathTokenSymbol (y)); } /** * String Symbols, Default t0 = 0, step = 0.1, tmax = 1 (Without Exact Solution) * * @param func f(t, y(t)) * @param y0 Initial Value y(t0) = y0 * @param t Independent Symbol String t * @param y Dependent Symbol String y(t) * @throws WrongInputException Null Input * @throws WrongCalculationException */ public DifferentialEquation (MathExpr func, double y0, String t, String y) throws WrongInputException, WrongCalculationException { this (null, func, 0, y0, 0.1, 1, new MathTokenSymbol (t), new MathTokenSymbol (y)); } /** * @return the exprExact */ public MathExpr getExprExact() { return exprExact; } /** * @param exprExact the exprExact to set */ public void setExprExact(MathExpr exprExact) { this.exprExact = exprExact; } /** * @return the methodName */ public String getMethodName() { return methodName; } /** * @param methodName the methodName to set */ public void setMethodName(String methodName) { this.methodName = methodName; } /** * @return the methodType */ public String getMethodType() { return methodType; } /** * @param methodType the methodType to set */ public void setMethodType(String methodType) { this.methodType = methodType; } /** * @return the solved */ public boolean isSolved() { return solved; } /** * @param solved the solved to set */ public void setSolved(boolean solved) { this.solved = solved; } /** * @return the err */ public boolean isErr() { return err; } /** * @param err the err to set */ public void setErr(boolean err) { this.err = err; } /** * @return the hasExact */ public boolean isHasExact() { return hasExact; } /** * @param hasExact the hasExact to set */ public void setHasExact(boolean hasExact) { this.hasExact = hasExact; } /** * @return the errorsPerc */ public double[] getErrorsPerc() { return errorsPerc; } /** * @param errorsPerc the errorsPerc to set */ public void setErrorsPerc(double[] errorsPerc) { this.errorsPerc = errorsPerc; } /** * @return the errorPercAvg */ public double getErrorsPercAvg() { return errorsPercAvg; } /** * @param errorPercAvg the errorPercAvg to set */ public void setErrorsPercAvg(double errorPercAvg) { this.errorsPercAvg = errorPercAvg; } /** * @return the errorPercVar */ public double getErrorsPercVar() { return errorsPercVar; } /** * @param errorPercVar the errorPercVar to set */ public void setErrorsPercVar(double errorPercVar) { this.errorsPercVar = errorPercVar; } /** * @return the errorPercSd */ public double getErrorsPercSd() { return errorsPercSd; } /** * @param errorPercSd the errorPercSd to set */ public void setErrorsPercSd(double errorPercSd) { this.errorsPercSd = errorPercSd; } /** * @return the func */ public MathExpr getFunc() { return func; } /** * @return the t0 */ public double getT0() { return t0; } /** * @return the y0 */ public double getY0() { return y0; } /** * @return the step */ public double getStep() { return step; } /** * @return the tmax */ public double getTmax() { return tmax; } /** * @return the stepNumber */ public int getStepNumber() { return stepNumber; } /** * @return the timeInterval */ public double[] getTimeInterval() { return timeInterval; } /** * @return the t */ public MathTokenSymbol getT() { return t; } /** * @return the y */ public MathTokenSymbol getY() { return y; } /** * @return the yk */ public double[] getYk() { return yk; } /** * @param yk the yk to set */ public void setYk(double[] yk) { this.yk = yk; } /** * @return the tol */ public double getTol() { return tol; } /** * Compute The Errors Done By Solving Numerically The Differential Equation * * @param exactSolution * @throws WrongInputException * @throws WrongCalculationException * @throws WrongExpressionException */ public double[] errors (MathExpr exactSolution) throws WrongInputException, WrongCalculationException, WrongExpressionException { if (exactSolution == null) { throw new WrongInputException ("DifferentialEquation.errors()- Null ExactSolution"); } if (!this.isSolved()) { throw new WrongInputException ("DifferentialEquation.errors()- Differential Equation Has Not Been Solved Numerically"); } // Exact Solution double[] exactk = new double[this.getStepNumber()]; // Exact Y Solution Interval for (int i = 0; i < this.getStepNumber(); i++) { // Computing The Exact Solution Values exactk[i] = exactSolution.evalSymbolic(this.timeInterval[i]).getOperandDouble(); } // Errors Computation double[] errorsPerc = new double[this.getStepNumber()]; for (int i = 0; i < this.getStepNumber(); i++) { errorsPerc[i] = Math.abs((exactk[i] - this.yk[i])/exactk[i]) * 100; } this.setErrorsPerc(errorsPerc); // Errors Percentage Average this.setErrorsPercAvg (MathNum.Stat.avg ( this.getErrorsPerc() ) ); // Errors Percentage Variance this.setErrorsPercVar ( MathNum.Stat.var ( this.getErrorsPerc(), this.getErrorsPercAvg() ) ); // Errors Percentage Standard Deviation this.setErrorsPercSd ( MathNum.Stat.sd(this.getErrorsPercVar()) ); // Errors Flag Set To True this.setErr (true); return null; } /** * Clone The Differential Equation */ public DifferentialEquation clone () { // Instantiate New DifferentialEquation Object DifferentialEquation newDiff = null; try { // Instantiate New DifferentialEquation Object newDiff = new DifferentialEquation (this.exprExact, this.func, this.t0, this.y0, this.step, this.tmax, this.t, this.y); if (this.solved) { // Already Solved, Copy The Solution newDiff.setSolved(true); // Set Solved double[] newYk = new double[yk.length]; for (int i = 0; i < yk.length; i++) { newYk[i] = yk[i]; } newDiff.setYk(newYk); // Set Approximate Solution if (this.err) { // Already Computed The Errors newDiff.setErr(true); // Set Err newDiff.setErrorsPercAvg (this.errorsPercAvg); // Clone Average newDiff.setErrorsPercVar (this.errorsPercVar); // Clone Variance newDiff.setErrorsPercSd (this.errorsPercSd); // Clone Standard Deviation double[] newErrorsPerc = new double[this.stepNumber]; for (int i = 0; i < this.stepNumber; i++) { newErrorsPerc[i] = this.errorsPerc[i]; } newDiff.setYk(newErrorsPerc); } } } catch (WrongInputException | WrongCalculationException e) { e.printStackTrace(); } return newDiff; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "DifferentialEquation \nfunc=" + func + "\nexprExact=" + exprExact + "\nt0=" + t0 + "\ny0=" + y0 + "\nstep=" + step + "\ntmax=" + tmax + "\nstepNumber=" + stepNumber + "\nt=" + t + "\ny=" + y + "\ntol=" + tol + "\nmethodName=" + methodName + "\nmethodType=" + methodType + "\nsolved=" + solved + "\nerr=" + err + "\nhasExact=" + hasExact + "\nerrorsPercAvg=" + errorsPercAvg + "\nerrorsPercVar=" + errorsPercVar + "\nerrorsPercSd=" + errorsPercSd + "\n"; } }
package com.nantaaditya.parameterized.helper; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.restassured.RestAssured; import io.restassured.response.Response; import io.restassured.response.ValidatableResponse; import io.restassured.specification.RequestSpecification; import lombok.extern.slf4j.Slf4j; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.util.CollectionUtils; import org.springframework.util.ObjectUtils; import java.util.Map; import java.util.Optional; /** * created by pramuditya.anantanur **/ @Slf4j public abstract class BaseIntegrationTest { protected TestSpecification testSpecification; protected abstract void setUp() throws Exception; protected abstract void tearDown() throws Exception; @Autowired protected ObjectMapper objectMapper; public BaseIntegrationTest(TestSpecification testSpecification) { this.testSpecification = testSpecification; } @Before public void processSetUp() throws Exception { RestAssured.port = 18181; this.setUp(); } @Test public void test() throws Exception { if (!ObjectUtils.isEmpty(testSpecification.getBeforeTest())) { testSpecification.getBeforeTest().apply(); } this.doTestApi(testSpecification); if (!ObjectUtils.isEmpty(testSpecification.getAfterTest())) { testSpecification.getAfterTest().apply(); } } @After public void processTearDown() throws Exception { this.tearDown(); } public void doTestApi(TestSpecification testSpecification) throws Exception { RequestSpecification requestSpecification = constructApi(testSpecification.getRequest(), testSpecification.getHeaders(), testSpecification.getParams()); Response response = null; switch (testSpecification.getHttpMethod()) { case GET: response = requestSpecification.get(testSpecification.getPath()); break; case POST: response = requestSpecification.post(testSpecification.getPath()); break; case PUT: response = requestSpecification.put(testSpecification.getPath()); break; case DELETE: response = requestSpecification.delete(testSpecification.getPath()); break; } response.prettyPrint(); ValidatableResponse validatableResponse = response .then() .statusCode(testSpecification.getResultAssertion().getStatus().value()); if (!CollectionUtils.isEmpty(testSpecification.getResultAssertion().getResults())) { testSpecification.getResultAssertion().getResults().entrySet() .forEach(result -> { validatableResponse.body(result.getKey(), result.getValue()); }); } } protected RequestSpecification constructApi(Object request, Map<String, Object> headers, Map<String, Object> params) throws JsonProcessingException { RequestSpecification requestSpecification = RestAssured.given() .header("Accept", MediaType.APPLICATION_JSON_VALUE); if (!CollectionUtils.isEmpty(headers)) { headers.entrySet().forEach(header -> { requestSpecification.header(header.getKey(), header.getValue()); }); } if (request != null) { requestSpecification .header("Content-Type", MediaType.APPLICATION_JSON_VALUE) .body(objectMapper.writeValueAsString(request)); } if (!CollectionUtils.isEmpty(params)) { params.entrySet().forEach(param -> { requestSpecification.when().queryParam(param.getKey(), param.getValue()); }); } return requestSpecification; } private HttpStatus getHttpStatus(TestSpecification testSpecification) { return Optional.ofNullable(testSpecification) .map(spec -> spec.getResultAssertion()) .map(assertion -> assertion.getStatus()) .orElseGet(() -> HttpStatus.OK); } }
package com.rockwellcollins.atc.limp.reasoning; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.rockwellcollins.atc.limp.Expr; import com.rockwellcollins.atc.limp.LocalProcedure; import com.rockwellcollins.atc.limp.VariableRef; public class ProcedureEnvironmentList { private List<ProcedureEnvironment> pel; public ProcedureEnvironmentList() { pel = new ArrayList<>(); } public List<ProcedureEnvironment> getProcedureEnvironmentList() { return pel; } public boolean containsLocalProcedure(LocalProcedure lp) { //Output true if lp is in the list for (ProcedureEnvironment pe : this.getProcedureEnvironmentList()) { if (pe.getLocalProcedureName() == lp.getName()) { return true; } } // If lp isn't in the list, return fale. return false; } public Map<VariableRef,Expr> getProgramEnvironment(LocalProcedure lp) { //Output ProcedureEnvironment if lp is in the list for (ProcedureEnvironment pe : this.getProcedureEnvironmentList()) { if (pe.getLocalProcedureName() == lp.getName()) { return pe.pvsMap; } } // If lp isn't in the list, return null. return null; } public Expr getValueOfVariable(LocalProcedure lp, VariableRef variable) { if (containsLocalProcedure(lp)) { Map<VariableRef,Expr> pvsMap = getProgramEnvironment(lp); return pvsMap.get(variable); } else { return null; } } //Check to see if a ProcedureEnvironment exists with the same lp name. If so, add to that one. Otherwise, create a new one. public void updateProcedureVariableState (LocalProcedure lp, VariableRef variable, Expr value) { if (containsLocalProcedure(lp)) { Map<VariableRef,Expr> pvsMap = getProgramEnvironment(lp); pvsMap.put(variable, value); } else { ProcedureEnvironment penew = new ProcedureEnvironment(lp); penew.pvsMap.put(variable, value); pel.add(penew); } } }
package testeUnidade; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.Serializable; import org.junit.Before; import org.junit.Test; import hotel.Estadia; public class EstadiaTest implements Serializable { private static final long serialVersionUID = 1L; private Estadia estadia1; private Estadia estadia2; private Estadia estadia3; private Estadia estadia4; @Before public void setUp() { try { estadia1 = new Estadia("A1", 2); estadia2 = new Estadia("2B", 5); estadia3 = new Estadia("3C", 7); estadia4 = new Estadia("4D", 9); } catch (Exception e) { } } @Test public void testEstadia() { // testando string IDQuarto vazio ou null try { estadia1 = new Estadia(" ", 2); fail("Lancamento de exception com ID do quarto invalido"); } catch (Exception msg) { assertEquals("ID do quarto nao pode ser nulo ou vazio.", msg.getMessage()); } try { estadia2 = new Estadia(null, 5); fail("Lancamento de exception com ID do quarto invalido"); } catch (Exception msg) { assertEquals("ID do quarto nao pode ser nulo ou vazio.", msg.getMessage()); } // testando int quantDias menor ou igual a zero try { estadia3 = new Estadia("3C", -7); fail("Lancamento de exception com quantidade de dias invalido"); } catch (Exception msg) { assertEquals("quantidade de dias nao pode ser menor ou igual a zero.", msg.getMessage()); } try { estadia4 = new Estadia("4D", 0); fail("Lancamento de exception com quantidade de dias invalido"); } catch (Exception msg) { assertEquals("quantidade de dias nao pode ser menor ou igual a zero.", msg.getMessage()); } } @Test public void testGets() { try { Estadia estadia5 = new Estadia("5E", 11); Estadia estadia6 = new Estadia("6F", 13); assertEquals("5E", estadia5.getIDQuarto()); assertEquals("6F", estadia6.getIDQuarto()); assertEquals(11, estadia5.getQuantDias()); assertEquals(13, estadia6.getQuantDias()); } catch (Exception e) { } } }
package br.com.tobyte.basic; import java.io.IOException; import java.util.List; /** * * @author Thiago */ public interface ReadFromByteArray { public abstract List<String> formatToList(byte[] bytes) throws IOException; }
package com.example.coordinatorlayoutdemo; import android.content.Context; import android.media.Image; import android.provider.Settings; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.v7.widget.Toolbar; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.Log; import android.view.Display; import android.view.View; import android.view.WindowManager; import android.widget.ImageView; /** * Created by 王春雪 on 2017/6/20. */ public class MyBehavior extends CoordinatorLayout.Behavior<FloatingActionButton> { private Context mContext; //这里的泛型是观察者 FloatingActionButton public MyBehavior(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; } @Override public boolean layoutDependsOn(CoordinatorLayout parent, FloatingActionButton child, View dependency) { //dependency是被观察者 return dependency instanceof AppBarLayout; } @Override public boolean onDependentViewChanged(CoordinatorLayout parent, FloatingActionButton child, View dependency) { if (dependency instanceof AppBarLayout) { int toolBarHeight = parent.findViewById(R.id.toolbar).getHeight(); ImageView imageView = (ImageView) parent.findViewById(R.id.imgview); //floatingActionButton的位移比上APPBarLayout的位移, // 这里floatingActionButton是相对于AppBarlayout的相对位移,为toolBar高度的1/2, // appBarLayout的位移为appbarLayout的高度减去toolbar的高度 float ratio = toolBarHeight / 2 / ((float) (dependency.getHeight() - toolBarHeight)); int height = (int) ((int) dependency.getY() * ratio); child.setTranslationY(height); //这里floatingActionBar在X轴上的位移为屏幕宽度减去floatingActionBar宽度的一半 //根据APPbarLayout在Y轴上的位移计算floatingActionButton在X轴上的位移变化 float width = getDisplayWidth(mContext); float radioW = (width - child.getWidth()) / 2 / (dependency.getHeight() - toolBarHeight); int tWidth = (int) (dependency.getY() * radioW) * (-1); child.setTranslationX(tWidth); //floatingActionButton的透明度变化 child.setAlpha((1+(dependency.getY() / (dependency.getHeight() - toolBarHeight)))); //imageview的变化 imageView.setAlpha((-1)*dependency.getY() / (dependency.getHeight() - toolBarHeight)); } return true; } public int getDisplayWidth(Context context) { Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); return metrics.widthPixels; } }
/* * Purpose:-Write a program to read in Stock Names, Number of Share, Share Price. * Print a Stock Report with total value of each Stock and the total value of Stock. * * @Author:-Arpana Kumari * Version:-1.0 * @Since:-11 May, 2018 */ import java.io.FileNotFoundException; import java.io.FileReader; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import com.bridgeit.utility.Utility; public class StockReport { public static void main(String[] args) { String companyName; long numberOfShares; long sharePrice; long price; long TOTAL = 0; JSONParser parser = new JSONParser(); System.out.println(" **********STOCK REPORT********** "); System.out.println(); System.out.println("Company Name" + "----------" + "Number of shares" + "-----------" + "Share Price"); try { JSONArray jsonarray = (JSONArray) parser.parse(new FileReader("stock.json")); for (Object object : jsonarray) { JSONObject jsonObject = (JSONObject) object; companyName = (String) jsonObject.get("Company Name"); System.out.print(companyName + "--------------------"); numberOfShares = (long) jsonObject.get("Number Of Shares"); System.out.print(numberOfShares + "-----------------------"); sharePrice = (long) jsonObject.get("Share Price"); System.out.println(sharePrice); price = numberOfShares * sharePrice; System.out.print("Price per share =: " + price); System.out.println(); TOTAL = TOTAL + price; System.out.println(); } System.out.println(); System.out.println("TOTAL Share Price Of Company = " + TOTAL); } catch (Exception e) { e.printStackTrace(); } } }
package com.practice; import java.sql.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; public class pracproj { static void map() { HashMap<String, Object> hs = new LinkedHashMap<String, Object>(); hs.put("Abc", "AD01"); System.out.println(((String) hs.get("Abc")).toLowerCase()); } public static boolean usernameVal(String pass) { Pattern pattern = Pattern.compile("[a-zA-Z0-9]{5,}"); Matcher matcher = pattern.matcher(pass); Boolean boolean1 = matcher.matches(); return boolean1; } public static boolean passValid(String pass) { Pattern pattern = Pattern.compile("((?=.*[a-z])(?=.*\\d)(?=.*[A-Z])(?=.*[@#$%!]).{6,20})"); Matcher matcher = pattern.matcher(pass); Boolean boolean1 = matcher.matches(); return boolean1; } public static boolean dateValid(String date) { return Pattern.matches("^[0-3]?[0-9]/[0-3]?[0-9]/(?:[0-9]{2})?[0-9]{2}$", date); } public static boolean mailValid(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,})$"); Matcher matcher = pattern.matcher(email); Boolean boolean2 = matcher.matches(); return boolean2; } public static void Date() { String date1 = "11/12/1996"; String date2 = "15/11/2020"; String[] date1arr = date1.split("/"); for (int i = 0; i < date1arr.length; i++) { System.out.println(date1arr[i]); } int date1int = Integer.parseInt(date1arr[2]); System.out.println(date1int); } public static void main(String[] args) { map(); // System.out.println(usernameVal("Mayanksi191")); // System.out.println(usernameVal("aA9_asdasdas")); // System.out.println(usernameVal("+*,aABCDasdasd9")); // System.out.println("------------------------"); System.out.println(passValid("mayanksi191@gmail.com")); System.out.println(passValid("qwerty@123")); // System.out.println(dateValid("12/05/1996")); // System.out.println(dateValid("30/03/2060")); // System.out.println(dateValid("31/02/2020")); // System.out.println(dateValid("13/04/2020")); } }
package com.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Mapper; import com.entity.Video; @Mapper public interface VideoDao { /** * 添加视频信息 * * @param video * @return */ public Integer addVideo(Video video); // 添加视频详情 public void add(Video v); // 修改视频详情 public void upd(Video v); // 删除视频详情 public void del(Integer v_id); // 查询视频详情 public List<Video> queryById(Integer v_id); // 查询所有视频信息 public List<Video> queryAll(); // 分页查询所有视频信息 public List<Video> queryByPage(Integer page, Integer limit); // 跟据课程查询所有视频信息 public List<Video> queryVideoByC_id(Integer c_id); // 根据课程查询所有的视频信息 public List<Map<String,Object>> queryByVideo(Integer c_id); }
package ls.example.t.zero2line.base; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.support.annotation.IdRes; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import ls.example.t.zero2line.util.*; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2017/03/28 * desc : base about v4-fragment * </pre> */ public abstract class BaseFragment extends android.support.v4.app.Fragment implements IBaseView { private static final String TAG = "BaseFragment"; private static final String STATE_SAVE_IS_HIDDEN = "STATE_SAVE_IS_HIDDEN"; private android.view.View.OnClickListener mClickListener = new android.view.View.OnClickListener() { @Override public void onClick(android.view.View v) { onDebouncingClick(v); } }; protected android.app.Activity mActivity; protected android.view.LayoutInflater mInflater; protected android.view.View mContentView; @Override public void onAttach(android.content.Context context) { super.onAttach(context); mActivity = (android.app.Activity) context; } @Override public void onCreate(@android.support.annotation.Nullable android.os.Bundle savedInstanceState) { android.util.Log.d(TAG, "onCreate: "); super.onCreate(savedInstanceState); if (savedInstanceState != null) { boolean isSupportHidden = savedInstanceState.getBoolean(STATE_SAVE_IS_HIDDEN); android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction(); if (isSupportHidden) { ft.hide(this); } else { ft.show(this); } ft.commitAllowingStateLoss(); } } @android.support.annotation.Nullable @Override public android.view.View onCreateView(@android.support.annotation.NonNull android.view.LayoutInflater inflater, @android.support.annotation.Nullable android.view.ViewGroup container, @android.support.annotation.Nullable android.os.Bundle savedInstanceState) { android.util.Log.d(TAG, "onCreateView: "); mInflater = inflater; setRootLayout(bindLayout()); return mContentView; } @android.annotation.SuppressLint("ResourceType") @Override public void setRootLayout(@android.support.annotation.LayoutRes int layoutId) { if (layoutId <= 0) return; mContentView = mInflater.inflate(layoutId, null); } @Override public void onViewCreated(@android.support.annotation.NonNull android.view.View view, @android.support.annotation.Nullable android.os.Bundle savedInstanceState) { android.util.Log.d(TAG, "onViewCreated: "); super.onViewCreated(view, savedInstanceState); android.os.Bundle bundle = getArguments(); initData(bundle); } @Override public void onActivityCreated(@android.support.annotation.Nullable android.os.Bundle savedInstanceState) { android.util.Log.d(TAG, "onActivityCreated: "); super.onActivityCreated(savedInstanceState); initView(savedInstanceState, mContentView); doBusiness(); } @Override public void onDestroyView() { android.util.Log.d(TAG, "onDestroyView: "); if (mContentView != null) { ((android.view.ViewGroup) mContentView.getParent()).removeView(mContentView); } super.onDestroyView(); } @Override public void onSaveInstanceState(@android.support.annotation.NonNull android.os.Bundle outState) { android.util.Log.d(TAG, "onSaveInstanceState: "); super.onSaveInstanceState(outState); outState.putBoolean(STATE_SAVE_IS_HIDDEN, isHidden()); } @Override public void onDestroy() { android.util.Log.d(TAG, "onDestroy: "); super.onDestroy(); } public void applyDebouncingClickListener(android.view.View... views) { ClickUtils.applyGlobalDebouncing(views, mClickListener); } public <T extends android.view.View> T findViewById(@android.support.annotation.IdRes int id) { if (mContentView == null) throw new NullPointerException("ContentView is null."); return mContentView.findViewById(id); } }
package com.zte.ffa.controller; /** * @author: ShuaiLing * @date: 2019年8月22日 */ public class Test1 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("xnwenj"); System.out.println("xndfsdfsdfds"); System.out.println("qqqq"); System.out.println("gggg"); System.out.println("ggggnnnnnn"); System.out.println("eeee"); System.out.println("eeee"); System.out.println("eeee"); System.out.println("eeee"); System.out.println("eeee"); } }