text
stringlengths
10
2.72M
package com.test.shortest; import java.util.List; class HeapUtils { /** * .从下至上,堆化 * .默认堆化到第一个 * @param dataList 数组 * @param lastIndex 不满足堆化的index[开始的index] * @param isMinTop true(小顶堆),false(大顶堆) */ static <T extends Comparable<T>> void heapifyUp(List<T> dataList, int lastIndex, boolean isMinTop) { while (lastIndex > 1) { int preIndex = lastIndex / 2; boolean childCompare = compare(dataList, preIndex, lastIndex, isMinTop); if (childCompare) // 插入不满足要求 { swap(dataList, preIndex, lastIndex); lastIndex = preIndex; } else { break; } } } /** * .从上至下,堆化 * @param dataList 数组 * @param pre 不满足堆化的index[开始的index] * @param maxIndex 堆化的结束节点 * @param isMinTop true(小顶堆),false(大顶堆) */ static <T extends Comparable<T>> void heapifyDown(List<T> dataList, int pre, int last, boolean isMinTop) { int preIndex = pre; int maxIndex = last / 2; // 最大非叶子点,index boolean isOdd = (last & 0x01) == 0; // 长度,是否是奇数 while (preIndex <= maxIndex) // 非叶子节点 { if (isOdd && preIndex == maxIndex) // 一个叶子节点 { boolean childCompare = compare(dataList, preIndex, preIndex * 2, isMinTop); if (childCompare) { swap(dataList, preIndex, preIndex * 2); preIndex *= 2; } else { break; } } else // 两个叶子节点 { boolean leftCompare = compare(dataList, preIndex, preIndex * 2, isMinTop); boolean rightCompare = compare(dataList, preIndex, preIndex * 2 + 1, isMinTop); if (leftCompare || rightCompare) { boolean childCompare = compare(dataList, preIndex * 2, preIndex * 2 + 1, isMinTop); int nextIndex = !childCompare ? preIndex * 2 : preIndex * 2 + 1; swap(dataList, preIndex, nextIndex); preIndex = nextIndex; } else { break; } } } } private static <T extends Comparable<T>> boolean compare(List<T> dataList, int pre, int last, boolean isMinTop) { T preValue = dataList.get(pre); T lastValue = dataList.get(last); if (isMinTop) { return preValue.compareTo(lastValue) > 0; } else { return preValue.compareTo(lastValue) < 0; } } private static <T> void swap(List<T> dataList, int pre, int last) { if (pre != last) { T temp = dataList.get(pre); dataList.set(pre, dataList.get(last)); dataList.set(last, temp); } } }
public class Blob extends File { private String m_Content; /*stam comment*\ @Override public String MakeSH1() { return GetSH1FromContent(m_Content); } }
package pl.morecraft.dev.datagrammer.commands; import pl.morecraft.dev.datagrammer.engine.Command; import pl.morecraft.dev.datagrammer.misc.Consoler; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Objects; public class Init extends Command { @SuppressWarnings("Duplicates") @Override public void setup() { addAlias("init", false); addAlias("i", false); setArgsCount(2); setArgsInfo("[host] [port]"); setShortInfo("Bounds socket to [host]:[port]"); mustBeBound(false); mustBeConnected(false); mustBeNotClosed(false); mustBeNotNull(false); } @Override public DatagramSocket execute(DatagramSocket socket, Consoler out) throws UnknownHostException, SocketException { String[] s = getArgs(); s[0] = Objects.equals(s[0], "l") ? "localhost" : s[0]; socket = new DatagramSocket(Integer.parseInt(s[1]), InetAddress.getByName(s[0])); out.println("Bound to " + s[0] + ":" + s[1]); return socket; } }
//good job! //using a complete sum minus a real sum is the missing number public class Solution { public int missingNumber(int[] nums) { int sum = ((nums.length + 1) * nums.length) >> 1; int realSum = 0; for (int i = 0; i < nums.length; i++) { realSum += nums[i]; } // System.out.println(sum + " " + realSum); return sum - realSum; } }
package edu.ncsu.csc.itrust2.apitest; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import edu.ncsu.csc.itrust2.config.RootConfiguration; import edu.ncsu.csc.itrust2.forms.admin.UserForm; import edu.ncsu.csc.itrust2.forms.hcp.OfficeVisitForm; import edu.ncsu.csc.itrust2.forms.patient.AppointmentRequestForm; import edu.ncsu.csc.itrust2.models.enums.AppointmentType; import edu.ncsu.csc.itrust2.models.enums.Role; import edu.ncsu.csc.itrust2.models.enums.Status; import edu.ncsu.csc.itrust2.models.persistent.Hospital; import edu.ncsu.csc.itrust2.models.persistent.OfficeVisit; import edu.ncsu.csc.itrust2.models.persistent.Patient; import edu.ncsu.csc.itrust2.mvc.config.WebMvcConfiguration; /** * Test for the API functionality for interacting with office visits * * @author Kai Presler-Marshall * */ @RunWith ( SpringJUnit4ClassRunner.class ) @ContextConfiguration ( classes = { RootConfiguration.class, WebMvcConfiguration.class } ) @WebAppConfiguration public class APIOfficeVisitTest { private MockMvc mvc; @Autowired private WebApplicationContext context; /** * Sets up test */ @Before public void setup () { mvc = MockMvcBuilders.webAppContextSetup( context ).build(); final Patient p = Patient.getPatient( "patient" ); if ( p != null ) { p.delete(); } } /** * Tests getting a non existent office visit and ensures that the correct * status is returned. * * @throws Exception */ @Test public void testGetNonExistentOfficeVisit () throws Exception { mvc.perform( get( "/api/v1/officevisits/-1" ) ).andExpect( status().isNotFound() ); } /** * Tests deleting a non existent office visit and ensures that the correct * status is returned. * * @throws Exception */ @Test public void testDeleteNonExistentOfficeVisit () throws Exception { mvc.perform( delete( "/api/v1/officevisits/-1" ) ).andExpect( status().isNotFound() ); } /** * Tests handling of errors when creating a visit for a pre-scheduled * appointment. * * @throws Exception */ @Test public void testPreScheduledOfficeVisit () throws Exception { final UserForm hcp = new UserForm( "hcp", "123456", Role.ROLE_HCP, 1 ); mvc.perform( post( "/api/v1/users" ).contentType( MediaType.APPLICATION_JSON ) .content( TestUtils.asJsonString( hcp ) ) ); final UserForm patient = new UserForm( "patient", "123456", Role.ROLE_PATIENT, 1 ); mvc.perform( post( "/api/v1/users" ).contentType( MediaType.APPLICATION_JSON ) .content( TestUtils.asJsonString( patient ) ) ); mvc.perform( delete( "/api/v1/appointmentrequests" ) ); final AppointmentRequestForm appointmentForm = new AppointmentRequestForm(); appointmentForm.setDate( "11/19/2030" ); appointmentForm.setTime( "4:50 AM" ); appointmentForm.setType( AppointmentType.GENERAL_CHECKUP.toString() ); appointmentForm.setStatus( Status.APPROVED.toString() ); appointmentForm.setHcp( "hcp" ); appointmentForm.setPatient( "patient" ); appointmentForm.setComments( "Test appointment please ignore" ); mvc.perform( post( "/api/v1/appointmentrequests" ).contentType( MediaType.APPLICATION_JSON ) .content( TestUtils.asJsonString( appointmentForm ) ) ).andExpect( status().isOk() ); mvc.perform( delete( "/api/v1/officevisits" ) ); final OfficeVisitForm visit = new OfficeVisitForm(); visit.setPreScheduled( "yes" ); visit.setDate( "11/19/2030" ); visit.setTime( "4:50 AM" ); visit.setHcp( "hcp" ); visit.setPatient( "patient" ); visit.setNotes( "Test office visit" ); visit.setType( AppointmentType.GENERAL_CHECKUP.toString() ); visit.setHospital( "iTrust Test Hospital 2" ); mvc.perform( post( "/api/v1/officevisits" ).contentType( MediaType.APPLICATION_JSON ) .content( TestUtils.asJsonString( visit ) ) ).andExpect( status().isOk() ); mvc.perform( get( "/api/v1/officevisits" ) ).andExpect( status().isOk() ) .andExpect( content().contentType( MediaType.APPLICATION_JSON_UTF8_VALUE ) ); mvc.perform( delete( "/api/v1/officevisits" ) ); visit.setDate( "12/20/2031" ); // setting a pre-scheduled appointment that doesn't match should not // work. mvc.perform( post( "/api/v1/officevisits" ).contentType( MediaType.APPLICATION_JSON ) .content( TestUtils.asJsonString( visit ) ) ).andExpect( status().isBadRequest() ); } /** * Tests OfficeVisitAPI * * @throws Exception */ @Test public void testOfficeVisitAPI () throws Exception { /* * Create a HCP and a Patient to use. If they already exist, this will * do nothing */ final UserForm hcp = new UserForm( "hcp", "123456", Role.ROLE_HCP, 1 ); mvc.perform( post( "/api/v1/users" ).contentType( MediaType.APPLICATION_JSON ) .content( TestUtils.asJsonString( hcp ) ) ); final UserForm patient = new UserForm( "patient", "123456", Role.ROLE_PATIENT, 1 ); mvc.perform( post( "/api/v1/users" ).contentType( MediaType.APPLICATION_JSON ) .content( TestUtils.asJsonString( patient ) ) ); /* Create a Hospital to use too */ final Hospital hospital = new Hospital( "iTrust Test Hospital 2", "1 iTrust Test Street", "27607", "NC" ); mvc.perform( post( "/api/v1/hospitals" ).contentType( MediaType.APPLICATION_JSON ) .content( TestUtils.asJsonString( hospital ) ) ); mvc.perform( delete( "/api/v1/officevisits" ) ); final OfficeVisitForm visit = new OfficeVisitForm(); visit.setDate( "4/16/2048" ); visit.setTime( "9:50 AM" ); visit.setHcp( "hcp" ); visit.setPatient( "patient" ); visit.setNotes( "Test office visit" ); visit.setType( AppointmentType.GENERAL_CHECKUP.toString() ); visit.setHospital( "iTrust Test Hospital 2" ); /* Create the Office Visit */ mvc.perform( post( "/api/v1/officevisits" ).contentType( MediaType.APPLICATION_JSON ) .content( TestUtils.asJsonString( visit ) ) ).andExpect( status().isOk() ); mvc.perform( get( "/api/v1/officevisits" ) ).andExpect( status().isOk() ) .andExpect( content().contentType( MediaType.APPLICATION_JSON_UTF8_VALUE ) ); /* * We need the ID of the office visit that actually got _saved_ when * calling the API above. This will get it */ final Long id = OfficeVisit.getForPatient( patient.getUsername() ).get( 0 ).getId(); visit.setId( id.toString() ); // Second post should fail with a conflict since it already exists mvc.perform( post( "/api/v1/officevisits" ).contentType( MediaType.APPLICATION_JSON ) .content( TestUtils.asJsonString( visit ) ) ).andExpect( status().isConflict() ); mvc.perform( get( "/api/v1/officevisits/" + id ) ).andExpect( status().isOk() ) .andExpect( content().contentType( MediaType.APPLICATION_JSON_UTF8_VALUE ) ); visit.setTime( "9:45 AM" ); mvc.perform( put( "/api/v1/officevisits/" + id ).contentType( MediaType.APPLICATION_JSON ) .content( TestUtils.asJsonString( visit ) ) ).andExpect( status().isOk() ) .andExpect( content().contentType( MediaType.APPLICATION_JSON_UTF8_VALUE ) ); // PUT with the non-matching IDs should fail mvc.perform( put( "/api/v1/officevisits/" + 1 ).contentType( MediaType.APPLICATION_JSON ) .content( TestUtils.asJsonString( visit ) ) ).andExpect( status().isConflict() ); // PUT with ID not in database should fail final long tempId = 101; visit.setId( "101" ); mvc.perform( put( "/api/v1/officevisits/" + tempId ).contentType( MediaType.APPLICATION_JSON ) .content( TestUtils.asJsonString( visit ) ) ).andExpect( status().isNotFound() ); // Reset ID to old id visit.setId( id.toString() ); mvc.perform( delete( "/api/v1/officevisits/" + id ) ).andExpect( status().isOk() ); mvc.perform( delete( "/api/v1/officevisits" ) ); } }
package javaBasics; public class arrayConcept { public static void main(String[] arg) { // Array: to store similar data type values in a Array // int Array // Size is Fixed - Static Array - To over come this - we use Collections - ArrayList, HashTable, Dynamic Array int i[] = new int[4]; // Static Array i[0] = 10; i[1] = 20; i[2] = 30; i[3] = 40; System.out.println(i[2]); System.out.println(i[3]); System.out.println(i.length); // Size of Array // print All values of Array; use FOR loop for(int j=0;j<i.length;j++) { System.out.println(i[j]); } // 2. Double Array double d[] = new double[3]; d[0] = 12.33; d[1] = 13.44; d[2] = 44.55; System.out.println(d[2]); //3. Char Array char c[] = new char[3]; c[0]= 'a'; c[1]='2'; c[2]='S'; System.out.println(c[2]); //4. Boolean Array boolean b[] = new boolean[2]; b[0]= true; b[1]= false; //5. String Array String s[] = new String[3]; s[0] = "test"; s[1] = "Hello"; s[2] = "World"; System.out.println(s[1]); //6. Object Array ( To store different Data types ) Object ob[] = new Object[6]; ob[0] = "Tom"; ob[1] = 25; ob[2] = 12.33; ob[3] = "1/2/2000"; ob[4] = "M"; ob[5] = "London"; System.out.println(ob[5]); } }
//Author: Ayrton Pereira //Date: 22/04/2020 //Objective: Use aritmetric operation package cap5aritmetric; public class Aritmetric_class { public static void main(String[] args) { int a = 20, b = 30, c = 2, d = 6; float z = 30.9f, y = 5.5f, x = 6.6f; System.out.println("--- Values ---"); System.out.println("a = " + a + "b = " + b + "c = " + c + "d = " + d); System.out.println(" "); System.out.println("z = " + z + "y = " + y + "x = " + x); System.out.println("a + z = " + (a + z)); System.out.println("x - b = " + (x - z)); System.out.println("d * y = " + (d * y)); System.out.println("c / d = " + (c / d)); System.out.println("d % a = " + (d % a)); System.out.println("Mix operation 1 = " + ((a + z) + (d * x) - 15)); System.out.println("Mix operation 2 = " + ((c % a) * 2)); } }
package com.baway.fuzhiyan.fuzhiyan20170728; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ListView; import android.widget.Toast; import com.google.gson.Gson; import org.xutils.common.Callback; import org.xutils.http.RequestParams; import org.xutils.x; import java.util.ArrayList; import java.util.List; /* * author:付智焱 * time:2017-7-28 14:38:35 * * 类用途:加载主页面的布局。。显示数据 * * */ public class MainActivity extends AppCompatActivity { private ListView recyclerView; private ListAdapter myAdapter; private List<UserBean.DataBean> list = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = (ListView) findViewById(R.id.recyclerView); initData(); } private void initData() { RequestParams params=new RequestParams("http://www.yulin520.com/a2a/impressApi/news/mergeList?sign=C7548DE604BCB8A17592EFB9006F9265&pageSize=20&gender=2&ts=1871746850&page=1"); x.http().get(params, new Callback.CommonCallback<String>() { @Override public void onSuccess(String result) { Gson gson=new Gson(); UserBean bean= gson.fromJson(result,UserBean.class); list=bean.getData(); myAdapter = new ListAdapter(MainActivity.this, list); recyclerView.setAdapter(myAdapter); } @Override public void onError(Throwable ex, boolean isOnCallback) { } @Override public void onCancelled(CancelledException cex) { } @Override public void onFinished() { } }); } // }
import java.util.ArrayList; import java.util.Arrays; import java.util.Deque; /* * @lc app=leetcode.cn id=113 lang=java * * [113] 路径总和 II */ import java.util.List; // @lc code=start /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>>result = new ArrayList<>(); Deque<Integer> path = new ArrayDeque<>(); pathSum(root, sum, path, result); return result; } private void pathSum(TreeNode root, int sum, Deque<Integer> path, List<List<Integer>>result){ if(root == null){ return; } path.addLast(root.val); int currentSum = sum - root.val; if(root.left == null && root.right==null && currentSum==0){ //叶子节点 result.add(new ArrayList<>(path)); path.removeLast(); return; } pathSum(root.left, currentSum, path, result); pathSum(root.right, currentSum, path, result); path.removeLast(); } } // @lc code=end
import fenestra.Palette; import javax.swing.*; import java.awt.*; /** * zamma on 3/31/18. */ public class MessageBox extends JPanel { public MessageBox(String nickName, String date, String message, boolean isItself) { JPanel jpnlNickDate = new JPanel(new BorderLayout()); JLabel jlblNick = new JLabel(nickName); jpnlNickDate.add(jlblNick, BorderLayout.LINE_START); JLabel jlblDate = new JLabel(date); jpnlNickDate.add(jlblDate, BorderLayout.LINE_END); JPanel jpnlMessage = new JPanel(); JLabel jlblMessage = new JLabel(message); jpnlMessage.add(jlblMessage); if (!isItself) { jpnlNickDate.setBackground(Palette.middleYellowRed); } else { jpnlNickDate.setBackground(Palette.aztecGold); setBackground(Palette.cameoPink); jpnlMessage.setBackground(Palette.cameoPink); } setLayout(new BorderLayout()); add(jpnlNickDate, BorderLayout.PAGE_START); if (isItself) add(jpnlMessage, BorderLayout.LINE_START); else add(jpnlMessage, BorderLayout.LINE_END); setBorder(BorderFactory.createLineBorder(Palette.mistyRose, 5)); setMaximumSize(new Dimension(Main.m.getSessionHistoryPane().getWidth(), getPreferredSize().height)); } }
/* Ara - capture species and specimen data * * Copyright (C) 2009 INBio (Instituto Nacional de Biodiversidad) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.inbio.ara.dto.germplasm; import org.inbio.ara.dto.BaseEntityOrDTOFactory; import org.inbio.ara.persistence.germplasm.AccessionMovement; import org.inbio.ara.persistence.germplasm.AccessionMovementPK; /** * * @author dasolano */ public class AccessionMovementDTOFactory extends BaseEntityOrDTOFactory<AccessionMovement ,AccessionMovementDTO> { @Override public AccessionMovement getEntityWithPlainValues(AccessionMovementDTO dto) { AccessionMovement accessionMovement = new AccessionMovement(); AccessionMovementPK accessionMovementPK = new AccessionMovementPK(dto.getAccessionId(), dto.getAccessionMovementDate()); accessionMovement.setAccessionMovementPK(accessionMovementPK); accessionMovement.setAccessionMovementTypeId(dto.getAccessionMovementTypeId()); accessionMovement.setNotes(dto.getNotes()); accessionMovement.setResponsablePersonId(dto.getResponsablePersonId()); accessionMovement.setWeight(dto.getWeight()); return accessionMovement; } @Override public AccessionMovement updateEntityWithPlainValues(AccessionMovementDTO dto, AccessionMovement e) { e.setAccessionMovementTypeId(dto.getAccessionMovementTypeId()); e.setNotes(dto.getNotes()); e.setResponsablePersonId(dto.getResponsablePersonId()); e.setWeight(dto.getWeight()); return e; } public AccessionMovementDTO createDTO(AccessionMovement entity) { AccessionMovementDTO dto = new AccessionMovementDTO(); dto.setAccessionId(entity.getAccessionMovementPK().getAccessionId()); dto.setAccessionMovementDate(entity.getAccessionMovementPK().getAccessionMovementDate()); dto.setAccessionMovementTypeId(entity.getAccessionMovementTypeId()); dto.setNotes(entity.getNotes()); dto.setResponsablePersonId(entity.getResponsablePersonId()); dto.setWeight(entity.getWeight()); return dto; } }
package heylichen.divideconquer; import org.junit.Test; public class LinearMaxSubarrayTest { @Test public void name() { LinearMaxSubarray maxSubarray = new LinearMaxSubarray(createDailyPrices()); MaxSubarraySolution solution = maxSubarray.calculate(); System.out.println(solution); } private int[] createDailyPrices() { return new int[]{100, 113, 110, 85, 105, 102, 86, 63, 81, 101, 94, 106, 101, 79, 94, 90, 97}; } }
/* * Copyright 2019 The Android Open Source Project * * 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. */ import java.lang.reflect.Field; import java.lang.reflect.Constructor; import java.lang.reflect.Method; class Main { public static void main(String[] args) { System.loadLibrary(args[0]); System.out.println("App image loaded " + checkAppImageLoaded()); int regionSize = getRegionSize(); int objectsSectionSize = checkAppImageSectionSize(Main.class); System.out.println("Region size " + regionSize); System.out.println("App image section size large enough " + (objectsSectionSize > regionSize)); if (objectsSectionSize <= regionSize) { System.out.println("Section size " + objectsSectionSize); } } public static native boolean checkAppImageLoaded(); public static native int getRegionSize(); public static native int checkAppImageSectionSize(Class c); }
/** * Copyright 2009 The European Bioinformatics Institute, and others. * * 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 uk.ac.ebi.intact.view.webapp.model; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.common.params.FacetParams; import org.hupo.psi.mi.psicquic.model.PsicquicSolrException; import org.primefaces.model.LazyDataModel; import org.primefaces.model.SortOrder; import psidev.psi.mi.tab.PsimiTabException; import psidev.psi.mi.tab.model.Alias; import psidev.psi.mi.tab.model.BinaryInteraction; import psidev.psi.mi.tab.model.CrossReference; import psidev.psi.mi.tab.model.Interactor; import uk.ac.ebi.intact.dataexchange.psimi.solr.FieldNames; import uk.ac.ebi.intact.dataexchange.psimi.solr.IntactSolrSearchResult; import uk.ac.ebi.intact.dataexchange.psimi.solr.IntactSolrSearcher; import uk.ac.ebi.intact.view.webapp.util.MitabFunctions; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.*; /** * TODO comment that class header * * @author Bruno Aranda (baranda@ebi.ac.uk) * @version $Id$ */ public class LazySearchResultDataModel extends LazyDataModel<BinaryInteraction> { private static final Log log = LogFactory.getLog(LazySearchResultDataModel.class); private SolrQuery solrQuery; private IntactSolrSearcher solrSearcher; private IntactSolrSearchResult result; private List<BinaryInteraction> binaryInteractions; private int numberOfBinaryInteractionsToShow; public LazySearchResultDataModel(SolrServer solrServer, SolrQuery solrQuery) throws SolrServerException, PsicquicSolrException { this.solrSearcher = new IntactSolrSearcher(solrServer); this.solrQuery = solrQuery != null ? solrQuery.getCopy() : null; prepareNegativeSolrQuery(); } @Override public List<BinaryInteraction> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) { if (solrQuery == null) { // add a error message FacesContext context = FacesContext.getCurrentInstance(); if (context != null){ FacesMessage facesMessage = new FacesMessage( FacesMessage.SEVERITY_ERROR, "Query is empty", "Cannot fetch any results because query is empty. Please enter a query." ); context.addMessage( null, facesMessage ); } return Collections.EMPTY_LIST; } else { this.binaryInteractions = null; prepareSolrQuery(first, pageSize, sortField, sortOrder); List<BinaryInteraction> interactions = new ArrayList<BinaryInteraction>(pageSize); if (result != null) { try { for (BinaryInteraction<Interactor> ibi : result.getBinaryInteractionList()) { flipIfNecessary(ibi); interactions.add(ibi); } } catch (PsimiTabException e) { FacesContext context = FacesContext.getCurrentInstance(); if (context != null){ FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Temporarily impossible to retrieve results", solrQuery.getQuery()); context.addMessage(null, facesMessage); } log.fatal("Impossible to retrieve results for query " + solrQuery.getQuery(), e); } catch (IOException e) { FacesContext context = FacesContext.getCurrentInstance(); if (context != null){ FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Temporarily impossible to retrieve results", solrQuery.getQuery()); context.addMessage(null, facesMessage); } log.fatal("Impossible to retrieve results for query " + solrQuery.getQuery(), e); } } this.binaryInteractions = interactions; return interactions; } } private void prepareSolrQuery(int first, int pageSize, String sortField, SortOrder sortOrder) { SolrQuery copyQuery = solrQuery.getCopy(); copyQuery.setStart(first) .setRows(pageSize) .setFacet(true) .setFacetMissing(false) .addFacetField(FieldNames.COMPLEX_EXPANSION_FACET) .addFacetField(FieldNames.NEGATIVES_FACET); // add some limit to faceting for performances improvement copyQuery.set(FacetParams.FACET_OFFSET, 0); // we know that we have only 4 type of expansion methods : spoke expanded, no expansion, matrix or bipartite copyQuery.setFacetLimit(4); // sort by intact mi score desc if (copyQuery.getSortField() == null && sortField != null) { if (sortOrder.equals(SortOrder.ASCENDING)){ copyQuery.setSortField(sortField, SolrQuery.ORDER.asc); } else if (sortOrder.equals(SortOrder.DESCENDING)){ copyQuery.setSortField(sortField, SolrQuery.ORDER.desc); } } if (log.isDebugEnabled()) { try { log.debug("Fetching results: "+ URLDecoder.decode(copyQuery.toString(), "UTF-8")); } catch (UnsupportedEncodingException e) { log.fatal(e); } } try { result = solrSearcher.search(copyQuery); } catch (PsicquicSolrException e) { FacesContext context = FacesContext.getCurrentInstance(); if (context != null){ FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Temporarily impossible to retrieve results", copyQuery.getQuery()); context.addMessage(null, facesMessage); } log.fatal("Impossible to retrieve results for query " + copyQuery.getQuery(), e); result = null; } catch (SolrServerException e) { FacesContext context = FacesContext.getCurrentInstance(); if (context != null){ FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Temporarily impossible to retrieve results", copyQuery.getQuery()); context.addMessage(null, facesMessage); } log.fatal("Impossible to retrieve results for query " + copyQuery.getQuery(), e); result = null; } } private void prepareNegativeSolrQuery() throws SolrServerException, PsicquicSolrException { SolrQuery copyQuery = solrQuery.getCopy(); copyQuery.setStart(0) .setRows(0); // add negative filter copyQuery.addFilterQuery(FieldNames.NEGATIVE+":true"); IntactSolrSearchResult negativeResults = solrSearcher.search(copyQuery); this.numberOfBinaryInteractionsToShow = Long.valueOf(negativeResults.getNumberResults()).intValue(); } public int getRowCount() { if (result == null) { load(0,0, null, SortOrder.ASCENDING, null); } if (result != null){ return Long.valueOf(result.getNumberResults()).intValue(); } return 0; } private void flipIfNecessary(BinaryInteraction<Interactor> binaryInteraction) { final Interactor interactorA = binaryInteraction.getInteractorA(); final Interactor interactorB = binaryInteraction.getInteractorB(); final boolean matchesA = matchesQuery(interactorA); final boolean matchesB = matchesQuery(interactorB); if (matchesA && !matchesB) { // nothing } else if (!matchesA && matchesB) { binaryInteraction.flip(); } else { String id1 = interactorA != null ? (!interactorA.getIdentifiers().isEmpty() ? interactorA.getIdentifiers().iterator().next().getIdentifier() : "") : ""; String id2 = interactorB != null ? (!interactorB.getIdentifiers().isEmpty() ? interactorB.getIdentifiers().iterator().next().getIdentifier() : "") : ""; int comp = id1.compareTo(id2); if (comp > 0){ binaryInteraction.flip(); } } } private boolean matchesQuery(Interactor interactor) { String queries[] = solrQuery.getQuery().split(" "); if (interactor == null){ return false; } for (String query : queries) { if ("NOT".equalsIgnoreCase(query) || "AND".equalsIgnoreCase(query) || "OR".equalsIgnoreCase(query)) { continue; } if (matchesQueryAliases(query, interactor.getAliases())) { return true; } else if (matchesQueryXrefs(query, interactor.getIdentifiers())) { return true; }else if (matchesQueryXrefs(query, interactor.getAlternativeIdentifiers())) { return true; } else if (matchesQueryXrefs(query, interactor.getXrefs())) { return true; } } return false; } private boolean matchesQueryAliases(String query, Collection<Alias> aliases) { for (Alias alias : aliases) { if (query.toLowerCase().toLowerCase().endsWith(alias.getName().toLowerCase())) { return true; } } return false; } private boolean matchesQueryXrefs(String query, Collection<CrossReference> xrefs) { for (CrossReference xref : xrefs) { if (query.toLowerCase().endsWith(xref.getIdentifier().toLowerCase())) { return true; } } return false; } public IntactSolrSearchResult getResult() { return result; } public SolrQuery getSearchQuery() { return solrQuery; } public boolean isSameThanPrevious() { if (getRowIndex() > 0) { final BinaryInteraction previousInteraction = getInteraction(getRowIndex() - 1); final BinaryInteraction currentInteraction = getInteraction(getRowIndex()); String previousInteractorAName = previousInteraction.getInteractorA() != null ? MitabFunctions.getIntactIdentifierFromCrossReferences(previousInteraction.getInteractorA().getAlternativeIdentifiers()) : null; String previousInteractorBName = previousInteraction.getInteractorB() != null ? MitabFunctions.getIntactIdentifierFromCrossReferences(previousInteraction.getInteractorB().getAlternativeIdentifiers()) : null; String currentInteractorAName = currentInteraction.getInteractorA() != null ? MitabFunctions.getIntactIdentifierFromCrossReferences(currentInteraction.getInteractorA().getAlternativeIdentifiers()) : null; String currentInteractorBName = currentInteraction.getInteractorB() != null ? MitabFunctions.getIntactIdentifierFromCrossReferences(currentInteraction.getInteractorB().getAlternativeIdentifiers()) : null; return areEquals(previousInteractorAName, currentInteractorAName) && areEquals(previousInteractorBName, currentInteractorBName) ; } return false; } public boolean isNegative() { final BinaryInteraction currentInteraction = getInteraction(getRowIndex()); return currentInteraction.isNegativeInteraction(); } private boolean areEquals(String name1, String name2){ if (name1 == null && name2 == null){ return true; } else if (name1 != null && name2 != null){ return name1.equalsIgnoreCase(name2); } return false; } private BinaryInteraction getInteraction(int rowIndex) { final BinaryInteraction binaryInteraction = binaryInteractions.get(rowIndex); return binaryInteraction; } public int getNumberOfBinaryInteractionsToShow() { return numberOfBinaryInteractionsToShow; } }
package exceptionprograms; public class ErrorTest { public static void main( String[] args ) { try{ System.out.println("Error test"); throw new Error("imtiaz"); /* because errors are unchecked*/ }catch( Error e){ { System.out.println(e.getMessage()); } } } }
package Problem_10699; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; public class Main { public static void main(String[] args) { LocalDateTime utcDateTime = LocalDateTime.now(ZoneId.of("UTC+00:00")); ZonedDateTime seoulDateTime = utcDateTime.atZone(ZoneId.of("Asia/Seoul")).plusHours(9); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); System.out.println(seoulDateTime.format(formatter)); } }
package org.giddap.dreamfactory.codeforces; import java.io.PrintWriter; import java.util.Scanner; /** * Implementing 'ceiling of a / b' by using '(a + b - 1) / b' */ public class P001aTheatreSquare implements Runnable { public static void main(String[] args) { new Thread(new P001aTheatreSquare()).start(); } private long solve(final int m, final int n, final int a) { long z = (n + a - 1) / a; long x = (m + a - 1) / a; long c = z * x; return c; } public void run() { Scanner in = null; PrintWriter out = null; try { in = new Scanner(System.in); out = new PrintWriter(System.out); int n = in.nextInt(); int m = in.nextInt(); int a = in.nextInt(); out.println(solve(n, m, a)); } catch (Exception e) { e.printStackTrace(); } finally { in.close(); out.close(); } } }
package com.example.Backend.Dao; import com.example.Backend.Model.Comment; import com.example.Backend.Model.User; import java.util.List; import java.util.Optional; import java.util.UUID; public interface UserDao { int insertUser(UUID id, User user); default int insertUser(User user){ UUID id = UUID.randomUUID(); return insertUser(id,user); } List<User> selectAllUser(); Optional<User> selectUserById(UUID Id); int deleteUserById(UUID Id); }
package kr.co.shop.constant; import kr.co.shop.common.util.UtilsText; public interface MappersPayment { // 교환 매출 처리(30분마다) String OC_PAYMENT_DAO = "kr.co.shop.batch.payment.repository.master.OcOrderPaymentDao"; String OC_PAYMENT_DAO_SELECT_OCCART_COUNT = UtilsText.concat(OC_PAYMENT_DAO, ".", "selectNewChangeProduct"); String OC_PAYMENT_DAO_INSERT_SALES_PROC_DELIVERY = UtilsText.concat(OC_PAYMENT_DAO, ".", "insertSalesProcDelivery"); // 반품 매출 처리(매일 0시 25분 부터 30분마다) String OC_PAYMENT_DAO_SELECT_NEW_RETURN_DLVY_ID = UtilsText.concat(OC_PAYMENT_DAO, ".", "selectNewReturnDlvyId"); }
package com.sunrj.application.System.Service.impl.Department; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.sunrj.application.System.Service.Department.SysDepartmentService; import com.sunrj.application.System.dao.Department.SysDepartmentMapper; import com.sunrj.application.System.model.Department.SysDepartment; import com.sunrj.application.System.model.Department.SysDepartmentExample; @Service public class SysDepartmentServiceImpl implements SysDepartmentService{ @Autowired(required=false) private SysDepartmentMapper sysDepartmentMapper; @Override public List<SysDepartment> selectDepartmentList(SysDepartmentExample dto) { List<SysDepartment> resultList=sysDepartmentMapper.selectByExample(dto); return resultList; } @Override public int insertDepartment(SysDepartmentExample dto) { // TODO Auto-generated method stub return 0; } }
import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static java.util.Arrays.asList; /** * Created by Daniel on 12-Jan-17. */ public class SpiralMatrixTest { private static SpiralMatrix sut; @BeforeClass public static void setup(){ sut = new SpiralMatrix(); } @Test public void test(){ ArrayList<Integer> r1 = new ArrayList<>(asList(1, 2)); ArrayList<Integer> r2 = new ArrayList<>(asList(4, 3)); ArrayList<ArrayList<Integer>> mat = new ArrayList<>(); mat.add(r1); mat.add(r2); ArrayList<Integer> integers = sut.spiralOrder(mat); List<Integer> actual =integers; Assert.assertEquals(asList(1, 2, 3, 4), actual); } @Test public void test2(){ ArrayList<Integer> r1 = new ArrayList<>(asList(1, 2, 3)); ArrayList<Integer> r2 = new ArrayList<>(asList(8, 9, 4)); ArrayList<Integer> r3 = new ArrayList<>(asList(7, 6, 5)); ArrayList<ArrayList<Integer>> mat = new ArrayList<>(); mat.add(r1); mat.add(r2); mat.add(r3); ArrayList<Integer> integers = sut.spiralOrder(mat); List<Integer> actual =integers; Assert.assertEquals(asList(1, 2, 3, 4, 5, 6, 7, 8, 9), actual); } @Test public void test3(){ ArrayList<Integer> r1 = new ArrayList<>(asList(1)); ArrayList<ArrayList<Integer>> mat = new ArrayList<>(); mat.add(r1); ArrayList<Integer> integers = sut.spiralOrder(mat); List<Integer> actual =integers; Assert.assertEquals(asList(1), actual); } @Test public void test4(){ ArrayList<Integer> r1 = new ArrayList<>(asList(1, 2, 3)); ArrayList<Integer> r2 = new ArrayList<>(asList(6, 5, 4)); ArrayList<ArrayList<Integer>> mat = new ArrayList<>(); mat.add(r1); mat.add(r2); ArrayList<Integer> integers = sut.spiralOrder(mat); List<Integer> actual =integers; Assert.assertEquals(asList(1, 2, 3, 4, 5, 6), actual); } @Test public void test5(){ ArrayList<Integer> r1 = new ArrayList<>(asList(1, 2, 3)); ArrayList<ArrayList<Integer>> mat = new ArrayList<>(); mat.add(r1); ArrayList<Integer> integers = sut.spiralOrder(mat); List<Integer> actual =integers; Assert.assertEquals(asList(1, 2, 3), actual); } @Test public void test6(){ ArrayList<Integer> r1 = new ArrayList<>(asList(1)); ArrayList<Integer> r2 = new ArrayList<>(asList(2)); ArrayList<Integer> r3 = new ArrayList<>(asList(3)); ArrayList<ArrayList<Integer>> mat = new ArrayList<>(); mat.add(r1); mat.add(r2); mat.add(r3); ArrayList<Integer> integers = sut.spiralOrder(mat); List<Integer> actual =integers; Assert.assertEquals(asList(1, 2, 3), actual); } }
package com.marijannovak.littletanks; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.math.Intersector; import java.util.ArrayList; /** * Created by marij on 30.3.2017.. */ class Enemy extends MovingUnit { public Enemy(Texture texture) { super(texture); } public int isShot(ArrayList<Bullet> bulletList) //vraca koji metak ga je pogodio { int check = -1; for(int i = 0; i < bulletList.size(); i++) { if(Intersector.overlapConvexPolygons(this.getCollisionBox(), bulletList.get(i).getCollisionBox())) { check = i; } } return check; } }
package Level1; import java.util.Scanner; public class Test15 { /* * 문제 두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오. 입력 첫째 줄에 테스트 케이스의 개수 T가 주어진다. 각 테스트 케이스는 한 줄로 이루어져 있으며, 각 줄에 A와 B가 주어진다. (0 < A, B < 10) 출력 각 테스트 케이스마다 "Case #x: "를 출력한 다음, A+B를 출력한다. 테스트 케이스 번호는 1부터 시작한다. */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); int a ; int b ; int result[] = new int[t]; for(int i =0; i < t; i++) { a = sc.nextInt(); b = sc.nextInt(); result[i] = a+b; } for(int i = 0; i < t; i++) { System.out.println("Case #"+(i+1)+": " + result[i]); } } }
package io.chark.food.app.moderate.thread; import io.chark.food.app.account.AccountService; import io.chark.food.app.administrate.audit.AuditService; import io.chark.food.app.thread.ThreadService; import io.chark.food.domain.thread.Thread; import io.chark.food.domain.thread.ThreadRepository; import io.chark.food.util.exception.NotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.stereotype.Service; import java.util.Date; import java.util.List; import java.util.Optional; @Service public class ThreadModerationService { private final ThreadRepository threadRepository; private final ThreadService threadService; private final AuditService auditService; private final AccountService accountService; private static final Logger LOGGER = LoggerFactory.getLogger(ThreadModerationService.class); @Autowired public ThreadModerationService(ThreadRepository threadRepository, AuditService auditService, ThreadService threadService, AccountService accountService) { this.threadRepository = threadRepository; this.auditService = auditService; this.threadService = threadService; this.accountService = accountService; } public List<Thread> getThreads(){ return threadRepository.findAll(); } public Thread getThread(Long id){ Thread thread = threadRepository.findOne(id); if (thread == null) { auditService.warn("Attempted to query non-existing Thread with id: %d", id); throw new NotFoundException(Thread.class, id); } return thread; } public Optional<Thread> saveThread(long id, Thread threadDetails) { Optional<Thread> optional; if (id <= 0) { optional = threadService.register( threadDetails.getAccount(), threadDetails.getTitle(), threadDetails.getDescription(), threadDetails.isRegistrationRequired(), threadDetails.getThreadCategory() ); } else { optional = Optional.of(threadRepository.findOne(id)); } if (!optional.isPresent()) { return Optional.empty(); } optional = threadService.update(optional.get(), threadDetails); // Update other details editable only by admins. Thread thread = optional.get(); thread.setAccount(accountService.getAccount()); thread.setTitle(threadDetails.getTitle()); thread.setDescription(threadDetails.getDescription()); thread.setThreadLink(threadDetails.getThreadLink()); thread.setEditDate(new Date()); thread.setRegistrationRequired(threadDetails.isRegistrationRequired()); try { thread = threadRepository.save(thread); LOGGER.debug("Saved Thread{id={}}", thread.getId()); auditService.debug("%s Thread with id: %d via admin panel", id <= 0 ? "Created new" : "Updated", thread.getId()); return Optional.of(thread); } catch (DataIntegrityViolationException e) { LOGGER.error("Could not save thread", e); auditService.error("Failed to save thread"); return Optional.empty(); } } public void delete(long id) { Thread thread = threadRepository.findOne(id); threadRepository.delete(thread); auditService.info("Deleted Thread with id: %d", id); } }
package collections; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; public class Test_HashSet { public static void main(String[] args) { // Set -> SortedSet -> NavigableSet -> TreeSet Set hashSet = new TreeSet(new ComparadorPessoaID()); hashSet.add(new Pessoa(1, "Rodrigo")); hashSet.add(new Pessoa(2, "Maria")); hashSet.add(new Pessoa(3, "Joćo")); for (Object obj : hashSet) { System.out.println(obj); } } } class ComparadorPessoaID implements Comparator { // this // obj public int compare(Object o1, Object o2) { if (o1 instanceof Pessoa && o2 instanceof Pessoa) { Pessoa p1 = (Pessoa) o1; Pessoa p2 = (Pessoa) o2; int id1 = p1.getId(); int id2 = p2.getId(); // 1 - 2 == -1 return id1 - id2; } return -1; } } class ComparadorPessoaNome implements Comparator { // this // obj public int compare(Object o1, Object o2) { if (o1 instanceof Pessoa && o2 instanceof Pessoa) { Pessoa p1 = (Pessoa) o1; Pessoa p2 = (Pessoa) o2; String nomePessoa1 = p1.getNome(); String nomePessoa2 = p2.getNome(); return nomePessoa1.compareTo(nomePessoa2); } return -1; } }
/** * This Problem Set focused on manipulating Arrays and ArrayLists, in addition * to practicing more complex algorithms. Through this lab, I not only learned * the basic commands with ArrayLists, but I also learned how to use them effectively, * as they can a changeable capacity. There were also many problems related to sorting or finding the greatest value. * I approached these problems the same way: I keep a variable that holds the record * and check other elements to see if they top the record. If so, then I would set the record * to that value. To summarize, This lab helped me learn a lot about ArrayLists, as * well as how to design algorithms for sorting and finding specific values. * * @author Collin Wen * @version 1.0 */ import java.util.ArrayList; import java.util.Arrays; public class PS1Runner { public static void main (String[] args) { System.out.println("------ createWedge Method ------"); int[] wedge = ProblemSet1.createWedge(1); printArray(wedge); System.out.println(""); int[] wedge2 = ProblemSet1.createWedge(5); printArray(wedge2); System.out.println(""); int[] wedge3 = ProblemSet1.createWedge(13); printArray(wedge3); System.out.println(""); System.out.println("------ fibArray Method ------"); int[] fib = ProblemSet1.fibArray(2); printArray(fib); System.out.println(""); int[] fib2 = ProblemSet1.fibArray(6); printArray(fib2); System.out.println(""); int[] fib3 = ProblemSet1.fibArray(10); printArray(fib3); System.out.println(""); System.out.println("------ isMedian Method ------"); double[] dbl = {0.0,1.3,4.8,7.3,6.2,5.9,2.6,3.7,8.4,10.3}; printArray(dbl); System.out.println("Median = 5 : " + ProblemSet1.isMedian(dbl, 5.0)); double[] dbl1 = {0.0, 9.9, 6.6, 7.8, 4.2, 4.5}; printArray(dbl1); System.out.println("Median = 3 : " + ProblemSet1.isMedian(dbl1, 3.0)); double[] dbl3 = {1.0, 1.0, 1.0, 2.0, 3.0, 5.0, 7.0, 8.0, 10.0, 200.0}; printArray(dbl3); System.out.println("Median = 4 : " + ProblemSet1.isMedian(dbl3, 4.0)); System.out.println("------ rotate Method(s) ------"); int[] rotateL = {0,1,2,3,4,5,6,7,8,9}; printArray(rotateL); ProblemSet1.rotateLeft(rotateL); System.out.print("Rotate Left: "); printArray(rotateL); System.out.println(""); int[] rotateR = {0,1,5,3,6,8,4,7,8,3,5}; printArray(rotateR); ProblemSet1.rotateRight(rotateR); System.out.print("Rotate Right: "); printArray(rotateR); System.out.println(""); int[] rotate2 = {0,2,5,7,2,45,7,3,63,4,7,2,66}; printArray(rotate2); ProblemSet1.rotate(rotate2, 3); System.out.print("Rotate +3 (right): "); printArray(rotate2); System.out.println(""); int[] rotate3 = {34,6,7,455,2}; printArray(rotate3); ProblemSet1.rotate(rotate3, -4); System.out.print("Rotate -4 (left): "); printArray(rotate3); System.out.println(""); System.out.println("------ convert Method ------"); ArrayList<Integer> conv = new ArrayList<>(Arrays.asList(1,2,3,4,5)); ArrayList<Integer> conv2 = new ArrayList<>(Arrays.asList(0,4,66,3,4,75,45)); ArrayList<Integer> conv3 = new ArrayList<>(Arrays.asList(10,3,5)); System.out.print(conv + " convert to: "); printArray(ProblemSet1.convert(conv)); System.out.println(""); System.out.print(conv2 + " convert to: "); printArray(ProblemSet1.convert(conv2)); System.out.println(""); System.out.print(conv3 + " convert to: "); printArray(ProblemSet1.convert(conv3)); System.out.println(""); System.out.println("------ isEqual (helper) Method ------"); System.out.println("pingry = PiNgRy : " + ProblemSet1.isEqual("pingry", "PiNgRy")); System.out.println("dog = CAT : " + ProblemSet1.isEqual("dog", "CAT")); System.out.println("JAva = jAVA : " + ProblemSet1.isEqual("JAva", "jAVA")); System.out.println("------ equalsIgnoreCase Method ------"); ArrayList<String> eIC = new ArrayList<>(Arrays.asList("Dog", "cat", "lion", "zebra", "donkey")); ArrayList<String> eIC2 = new ArrayList<>(Arrays.asList("CAT", "ZEBRA", "DOnkeY", "DoG", "lION")); ArrayList<String> eIC3 = new ArrayList<>(Arrays.asList("Cat", "Cat", "Dog", "Lion", "Donkey", "DONKEY")); ArrayList<String> eIC4 = new ArrayList<>(Arrays.asList("DONKEY", "CAT", "LION", "Zebra", "dOg")); System.out.print(eIC); System.out.print(" = "); System.out.print(eIC2);; System.out.println(" : " + ProblemSet1.equalsIgnoreCase(eIC, eIC2)); System.out.print(eIC3); System.out.print(" = "); System.out.print(eIC); System.out.println(" : " + ProblemSet1.equalsIgnoreCase(eIC3, eIC)); System.out.print(eIC4); System.out.print(" = "); System.out.print(eIC2); System.out.println(" : " + ProblemSet1.equalsIgnoreCase(eIC4, eIC2)); System.out.println("------ top5 Method ------"); int[] top = {9,8,7,6,5,4,3,2,1}; printArray(top); System.out.print(" Top 5: " + ProblemSet1.top5(top)); System.out.println(""); int[] top2 = {3,464,232,86,964}; printArray(top2); System.out.print(" Top 5: " + ProblemSet1.top5(top2)); System.out.println(""); int[] top3 = {-2,4,-5,-7,-9,2,-1,3,-7,0,-2}; printArray(top3); System.out.print(" Top 5: " + ProblemSet1.top5(top3)); System.out.println(""); System.out.println("------ getFirst Method ------"); ArrayList<String> first = new ArrayList<>(Arrays.asList("z", "b", "c", "d", "e", "a")); System.out.print(first + " First: " + ProblemSet1.getFirst(first)); System.out.println(""); ArrayList<String> first2 = new ArrayList<>(Arrays.asList("pingry", "GO BIG BLUE", "pingrybigblue")); System.out.print(first2 + " First: " + ProblemSet1.getFirst(first2)); System.out.println(""); ArrayList<String> first3 = new ArrayList<>(Arrays.asList("abcdefg", "bcdefg", "cdefg", "defg")); System.out.print(first3 + " First: " + ProblemSet1.getFirst(first3)); System.out.println(""); System.out.println("------ replace Method ------"); char[][] cArr = {{'1','2','0'}, {'a','b','n'}, {'5', 'g', ','}}; printArray(cArr); ProblemSet1.replace(cArr); System.out.println(""); printArray(cArr); System.out.println(""); char[][] cArr2 = {{'1','2','0','a','6'}, {'a','b','n','k',';'}, {'5', 'g', ',','q','m'}}; printArray(cArr2); ProblemSet1.replace(cArr2); System.out.println(""); printArray(cArr2); System.out.println(""); char[][] cArr3 = {{'0','1','2','3','a'}, {'6','5','4', 'b'}, {'9','8','7'}}; printArray(cArr3); ProblemSet1.replace(cArr3); System.out.println(""); printArray(cArr3); System.out.println("------ multiply Method ------"); int[][] twoD = {{1,2},{3,4}}; int[][] twoD2 = {{4,2},{7,3}}; printArray(twoD); System.out.println("Multiplied by: "); printArray(twoD2); System.out.println("Equals: "); printArray(ProblemSet1.multiply(twoD, twoD2)); System.out.println(""); int[][] twoD3 = {{1,2},{3,4}}; int[][] twoD4 = {{5,6},{7,8}}; printArray(twoD3); System.out.println("Multiplied by: "); printArray(twoD4); System.out.println("Equals: "); printArray(ProblemSet1.multiply(twoD3, twoD4)); System.out.println(""); int[][] twoD5 = {{1,2,3},{4,5,6}}; //2 x 3 int[][] twoD6 = {{5,6},{7,8},{9,10}}; //3 x 2 printArray(twoD5); System.out.println("Multiplied by: "); printArray(twoD6); System.out.println("Equals: "); printArray(ProblemSet1.multiply(twoD5, twoD6)); } public static void printArray (int[] arr) { for(int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } public static void printArray (char[] arr) { for(int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } public static void printArray (double[] arr) { for(int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } public static void printArray (String[] arr) { for(int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } public static void printArray (int[][] arr) { for(int i = 0; i < arr.length; i++) { for(int a = 0; a < arr[i].length; a++) { System.out.print(arr[i][a] + " "); } System.out.println(""); } } public static void printArray (char[][] arr) { for(int i = 0; i < arr.length; i++) { for(int a = 0; a < arr[i].length; a++) { System.out.print(arr[i][a] + " "); } System.out.println(""); } } public static void printArray (ArrayList<String> arr) { for(int i = 0; i < arr.size(); i++) { System.out.print(arr.get(i) + " "); } } }
package ua.training.constant; /** * Description: This is list of regular expressions * * @author Zakusylo Pavlo */ public interface RegexExpress { String LANG_PAGE = "/swft/[A-Za-z]{2,}"; String REDIRECT_PAGE = ".*/swft/"; String USER_NAME_US = "^[A-Z][a-z]+$"; String USER_NAME_US2 = "^[A-Z][a-z]+-[A-Z][a-z]+$"; String USER_NAME_UA = "^[\u0410-\u0429\u042C\u042E\u042F\u0407\u0406\u0404\u0490]" + "\'?([\u0430-\u0449\u044C\u044E\u044F\u0457\u0456\u0454\u0491]+" + "\'?)?[\u0430-\u0449\u044C\u044E\u044F\u0457\u0456\u0454\u0491]+$"; String USER_NAME_UA2 = "^[\u0410-\u0429\u042C\u042E\u042F\u0407\u0406\u0404\u0490]" + "\'?([\u0430-\u0449\u044C\u044E\u044F\u0457\u0456\u0454\u0491]+" + "\'?)?[\u0430-\u0449\u044C\u044E\u044F\u0457\u0456\u0454\u0491]+-" + "[\u0410-\u0429\u042C\u042E\u042F\u0407\u0406\u0404\u0490]" + "\'?([\u0430-\u0449\u044C\u044E\u044F\u0457\u0456\u0454\u0491]+" + "\'?)?[\u0430-\u0449\u044C\u044E\u044F\u0457\u0456\u0454\u0491]+$"; String USER_EMAIL = "\\w{2,}@[a-z]{3,}\\.[a-z]{2,}"; String USER_EMAIL2 = "\\w{2,}@[a-z]{3,}\\.[a-z]{3,}\\.[a-z]{2,}"; String USER_EMAIL3 = "\\w{2,}@.{3,}\\.[a-z]{3,}\\.[a-z]{2,}"; String DISH_NAME_US = "^[A-Z][a-z]+(\\s[A-Za-z]+)?(\\s[A-Za-z]+)?$"; String DISH_NAME_UA = "^[\u0410-\u0429\u042C\u042E\u042F\u0407\u0406\u0404\u0490][`´''ʼ’ʼ’]?" + "([\u0430-\u0449\u044C\u044E\u044F\u0457\u0456\u0454\u0491]+[`´''ʼ’ʼ’]?)?" + "[\u0430-\u0449\u044C\u044E\u044F\u0457\u0456\u0454\u0491]+" + "(\\s[\u0410-\u0429\u042C\u042E\u042F\u0407\u0406\u0404\u0490\u0430-" + "\u0449\u044C\u044E\u044F\u0457\u0456\u0454\u0491][`´''ʼ’ʼ’]?" + "([\u0430-\u0449\u044C\u044E\u044F\u0457\u0456\u0454\u0491]+[`´''ʼ’ʼ’]?)?" + "[\u0430-\u0449\u044C\u044E\u044F\u0457\u0456\u0454\u0491]+)?" + "(\\s[\u0410-\u0429\u042C\u042E\u042F\u0407\u0406\u0404\u0490\u0430-" + "\u0449\u044C\u044E\u044F\u0457\u0456\u0454\u0491][`´''ʼ’ʼ’]?" + "([\u0430-\u0449\u044C\u044E\u044F\u0457\u0456\u0454\u0491]+[`´''ʼ’ʼ’]?)?" + "[\u0430-\u0449\u044C\u044E\u044F\u0457\u0456\u0454\u0491]+)?"; }
package wc; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; /** * The Class ProcessRawTwitter. */ public class ProcessRawTwitter { /** * The main method. * * @param args the arguments * @throws IOException Signals that an I/O exception has occurred. */ public static void main(String[] args) throws IOException { File folder = new File(args[0]); String csv = ProcessRawTwitter.listFilesForFolder(folder); try (PrintWriter out = new PrintWriter("filename.txt")) { out.println(csv); } } /** * List files for folder. * * @param folder the folder * @return the string * @throws IOException Signals that an I/O exception has occurred. */ public static String listFilesForFolder(final File folder) throws IOException { String file = null; for (final File fileEntry : folder.listFiles()) { if (fileEntry.isDirectory()) { listFilesForFolder(fileEntry); } else { System.out.println(fileEntry.getName()); file = ProcessRawTwitter.readFile(fileEntry.getName()); } } return file; } /** * Read file. * * @param fileName the file name * @return the string * @throws IOException Signals that an I/O exception has occurred. */ public static String readFile(String fileName) throws IOException { System.out.println(fileName); BufferedReader br = new BufferedReader(new FileReader(fileName)); try { StringBuilder sb = new StringBuilder(); String line = br.readLine(); System.out.println(line); while (line != null) { sb.append(line); sb.append(","); line = br.readLine(); } return sb.toString(); } finally { br.close(); } } }
package com.badawy.carservice.adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.badawy.carservice.R; import com.badawy.carservice.models.SparePartDetailsModel; import java.util.ArrayList; public class SparePartDetailsAdapter extends RecyclerView.Adapter<SparePartDetailsAdapter.SparePartDetailsViewHolder>{ private ArrayList<SparePartDetailsModel> detailsList; private Context context; public SparePartDetailsAdapter(ArrayList<SparePartDetailsModel> detailsList, Context context) { this.detailsList = detailsList; this.context = context; } @NonNull @Override public SparePartDetailsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemLayout = LayoutInflater.from(context).inflate(R.layout.item_product_details, parent, false); return new SparePartDetailsViewHolder(itemLayout); } @Override public void onBindViewHolder(@NonNull SparePartDetailsViewHolder holder, int position) { holder.detailName.setText(detailsList.get(position).getDetailName().trim()); holder.detailValue.setText(detailsList.get(position).getDetailValue().trim()); } @Override public int getItemCount() { return detailsList.size(); } class SparePartDetailsViewHolder extends RecyclerView.ViewHolder { TextView detailName,detailValue; SparePartDetailsViewHolder(@NonNull View itemView) { super(itemView); this.detailName = itemView.findViewById(R.id.item_productDetails_name); this.detailValue = itemView.findViewById(R.id.item_productDetails_value); } } }
package com.metoo.manage.admin.action; import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.Field; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.nutz.json.Json; import org.nutz.json.JsonFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.metoo.core.annotation.SecurityMapping; import com.metoo.core.beans.BeanUtils; import com.metoo.core.beans.BeanWrapper; import com.metoo.core.domain.virtual.SysMap; import com.metoo.core.mv.JModelAndView; import com.metoo.core.query.support.IPageList; import com.metoo.core.tools.CommUtil; import com.metoo.foundation.domain.Goods; import com.metoo.foundation.domain.GoodsCase; import com.metoo.foundation.domain.GoodsClass; import com.metoo.foundation.domain.query.GoodsCaseQueryObject; import com.metoo.foundation.domain.query.GoodsQueryObject; import com.metoo.foundation.service.IGoodsCaseService; import com.metoo.foundation.service.IGoodsClassService; import com.metoo.foundation.service.IGoodsService; import com.metoo.foundation.service.ISysConfigService; import com.metoo.foundation.service.IUserConfigService; /** * * <p> * Title: GoodsCaseManageAction.java * </p> * * <p> * Description: 平台橱窗管理控制器,用来管理首页等页面橱窗展示,首页橱窗展示位置在推荐商品通栏的tab页 * </p> * * <p> * Copyright: Copyright (c) 2015 * </p> * * <p> * Company: 沈阳网之商科技有限公司 www.koala.com * </p> * * @author erikzhang * * @date 2014-9-16 * * @version koala_b2b2c 2015 */ @Controller public class GoodsCaseManageAction { @Autowired private ISysConfigService configService; @Autowired private IUserConfigService userConfigService; @Autowired private IGoodsCaseService goodscaseService; @Autowired private IGoodsService goodsService; @Autowired private IGoodsClassService goodsClassService; /** * GoodsCase列表页 * * @param currentPage * @param orderBy * @param orderType * @param request * @return */ @SecurityMapping(title = "橱窗列表", value = "/admin/goods_case_list.htm*", rtype = "admin", rname = "橱窗管理", rcode = "goods_case", rgroup = "装修") @RequestMapping("/admin/goods_case_list.htm") public ModelAndView goods_case_list(HttpServletRequest request, HttpServletResponse response, String currentPage, String orderBy, String orderType) { ModelAndView mv = new JModelAndView("admin/blue/goods_case_list.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 0, request, response); String url = this.configService.getSysConfig().getAddress(); if (url == null || url.equals("")) { url = CommUtil.getURL(request); } String params = ""; GoodsCaseQueryObject qo = new GoodsCaseQueryObject(currentPage, mv, orderBy, orderType); qo.setOrderBy("sequence"); qo.setOrderType("asc"); IPageList pList = this.goodscaseService.list(qo); CommUtil.saveIPageList2ModelAndView(url + "/admin/goodscase_list.htm", "", params, pList, mv); return mv; } /** * goodscase添加管理 * * @param request * @return * @throws ParseException */ @SecurityMapping(title = "橱窗添加", value = "/admin/goods_case_add.htm*", rtype = "admin", rname = "橱窗管理", rcode = "goods_case", rgroup = "装修") @RequestMapping("/admin/goods_case_add.htm") public ModelAndView goods_case_add(HttpServletRequest request, HttpServletResponse response, String currentPage) { ModelAndView mv = new JModelAndView("admin/blue/goods_case_add.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 0, request, response); mv.addObject("currentPage", currentPage); return mv; } /** * goodscase编辑管理 * * @param id * @param request * @return * @throws ParseException */ @SecurityMapping(title = "橱窗编辑", value = "/admin/goods_case_edit.htm*", rtype = "admin", rname = "橱窗管理", rcode = "goods_case", rgroup = "装修") @RequestMapping("/admin/goods_case_edit.htm") public ModelAndView goods_case_edit(HttpServletRequest request, HttpServletResponse response, String id, String currentPage) { ModelAndView mv = new JModelAndView("admin/blue/goods_case_add.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 0, request, response); if (id != null && !id.equals("")) { GoodsCase goodscase = this.goodscaseService.getObjById(Long .parseLong(id)); List list = (List) Json.fromJson(goodscase.getCase_content()); mv.addObject("count", list.size()); mv.addObject("obj", goodscase); mv.addObject("currentPage", currentPage); mv.addObject("edit", true); } return mv; } /** * goodscase保存管理 * * @param id * @return */ @SecurityMapping(title = "橱窗保存", value = "/admin/goods_case_save.htm*", rtype = "admin", rname = "橱窗管理", rcode = "goods_case", rgroup = "装修") @RequestMapping("/admin/goods_case_save.htm") public ModelAndView goods_case_save(HttpServletRequest request, HttpServletResponse response, String id, String currentPage, String cmd, String list_url, String add_url, String case_name, String display, String sequence, String case_id, String case_content) { GoodsCase goodscase = null; if (id.equals("")) { goodscase = new GoodsCase(); goodscase.setAddTime(new Date()); } else { goodscase = this.goodscaseService.getObjById(Long.parseLong(id)); } goodscase.setDisplay(CommUtil.null2Int(display)); goodscase.setCase_name(case_name); goodscase.setSequence(CommUtil.null2Int(sequence)); goodscase.setCase_id(case_id); if (case_content != null && !case_content.equals("")) { List list = new ArrayList(); for (String str : case_content.split(",")) { if (str != null && !str.equals("")) { list.add(CommUtil.null2Long(str)); } } Map map = new HashMap(); map.put("ids", list); goodscase.setCase_content(Json.toJson(list, JsonFormat.compact())); } if (id.equals("")) { this.goodscaseService.save(goodscase); } else this.goodscaseService.update(goodscase); ModelAndView mv = new JModelAndView("admin/blue/success.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 0, request, response); mv.addObject("list_url", list_url); mv.addObject("op_title", "保存橱窗成功"); if (add_url != null) { mv.addObject("add_url", add_url + "?currentPage=" + currentPage); } return mv; } @SecurityMapping(title = "橱窗删除", value = "/admin/goods_case_del.htm*", rtype = "admin", rname = "橱窗管理", rcode = "goods_case", rgroup = "装修") @RequestMapping("/admin/goods_case_del.htm") public String goods_case_del(HttpServletRequest request, HttpServletResponse response, String mulitId, String currentPage) { String[] ids = mulitId.split(","); for (String id : ids) { if (!id.equals("")) { GoodsCase goodscase = this.goodscaseService.getObjById(Long .parseLong(id)); this.goodscaseService.delete(Long.parseLong(id)); } } return "redirect:goods_case_list.htm?currentPage=" + currentPage; } @SecurityMapping(title = "橱窗Ajax更新", value = "/admin/goods_case_del.htm*", rtype = "admin", rname = "橱窗管理", rcode = "goods_case", rgroup = "装修") @RequestMapping("/admin/goods_case_ajax.htm") public void goods_case_ajax(HttpServletRequest request, HttpServletResponse response, String id, String fieldName, String value) throws ClassNotFoundException { GoodsCase obj = this.goodscaseService.getObjById(Long.parseLong(id)); Field[] fields = GoodsCase.class.getDeclaredFields(); BeanWrapper wrapper = new BeanWrapper(obj); Object val = null; for (Field field : fields) { // System.out.println(field.getName()); if (field.getName().equals(fieldName)) { Class clz = Class.forName("java.lang.String"); if (field.getType().getName().equals("int")) { clz = Class.forName("java.lang.Integer"); } if (field.getType().getName().equals("boolean")) { clz = Class.forName("java.lang.Boolean"); } if (!value.equals("")) { val = BeanUtils.convertType(value, clz); } else { val = !CommUtil.null2Boolean(wrapper .getPropertyValue(fieldName)); } if (field.getName().equals("display")) { if (obj.getDisplay() == 1) { obj.setDisplay(0); val = obj.getDisplay(); } else { obj.setDisplay(1); val = obj.getDisplay(); } } wrapper.setPropertyValue(fieldName, val); } } this.goodscaseService.update(obj); response.setContentType("text/plain"); response.setHeader("Cache-Control", "no-cache"); response.setCharacterEncoding("UTF-8"); PrintWriter writer; try { writer = response.getWriter(); writer.print(val.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @SecurityMapping(title = "橱窗商品添加", value = "/admin/goods_case_goods.htm*", rtype = "admin", rname = "橱窗管理", rcode = "goods_case", rgroup = "装修") @RequestMapping("/admin/goods_case_goods.htm") public ModelAndView goods_case_goods(HttpServletRequest request, HttpServletResponse response, String currentPage, String id, String goods_ids) { ModelAndView mv = new JModelAndView("admin/blue/goods_case_goods.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 0, request, response); if (goods_ids != null && !goods_ids.equals("")) { List<Goods> goods_list = new ArrayList<Goods>(); String ids[] = goods_ids.split(","); for (String gid : ids) { if (!gid.equals("")) { Goods obj = this.goodsService.getObjById(CommUtil .null2Long(gid)); goods_list.add(obj); } } mv.addObject("goods_list", goods_list); } else if (id != null && !id.equals("")) { List<Goods> goods_list = new ArrayList<Goods>(); GoodsCase goodscase = this.goodscaseService.getObjById(CommUtil .null2Long(id)); List list = (List) Json.fromJson(goodscase.getCase_content()); for (Object obj : list) { Goods goods = this.goodsService.getObjById(CommUtil .null2Long(obj)); goods_list.add(goods); } mv.addObject("goods_list", goods_list); } mv.addObject("goods_ids", goods_ids); mv.addObject("id", id); return mv; } @SecurityMapping(title = "商品分类异步加载", value = "/admin/goods_case_gc.htm*", rtype = "admin", rname = "橱窗管理", rcode = "goods_case", rgroup = "装修") @RequestMapping("/admin/goods_case_gc.htm") public ModelAndView goods_case_gc(HttpServletRequest request, HttpServletResponse response, String currentPage) { ModelAndView mv = new JModelAndView("admin/blue/goods_case_gc.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 0, request, response); List<GoodsClass> gcs = this.goodsClassService .query("select obj from GoodsClass obj where obj.parent.id is null order by obj.sequence asc", null, -1, -1); mv.addObject("gcs", gcs); return mv; } @SecurityMapping(title = "商品加载", value = "/admin/goods_case_goods_load.htm*", rtype = "admin", rname = "橱窗管理", rcode = "goods_case", rgroup = "装修") @RequestMapping("/admin/goods_case_goods_load.htm") public ModelAndView goods_case_goods_load(HttpServletRequest request, HttpServletResponse response, String currentPage, String gc_id, String goods_name) { ModelAndView mv = new JModelAndView( "admin/blue/goods_case_goods_load.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 0, request, response); GoodsQueryObject qo = new GoodsQueryObject(currentPage, mv, "addTime", "desc"); qo.setPageSize(7); if (!CommUtil.null2String(gc_id).equals("")) { Set<Long> ids = this.genericIds(this.goodsClassService .getObjById(CommUtil.null2Long(gc_id))); Map paras = new HashMap(); paras.put("ids", ids); qo.addQuery("obj.gc.id in (:ids)", paras); } if (!CommUtil.null2String(goods_name).equals("")) { qo.addQuery("obj.goods_name", new SysMap("goods_name", "%" + goods_name + "%"), "like"); } qo.addQuery("obj.goods_status", new SysMap("goods_status", 0), "="); IPageList pList = this.goodsService.list(qo); CommUtil.saveIPageList2ModelAndView(CommUtil.getURL(request) + "/admin/goods_case_goods_load.htm", "", "&gc_id=" + gc_id + "&goods_name=" + goods_name, pList, mv); return mv; } private Set<Long> genericIds(GoodsClass gc) { Set<Long> ids = new HashSet<Long>(); ids.add(gc.getId()); for (GoodsClass child : gc.getChilds()) { Set<Long> cids = genericIds(child); for (Long cid : cids) { ids.add(cid); } ids.add(child.getId()); } return ids; } }
package test.innerclass; import java.util.ArrayList; import java.util.Arrays; public class test1 { public static void main(String[] args) { // OutClass outClass = new OutClass(); // OutClass2 outClass2 = new OutClass2(); // // OutClass.InnerClass innerClass = outClass.new InnerClass(); // // innerClass.display(); // outClass2.out(); // // new OutClass3(){ // @Override // public void say(){ // System.out.println("bbbbb"); // } // }.say(); ArrayList<Integer> arrayList = new ArrayList<>(Arrays.asList(1,2,3,4,5)); int recv = 0; int pop; while(arrayList.size()!=0){ pop=arrayList.get(0); recv=recv*10+pop; arrayList.remove(0); } System.out.println(recv); } }
package edu.uab.cvc.huntingwords.screens.fragments; import android.app.Fragment; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import edu.uab.cvc.huntingwords.R; import edu.uab.cvc.huntingwords.presenters.ConnectPresenter; import edu.uab.cvc.huntingwords.presenters.ConnectPresenterImpl; import edu.uab.cvc.huntingwords.screens.Utils; import edu.uab.cvc.huntingwords.screens.views.LoginView; import static edu.uab.cvc.huntingwords.Utils.CURRENT_SCORE_DIFF; import static edu.uab.cvc.huntingwords.Utils.CURRENT_SCORE_MATCH; /** * Created by carlosb on 05/04/18. */ public class Connect extends Fragment implements LoginView { private ConnectPresenter presenter; @BindView(R.id.edit_username) EditText username; @BindView(R.id.edit_pasword) EditText password; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.login_fragment, container, false); ButterKnife.bind(this, view); presenter = new ConnectPresenterImpl(this); view.setBackgroundColor(Utils.GetBackgroundColour(this.getActivity())); return view; } @OnClick(R.id.connect) public void login () { String user= username.getText().toString(); String pass= password.getText().toString(); this.presenter.login(user,pass); } @OnClick(R.id.signin) public void signin() { String user= username.getText().toString(); String pass= password.getText().toString(); this.presenter.signin(user,pass); } @OnClick(R.id.disconnect) public void disconnect() { setUpAnonymousParameters(); TextView textView = (TextView)getActivity().findViewById(R.id.logged_user); getActivity().runOnUiThread( () -> textView.setText(getString(R.string.anonym))); } @Override public void updateLogin(String username) { TextView textView = (TextView)getActivity().findViewById(R.id.logged_user); new Thread() { public void run() { getActivity().runOnUiThread( () -> { getActivity().runOnUiThread( () -> textView.setText(username)); }); } }.start(); } @Override public void setUpLoginParameters(String username, String passw) { SharedPreferences preferences = getActivity().getSharedPreferences( getString(R.string.preferences_file), Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putString(edu.uab.cvc.huntingwords.Utils.PARAM_USERNAME,username); editor.putString(edu.uab.cvc.huntingwords.Utils.PARAM_PASSWORD,passw); editor.commit(); } @Override public void setUpScoreParameters(Integer scoreMatch, Integer scoreDiff) { SharedPreferences preferences = getActivity().getSharedPreferences( getString(R.string.preferences_file), Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putInt(CURRENT_SCORE_MATCH,scoreMatch); editor.putInt(CURRENT_SCORE_DIFF,scoreDiff); editor.commit(); } public void setUpAnonymousParameters() { SharedPreferences preferences = getActivity().getSharedPreferences( getString(R.string.preferences_file), Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putString(edu.uab.cvc.huntingwords.Utils.PARAM_USERNAME,getString(R.string.anonym)); editor.commit(); } @Override public void errorLogin() { new Thread() { public void run() { getActivity().runOnUiThread( () -> { Toast.makeText(getActivity(),getString(R.string.logged_fail),Toast.LENGTH_LONG).show(); }); } }.start(); } }
package org.giddap.dreamfactory.leetcode.onlinejudge.implementations; import org.giddap.dreamfactory.leetcode.commons.ListNode; import org.giddap.dreamfactory.leetcode.onlinejudge.MergeTwoSortedLists; public class MergeTwoSortedListsIterativeImpl implements MergeTwoSortedLists { @Override public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode newhead = new ListNode(0); ListNode prev = newhead; while (l1 != null && l2 != null) { if (l1.val < l2.val) { prev.next = l1; prev = l1; l1 = l1.next; } else { prev.next = l2; prev = l2; l2 = l2.next; } } if (l1 != null) { prev.next = l1; } else { prev.next = l2; } return newhead.next; } }
package view.insuranceSystemView.rewardView.lawyer; import java.awt.Color; import java.awt.event.ActionListener; import model.data.employeeData.rewardEmployeeData.LawyerData; import model.data.rewardData.AccidentData; import model.data.rewardData.AccidentInvestigationData; import model.data.rewardData.LossCheckData; import model.data.rewardData.PayJudgeData; import model.data.rewardData.RewardData; import model.dataList.IntDataList; import view.aConstant.InsuranceSystemViewConstant; import view.component.BasicLabel; import view.component.SeparateLine; import view.component.button.ActionButton; import view.component.button.LinkButton; import view.component.textArea.OutputTextArea; import view.insuranceSystemView.absInsuranceSystemView.InsuranceSystemView; @SuppressWarnings("serial") public class ShowRewardDataInfoForLwView extends InsuranceSystemView{ // Static public enum EActionCommands {writeSueReport} public ShowRewardDataInfoForLwView(LawyerData user, ActionListener actionListener, int taskID, IntDataList<RewardData> rewardDataList) { RewardData rewardData = rewardDataList.search(user.getTaskList().search(taskID).getRewardDataID()); AccidentData accidentData = rewardData.getAccidentData(); AccidentInvestigationData accidentInvestigationData = rewardData.getAccidentInvestigationData(); PayJudgeData payJudgeData = rewardData.getPayJudgeData(); LossCheckData lossCheckData = rewardData.getLossData(); this.addComponent(new BasicLabel("요청하신 사고 데이터 입니다.")); this.addComponent(new SeparateLine(Color.black)); this.addComponent(new OutputTextArea("사고 유형", accidentData.getType())); this.addComponent(new OutputTextArea("사고 위치", accidentData.getLocation())); this.addComponent(new OutputTextArea("사고 시간", accidentData.getDate())); this.addComponent(new BasicLabel("요청하신 사고 조사 데이터 입니다.")); this.addComponent(new SeparateLine(Color.black)); this.addComponent(new OutputTextArea("사고 시나리오", accidentInvestigationData.getScenario())); this.addComponent(new OutputTextArea("피해", accidentInvestigationData.getDamage())); this.addComponent(new OutputTextArea("사고 처리", accidentInvestigationData.getTreatment())); this.addComponent(new OutputTextArea("사고 처리 비용", Integer.toString(accidentInvestigationData.getTreatmentCost()))); this.addComponent(new BasicLabel("요청하신 면/부책 판단 데이터 입니다.")); this.addComponent(new SeparateLine(Color.black)); this.addComponent(new OutputTextArea("면/부책 결과", payJudgeData.getPayJudge())); this.addComponent(new OutputTextArea("면/부책 근거", payJudgeData.getJudgementEvidence())); this.addComponent(new OutputTextArea("관련 법률", payJudgeData.getRelatedLaw())); this.addComponent(new BasicLabel("요청하신 손해사정 데이터 입니다.")); this.addComponent(new SeparateLine(Color.black)); this.addComponent(new OutputTextArea("지급 보험금", Integer.toString(lossCheckData.getPay()))); this.addComponent(new OutputTextArea("판단 근거", lossCheckData.getJudgeEvidence())); this.addComponent(new ActionButton("소송 결과 입력", EActionCommands.writeSueReport.name(), actionListener)); this.addToLinkPanel( new LinkButton(InsuranceSystemViewConstant.SomeThingLookGreat, "", null), new LinkButton(InsuranceSystemViewConstant.SomeThingLookNide, "", null) ); } }
package tasks; import java.io.File; import java.util.List; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import queue.Queue; import queue.TextQueue; import utils.CommonCrawlSource; import utils.CommonCrawlSource.WARC_TYPE; public class LoadArchivesIntoQueue { private final static Options options; static { options = new Options(); options.addOption("c", "crawl", true, "Name of the crawl to use."); options.addOption("q", "queuePath", true, "Path to TextQeue directory."); options.addOption("r", "range", true, "Define subrange of urls starting from 1 (e.g. 1-100)."); options.addOption("p", "part", true, "Define fraction of urls to use starting from 1 (e.g. 1/20)."); options.addOption("d", "delete", false, "Clear queue before loading"); } public static void main(String[] args) { CommandLineParser parser = new BasicParser(); CommandLine cmd; try { cmd = parser.parse(options, args); String crawl = cmd.getOptionValue("c"); String queuePath = cmd.getOptionValue("q"); String range = cmd.getOptionValue("r"); String part = cmd.getOptionValue("p"); boolean reset = cmd.hasOption("d"); List<String> archives = new CommonCrawlSource(crawl).archiveList(WARC_TYPE.WET, true); Queue<String> queue = new TextQueue(new File(queuePath)); if (reset) { queue.reset(); } int start = 0; int end = archives.size(); if (range != null) { String[] parts = range.split("-"); start = Math.max(Integer.parseInt(parts[0]) - 1, 0); end = Math.min(Integer.parseInt(parts[1]), archives.size()); } else if (part != null) { String[] parts = part.split("/"); int partNo = Integer.parseInt(parts[0]); int partCo = Integer.parseInt(parts[1]); int partSize = (int) Math.ceil(archives.size() / partCo); start = (partNo - 1) * partSize; end = Math.min(partNo * partSize, archives.size()); } queue.add(TextQueue.joinLines(archives.subList(start, end))); } catch (ParseException e) { e.printStackTrace(); } } }
package model; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Klasse für die Verwaltung der importierten Feriendaten. * * @author Sebastian Drath * */ public class Holidays { private static Map<Integer, YearHolidays> holidays; /** * Es werden importierte Feriendaten hinzugefügt. * * Die Beschreibung liegt als Text vor. Beginn und Ende von Ferien wird mit Daten im Format dd.MM. angegeben. * Einzelne Tage bzw. Ferienbereiche sind durch "/" getrennt. * Beispiele: "dd.MM.-dd.MM" für Ferienbereiche, "dd.MM." für einzelne Tage oder "dd.MM.-dd.MM./dd.MM." für einen Bereich und einzelnen Tag. * Das Bundesland und der Name dürfen nicht null entsprechen. * * @param year Das Jahr in dem die Ferien liegen * @param state Das Bundesland in dem die Ferien sind * @param name Der Name der Ferien * @param description Die Beschreibung der Daten im oben beschriebenen Format * @return true, wenn die Ferien hinzugefügt wurden, false bei fehlerhaften Parametern */ public static boolean addHoliday(int year, FederalState state, String name, String description) { if(name == null || state == null || state == FederalState.DEF) return false; if(description == null || description.equals("-")) return true; // ist ok, weil in manchen Bundesländern bestimmte Ferien nicht existieren und durch ein - gekennzeichnet sind // analysiere Beschreibung // ggf. mehrere Ferienbereiche pro Beschreibung (bspw Brückentage an zwei getrennten Tagen) for(String part: description.split("/")) { String[] days = part.split("-"); if(days.length < 1 || days.length > 2) { System.err.println("invalid holiday format: " + part); return false; } DateFormat df = new SimpleDateFormat("dd.MM.yyyy/HH:mm"); Date from, to; boolean intoNextYear = false; try { from = df.parse(days[0] + year + "/00:00"); // vom Beginn des ersten Tages to = df.parse(days[days.length-1] + year + "/23:59"); // bis zum Ende des letzten Tages if(to.before(from)) { // Wenn das Ende vor dem Beginn liegt wird die Jahreszahl des Endes inkrementiert (Weihnachtsferien zählen zu dem Jahr, in dem sie beginnen) to = df.parse(days[days.length-1] + (year+1) + "/23:59"); intoNextYear = true; } } catch (ParseException e) { System.err.println("Could not parse date: " + part); return false; } addHoliday(year, state, name, from, to); // Wenn die Ferien über 2 Jahre gehen (bspw. Weihnachtsferien) werden sie beiden Jahren zugeordnet if(intoNextYear) addHoliday(year+1, state, name, from, to); } return true; } /** * Bestimmt, ob für an dem Datum in dem Bundesland Ferien sind oder nicht * * @param date das Datum * @param state das Bundesland * @return true, wenn zur gegebenen Zeit in dem Bundesland Ferien sind, false ansonsten */ public static boolean isHoliday(Date date, FederalState state) { if(date == null || state == null || state == FederalState.DEF || holidays == null) return false; Calendar c = Calendar.getInstance(); c.setTime(date); int year = c.get(Calendar.YEAR); //System.out.println("questioning: " + year); if (holidays.containsKey(year)) { return holidays.get(year).isHoliday(date, state); } else { System.err.println("No holiday Data available for " + year); return false; } } /** * Überprüft, ob die hinzugefügten Daten vollständig sind, d.h. ob für jedes Jahr die Ferien für alle 16 Bundesländer importiert wurden. * * @return true, wenn die Feriendaten vollständig sind, false ansonsten */ public static boolean checkIntegrity() { boolean result = true; for(int year: holidays.keySet()) { result &= holidays.get(year).checkIntegrity(); } return result; } /** * Fügt einen Ferienbereich hinzu. * * @param year Jahr * @param state Bundesland * @param name Ferienname * @param from Datum des Beginns * @param to Datum des Endes */ private static void addHoliday(int year, FederalState state, String name, Date from, Date to) { if(holidays == null) { holidays = new HashMap<>(); } if(!holidays.containsKey(year)) { //System.out.println("Year " + year + " added"); holidays.put(year, new YearHolidays()); } holidays.get(year).addHoliday(state, name, from, to); } } /** * Repräsentiert die Ferien innerhalb eines Jahres für alle Bundesländer. * * @author Sebastian Drath * */ class YearHolidays { private Map<FederalState, List<Holiday>> allHolidays; public YearHolidays() { allHolidays = new HashMap<>(); } /** * Überprüft ob für jedes Bundesland innerhalb des Jahres Ferien vorliegen. * * @return true, wenn alle Bundesländer importiert wurden, false ansonsten */ public boolean checkIntegrity() { return allHolidays.size() == 16; } public void addHoliday(FederalState state, String name, Date from, Date to) { if(!allHolidays.containsKey(state)) { List<Holiday> h = new ArrayList<>(); allHolidays.put(state, h); } allHolidays.get(state).add(new Holiday(name, from, to)); } public boolean isHoliday(Date date, FederalState state) { if(allHolidays.containsKey(state)) { for(Holiday h: allHolidays.get(state)) { if(h.isHoliday(date)) return true; } return false; } else { System.err.println("No holiday Data available for " + state); return false; } } } /** * Ein Ferienbereich. * * @author Sebastian Drath * */ class Holiday { private String name; private Date from, to; /** * Erstellt einen einzelnen Ferienbereich. * * @param name Name der Ferien * @param from Datum des Beginns * @param to Datum des Endes */ public Holiday(String name, Date from, Date to) { this.name = name; this.from = from; this.to = to; } /** * Gibt Feriennamen zurück. * * @return Ferienname */ public String getName() { return this.name; } /** * Gibt zurück, ob sich das Datum innerhalb dieses Ferienbereichs befindet. * * @param date angefordertes Datum * @return true, wenn das Datum innerhalb der Ferien liegt, false ansonsten */ public boolean isHoliday(Date date) { return date.after(from) && date.before(to); } }
package com.example.devansh.personalhealthcarechatbot; import android.content.Context; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; public class LogIn extends AppCompatActivity implements View.OnClickListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_in); findViewById(R.id.btnShowChat).setOnClickListener(this); } @Override public void onClick(View view) { SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE); //SharedPreferences.Editor editor = sharedPref.edit(); String usrname = "" + ((TextView)(findViewById(R.id.editLogInUsername))).getText(); String pass = "" +((TextView)(findViewById(R.id.editLogInPassword))).getText(); if(sharedPref.contains(usrname)) { Log.d("test-login", "username is already added"); String dictPass = sharedPref.getString(usrname, pass); Log.d("test-login", "we click on log in and we got : " + dictPass); }else{ Log.d("test-login", "Username does not exist"); } } }
package com.lenovohit.ssm.base.model; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import com.lenovohit.core.model.BaseIdModel; /** * 出库明细 * @author wang * */ @Entity @Table(name="SSM_MATERIAL_DETAIL_OUT") public class MaterialDetailOut extends BaseIdModel { private static final long serialVersionUID = -5855416698692933351L; private int outPutAccount;//出库数量 private String outPutTime;//出库时间 private String operator;//操作人 private Machine machine;//自助机编号 private Material material;//材料编号 private String outTime;//时间 public int getOutPutAccount() { return outPutAccount; } public void setOutPutAccount(int outPutAccount) { this.outPutAccount = outPutAccount; } public String getOutPutTime() { return outPutTime; } public void setOutPutTime(String outPutTime) { this.outPutTime = outPutTime; } public String getOperator() { return operator; } public void setOperator(String operator) { this.operator = operator; } @JoinColumn(name = "MACHINE_ID") @ManyToOne public Machine getMachine() { return machine; } public void setMachine(Machine machine) { this.machine = machine; } @JoinColumn(name = "MATERIAL_ID") @ManyToOne public Material getMaterial() { return material; } public void setMaterial(Material material) { this.material = material; } public String getOutTime() { return outTime; } public void setOutTime(String outTime) { this.outTime = outTime; } }
package dproxy; /** * Created by whatisjava on 17-9-15. */ public class AdminServiceImpl implements AdminService { public void addAdmin() { System.out.println("add admin action..."); } }
package coffeshop.business.concretes; import coffeshop.business.abstracts.CustomerService; import coffeshop.entities.concretes.Customer; public class BaseCustomerManager implements CustomerService { public void register(Customer customer) { System.out.println("Müşteri kaydedildi: " + customer.getCustomerFirstName() + customer.getCustomerLastName()); } }
package slimeknights.tconstruct.library.capability.piggyback; import net.minecraft.nbt.NBTBase; import net.minecraft.util.EnumFacing; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.CapabilityInject; import net.minecraftforge.common.capabilities.CapabilityManager; import java.util.concurrent.Callable; public class CapabilityTinkerPiggyback implements Capability.IStorage<ITinkerPiggyback> { @CapabilityInject(ITinkerPiggyback.class) public static Capability<ITinkerPiggyback> PIGGYBACK = null; private static final CapabilityTinkerPiggyback INSTANCE = new CapabilityTinkerPiggyback(); private CapabilityTinkerPiggyback() { } public static void register() { CapabilityManager.INSTANCE.register(ITinkerPiggyback.class, INSTANCE, new Callable<ITinkerPiggyback>() { @Override public ITinkerPiggyback call() throws Exception { return new TinkerPiggybackHandler(); } }); } @Override public NBTBase writeNBT(Capability<ITinkerPiggyback> capability, ITinkerPiggyback instance, EnumFacing side) { return null; } @Override public void readNBT(Capability<ITinkerPiggyback> capability, ITinkerPiggyback instance, EnumFacing side, NBTBase nbt) { } }
package com.example.microgram.service; import com.example.microgram.dto.UserDTO; import com.example.microgram.exception.ResourceNotFoundException; import com.example.microgram.model.Publication; import com.example.microgram.model.User; import com.example.microgram.repository.PublicationRepository; import com.example.microgram.repository.UserRepository; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Slice; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.stream.IntStream; @Service public class UserService { private final UserRepository userRepository; private final PublicationRepository publicationRepository; public UserService(UserRepository userRepository, PublicationRepository publicationRepository){ this.userRepository=userRepository; this.publicationRepository=publicationRepository; } public void addPublication(String userId, String publicationId){ Publication publication = publicationRepository.getById(publicationId); var user = userRepository.getById(userId); List<Publication> pblList = new ArrayList<>(); pblList.add(publication); if (user.getPublications() != null) { IntStream.range(0, pblList.size()).forEachOrdered(i -> pblList.add(user.getPublications().get(i))); } user.setPublications(pblList); var userUpdate = User.builder() .id(user.getId()) .account(user.getAccount()) .email(user.getEmail()) .password(user.getPassword()) .publications(user.getPublications()) .publicationCount(user.getPublicationCount()) .subscriptionCount(user.getSubscriptionCount()) .subscriberCount(user.getSubscriberCount()) .build(); userRepository.save(userUpdate); UserDTO.from(userUpdate); } public UserDTO register(UserDTO userDTO){ var user = User.builder() .account(userDTO.getAccount()) .email(userDTO.getEmail()) .password(userDTO.getPassword()) .build(); userRepository.save(user); return UserDTO.from(user); } public Slice<UserDTO> findUsers(Pageable pageable) { Page<User> slice = userRepository.findAll(pageable); return slice.map(UserDTO::from); } public UserDTO findUser(String email){ User usr = userRepository.getByEmail(email); var user = userRepository.findById(usr.getId()) .orElseThrow(() -> new ResourceNotFoundException("Can't user movie with the email: " + email)); return UserDTO.from(user); } public Slice<UserDTO> showUsers(Pageable pageable) { Page<User> usersPage = userRepository.findAll(pageable); List<User> userList = usersPage.getContent(); List<User> users = new ArrayList<>(); User u = getUser(); IntStream.range(0, userList.size()).forEachOrdered(i -> { if (!userList.get(i).getId().equals(u.getId())) users.add(userList.get(i)); }); Page<User> page = new PageImpl<>(users, pageable, users.size()); return page.map(UserDTO::from); } public UserDTO loginUser(String email, String password) { var us = userRepository.selectUser(email, password); var user = userRepository.findById(us.getId()) .orElseThrow(() -> new ResourceNotFoundException("Can't find user with the email: " + email)); return UserDTO.from(user); } public boolean deleteUser(String id) { if (userRepository.existsById(id)) { userRepository.deleteById(id); return true; } else return false; } public User getUser() { // get current authenticated user Authentication auth = SecurityContextHolder.getContext().getAuthentication(); return userRepository.findByEmail(auth.getName()).get(); } }
package blog.dreamland.com.dao; import blog.dreamland.com.entity.LoginLog; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import tk.mybatis.mapper.common.Mapper; public interface LoginLogMapper extends Mapper<LoginLog>{ }
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.view; import java.util.Locale; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.xml.ResourceEntityResolver; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.Ordered; import org.springframework.core.io.Resource; import org.springframework.lang.Nullable; import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.servlet.View; /** * A {@link org.springframework.web.servlet.ViewResolver} implementation that uses * bean definitions in a dedicated XML file for view definitions, specified by * resource location. The file will typically be located in the WEB-INF directory; * the default is "/WEB-INF/views.xml". * * <p>This {@code ViewResolver} does not support internationalization at the level * of its definition resources. Consider {@link ResourceBundleViewResolver} if you * need to apply different view resources per locale. * * <p>Note: This {@code ViewResolver} implements the {@link Ordered} interface * in order to allow for flexible participation in {@code ViewResolver} chaining. * For example, some special views could be defined via this {@code ViewResolver} * (giving it 0 as "order" value), while all remaining views could be resolved by * a {@link UrlBasedViewResolver}. * * @author Juergen Hoeller * @since 18.06.2003 * @see org.springframework.context.ApplicationContext#getResource * @see UrlBasedViewResolver * @see BeanNameViewResolver * @deprecated as of 5.3, in favor of Spring's common view resolver variants * and/or custom resolver implementations */ @Deprecated public class XmlViewResolver extends AbstractCachingViewResolver implements Ordered, InitializingBean, DisposableBean { /** Default if no other location is supplied. */ public static final String DEFAULT_LOCATION = "/WEB-INF/views.xml"; @Nullable private Resource location; @Nullable private ConfigurableApplicationContext cachedFactory; private int order = Ordered.LOWEST_PRECEDENCE; // default: same as non-Ordered /** * Set the location of the XML file that defines the view beans. * <p>The default is "/WEB-INF/views.xml". * @param location the location of the XML file. */ public void setLocation(Resource location) { this.location = location; } /** * Specify the order value for this ViewResolver bean. * <p>The default value is {@code Ordered.LOWEST_PRECEDENCE}, meaning non-ordered. * @see org.springframework.core.Ordered#getOrder() */ public void setOrder(int order) { this.order = order; } @Override public int getOrder() { return this.order; } /** * Pre-initialize the factory from the XML file. * Only effective if caching is enabled. */ @Override public void afterPropertiesSet() throws BeansException { if (isCache()) { initFactory(); } } /** * This implementation returns just the view name, * as XmlViewResolver doesn't support localized resolution. */ @Override protected Object getCacheKey(String viewName, Locale locale) { return viewName; } @Override protected View loadView(String viewName, Locale locale) throws BeansException { BeanFactory factory = initFactory(); try { return factory.getBean(viewName, View.class); } catch (NoSuchBeanDefinitionException ex) { // Allow for ViewResolver chaining... return null; } } /** * Initialize the view bean factory from the XML file. * Synchronized because of access by parallel threads. * @throws BeansException in case of initialization errors */ protected synchronized BeanFactory initFactory() throws BeansException { if (this.cachedFactory != null) { return this.cachedFactory; } ApplicationContext applicationContext = obtainApplicationContext(); Resource actualLocation = this.location; if (actualLocation == null) { actualLocation = applicationContext.getResource(DEFAULT_LOCATION); } // Create child ApplicationContext for views. GenericWebApplicationContext factory = new GenericWebApplicationContext(); factory.setParent(applicationContext); factory.setServletContext(getServletContext()); // Load XML resource with context-aware entity resolver. XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory); reader.setEnvironment(applicationContext.getEnvironment()); reader.setEntityResolver(new ResourceEntityResolver(applicationContext)); reader.loadBeanDefinitions(actualLocation); factory.refresh(); if (isCache()) { this.cachedFactory = factory; } return factory; } /** * Close the view bean factory on context shutdown. */ @Override public void destroy() throws BeansException { if (this.cachedFactory != null) { this.cachedFactory.close(); } } }
/** * */ package TestCity; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import City.City; import City.Inhabitant; import Content.TextContent; import Letters.Letter; import Letters.SimpleLetter; /** * Tests for Inhabitant * * @author Alex Dalencourt * @author Sellenia Chikhoune * */ public class InhabitantTest { private Inhabitant inhabitant; private City city; @Before public void createInhabitant() { this.city = new City("New York"); this.inhabitant = new Inhabitant(this.city, "Iron Man"); } @Test public void test_createInhabitant() { Assert.assertEquals(this.city, this.inhabitant.getCity()); Assert.assertEquals("Iron Man", this.inhabitant.getName()); Assert.assertNotNull(this.inhabitant.getBalence()); } @Test public void test_withdraw() { int amount = 50; this.inhabitant.credit(amount); Assert.assertEquals(amount, this.inhabitant.getBalence(), 0); amount /= 2; this.inhabitant.withdraw(amount); Assert.assertEquals(amount, this.inhabitant.getBalence(), 0); } @Test public void test_credit() { int amount = 50; Assert.assertEquals(0, this.inhabitant.getBalence(), 0); this.inhabitant.credit(amount); Assert.assertEquals(amount, this.inhabitant.getBalence(), 0); } @Test public void test_sendLetter() { this.inhabitant.credit(20); Letter<?> letter = new SimpleLetter(this.inhabitant, this.inhabitant, new TextContent("Hello")); float balance = this.inhabitant.getBalence() - letter.getCost(); this.inhabitant.sendLetter(letter); Assert.assertEquals(balance, this.inhabitant.getBalence(), 0); } }
package com.gsccs.sme.plat.shop.model; import java.util.Date; public class OrderitemT { private String id; private Long orderid; private Long productid; private Long goodsid; private Integer num; private Float price; private Float totalfee; private String buyerid; private String sellerid; private Date addtime; private String goodstitle; private String goodsurl; private String specstr; private String status; public String getId() { return id; } public void setId(String id) { this.id = id; } public Long getOrderid() { return orderid; } public void setOrderid(Long orderid) { this.orderid = orderid; } public Long getProductid() { return productid; } public void setProductid(Long productid) { this.productid = productid; } public Long getGoodsid() { return goodsid; } public void setGoodsid(Long goodsid) { this.goodsid = goodsid; } public Integer getNum() { return num; } public void setNum(Integer num) { this.num = num; } public Float getPrice() { return price; } public void setPrice(Float price) { this.price = price; } public Float getTotalfee() { return totalfee; } public void setTotalfee(Float totalfee) { this.totalfee = totalfee; } public String getBuyerid() { return buyerid; } public void setBuyerid(String buyerid) { this.buyerid = buyerid; } public String getSellerid() { return sellerid; } public void setSellerid(String sellerid) { this.sellerid = sellerid; } public Date getAddtime() { return addtime; } public void setAddtime(Date addtime) { this.addtime = addtime; } public String getGoodstitle() { return goodstitle; } public void setGoodstitle(String goodstitle) { this.goodstitle = goodstitle; } public String getGoodsurl() { return goodsurl; } public void setGoodsurl(String goodsurl) { this.goodsurl = goodsurl; } public String getSpecstr() { return specstr; } public void setSpecstr(String specstr) { this.specstr = specstr; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
package com.example.onemap; import java.util.Locale; public class Layer { private String id; private String layerName; private int layerSize; private String lDesc; private String display; private String createAt; public Layer() { } public Layer(String layerName, int layerSize,String desciption, String display, String pDesc, String styleLink, String createAt) { super(); this.layerName = layerName; this.layerSize = layerSize; this.lDesc = desciption; this.display = display; this.createAt = createAt; } public String toString() { return String.format(Locale.getDefault(), "[Id: %s,LayerName: %s,LayerSize: %s, LDesc: %s, Display: %s , CreateAt: %s]", id, layerName,layerSize, lDesc, display, createAt); } public String getId() { return id; } public String getLayerName() { return layerName; } public int getLayerSize(){ return layerSize; } public String getDesc() { return lDesc; } public String getDisplay() { return display; } public String getCreateAt() { return createAt; } /** * 不要自己設id,dbHepler會幫忙自動設定 */ public void setId(String id) { this.id = id; } public void setLayerName(String layerName) { this.layerName = layerName; } public void setLayerSize(int size){ this.layerSize = size; } public void setLDesc(String description) { this.lDesc = description; } public void setDisplay(String display) { this.display = display; } /** * set dataTime from OtherTools.get */ public void setCreateAt(String createAt) { this.createAt = createAt; } }
package co.company.spring.controller; import lombok.Data; @Data public class SlipVO { String slipAmount; String salDt; String customer; String bankAcct; }
package com.xinyuf.activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.TextView; import com.xinyuf.bean.Article; import com.xinyuf.job.ArticleContentJob; import com.xinyuf.view.ObservableScrollView; import com.xinyuf.wsh.App; import com.xinyuf.wsh.R; import org.litepal.crud.DataSupport; public class ContentActivity extends AppCompatActivity { private ObservableScrollView scrollView; private TextView mTitle; private TextView mAuthor; private WebView mContent; private ProgressBar mLoading; private Article article; private ImageButton mFab; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_content); article = (Article) this.getIntent().getSerializableExtra("article"); initToolBar(); scrollView = (ObservableScrollView) this.findViewById(R.id.scrollView); mContent = (WebView) this.findViewById(R.id.content); mTitle = (TextView) this.findViewById(R.id.title); mAuthor = (TextView) this.findViewById(R.id.author); mLoading = (ProgressBar) this.findViewById(R.id.loading); if (article != null) { mTitle.setText(article.getTitle()); mAuthor.setText(article.getAuthor() + " " + article.getDate()); } mContent.getSettings().setJavaScriptEnabled(true); mContent.getSettings().setSupportZoom(false); mContent.getSettings().setBuiltInZoomControls(false); mContent.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS); mContent.getSettings().setDefaultFontSize(18); mContent.getSettings().setDefaultTextEncodingName("UTF-8"); mContent.getSettings().setUseWideViewPort(true); mContent.getSettings().setLoadsImagesAutomatically(true); mContent.setHorizontalScrollbarOverlay(false); ArticleContentJob job = new ArticleContentJob(article, new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 1: mLoading.setVisibility(View.GONE); if (mContent != null) { article = DataSupport.find(Article.class, article.getId()); Log.v("content", article.getContent()); mContent.loadData(article.getContent(), "text/html; charset=UTF-8", null); } break; case -1: mLoading.setVisibility(View.GONE); if (mContent != null) { mContent.loadData(getString(R.string.loading_error), "text/html; charset=UTF-8", null); } break; } } }); App.getInstance().getJobManager().addJobInBackground(job); mLoading.setVisibility(View.VISIBLE); //scrollview scrollView.setOnScrollViewListener(new ObservableScrollView.OnScrollViewListener() { @Override public void onScrollChanged(int x, int y, int oldx, int oldy) { } @Override public void onScrollTop() { } @Override public void onScrollBottom() { } }); //fab_circle_menu mFab = (ImageButton) this.findViewById(R.id.fab); } private void initToolBar() { Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar); // App Logo setSupportActionBar(mToolbar); //Navigation Icon getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用 getSupportActionBar().setDisplayHomeAsUpEnabled(true); mToolbar.setNavigationIcon(R.mipmap.ic_back); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_content, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } if (id == R.id.action_share) { return true; } return super.onOptionsItemSelected(item); } }
package com.wangzhu.jms; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MyMessageListener implements MessageListener { private static final Logger logger = LoggerFactory .getLogger(MyMessageListener.class); public void onMessage(Message message) { TextMessage msg = null; if (message instanceof TextMessage) { msg = (TextMessage) message; try { MyMessageListener.logger.info("Reading message:{}", msg.getText()); } catch (JMSException e) { e.printStackTrace(); } } else { MyMessageListener.logger.info("Message of wrong type:{}", message .getClass().getName()); } } }
package com.angular.angular.entity; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import java.io.Serializable; import java.util.UUID; @Setter @Getter @NoArgsConstructor @Entity(name = "ProductEntity") @Table(name = "products") public class ProductEntity implements Serializable { @Id private String id = UUID.randomUUID().toString().replace("-", "").substring(0, 16); @Column(nullable = false, length = 25) private String productName; @Column(nullable = false) private String productImages; @ManyToOne @JoinColumn(name = "category_id") private CategoryEntity category; }
package com.yc.education.mapper.stock; import com.yc.education.model.stock.StockOutSale; import com.yc.education.util.MyMapper; import org.apache.ibatis.annotations.Param; import java.util.List; public interface StockOutSaleMapper extends MyMapper<StockOutSale> { /** * @Author BlueSky * @Description //TODO 通过销货单号查找销货出货单 * @Date 15:02 2019/4/4 **/ StockOutSale getStockOutSaleBySaleNo(@Param("saleNo") String saleNo); /** * 查询最大订单号 * @return */ String getMaxOrderNo(); /** * 查询全部订单 * @return */ List<StockOutSale> listStockOutSaleAll(@Param("text") String text); /** * 根据订货单号查询 * @param orderno * @return */ StockOutSale getStockOutSale(@Param("orderno") String orderno); /** * 最后一条数据 * @return */ StockOutSale getLastStockOutSale(); /** * 第一条数据 * @return */ StockOutSale getFirstStockOutSale(); /** * 获取上下页数据 * @return */ StockOutSale getStockOutSaleByPage(@Param("page") int page, @Param("rows")int rows); /** * 统计订单数量 * @return */ int getStockOutSaleCount(); /** * 查询未审核数据 * @return */ List<StockOutSale> listStockOutSaleNotSh(); /** * 根据销货单号查询 * @param outboundNo * @return */ StockOutSale getStockOutSaleByOutboundNo(@Param("outboundNo") String outboundNo); }
package com.zantong.mobilecttx.card.activity; import android.content.Context; import android.content.Intent; import android.text.Html; import android.text.TextUtils; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.zantong.mobilecttx.BuildConfig; import com.zantong.mobilecttx.R; import com.zantong.mobilecttx.api.CallBack; import com.zantong.mobilecttx.api.CarApiClient; import com.zantong.mobilecttx.api.FileDownloadApi; import com.zantong.mobilecttx.api.HandleCTCardApiClient; import com.zantong.mobilecttx.base.activity.BaseMvpActivity; import com.zantong.mobilecttx.base.basehttprequest.Retrofit2Utils; import com.zantong.mobilecttx.base.bean.BaseResult; import com.zantong.mobilecttx.base.bean.Result; import com.zantong.mobilecttx.base.interf.IBaseView; import com.zantong.mobilecttx.card.bean.YingXiaoResult; import com.zantong.mobilecttx.card.dto.ApplyCTCardDTO; import com.zantong.mobilecttx.card.dto.CheckCtkDTO; import com.zantong.mobilecttx.card.dto.QuickApplyCardDTO; import com.zantong.mobilecttx.card.dto.YingXiaoDataDTO; import com.zantong.mobilecttx.common.Config; import com.zantong.mobilecttx.common.PublicData; import com.zantong.mobilecttx.common.activity.CommonTwoLevelMenuActivity; import com.zantong.mobilecttx.common.bean.CommonTwoLevelMenuBean; import com.zantong.mobilecttx.presenter.HelpPresenter; import com.zantong.mobilecttx.user.dto.CancelRechargeOrderDTO; import com.zantong.mobilecttx.utils.ReadFfile; import cn.qqtheme.framework.util.ToastUtils; import com.zantong.mobilecttx.utils.dialog.NetLocationDialog; import com.zantong.mobilecttx.utils.rsa.RSAUtils; import com.zantong.mobilecttx.widght.SettingItemView; import com.zantong.mobilecttx.widght.UISwitchButton; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import butterknife.Bind; import butterknife.OnClick; import cn.qqtheme.framework.util.FileUtils; import cn.qqtheme.framework.util.log.LogUtils; import okhttp3.ResponseBody; import retrofit2.Response; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class ApplyCardFourStepActvity extends BaseMvpActivity<IBaseView, HelpPresenter> implements HandleCTCardApiClient.ResultInterface { @Bind(R.id.activity_apply_four_huaikuan_type) SettingItemView mHuaikuanType; //自动还款 @Bind(R.id.activity_apply_four_bank_card) EditText mBankCard; //银行卡号 @Bind(R.id.activity_apply_four_open_email) UISwitchButton mOpenEmail; //是否开启邮件对账 @Bind(R.id.activity_apply_four_mail) EditText mMail; //邮箱 @Bind(R.id.activity_apply_four_open_balance) UISwitchButton mOpenBalance; //是否开启余额变动提醒 @Bind(R.id.activity_apply_four_lingka_wangdian) SettingItemView mLingkaWangdian; //领卡网点 @Bind(R.id.activity_apply_four_fangchan_info) EditText mFangchanInfo; //房产信息 @Bind(R.id.activity_apply_four_car_num) EditText mCarNum; //车牌号 @Bind(R.id.apply_four_hint) TextView mHint; //车牌号 @Bind(R.id.four_next) Button mNext; @Bind(R.id.activity_apply_four_yingxiao) EditText mYingxiao; //营销代码 private ApplyCTCardDTO applyCTCardDTO; private QuickApplyCardDTO quickApplyCardDTO; //快捷 private int form;//1 快捷办卡 private String wangdianAdress; private InputStream is; private FileOutputStream fos; private String mEmpNum;//获取的营销代码 public static Intent getIntent(Context context, String fileNum, String name, String idCard, String yXdate) { Intent intent = new Intent(context, ApplyCardFourStepActvity.class); intent.putExtra("filenum", fileNum); intent.putExtra("name", name); intent.putExtra("idCard", idCard); intent.putExtra("date", yXdate); intent.putExtra("form", 1); return intent; } @Override public void initView() { mOpenBalance.setClickable(true); } @Override public void initData() { setTitleText("申办畅通卡"); mHint.setText(Html.fromHtml(getResources().getString(R.string.apply_four_hint))); form = getIntent().getIntExtra("form", 0); if (form == 1) { quickApplyCardDTO = new QuickApplyCardDTO(); mHuaikuanType.setFocusable(false); mHuaikuanType.setFocusableInTouchMode(false); mHuaikuanType.setClickable(false); initQuickValue(); } else { applyCTCardDTO = (ApplyCTCardDTO) getIntent().getSerializableExtra("data"); mHuaikuanType.setFocusable(true); mHuaikuanType.setFocusableInTouchMode(true); mHuaikuanType.setClickable(true); initValue(); } getYingCode(); } /** * 快捷办卡赋初始值 */ private void initQuickValue() { quickApplyCardDTO.setCtftp("0"); quickApplyCardDTO.setUsrname(getIntent().getStringExtra("name")); quickApplyCardDTO.setUsrid(PublicData.getInstance().mLoginInfoBean.getUsrid()); quickApplyCardDTO.setCtfnum(RSAUtils.strByEncryption(getIntent().getStringExtra("idCard"), true)); quickApplyCardDTO.setFilenum(RSAUtils.strByEncryption(getIntent().getStringExtra("filenum"), true)); quickApplyCardDTO.setPhoenum(RSAUtils.strByEncryption(PublicData.getInstance().mLoginInfoBean.getPhoenum(), true)); quickApplyCardDTO.setCtfvldprd(getIntent().getStringExtra("date")); quickApplyCardDTO.setActnotf("0");//默认不开启自动还款 quickApplyCardDTO.setElecbillsign("0"); quickApplyCardDTO.setAutcrepymtmth("0");//9 mHuaikuanType.setRightText("人民币自动转存"); mHuaikuanType.setRightTextColor(getResources().getColor(R.color.gray_25)); mOpenBalance.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { quickApplyCardDTO.setActnotf("1"); } else { quickApplyCardDTO.setActnotf("0"); } } }); mOpenEmail.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { quickApplyCardDTO.setElecbillsign("1"); } else { quickApplyCardDTO.setElecbillsign("0"); } } }); } /** * 赋初始值 */ private void initValue() { applyCTCardDTO.setActnotf("1"); applyCTCardDTO.setElecbillsign("0"); applyCTCardDTO.setAutcrepymtmth("9"); mHuaikuanType.setRightText("不开通"); mHuaikuanType.setRightTextColor(getResources().getColor(R.color.gray_25)); mOpenBalance.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { applyCTCardDTO.setActnotf("1"); } else { applyCTCardDTO.setActnotf("0"); } } }); mOpenEmail.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { applyCTCardDTO.setElecbillsign("1"); } else { applyCTCardDTO.setElecbillsign("0"); } } }); } @OnClick({R.id.activity_apply_four_huaikuan_type, R.id.activity_apply_four_lingka_wangdian, R.id.four_next}) public void onClick(View view) { switch (view.getId()) { case R.id.activity_apply_four_huaikuan_type: startActivityForResult(CommonTwoLevelMenuActivity.getIntent(this, 9), 10009); break; case R.id.activity_apply_four_lingka_wangdian: lingQuWangDianDialog(); break; case R.id.four_next: checkData(); break; } } /** * 检测数据 */ private void checkData() { // if (applyCTCardDTO.getElecbillsign().equals("1")) { // ToastUtils.showShort(this, "您已开通Email对账单请填写邮箱地址"); // return; // } String email = mMail.getText().toString(); if ("".equals(email)){ email = "690635872@qq.com"; } // if (TextUtils.isEmpty(email)) { // ToastUtils.showShort(this, "邮箱不可为空"); // return; // } String bankData = mBankCard.getText().toString(); //autcrepymtmth 0是开通提醒 9是不开通 if (form == 1) { if (TextUtils.isEmpty(bankData)) { ToastUtils.showShort(this, "自动还款转出卡号不可为空"); return; } if (TextUtils.isEmpty(quickApplyCardDTO.getGetbrno())) { ToastUtils.showShort(this, "请选择领卡网点"); return; } quickApplyCardDTO.setTurnoutacnum(bankData); quickApplyCardDTO.setElecmail(email); if (TextUtils.isEmpty(quickApplyCardDTO.getDscode()) && TextUtils.isEmpty(quickApplyCardDTO.getDscodegs())) { quickApplyCardDTO.setDscode("TZ666666"); quickApplyCardDTO.setDscodegs("TZ666666"); } } else { if ("0".equals(applyCTCardDTO.getAutcrepymtmth()) && TextUtils.isEmpty(bankData)) { ToastUtils.showShort(this, "自动还款转出卡号不可为空"); return; } if (TextUtils.isEmpty(applyCTCardDTO.getGetbrno())) { ToastUtils.showShort(this, "请选择领卡网点"); return; } applyCTCardDTO.setTurnoutacnum(bankData); applyCTCardDTO.setElecmail(email); if (TextUtils.isEmpty(applyCTCardDTO.getDscode()) && TextUtils.isEmpty(applyCTCardDTO.getDscodegs())) { applyCTCardDTO.setDscode("TZ666666"); applyCTCardDTO.setDscodegs("TZ666666"); } } commitInfo(); } /** * 得到营销代码 */ private void getYingCode() { CancelRechargeOrderDTO dto = new CancelRechargeOrderDTO(); CarApiClient.getYingXiaoCode(this, dto, new CallBack<YingXiaoResult>() { @Override public void onSuccess(YingXiaoResult result) { if (result.getResponseCode() == 2000) { mEmpNum = result.getData().getEmpNum(); mYingxiao.setText(mEmpNum); if (form == 1){//快捷办卡 quickApplyCardDTO.setDscode(result.getData().getEmpNum()); quickApplyCardDTO.setDscodegs(result.getData().getEmpNum()); }else{ applyCTCardDTO.setDscode(result.getData().getEmpNum()); applyCTCardDTO.setDscodegs(result.getData().getEmpNum()); } } } @Override public void onError(String errorCode, String msg) { super.onError(errorCode, msg); } }); } /** * 领取网点dialog */ private void lingQuWangDianDialog() { try { NetLocationDialog dialog = new NetLocationDialog(this, null, new NetLocationDialog.OnChooseDialogListener() { @Override public void back(String[] data) { String address = data[0] + data[2]; wangdianAdress = address; if (address.length() > 20) { address = address.substring(0, 20) + "..."; } mLingkaWangdian.setRightText(address); mLingkaWangdian.setRightTextColor(getResources().getColor(R.color.gray_25)); if (form == 1) { quickApplyCardDTO.setGetbrno(data[1]); } else { applyCTCardDTO.setGetbrno(data[1]); } } }); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.show(); } catch (Exception e) { e.printStackTrace(); downloadTxt(); ToastUtils.showShort(this, "获取网点失败,正在为你重新获取"); } } /** * 提交办卡信息 */ private void commitInfo() { showDialogLoading(); if (form == 1) { HandleCTCardApiClient.htmlLocal(this, "cip.cfc.u010.01", quickApplyCardDTO, this); } else { HandleCTCardApiClient.htmlLocal(this, "cip.cfc.u007.01", applyCTCardDTO, this); } } /** * 申办畅通卡时间校验接口 */ private void checkCtkDate() { CheckCtkDTO checkCtkDTO = new CheckCtkDTO(); if (form == 1) { //checkCtkDTO.setApplyCode(quickApplyCardDTO.getFilenum()); //已经加密 checkCtkDTO.setApplyCode(PublicData.getInstance().filenum); } else { //checkCtkDTO.setApplyCode(applyCTCardDTO.getFilenum()); //已经加密 checkCtkDTO.setApplyCode(PublicData.getInstance().filenum); } checkCtkDTO.setApplyInterface("banka"); checkCtkDTO.setFlag("1"); CarApiClient.checkCtk(this, checkCtkDTO, new CallBack<BaseResult>() { @Override public void onSuccess(BaseResult result) { hideDialogLoading(); if (result.getResponseCode() == 2000) { commitInfo(); } else { ToastUtils.showShort(ApplyCardFourStepActvity.this, "七天之内不能重复办卡"); } } }); } @Override public void resultSuccess(Result result) { hideDialogLoading(); if (result.getSYS_HEAD().getReturnCode().equals("000000")) { commitYingXiaoDataForLYT(); checkCtkDate(); startActivity(ApplySuccessActvity.getIntent(this, wangdianAdress)); } } @Override public void resultError(String msg) { hideDialogLoading(); Toast.makeText(ApplyCardFourStepActvity.this, Config.getErrMsg("1"), Toast.LENGTH_SHORT).show(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 10009 && resultCode == 1009 && data != null) { CommonTwoLevelMenuBean commonTwoLevelMenuBean = (CommonTwoLevelMenuBean) data.getSerializableExtra("data"); ToastUtils.showShort(this,"选择了"+commonTwoLevelMenuBean.getId()); if (form == 1){ quickApplyCardDTO.setAutcrepymtmth(String.valueOf(commonTwoLevelMenuBean.getId())); }else{ applyCTCardDTO.setAutcrepymtmth(String.valueOf(commonTwoLevelMenuBean.getId())); } mHuaikuanType.setRightText(commonTwoLevelMenuBean.getContext()); mHuaikuanType.setRightTextColor(getResources().getColor(R.color.gray_25)); } } /** * 办卡申请成功后,提交营销代码 */ private void commitYingXiaoDataForLYT(){ YingXiaoDataDTO dto = new YingXiaoDataDTO(); dto.setUsrnum(RSAUtils.strByEncryption(PublicData.getInstance().userID,true)); if (TextUtils.isEmpty(mYingxiao.getText().toString())){ dto.setEmpNum(mEmpNum); }else{ dto.setEmpNum(mYingxiao.getText().toString()); } CarApiClient.commitYingXiaoData(this, dto, new CallBack<BaseResult>() { @Override public void onSuccess(BaseResult result) { if (result.getResponseCode() == 2000){ ToastUtils.showShort(ApplyCardFourStepActvity.this,"已提交营销代码"); } } }); } /** * 下载文件txt */ public void downloadTxt() { Observable .create(new Observable.OnSubscribe<String>() { @Override public void call(Subscriber<? super String> subscriber) { downloadFile(subscriber); } }) .subscribeOn(Schedulers.io()) // .sample(1, TimeUnit.SECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<String>() { @Override public void onCompleted() { PublicData.getInstance().mNetLocationBean = ReadFfile.readNetLocationFile(getApplicationContext()); } @Override public void onError(Throwable e) { LogUtils.e(e.getMessage()); } @Override public void onNext(String s) { } }); } private void downloadFile(Subscriber<? super String> subscriber) { FileDownloadApi api = new Retrofit2Utils().getRetrofitHttps(BuildConfig.APP_URL).create(FileDownloadApi.class); Response<ResponseBody> response = null; try { response = api.downloadFileWithFixedUrl("download/icbcorg.txt").execute(); } catch (IOException e) { subscriber.onError(e); } if (response != null && response.isSuccessful()) { InputStream inputStream = response.body().byteStream(); String filePath = FileUtils.icbTxtFilePath(getApplicationContext(), FileUtils.DOWNLOAD_DIR); File txtFile = new File(filePath); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(txtFile); int count; byte[] buffer = new byte[1024 * 8]; while ((count = inputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, count); } fileOutputStream.flush(); subscriber.onCompleted(); } catch (IOException e) { subscriber.onError(e); } finally { try { inputStream.close(); if (fileOutputStream != null) fileOutputStream.close(); } catch (IOException e) { subscriber.onError(e); } } } else { subscriber.onError(new Exception("银行网点接口请求异常,请退出页面稍后重试")); } } @Override public HelpPresenter initPresenter() { return new HelpPresenter(); } @Override protected int getContentResId() { return R.layout.activity_bid_four_step; } @Override protected void onDestroy() { super.onDestroy(); PublicData.getInstance().filenum = ""; } }
package com.shawnsrecords.demo.controllers; import com.shawnsrecords.demo.entities.Album; import com.shawnsrecords.demo.storage.AlbumStorage; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import java.util.Collection; @RestController public class AlbumController { // Instance Variables private AlbumStorage albumStorage; // Constructor public AlbumController(AlbumStorage albumStorage) { this.albumStorage = albumStorage; } // Getters public AlbumStorage getAlbumStorage() { return albumStorage; } // Mapping Methods @GetMapping("/api/albums") public Collection<Album> findAllAlbums() { return albumStorage.findAllAlbums(); } @GetMapping("/api/albums/{id}") public Album findAlbumById(@PathVariable long id) { return albumStorage.findAlbumById(id); } }
package com.java.method; public class Boy { static Boy obj = new Boy(); public static void main(String[] args) { Human.walk(); obj.talking(); } public void talking() { System.out.println("Boy is talking"); } }
package com.grandsea.ticketvendingapplication.view; import android.content.Context; import android.os.Handler; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.LayoutInflater; import android.widget.LinearLayout; import android.widget.TextView; import com.grandsea.ticketvendingapplication.R; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by Grandsea09 on 2017/10/7. */ public class MyTimeView extends LinearLayout { private TextView tvDate, tvMin; private Handler mHandler=new Handler(); private Runnable mRunnable ; public MyTimeView(Context context) { this(context, null); } public MyTimeView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public MyTimeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); LayoutInflater.from(context).inflate(R.layout.view_my_time, this); tvDate = ((TextView) findViewById(R.id.vmt_date)); tvMin = ((TextView) findViewById(R.id.vmt_min)); setTime(); refreshTime(1*2000); } private void setTime() { SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd HH:mm "); SimpleDateFormat formatter3 = new SimpleDateFormat("HH:mm"); Date curDate = new Date(System.currentTimeMillis());//获取当前时间 String dateStr = formatter1.format(curDate); String dateStr2 = formatter2.format(curDate); String dateStr3 = formatter3.format(curDate); tvDate.setText(dateStr+""); tvMin.setText(dateStr3+""); } private void refreshTime(final int time) { //保证只有一个mRunnable,并且使用该mRunnable调用自己,不会因为线程乱开而影响程序(导致ANR异常) mRunnable =new Runnable() { @Override public void run() { setTime(); mHandler.postDelayed(this, time); } }; mHandler.postDelayed(mRunnable,time); } public void stopRefresh(){ mHandler.removeCallbacks(mRunnable); } }
package interpreter.exceptions; public class UndefinedIdentifierException extends Throwable { }
package es.unileon.xijoja.hospital.login; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; import java.sql.SQLException; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.KeyStroke; import es.unileon.xijoja.hospital.InfoWindow; import es.unileon.xijoja.hospital.Logs; import es.unileon.xijoja.hospital.PersonalDAO; import es.unileon.xijoja.hospital.admin.AdminWindow; import es.unileon.xijoja.hospital.secretary.SecretaryWindow; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JButton; import javax.swing.JPasswordField; import javax.swing.JPopupMenu; import javax.swing.ActionMap; import javax.swing.ImageIcon; import javax.swing.InputMap; import java.awt.Color; import java.awt.Font; import java.awt.Image; @SuppressWarnings("serial") public class LoginWindow extends JFrame { private static final int PWIDTH = 750; private static final int PHEIGH = 348; private static final int WHEN_IN_FOCUSED_WINDOW = 0; private ControlerLoginWindow listener; /* LOGIN */ protected JPanel loginPanel; protected JTextField loginUser; protected JPasswordField loginPassword; protected PersonalDAO dao; protected JLabel lblLoginError; private Logs log = new Logs(); public LoginWindow() throws IOException { log.InfoLog("SE INICIA LA PANTALLA DE LOGIN"); getContentPane().setBackground(Color.WHITE); setBackground(Color.WHITE); this.listener = new ControlerLoginWindow(this); setBounds(1024 / 4, 768 / 6, PWIDTH, PHEIGH); setUndecorated(true); setTitle("Login"); try { initComponents(); } catch (IOException e) { e.printStackTrace(); } } private void initComponents() throws IOException { dao = new PersonalDAO();// LLamamos al patron getContentPane().setLayout(null); JButton crossButton = new JButton(new ImageIcon(LoginWindow.class.getResource("/resources/cross.png"))); crossButton.setBounds(720, 11, 15, 15); getContentPane().add(crossButton); crossButton.setBackground(null); crossButton.setBorder(null); crossButton.setOpaque(false); crossButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { System.exit(0); } }); JButton minButton = new JButton(new ImageIcon(LoginWindow.class.getResource("/resources/min.png"))); minButton.setBorder(null); minButton.setBackground(null); minButton.setBounds(690, 11, 15, 15); minButton.setOpaque(false); getContentPane().add(minButton); minButton.addActionListener(new ActionListener() { @SuppressWarnings("deprecation") public void actionPerformed(ActionEvent e) { setExtendedState(JFrame.CROSSHAIR_CURSOR); } }); JLabel backgroundLabel = new JLabel(new ImageIcon(LoginWindow.class.getResource("/resources/fondo.jpg"))); backgroundLabel.setBounds(218, 0, 532, 348); getContentPane().add(backgroundLabel); loginPanel = new JPanel(); loginPanel.setBackground(Color.WHITE); loginPanel.setBounds(0, 0, 750, 348); getContentPane().add(loginPanel); loginPanel.setLayout(null); JLabel iconLabel = new JLabel(new ImageIcon(LoginWindow.class.getResource("/resources/icon.png"))); iconLabel.setBounds(23, 62, 45, 45); loginPanel.add(iconLabel); loginUser = new JTextField(); loginUser.setBackground(Color.WHITE); loginUser.setBounds(83, 115, 115, 20); loginPanel.add(loginUser); loginUser.setColumns(10); loginUser.addKeyListener(listener); loginPassword = new JPasswordField(); loginPassword.setBounds(83, 146, 115, 20); loginPanel.add(loginPassword); loginPassword.addKeyListener(listener); JLabel lblUser = new JLabel("USER"); lblUser.setFont(new Font("Yu Gothic UI Semibold", Font.PLAIN, 11)); lblUser.setBounds(49, 118, 73, 14); loginPanel.add(lblUser); JLabel lblPassword = new JLabel("PASSWORD"); lblPassword.setFont(new Font("Yu Gothic UI Semibold", Font.PLAIN, 11)); lblPassword.setBounds(23, 146, 90, 14); loginPanel.add(lblPassword); JButton btnLogin = new JButton("Login"); btnLogin.setFont(new Font("Yu Gothic UI Semibold", Font.PLAIN, 11)); btnLogin.setBounds(125, 177, 73, 23); btnLogin.setBackground(null); // btnLogin.setBorder(null); btnLogin.setOpaque(false); btnLogin.addKeyListener(listener); btnLogin.addActionListener(listener); loginPanel.add(btnLogin); JButton buttonInfo = new JButton(new ImageIcon(LoginWindow.class.getResource("/resources/--ndice.png"))); buttonInfo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { InfoWindow info = new InfoWindow("general"); info.setVisible(true); } }); buttonInfo.setOpaque(false); buttonInfo.setBorder(null); buttonInfo.setBackground((Color) null); buttonInfo.setBounds(10, 314, 23, 23); loginPanel.add(buttonInfo); ImageIcon icon = new ImageIcon(LoginWindow.class.getResource("/resources/settings.png")); Image scaleImage = icon.getImage().getScaledInstance(23, 23,Image.SCALE_DEFAULT); JButton buttonSettings = new JButton(new ImageIcon(scaleImage)); buttonSettings.setOpaque(false); buttonSettings.setBorder(null); buttonSettings.setBackground((Color) null); buttonSettings.setBounds(40, 314, 23, 23); loginPanel.add(buttonSettings); JPopupMenu popupMenu = new JPopupMenu("Configuracion"); JMenuItem resetMenuItem = new JMenuItem("Resetear la base de datos"); resetMenuItem.addActionListener(listener); popupMenu.add(resetMenuItem); popupMenu.addSeparator(); JMenuItem exportMenuItem = new JMenuItem("Exportar la base de datos"); exportMenuItem.addActionListener(listener); popupMenu.add(exportMenuItem); buttonSettings.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ae) { popupMenu.show(buttonSettings, buttonSettings.getWidth()/2, buttonSettings.getHeight()/2); } } ); // buttonSettings.addActionListener(listener); lblLoginError = new JLabel(""); lblLoginError.setFont(new Font("Tahoma", Font.PLAIN, 10)); lblLoginError.setForeground(Color.RED); lblLoginError.setBounds(38, 211, 160, 14); loginPanel.add(lblLoginError); } }
package com.sirma.itt.javacourse.test.intro.task5.arrayReverse; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Arrays; import org.junit.Test; import com.sirma.itt.javacourse.intro.task5.arrayReverse.ReverseArray; /** * Unit test class for ReverseArray. * * @author simeon */ public class ReverseArrayUnitTest { private ArrayList<Integer> result = new ArrayList<Integer>(); private ArrayList<Integer> arr = new ArrayList<Integer>(); /** * Unit test for the ReverseArray. */ @Test public void testReverseArray() { result.addAll(Arrays.asList(9, 8, 7, 6, 5, 4, 3, 2, 1)); arr.addAll(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9)); ReverseArray rev = new ReverseArray(); assertEquals(result, rev.reverseArray(arr)); } }
import java.util.Arrays; public class fifth { public static void find_common_elements(char[] arr1,char[] arr2){ char[] result_arr; if(arr1.length<arr2.length) { result_arr=new char[arr1.length]; } else{ result_arr=new char[arr2.length]; } System.out.println(result_arr.length); int count=0; for(int i=0;i< arr1.length;i++){ for(int j=0;j<arr2.length;j++){ if(arr1[i]==arr2[j]){ boolean flag=true; for (int k=0;k<result_arr.length;k++){ if(result_arr[k]==arr1[i]){ flag=false; break; } } if(flag==true){ result_arr[count++]=arr1[i]; } } } } for (char c:result_arr){ if(Character.isLetter(c)) System.out.println("duplicate characters are :"+c); } } public static void main(String[] args) { String s1="ankitgupta"; String s2="aritpgupta"; find_common_elements(s1.toCharArray(),s2.toCharArray()); } }
package com.wen.test.controller; import com.wen.test.model.Users; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import java.util.ArrayList; import java.util.Date; import java.util.List; @Controller public class UserController { @RequestMapping(value = "thymeleaf") public String tesTthymeleaf(ModelMap model){ Users users= new Users(); //简单数据演示 users.setAge(100); users.setBirthday(new Date()); users.setUsername("文"); //放到mode中,这个类似于request.setAttribute()一次性使用 model.addAttribute("users",users); //模拟数据库查出来的集合。用在thymeleaf中演示 List<String> list= new ArrayList<String>(); for (int i=0;i<10;i++) { list.add("我是第"+i+"个"); } model.addAttribute("list",list); return "index"; } }
public class BuyingTshirts { public int meet(int T, int[] Q, int[] P) { int count = 0; int qMoney = 0; int pMoney = 0; for(int i = 0; i < Q.length; ++i) { qMoney += Q[i]; pMoney += P[i]; if(T <= qMoney) { qMoney -= T; if(T <= pMoney) { pMoney -= T; ++count; } } else if(T <= pMoney) { pMoney -= T; } } return count; } }
package com.codigo.smartstore.sdk.core.metrics.mass; import com.codigo.smartstore.sdk.core.metrics.IMetricDimension; import com.codigo.smartstore.sdk.core.metrics.IMetricUnit; public class MetricUnitMass implements IMetricUnit { /** * Gets the metric unit. * * @return the metric unit */ @Override public IMetricDimension getMetricUnit() { // TODO Auto-generated method stub return null; } /** * Gets the metric value. * * @return the metric value */ @Override public double getMetricValue() { // TODO Auto-generated method stub return 0; } }
package cshekhar.springboot.Rules; import cshekhar.springboot.DAO.AlertDao; import cshekhar.springboot.model.Alert; import cshekhar.springboot.model.Metric; import org.easyrules.annotation.Rule; import org.easyrules.annotation.Action; import org.easyrules.annotation.Condition; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; /** * Created by cshekhar on 7/5/17. */ @Rule(name = "overweightrule", description = "Adds the entry to alert db if person is overweight.") public class OverWeightRule { Metric metric; long base = 150; AlertDao al = new AlertDao(); public OverWeightRule(Metric metric) { this.metric = metric; } @Condition public boolean isOverWeight() { System.out.println("------------++++++++________" + base); if((float)metric.getValue() > 1.1 * base) return true; return false; } @Action public void addAlertOverweight(){ Alert alert = new Alert("OverWeight", metric.getTimeStamp(), metric.getValue()); al.create(alert); } }
import org.junit.Test; import static org.junit.Assert.*; public class OdcinekTest { @Test public void OdcinekTest() { Punkt punkt1 = new Punkt(1.0, 1.0); Odcinek odcinek = new Odcinek(punkt1, 3.0, 1.0); assertEquals(odcinek.getPunkt2().getX(), 3.0, 0.001 ); } @Test public void shiftTest() { Odcinek odcinek = new Odcinek(0,1.0,5.0,1.0); odcinek.shift(1.0, 1.0); double nowaWspolrzednaX1 = odcinek.getPunkt1().getX(); double nowaWspolrzednaX2 = odcinek.getPunkt2().getX(); assertEquals(nowaWspolrzednaX1, 1.0, 0.001); assertEquals(nowaWspolrzednaX2, 6.0, 0.001); } @Test public void pointDistanceTest() { Punkt punkt1 = new Punkt(1.0, 1.0); Punkt punkt2 = new Punkt(2.0, 2.0); Odcinek odcinek = new Odcinek(punkt1, 3.0, 1.0); assertEquals(odcinek.pointDistance(punkt2), 1.0, 0.001 ); } }
package com.sshfortress.service.init; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import com.sshfortress.dao.system.mapper.SysConfigMapper; public class SysConfig { Logger log=Logger.getLogger(SysConfig.class); public static Map<String,String> SYS_CONFIG_MAP = new HashMap<String,String>(); @Autowired private SysConfigMapper sysConfigMapper; /** * 系统启动时初始化加载配置 */ public void init() { StringBuilder sbu = new StringBuilder("SELECT id,ckey,cvalue,group_code,config_name FROM sys_config "); List<Map<String,Object>> config = sysConfigMapper.selectByAll(); for(int i=0; config!=null && !config.isEmpty() && i<config.size(); i++){ SYS_CONFIG_MAP.put(config.get(i).get("ckey").toString(), String.valueOf(config.get(i).get("cvalue"))); } System.out.print("sys_config缓存加载完成,共加载配置项:"+config.size()); log.info("sys_config缓存加载完成,共加载配置项:"+config.size()); } /** * * 描述:获取配置接口 * @param * @return String */ public static String getValue(String key){ return SYS_CONFIG_MAP.get(key); } }
package com.jpa.study.project.dto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * Created by yongyeonkim on 2017. 2. 19.. */ @Data @AllArgsConstructor @NoArgsConstructor public class MemberListDTO { private Long number; private String userId; private String userPass; private String userName; private String userPhone; private String userAddr; }
package edu.uiowa.icts.util; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.Ostermiller.util.ExcelCSVPrinter; public class CSVExport{ public CSVExport(){} private static final Log log = LogFactory.getLog(CSVExport.class); public ByteArrayOutputStream generateCSV(ArrayList<ArrayList<String>> args){ ByteArrayOutputStream csv = new ByteArrayOutputStream(); Object[] x; String[] y; try{ BufferedOutputStream out = new BufferedOutputStream(csv); ExcelCSVPrinter ex = new ExcelCSVPrinter(out); for (ArrayList<String> s : args) { x = s.toArray(); y = Arrays.asList(x).toArray(new String[x.length]); ex.writeln(y); } }catch (Exception e){ log.error("error creating csv",e); } return csv; } public String generateCSV(ArrayList<ArrayList<String>> args, boolean quote){ StringWriter stringWriter = new StringWriter(); Object[] x; String[] y; try{ ExcelCSVPrinter ex = new ExcelCSVPrinter(stringWriter, true, true); for (ArrayList<String> s : args) { x = s.toArray(); y = Arrays.asList(x).toArray(new String[x.length]); ex.writeln(y); } }catch (Exception e){ log.error("error creating csv",e); } return stringWriter.toString(); } }
package com.nepshop.controller; import com.nepshop.dao.OrderDAO; import com.nepshop.model.Order; import com.nepshop.model.OrderedProduct; import com.nepshop.model.Customer; import javax.servlet.RequestDispatcher; 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 javax.servlet.http.HttpSession; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @WebServlet("/orderservlet") public class OrderServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { HttpSession session = req.getSession(); Customer customer = (Customer) session.getAttribute("customer"); int customer_id = customer.getId(); String action = req.getParameter("action"); if (action.equals("order")) { String shipping_address = req.getParameter("shipping_address"); String phone = req.getParameter("phone"); String payment_method = req.getParameter("payment_method"); Double total_cost = Double.parseDouble(req.getParameter("total_cost")); String quantityList[] = req.getParameter("quantity_list").split(","); ; String productidList[] = req.getParameter("productid_list").split(","); int order_id = OrderDAO.createOrder(total_cost, customer_id, shipping_address, phone, payment_method); if (order_id != 0) { for (int i = 0; i < quantityList.length; i++) { int product_id = Integer.parseInt(productidList[i]); int quantity = Integer.parseInt(quantityList[i]); System.out.println(product_id + " " + quantity); boolean rs = OrderDAO.createOrderedProduct(product_id, order_id, quantity); if (rs) { session.setAttribute("flag", true); } } } RequestDispatcher rd = req.getRequestDispatcher("/includes/ecommerce/customer.jsp"); rd.forward(req, res); } else if (action.equals("display_ordered_products")) { List<OrderedProduct> orderedProducts = OrderDAO.getOrderedProduct(customer_id); session.setAttribute("flag", false); session.setAttribute("orderedProducts", orderedProducts); RequestDispatcher rd = req.getRequestDispatcher("/includes/ecommerce/orderedproduct.jsp"); rd.forward(req, res); } } void setToastMessage(HttpServletRequest req, String message, String type) { HttpSession session = req.getSession(); List<String> toast = new ArrayList<String>(Arrays.asList(message, type)); session.setAttribute("toast", toast); } }
package com.itheima.day_02.homework.feeder; public interface Swimming { public abstract void swim(); }
import java.util.*; import java.io.*; class Main { public static void main (String[] args) { Scanner sc=new Scanner(System.in); while(sc.hasNext()) { int k=sc.nextInt(),c=0; for(int i=k+1;i<=2*k;i++) { if((i*k)%(i-k)==0) c++; } System.out.println(c); for(int i=k+1;i<=2*k;i++) { if((i*k)%(i-k)==0) System.out.println("1/"+k+" = 1/"+(i*k)/(i-k)+" + 1/"+i); } } } }
package com.bs.guestbook.Controller; import javax.servlet.http.HttpServletRequest; import com.bs.guestbook.dao.Factory; import com.bs.guestbook.entity.Customer; import com.bs.guestbook.jsonview.Views; import com.bs.guestbook.model.AjaxResponseBody; import com.bs.guestbook.model.SearchCriteria; import com.fasterxml.jackson.annotation.JsonView; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import java.sql.SQLException; import java.util.List; @Controller @RequestMapping("/customers") public class CustomerController { private final String CUSTOMER_PAGE = "/customers/index"; // список всех закащиков private final String REDIRECT_CUSTOMERS = "redirect:/customers/index"; private final String REDIRECT_PAGE_ADD = "redirect:/customers/add"; private final String REDIRECT_PAGE_CUSTOMER = "redirect:/customers/index"; private final String CUSTOMERS_PAGE = "customers/customersPage"; private final String ADD_PAGE = "customers/addCustomer"; private final String EDIT_PAGE = "customers/editCustomer"; @Autowired private Factory factory; @RequestMapping(value = "/index", method = RequestMethod.GET) public String getCustomers(@RequestParam(value = "sortColumn", required = false) String sortColumn, @RequestParam(value = "pageNumber", required = false) String pageNumber, Model model) throws SQLException { List<Customer> customerList; if (sortColumn == null) { if (!(pageNumber == null)) { factory.getCustomerDao().setSelectedPageNumber(Integer.valueOf(pageNumber)); } customerList = factory.getCustomerDao().getAllCustomers(); } else { customerList = factory.getCustomerDao().getCustomersSortBy(sortColumn); } model.addAttribute("urlPage", CUSTOMER_PAGE + "?pageNumber="); model.addAttribute("selectedPageNumber", factory.getCustomerDao().getSelectedPageNumber()); model.addAttribute("pageNumber", factory.getCustomerDao().getPageNumberList()); model.addAttribute("customers", customerList); return CUSTOMER_PAGE; } @RequestMapping(value = "/customer", method = RequestMethod.GET) public String getCustomer(@RequestParam(value = "id", required = true) Integer id, Model model) throws SQLException { if (id != null) { Customer customer = factory.getCustomerDao().getCustomerById(id); if (customer == null) { return REDIRECT_PAGE_ADD + "?id=" + id; } else { model.addAttribute("customerID", id); model.addAttribute("customer", customer); return CUSTOMERS_PAGE; } } else { return CUSTOMER_PAGE; } } @RequestMapping(value = "/add", method = RequestMethod.GET) public String getPageAdd(Model model) throws SQLException { model.addAttribute("customer", new Customer()); return ADD_PAGE; } @RequestMapping(value = "/add", method = RequestMethod.POST) // public String addNewCustomer(@ModelAttribute("customer") Customer customer) throws SQLException { public @ResponseBody AjaxResponseBody addNewCustomer(@RequestBody Customer customer) { AjaxResponseBody result = new AjaxResponseBody(); if (!customer.getName().isEmpty() && !customer.getCompanyName().isEmpty()) { try { factory.getCustomerDao().addCustomer(customer); result.setUrl(CUSTOMER_PAGE); result.setOk(true); } catch (SQLException e) { result.setOk(false); result.setMsg(e.getMessage()); } } return result; } @RequestMapping(value = "/delete", method = RequestMethod.GET) public String deleteCustomer(@RequestParam(value = "id", required = true) Integer id, Model model) throws SQLException { Customer customer = factory.getCustomerDao().getCustomerById(id); if (customer != null) factory.getCustomerDao().deleteCustomer(customer); model.addAttribute("id", id); // Add id reference to Model return REDIRECT_CUSTOMERS; } @RequestMapping(value = "/edit", method = RequestMethod.GET) public String getEditPage(@RequestParam(value = "id", required = true) Integer id, Model model) throws SQLException { model.addAttribute("customerAttribute", factory.getCustomerDao().getCustomerById(id)); return EDIT_PAGE; } @RequestMapping(value = "/edit", method = RequestMethod.POST) public String editCustomer(@ModelAttribute("customerAttribute") Customer customer, @RequestParam(value = "id", required = true) Integer id, Model model) throws SQLException { factory.getCustomerDao().updateCustomer(customer); return REDIRECT_CUSTOMERS; } @RequestMapping(value = "/checkIsExistCustomer", method = RequestMethod.POST) public @ResponseBody AjaxResponseBody checkIsExist(@RequestBody SearchCriteria search) throws SQLException { AjaxResponseBody result = new AjaxResponseBody(); result.setOk(false); if (isValidSearchCriteria(search)) { result.setCode("200"); if (!(factory.getCustomerDao().getCustomerByName(search.getUsername()) == null)) { result.setMsg("Customer already exist"); result.setOk(true); } } else { result.setCode("400"); result.setMsg("Search criteria is empty!"); } return result; } private boolean isValidSearchCriteria(SearchCriteria search) { boolean valid = true; if (search == null) { valid = false; } if ((StringUtils.isEmpty(search.getUsername()))) { valid = false; } return valid; } public String getCurrentLoggedUsername() { return SecurityContextHolder.getContext().getAuthentication().getName(); } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.socket.sockjs.client; import java.net.URI; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.lang.Nullable; import org.springframework.web.client.HttpServerErrorException; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.sockjs.frame.SockJsFrame; import org.springframework.web.socket.sockjs.transport.TransportType; /** * Abstract base class for XHR transport implementations to extend. * * @author Rossen Stoyanchev * @since 4.1 */ public abstract class AbstractXhrTransport implements XhrTransport { protected static final String PRELUDE; static { byte[] bytes = new byte[2048]; Arrays.fill(bytes, (byte) 'h'); PRELUDE = new String(bytes, SockJsFrame.CHARSET); } protected final Log logger = LogFactory.getLog(getClass()); private boolean xhrStreamingDisabled; @Override public List<TransportType> getTransportTypes() { return (isXhrStreamingDisabled() ? Collections.singletonList(TransportType.XHR) : Arrays.asList(TransportType.XHR_STREAMING, TransportType.XHR)); } /** * An {@code XhrTransport} can support both the "xhr_streaming" and "xhr" * SockJS server transports. From a client perspective there is no * implementation difference. * <p>Typically an {@code XhrTransport} is used as "XHR streaming" first and * then, if that fails, as "XHR". In some cases however it may be helpful to * suppress XHR streaming so that only XHR is attempted. * <p>By default this property is set to {@code false} which means both * "XHR streaming" and "XHR" apply. */ public void setXhrStreamingDisabled(boolean disabled) { this.xhrStreamingDisabled = disabled; } /** * Whether XHR streaming is disabled or not. */ @Override public boolean isXhrStreamingDisabled() { return this.xhrStreamingDisabled; } // Transport methods @Override public CompletableFuture<WebSocketSession> connectAsync(TransportRequest request, WebSocketHandler handler) { CompletableFuture<WebSocketSession> connectFuture = new CompletableFuture<>(); XhrClientSockJsSession session = new XhrClientSockJsSession(request, handler, this, connectFuture); request.addTimeoutTask(session.getTimeoutTask()); URI receiveUrl = request.getTransportUrl(); if (logger.isDebugEnabled()) { logger.debug("Starting XHR " + (isXhrStreamingDisabled() ? "Polling" : "Streaming") + "session url=" + receiveUrl); } HttpHeaders handshakeHeaders = new HttpHeaders(); handshakeHeaders.putAll(request.getHandshakeHeaders()); connectInternal(request, handler, receiveUrl, handshakeHeaders, session, connectFuture); return connectFuture; } @Deprecated protected void connectInternal(TransportRequest request, WebSocketHandler handler, URI receiveUrl, HttpHeaders handshakeHeaders, XhrClientSockJsSession session, org.springframework.util.concurrent.SettableListenableFuture<WebSocketSession> connectFuture) { throw new UnsupportedOperationException("connectInternal has been deprecated in favor of connectInternal"); } protected abstract void connectInternal(TransportRequest request, WebSocketHandler handler, URI receiveUrl, HttpHeaders handshakeHeaders, XhrClientSockJsSession session, CompletableFuture<WebSocketSession> connectFuture); // InfoReceiver methods @Override public String executeInfoRequest(URI infoUrl, @Nullable HttpHeaders headers) { if (logger.isDebugEnabled()) { logger.debug("Executing SockJS Info request, url=" + infoUrl); } HttpHeaders infoRequestHeaders = new HttpHeaders(); if (headers != null) { infoRequestHeaders.putAll(headers); } ResponseEntity<String> response = executeInfoRequestInternal(infoUrl, infoRequestHeaders); if (response.getStatusCode() != HttpStatus.OK) { if (logger.isErrorEnabled()) { logger.error("SockJS Info request (url=" + infoUrl + ") failed: " + response); } throw new HttpServerErrorException(response.getStatusCode()); } if (logger.isTraceEnabled()) { logger.trace("SockJS Info request (url=" + infoUrl + ") response: " + response); } String result = response.getBody(); return (result != null ? result : ""); } protected abstract ResponseEntity<String> executeInfoRequestInternal(URI infoUrl, HttpHeaders headers); // XhrTransport methods @Override public void executeSendRequest(URI url, HttpHeaders headers, TextMessage message) { if (logger.isTraceEnabled()) { logger.trace("Starting XHR send, url=" + url); } ResponseEntity<String> response = executeSendRequestInternal(url, headers, message); if (response.getStatusCode() != HttpStatus.NO_CONTENT) { if (logger.isErrorEnabled()) { logger.error("XHR send request (url=" + url + ") failed: " + response); } throw new HttpServerErrorException(response.getStatusCode()); } if (logger.isTraceEnabled()) { logger.trace("XHR send request (url=" + url + ") response: " + response); } } protected abstract ResponseEntity<String> executeSendRequestInternal( URI url, HttpHeaders headers, TextMessage message); }
package Codigo1Calculadora; import javafx.application.Application; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.stage.Stage; public class Calculadora extends Application { private double numero1; private String operacion; private Stage ventana; @FXML private TextField display; @FXML void accionBasica(ActionEvent event) { numero1 = Double.valueOf(display.getText()); display.setText("0"); operacion = ((Button)event.getSource()) .getText(); } @FXML void accionIgual(ActionEvent event) { double numero2 = Double.valueOf(display.getText()); double resultado=0; switch (operacion) { case "+": resultado = numero1 + numero2; break; case "-": resultado = numero1 - numero2; break; case "*": resultado = numero1 * numero2; break; case "/": resultado = numero1 / numero2; break; } display.setText(String.valueOf(resultado)); } @FXML void agregaDigito(ActionEvent event) { Button boton = (Button)event.getSource(); String digito = boton.getText(); if(display.getText().equalsIgnoreCase("0")) { display.setText(digito); } else { display.setText(display.getText()+digito); } } @FXML void agregaPunto(ActionEvent event) { if( display.getText().contains(".") == false ) { display.setText(display.getText()+"."); } } @FXML void salir(ActionEvent event) { Platform.exit(); } @FXML void limpiarEntrada(ActionEvent event) { display.setText("0"); } @FXML void limpiarTodo(ActionEvent event) { numero1 = 0; operacion= ""; display.setText("0"); } @Override public void start(Stage primaryStage) throws Exception { ventana = primaryStage; Parent layout = FXMLLoader.load(getClass().getResource("Calculadora.fxml")); Scene scene = new Scene(layout); ventana.setScene(scene); ventana.setTitle("Calculadora Básica"); ventana.show(); } }
package com.adi.ho.jackie.versa_news.Youtube; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import com.adi.ho.jackie.versa_news.R; import com.adi.ho.jackie.versa_news.RecyclerViewStuff.YoutubeRecyclerAdapter; import com.google.android.youtube.player.YouTubeBaseActivity; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubePlayer; import com.google.android.youtube.player.YouTubePlayerView; import com.google.android.youtube.player.YouTubeStandalonePlayer; import com.google.api.services.youtube.YouTube; import com.google.api.services.youtube.model.Playlist; import java.util.ArrayList; public class PlayVideos extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener{ private YouTube youtube; private YouTube.Search.List query; private YouTubePlayerView playerView; private ArrayList<Playlist> mPlayListArrayList; public YoutubeHelper helper; ListView mVideosList; ArrayList<VideoItem> mVideos; private RecyclerView videoRecycler; // Your developer key goes here public static final String KEY = "AIzaSyCp4VCk-TmZPT82SmD_XISh4fx1oz8S_JE"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_play_videos); videoRecycler = (RecyclerView)findViewById(R.id.player_view); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(PlayVideos.this); videoRecycler.setHasFixedSize(true); videoRecycler.setLayoutManager(linearLayoutManager); mVideos= new ArrayList<>(); LoadYoutubeTask load= new LoadYoutubeTask(); load.execute(); // mVideosList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.d("id",mVideos.get(position).getId()); Intent intent = YouTubeStandalonePlayer.createPlaylistIntent(PlayVideos.this, KEY, mVideos.get(position).getId()); startActivity(intent); // Intent intent = new Intent(PlayVideos.this, PlayVideos.class); // intent.putExtra("video", mVideos.get(position).getId()); } }); } @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean restored) { if(!restored){ youTubePlayer.cueVideo(getIntent().getStringExtra("video")); } } @Override public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) { Toast.makeText(this, getString(R.string.failed), Toast.LENGTH_LONG).show(); } public ArrayList<Playlist> getVideosList(){ helper= new YoutubeHelper(PlayVideos.this); mPlayListArrayList = new ArrayList<>(); mPlayListArrayList = helper.getPlaylist(); for (Playlist playlist : mPlayListArrayList) { VideoItem videoItem = new VideoItem(); try{ videoItem.setThumbnailURL(playlist.getSnippet().getThumbnails().getStandard().getUrl()); }catch (Throwable throwable){ videoItem.setThumbnailURL("http://images.fineartamerica.com/images-medium-large/2-nyc-empire-nina-papiorek.jpg"); } videoItem.setId(playlist.getId()); Log.d("Video",videoItem.getId()); videoItem.setTitle(playlist.getSnippet().getTitle()); videoItem.setDescription(playlist.getSnippet().getDescription()); mVideos.add(videoItem); }return mPlayListArrayList; } public class LoadYoutubeTask extends AsyncTask<Void, Void, ArrayList<Playlist>> { @Override protected ArrayList<Playlist> doInBackground(Void... params) { return getVideosList(); } @Override protected void onPostExecute(ArrayList<Playlist> playlists) { super.onPostExecute(playlists); YoutubeRecyclerAdapter youtubeAdapter = new YoutubeRecyclerAdapter(PlayVideos.this,mVideos); videoRecycler.setAdapter(youtubeAdapter); } } }
package com.slavyanin.example.less3_floatingactionbutton; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; import com.melnykov.fab.FloatingActionButton; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView listView = (ListView) findViewById(R.id.list); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.attachToListView(listView); String[] items = new String[20]; for (int i = 0; i < 20; i++) { items[i] = "item [ " + (i + 1) + "]"; } ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items); listView.setAdapter(adapter); } }
package com.hardcoded.plugin.tracer; import java.util.ArrayList; import java.util.List; import com.hardcoded.plugin.ScrapMechanicPlugin; import com.hardcoded.plugin.utils.DataUtils; import ghidra.program.model.address.Address; import ghidra.program.model.listing.Program; import ghidra.program.model.mem.Memory; import ghidra.program.model.mem.MemoryAccessException; import ghidra.program.model.mem.MemoryBlock; /** * Reads the full content of a ghidra program and caches it. * * @author HardCoded * @since 0.1.0 * @date 2020-11-22 */ public class ProgramMemory { private final ScrapMechanicPlugin plugin; private Address[] memory_start; private byte[][] memory_bytes; public ProgramMemory(ScrapMechanicPlugin tool) { plugin = tool; } public void loadMemory() throws MemoryAccessException { Program program = plugin.getCurrentProgram(); if(program == null) return; Memory memory = program.getMemory(); MemoryBlock[] blocks = memory.getBlocks(); List<Address> starts = new ArrayList<>(); List<byte[]> list = new ArrayList<>(); for(MemoryBlock block : blocks) { if(!block.isInitialized()) continue; int length = (int)block.getEnd().subtract(block.getStart()); byte[] bytes = new byte[length]; block.getBytes(block.getStart(), bytes); list.add(bytes); starts.add(block.getStart()); } memory_bytes = list.toArray(byte[][]::new); memory_start = starts.toArray(Address[]::new); } public List<Address> findMatches(Address addr) { long offset = addr.getOffset(); byte[] bytes = new byte[getAddressSize()]; for(int i = 0; i < bytes.length; i++) { bytes[i] = (byte)((offset >> (8L * i)) & 0xff); } /*return findMatches( (offset ) & 0xff, (offset >> 8) & 0xff, (offset >> 16) & 0xff, (offset >> 24) & 0xff );*/ return findMatches(bytes); } public List<Address> findMatches(int... pattern) { byte[] array = new byte[pattern.length]; for(int i = 0; i < pattern.length; i++) array[i] = (byte)(pattern[i] & 0xff); return findMatches(array); } public List<Address> findMatches(byte... pattern) { List<Address> list = new ArrayList<>(); for(int i = 0; i < memory_start.length; i++) { Address start = memory_start[i]; byte[] bytes = memory_bytes[i]; for(int j = 0; j < bytes.length - pattern.length; j++) { for(int k = 0; k < pattern.length; k++) { if(bytes[j + k] != pattern[k]) break; if(k == pattern.length - 1) { list.add(start.add(j)); } } } } return list; } public Address readAddress(Address addr) { byte[] bytes = getBytes(addr, getAddressSize()); // TODO: Use the new method? StringBuilder sb = new StringBuilder(); for(int i = 0; i < bytes.length; i++) { sb.insert(0, String.format("%02x", bytes[i])); } return plugin.getCurrentProgram().getAddressFactory().getAddress(sb.toString()); } /** * This was used to read the pointer of a position this is now deprecated because * the pointer size could change * @param addr * @return */ public int readInt(Address addr) { byte[] bytes = getBytes(addr, 4); return DataUtils.getInt(bytes, 0); /* return (bytes[0] & 0xff) | ((bytes[1] & 0xff) << 8) | ((bytes[2] & 0xff) << 16) | ((bytes[3] & 0xff) << 24); */ } // TODO: Make sure this is correct public long readWithAddressSize(Address addr) { byte[] bytes = getBytes(addr, getAddressSize()); return DataUtils.getInteger(bytes, getAddressSize(), 0); /* long result = 0; for(int i = 0; i < 8; i++) { result |= ((bytes[i] & 0xffL) << (8L * i)); } return result; */ } public byte[] getBytes(Address addr, int size) { byte[] result = new byte[size]; for(int i = 0; i < memory_start.length; i++) { Address start = memory_start[i]; byte[] bytes = memory_bytes[i]; int offset = (int)addr.subtract(start); if(offset < 0 || offset >= bytes.length) continue; System.arraycopy(bytes, offset, result, 0, size); /*for(int j = 0; j < size; j++) { result[j] = bytes[offset + j]; }*/ } return result; } public boolean isValidAddress(Address addr) { for(int i = 0; i < memory_start.length; i++) { Address start = memory_start[i]; byte[] bytes = memory_bytes[i]; int offset = (int)addr.subtract(start); if(offset < 0 || offset >= bytes.length) continue; return true; } return false; } // note: If a string overlaps multiple memoryblocks than this might be a problem :& public String readTerminatedString(Address addr) { return readTerminatedString(addr, 256); } public String readTerminatedString(Address addr, int maxLength) { for(int i = 0; i < memory_start.length; i++) { Address start = memory_start[i]; byte[] bytes = memory_bytes[i]; int offset = (int)addr.subtract(start); if(offset < 0 || offset >= bytes.length) continue; int length = maxLength; if(length + offset >= bytes.length) { length = bytes.length - offset; } // StringBuilder sb = new StringBuilder(); int str_length = 0; for(int j = 0; j < length; j++) { if(bytes[offset + j] == 0) { str_length = j; break; } // byte b = bytes[offset + j]; // if(b == 0) break; // // sb.append((char)b); } if(str_length == 0) return ""; return new String(bytes, offset, str_length); // return sb.toString(); } return null; } public int getAddressSize() { return plugin.getCurrentProgram().getDefaultPointerSize(); } }
import java.util. Scanner; public class Question{ public static void main(String[] args){ Scanner input = new Scanner(System.in); System.out.println("Enter first number"); int firstNumber = input.nextInt(); System.out.println("Enter the second number"); int secondNumber = input.nextInt(); System.out.println("Enter thirdNumber"); int thirdNumber = input.nextInt(); int result1 = firstNumber + secondNumber; if(result1 > thirdNumber){ System.out.printf("%d is greater than the third number",result1); } if(result1 < thirdNumber){ System.out.printf("%d is greater than result",thirdNumber); } System.out.println(); System.out.printf("The character %c %c %c %c %c %c %c %c %c %c %c %c %c has the value %d %d %d %d %d %d %d %d %d %d %d %d %d", 'A','B','C','a','b','c','0','1','2','$','*','+','/', ((int) 'A'),((int) 'B'),((int) 'C'),((int) 'a'),((int) 'b'),((int) 'c'),((int) '0'),((int) '1'),((int) '2'),((int) '$'),((int) '*'),((int) '+'), ((int) '/')); } }
/*Problem Statement: Write a program to create a rectangular array containing a multiplication table from 1*1 up to 12*12. Output the table as 13 columns with the numeric values right-aligned in columns. (The first line of output will be the column headings, the first column with no heading, then the numbers 1 to 12 for the remaining columns. The first item in each of the succeeding lines is the row heading, which ranges from 1 to 12.) static void displayMultiplicationMatrix()*/ public class MatrixMulti { static void displayMultiplicationMatrix(int[][] table) { for(int i = 0 ; i < table.length ; ++i) { for(int j = 0 ; j < table[i].length ; ++j) { table[i][j] = (i+1)*(j+1); } } //print System.out.print(" :"); for(int j = 1 ; j <= table[0].length ; ++j) { System.out.print(" " + j); } System.out.println("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); for(int i = 0 ; i < table.length ; ++i) { System.out.print("Row" + (i<9 ? " ":" ") + (i+1) + ":"); for(int j = 0; j < table[i].length; ++j) { System.out.print((table[i][j] < 10 ? " " : table[i][j] < 100 ? " " : " ") + table[i][j]); } System.out.println(); } } public static void main(String[] args) { int[][] table = new int[12][12]; displayMultiplicationMatrix(table); } }
package com.hfjy.framework.database.base; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.Iterator; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.sql.DataSource; import org.slf4j.Logger; import com.hfjy.framework.database.entity.DBConnectionInfo; import com.hfjy.framework.logging.LoggerFactory; public class SimpleRealDBConnectionPool implements DBConnectionPool { private static Logger logger = LoggerFactory.getLogger(SimpleRealDBConnectionPool.class); private final DBConnectionInfo dbInfo; private Lock poolLock = new ReentrantLock(); private Lock connectionLock = new ReentrantLock(); private Queue<Connection> connectionQueue; public SimpleRealDBConnectionPool(DBConnectionInfo dbInfo) { this.dbInfo = dbInfo; try { createPool(); } catch (Exception e) { logger.error(e.getMessage(), e); } } public void createPool() { if (connectionQueue != null) { return; } try { poolLock.lock(); Driver driver = (Driver) (Class.forName(this.dbInfo.getDriveClass()).newInstance()); DriverManager.registerDriver(driver); connectionQueue = new ConcurrentLinkedQueue<>(); createConnections(dbInfo.getMinConnectionNum()); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { poolLock.unlock(); } } public int getConnectionNum() { if (connectionQueue == null) { return 0; } return this.connectionQueue.size(); } private void createConnections(long numConnections) { try { connectionLock.lock(); for (int i = 0; i < numConnections; i++) { if (this.dbInfo.getMaxConnectionNum() > 0 && this.connectionQueue.size() >= this.dbInfo.getMaxConnectionNum()) { break; } Connection newConnection = newConnection(); connectionQueue.offer(newConnection); } } catch (SQLException e) { logger.error(e.getMessage(), e); } finally { connectionLock.unlock(); } } private Connection newConnection() throws SQLException { Connection conn = null; if (dbInfo.getDbUsername() == null || dbInfo.getDbUsername().length() < 1) { conn = DriverManager.getConnection(dbInfo.getDbConnectionString()); } else { conn = DriverManager.getConnection(dbInfo.getDbConnectionString(), dbInfo.getDbUsername(), dbInfo.getDbPassword()); } if (connectionQueue.size() == 0) { DatabaseMetaData metaData = conn.getMetaData(); int driverMaxConnections = metaData.getMaxConnections(); if (driverMaxConnections > 0 && this.dbInfo.getMaxConnectionNum() > driverMaxConnections) { dbInfo.setMaxConnectionNum(driverMaxConnections); } } return conn; } public Connection getSingleConnection() throws SQLException { if (connectionQueue == null) { return null; } Connection conn = findFreeConnection(); while (conn == null) { wait(250); conn = findFreeConnection(); } return conn; } private Connection findFreeConnection() throws SQLException { if (connectionQueue.isEmpty()) { createConnections(dbInfo.getMinConnectionNum()); } Connection conn = connectionQueue.poll(); if (!testConnection(conn)) { conn = null; } return conn; } private boolean testConnection(Connection conn) { try { if (conn == null || conn.isClosed()) { return false; } if (dbInfo.getDbTestSQL() != null && dbInfo.getDbTestSQL().length() > 0) { conn.setAutoCommit(true); Statement stmt = conn.createStatement(); stmt.execute(dbInfo.getDbTestSQL()); stmt.close(); return true; } else { return conn.isValid(0); } } catch (SQLException e) { closeConnection(conn); return false; } } public void returnConnection(Connection conn) throws SQLException { if (connectionQueue == null) { return; } if (testConnection(conn)) { connectionQueue.offer(conn); } else { connectionQueue.offer(newConnection()); } } public void refreshConnectionPool() throws SQLException { poolLock.lock(); if (connectionQueue == null) { return; } Iterator<Connection> iterator = connectionQueue.iterator(); while (iterator.hasNext()) { Connection conn = iterator.next(); if (!testConnection(conn)) { connectionQueue.remove(conn); connectionQueue.offer(newConnection()); } } poolLock.unlock(); } public void closeConnectionPool() { poolLock.lock(); if (connectionQueue == null) { return; } while (connectionQueue.size() > 0) { Connection conn = connectionQueue.poll(); if (testConnection(conn)) { closeConnection(conn); } } connectionQueue = null; poolLock.unlock(); } private void closeConnection(Connection conn) { try { if (conn != null && !conn.isClosed()) { conn.close(); } } catch (SQLException e) { logger.error("Close Connection Error", e); } } private void wait(int mSeconds) { try { Thread.sleep(mSeconds); } catch (InterruptedException e) { } } @Override public DataSource getDataSource() { return null; } @Override public Connection getConnection() { Connection Connection = null; try { Connection = getSingleConnection(); } catch (Exception e) { logger.error(e.getMessage(), e); Connection = null; } return Connection; } @Override public boolean destroyConnection(Connection conn) { try { returnConnection(conn); } catch (Exception e) { logger.error(e.getMessage(), e); return false; } return true; } }
package gameView; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import gameController.ObservedGame; public class RollDieHandler implements ActionListener { ObservedGame gc; public RollDieHandler(ObservedGame game) { gc = game; } public void actionPerformed(ActionEvent arg0) { gc.rollDie(); } }
package org.testing.testScript; // Login - Video Play- Comment Post import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class TC_7 { public static void main(String []args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "C:\\Users\\Awanish\\Downloads\\chromedriver_win32 (2)\\chromedriver.exe"); WebDriver driver=new ChromeDriver(); driver.get("https://www.youtube.com"); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS); WebElement Signin=driver.findElement(By.cssSelector("paper-button[aria-label='Sign in']")); Signin.click(); WebElement Email=driver.findElement(By.cssSelector("input[aria-label='Email or phone']")); Email.sendKeys("awanish.tiwari@abbieit.com"); WebElement Next=driver.findElement(By.cssSelector("span[class='RveJvd snByac']")); Next.click(); WebElement Pass= driver.findElement(By.cssSelector("input[autocomplete='current-password']")); //(By.xpath("//div[text()='Gaming']")) Pass.sendKeys("Gmail@1234"); WebElement Next1=driver.findElement(By.xpath("//span[@class='CwaK9']")); Next1.click(); WebElement Trending=driver.findElement(By.xpath("//yt-formatted-string[text()='Trending']")); Trending.click(); WebElement A=driver.findElement(By.id("img")); A.click(); WebElement Signout=driver.findElement(By.xpath("//yt-formatted-string[text()='Sign out']")); Signout.click(); driver.close(); } }
package com.adt.guakebao.server.business; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import com.adt.guakebao.server.database.FunctionRealize; import com.adt.guakebao.server.model.Course; import com.adt.guakebao.server.model.Order; import com.adt.guakebao.server.model.Student; public class XMLFactory { private static String generateAndFormatXML(Document doc, String fileName) { String XML = ""; // 生成XML try { OutputFormat xmlFormat = new OutputFormat(); xmlFormat.setEncoding("UTF-8"); // 设置编码方式 xmlFormat.setNewlines(true); // 设置换行 xmlFormat.setIndent(true); // 生成缩进 xmlFormat.setIndent(" "); // 使用4个空格进行缩进, 可以兼容文本编辑器 // xml输出器 StringWriter out = new StringWriter(); XMLWriter xmlWriter = new XMLWriter(out, xmlFormat); xmlWriter.write(doc); xmlWriter.flush(); XML = out.toString(); // 文件输出 if (!"".equals(fileName)) { XMLWriter output = new XMLWriter(new FileWriter(new File(fileName)), xmlFormat); output.write(doc); output.close(); } } catch (IOException e) { System.out.println(e.getMessage()); } return XML; } public static String getCourseListXML(Student student, List<Course> courseList) { String XML = ""; Document document = DocumentHelper.createDocument(); Element root = DocumentHelper.createElement("GuaKeBao"); document.setRootElement(root); // 创建courseDetail节点,并添加到根节点 Element courseDetail = root.addElement("CourseDetail"); // 创建obligatoryCourseList(必修课)节点,并添加到courseDetail节点 Element obligatoryCourseList = courseDetail.addElement("ObligatoryCourseList"); // 创建collegeElectiveCourseList(院选课)节点,并添加到courseDetail节点 Element collegeElectiveCourseList = courseDetail.addElement("CollegeElectiveCourseList"); // 创建schoolElectiveCourseList(校选课)节点,并添加到courseDetail节点 Element schoolElectiveCourseList = courseDetail.addElement("SchoolElectiveCourseList"); // 创建englishCourseList(英语相关课)节点,并添加到courseDetail节点 Element englishCourseList = courseDetail.addElement("EnglishCourseList"); // 创建computerCourseList(计算机相关课)节点,并添加到courseDetail节点 Element computerCourseList = courseDetail.addElement("ComputerCourseList"); // 创建otherCourseList(计算机相关课)节点,并添加到courseDetail节点 Element otherCourseList = courseDetail.addElement("OtherCourseList"); for (int i = 0; i < courseList.size(); i++) { Element courseElement = DocumentHelper.createElement("Course"); Course course = courseList.get(i); courseElement.addAttribute("name", course.getCourseName()); courseElement.addAttribute("teacher", course.getCourseTeacher()); courseElement.addAttribute("credit", String.valueOf(course.getCourseCredit())); courseElement.addAttribute("compensationRate", String.valueOf(course.getCompensationRate())); courseElement.addAttribute("maxInsureSum", String.valueOf(course.getMaxInsureSum())); courseElement.addAttribute("maxReturnSum", String.valueOf(course.getCompensationRate() * course.getMaxInsureSum())); if (FunctionRealize.getCourseInsuranceStatus(student, course.getCourseName())) { courseElement.addAttribute("insuranceStatus", "已投保"); } else { courseElement.addAttribute("insuranceStatus", "投保"); } switch (course.getCourseType()) { case "必修": obligatoryCourseList.add(courseElement); break; case "院选": collegeElectiveCourseList.add(courseElement); break; case "校选": schoolElectiveCourseList.add(courseElement); break; } } // 为英语和计算机还有其他添加课程 Element cet4 = DocumentHelper.createElement("Course"); cet4.addAttribute("name", "英语四级"); cet4.addAttribute("teacher", "自己"); cet4.addAttribute("credit", "∞"); cet4.addAttribute("compensationRate", "3"); cet4.addAttribute("maxInsureSum", "100"); cet4.addAttribute("maxReturnSum", "300"); if (FunctionRealize.getCourseInsuranceStatus(student, "英语四级")) { cet4.addAttribute("insuranceStatus", "已投保"); } else { cet4.addAttribute("insuranceStatus", "投保"); } englishCourseList.add(cet4); Element cet6 = DocumentHelper.createElement("Course"); cet6.addAttribute("name", "英语六级"); cet6.addAttribute("teacher", "自己"); cet6.addAttribute("credit", "∞"); cet6.addAttribute("compensationRate", "5"); cet6.addAttribute("maxInsureSum", "100"); cet6.addAttribute("maxReturnSum", "500"); if (FunctionRealize.getCourseInsuranceStatus(student, "英语六级")) { cet6.addAttribute("insuranceStatus", "已投保"); } else { cet6.addAttribute("insuranceStatus", "投保"); } englishCourseList.add(cet6); Element ncre1 = DocumentHelper.createElement("Course"); ncre1.addAttribute("name", "计算机一级"); ncre1.addAttribute("teacher", "自己"); ncre1.addAttribute("credit", "∞"); ncre1.addAttribute("compensationRate", "1.55"); ncre1.addAttribute("maxInsureSum", "100"); ncre1.addAttribute("maxReturnSum", "155"); if (FunctionRealize.getCourseInsuranceStatus(student, "计算机一级")) { ncre1.addAttribute("insuranceStatus", "已投保"); } else { ncre1.addAttribute("insuranceStatus", "投保"); } computerCourseList.add(ncre1); Element ncre2 = DocumentHelper.createElement("Course"); ncre2.addAttribute("name", "计算机二级"); ncre2.addAttribute("teacher", "自己"); ncre2.addAttribute("credit", "∞"); ncre2.addAttribute("compensationRate", "1.95"); ncre2.addAttribute("maxInsureSum", "100"); ncre2.addAttribute("maxReturnSum", "195"); if (FunctionRealize.getCourseInsuranceStatus(student, "计算机二级")) { ncre2.addAttribute("insuranceStatus", "已投保"); } else { ncre2.addAttribute("insuranceStatus", "投保"); } computerCourseList.add(ncre2); Element ncre3 = DocumentHelper.createElement("Course"); ncre3.addAttribute("name", "计算机三级"); ncre3.addAttribute("teacher", "自己"); ncre3.addAttribute("credit", "∞"); ncre3.addAttribute("compensationRate", "2.35"); ncre3.addAttribute("maxInsureSum", "100"); ncre3.addAttribute("maxReturnSum", "235"); if (FunctionRealize.getCourseInsuranceStatus(student, "计算机三级")) { ncre3.addAttribute("insuranceStatus", "已投保"); } else { ncre3.addAttribute("insuranceStatus", "投保"); } computerCourseList.add(ncre3); XML = XMLFactory.generateAndFormatXML(document, "i:\\courseList"); return XML; } public static String getOrderListXML(List<Order> orderList) { String XML = ""; Document document = DocumentHelper.createDocument(); Element root = DocumentHelper.createElement("GuaKeBao"); document.setRootElement(root); Element orderListElement = root.addElement("OrderList"); for (int i = 0; i < orderList.size(); i++) { Element orderElement = DocumentHelper.createElement("Order"); Order order = orderList.get(i); orderElement.addAttribute("courseName", order.getCourseName()); orderElement.addAttribute("state", order.getState()); orderElement.addAttribute("beneficiary", order.getBeneficiary()); orderElement.addAttribute("insureSum", String.valueOf(order.getInsureSum())); orderElement.addAttribute("compensationRate", String.valueOf(order.getCompensationRate())); orderElement.addAttribute("effectDate", order.getEffectDate()); orderElement.addAttribute("returnSum", String.valueOf(order.getInsureSum() * order.getCompensationRate())); orderListElement.add(orderElement); } // 生成XML XML = XMLFactory.generateAndFormatXML(document, ""); return XML; } public static String getStudentInfoXML(Student student) { String XML = ""; Document document = DocumentHelper.createDocument(); Element root = DocumentHelper.createElement("GuaKeBao"); document.setRootElement(root); Element login = root.addElement("Login"); login.addAttribute("state", "success"); Element studentElement = login.addElement("Student"); studentElement.addAttribute("universityName", student.getUniversityName()); studentElement.addAttribute("collegeName", student.getCollegeName()); studentElement.addAttribute("majorName", student.getMajorName()); studentElement.addAttribute("stuNumber", String.valueOf(student.getStuNumber())); studentElement.addAttribute("stuName", student.getStuName()); studentElement.addAttribute("stuBirthDate", student.getStuBirthDate()); studentElement.addAttribute("stuPassword", student.getStuPassword()); studentElement.addAttribute("entryDate", student.getEntryDate()); studentElement.addAttribute("telNumber", student.getTelNumber()); studentElement.addAttribute("balance", String.valueOf(student.getBalance())); studentElement.addAttribute("validation", student.getValidation()); XML = XMLFactory.generateAndFormatXML(document, ""); return XML; } public static String getLoginFailureXML(String state) { String XML = ""; Document document = DocumentHelper.createDocument(); Element root = DocumentHelper.createElement("GuaKeBao"); document.setRootElement(root); Element login = root.addElement("Login"); login.addAttribute("state", state); XML = XMLFactory.generateAndFormatXML(document, ""); return XML; } public static String getVerificationXML(String code) { String XML = ""; Document document = DocumentHelper.createDocument(); Element root = DocumentHelper.createElement("GuaKeBao"); document.setRootElement(root); Element verification = root.addElement("Verification"); if ("".equals(code)) { verification.addAttribute("state", "failure"); }else if("exist".equals(code)){ verification.addAttribute("state", "exist"); } else { verification.addAttribute("state", "success"); verification.addAttribute("code", code); } XML = XMLFactory.generateAndFormatXML(document, ""); return XML; } }
package test.unit.org.testinfected.molecule.middlewares; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JMock; import org.jmock.integration.junit4.JUnit4Mockery; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.testinfected.molecule.Application; import org.testinfected.molecule.middlewares.DateHeader; import test.support.org.testinfected.molecule.unit.BrokenClock; import test.support.org.testinfected.molecule.unit.MockRequest; import test.support.org.testinfected.molecule.unit.MockResponse; import java.util.Date; import static test.support.org.testinfected.molecule.unit.DateBuilder.calendarDate; import static test.support.org.testinfected.molecule.unit.MockRequest.aRequest; import static test.support.org.testinfected.molecule.unit.MockResponse.aResponse; @RunWith(JMock.class) public class DateHeaderTest { Mockery context = new JUnit4Mockery(); Date now = calendarDate(2012, 6, 8).atMidnight().build(); DateHeader dateHeader = new DateHeader(BrokenClock.stoppedAt(now)); Application successor = context.mock(Application.class, "successor"); MockRequest request = aRequest(); MockResponse response = aResponse(); @Before public void chainWithSuccessor() { dateHeader.connectTo(successor); } @Test public void setsDateHeaderFromClockTime() throws Exception { context.checking(new Expectations() {{ oneOf(successor).handle(with(request), with(response)); }}); dateHeader.handle(request, response); response.assertHeader("Date", "Fri, 08 Jun 2012 04:00:00 GMT"); } }
package com.mingrisoft.generic; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.List; import org.apache.commons.dbutils.DbUtils; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; public class GenericQuery { private static String URL = "jdbc:mysql://localhost:3306/db_database13"; private static String DRIVER = "com.mysql.jdbc.Driver"; private static String USERNAME = "root"; private static String PASSWORD = "111"; private static Connection conn; public static Connection getConnection() { DbUtils.loadDriver(DRIVER); try { conn = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (SQLException e) { e.printStackTrace(); } return conn; } public static <T> List<T> query(String sql, Class<T> type) { QueryRunner qr = new QueryRunner(); List<T> list = null; try { list = qr.query(getConnection(), sql, new BeanListHandler<T>(type)); } catch (SQLException e) { e.printStackTrace(); } finally { DbUtils.closeQuietly(conn); } return list; } }
package businesslogic.promotionbl.HotelPromotion; import util.HotelPromotionType; import vo.HotelPromotionVO.HotelMultiRoomsPromotionVO; import vo.OrderVO; /** * Created by Qin Liu on 2016/12/10. */ public class HotelMultiRoomsPromotion extends HotelPromotion { private OrderVO orderVO; private HotelMultiRoomsPromotionVO hotelMultiRoomsPromotionVO; private HotelPromotionType hotelPromotionType = HotelPromotionType.MultiRooms; public HotelMultiRoomsPromotion(OrderVO orderVO, HotelMultiRoomsPromotionVO hotelMultiRoomsPromotionVO) { this.orderVO = (OrderVO) orderVO.clone(); this.hotelMultiRoomsPromotionVO = hotelMultiRoomsPromotionVO; } @Override public OrderVO calculatePrice() { int roomNum = orderVO.getRoomNum(); int leastRoomNum = hotelMultiRoomsPromotionVO.getRoomNum(); if(roomNum >= leastRoomNum) { orderVO.setPrice(orderVO.getPrice() * hotelMultiRoomsPromotionVO.getDiscount()); } return this.orderVO; } @Override public HotelPromotionType getHotelPromotionType() { return this.hotelPromotionType; } }
package People; public class Family { private Person[] ourFamily; private int numberOfFamily = 0; Family(int size) { ourFamily = new Person[size]; } void addPerson(Person p) { System.out.println("Attempting to add " + p); if(numberOfFamily >= ourFamily.length) { System.out.println("Family is full"); return; } for(int i = 0; i < numberOfFamily; i++) { if(p.equals(ourFamily[i])) { System.out.println("Duplicate, skipping...\n"); return; } } ourFamily[numberOfFamily] = p; numberOfFamily++; System.out.println("Added!\n"); } void printOutFamily() { System.out.println("Attempting to print family...\n"); for(int i = 0; i < numberOfFamily; i++) System.out.println(ourFamily[i]); } public static void main(String[] args) { Person fred= new Person("Fred Flintstone", 50); System.out.println("created " + fred); Person wilma = new Person("Wilma Flintstone", 48); Student george= new Student("George Flintstone", 21, "Politics", 3.1); System.out.println("created " + george); Student sue= new Student("Sue Flintstone", 24, "Nursing", 3.3); Student anotherGeorge= new Student("George Flintstone", 21, "Math", 3.4); Person yetAnotherGeorge= new Person("George Flintstone", 21); Family f = new Family(10); f.addPerson(fred); f.addPerson(wilma); f.addPerson(george); f.addPerson(sue); f.addPerson(anotherGeorge); f.addPerson(yetAnotherGeorge); anotherGeorge.setName("Georgie Flintstone"); f.addPerson(anotherGeorge); f.printOutFamily(); } }
package com.gome.manager.service.impl; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.gome.manager.common.Page; import com.gome.manager.dao.UserMapper; import com.gome.manager.domain.CodeRecord; import com.gome.manager.domain.User; import com.gome.manager.domain.UserBean; import com.gome.manager.service.UserService; /** * * 导读service接口实现类. * * <pre> * 修改日期 修改人 修改原因 * 2015年11月09日 caowei 新建 * </pre> */ @Service("userService") public class UserServiceImpl implements UserService { @Resource UserMapper userMapper; public Page<User> findUserListByPage(Page<User> page) { List<User> userList = userMapper.selectUserListByPage(page); if(userList!=null && userList.size()>0){ for (int i = 0; i < userList.size(); i++) { String createTime = userList.get(i).getCreateTime(); if(createTime.length()<15){ Date d = new Date(Long.parseLong(createTime)*1000); SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); String format = sdf.format(d); userList.get(i).setCreateTime(format); } } } int totalResult = userMapper.selectTotalResultByConditions(page.getConditions()); return new Page<User>(page.getPageNo(), page.getPageSize(), totalResult, userList, page.getConditions()); } @Override public int addUser(User user) { int id = userMapper.insertUser(user); return id; } @Override public User queryUserDetail(Long userId) { // TODO Auto-generated method stub User user = userMapper.queryUserDetail(userId); return user; } @Override public int verifyUser(User user) { // TODO Auto-generated method stub return 0; } @Override public int verifyUserName(User user) { return userMapper.verifyUserName(user); } @Override public int verifyUserPassword(User user) { // TODO Auto-generated method stub return userMapper.verifyUserPassword(user); } @Override public int addCodeRecord(CodeRecord codeRecord) { userMapper.addCodeRecord(codeRecord); return 1; } @Override public int updateUser(User user) { userMapper.updateUser(user); return 1; } @Override public User checkUser(User user) { // TODO Auto-generated method stub return userMapper.checkUser(user); } @Override public int getTotalBean(Long userId) { // TODO Auto-generated method stub Integer totalBean = userMapper.getTotalBean(userId); return totalBean; } @SuppressWarnings("static-access") @Override public int addUserBean(UserBean userBean) { String sourceType = userBean.getSourceType(); int amount=0; //来源1、点赞2、评论、3、完善资料4、签到5、新注册6、微互动 if(sourceType.equals("1")){ amount = 1; } if(sourceType.equals("2")){ //判断当前文章,当前用户是否评论过,评论过,只添加评论,不增加乐豆 int countBean = userMapper.queryUserGetBean(userBean); if(countBean==0){ amount = 5; }else{ amount = 0; } } if(sourceType.equals("3")){ amount = 20; userBean.setDescribes("完善资料赠送"); } if(sourceType.equals("4")){ Date date=new Date();//取时间 Calendar calendar = new GregorianCalendar(); calendar.setTime(date); calendar.add(calendar.DATE,-1);//把日期往后增加一天.整数往后推,负数往前移动 date=calendar.getTime(); //这个时间就是日期往后推一天的结果 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); String getTime1 = formatter.format(date); userBean.setGetTime(getTime1); UserBean userBean2 = userMapper.querySignDate(userBean); if(userBean2!=null){ userBean.setSourceId(userBean2.getSourceId()+1); } calendar.add(calendar.DATE,-1);//把日期往后增加一天.整数往后推,负数往前移动 date=calendar.getTime(); //这个时间就是日期往后推一天的结果 String getTime2 = formatter.format(date); userBean.setGetTime(getTime2); UserBean userBean3 = userMapper.querySignDate(userBean); if(userBean2!=null && userBean3!=null){ amount = 3; userBean.setDescribes("连续三天签到"); }else if(userBean2!=null && userBean3==null){ amount = 1; userBean.setDescribes("签到赠送"); }else{ amount = 1; userBean.setDescribes("签到赠送"); userBean.setSourceId(1L); } } if(sourceType.equals("5")){ amount =20; userBean.setDescribes("新注册奖励"); } if(sourceType.equals("6")){ amount = 10; } if(sourceType.equals("7") || sourceType.equals("8")){ amount = -20; } if(sourceType.equals("10")){ amount = 10; userBean.setDescribes("观看视频奖励"); } userBean.setAmount(amount); if(sourceType.equals("4")){ DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String signTime = df.format(new Date()); userBean.setSignTime(signTime); } DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String getTime = df.format(new Date()); userBean.setGetTime(getTime); userMapper.addUserBean(userBean); return 1; } @Override public List<UserBean> queryUserSign(UserBean userBean) { // TODO Auto-generated method stub return userMapper.queryUserSign(userBean); } @Override public void addAdvice(UserBean userBean) { // TODO Auto-generated method stub userMapper.addAdvice(userBean); } @Override public List<UserBean> queryUserBeans(UserBean userBean) { // TODO Auto-generated method stub return userMapper.queryUserBeans(userBean); } @Override public User queryUserInfo(User user) { // TODO Auto-generated method stub return userMapper.queryUserInfo(user); } @Override public User queryPassword(User user) { // TODO Auto-generated method stub return userMapper.queryPassword(user); } @Override public UserBean queryUserIfDownload(UserBean userBean) { // TODO Auto-generated method stub return userMapper.queryUserIfDownload(userBean); } @Override public UserBean querySignDate(UserBean userBean) { // TODO Auto-generated method stub return userMapper.querySignDate(userBean); } @Override public Page<UserBean> queryUserAdvices(Page<UserBean> page) { List<UserBean> userList = userMapper.queryUserAdvices(page); int totalResult = userMapper.queryUserAdvicesByConditions(page.getConditions()); return new Page<UserBean>(page.getPageNo(), page.getPageSize(), totalResult, userList, page.getConditions()); } }
package com.metoo.foundation.service.impl; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.metoo.core.dao.IGenericDAO; import com.metoo.core.query.GenericPageList; import com.metoo.core.query.PageObject; import com.metoo.core.query.support.IPageList; import com.metoo.core.query.support.IQueryObject; import com.metoo.foundation.domain.Tree; import com.metoo.foundation.service.ITreeService; @Service @Transactional public class TreeServiceImpl implements ITreeService{ @Resource(name = "treeDao") private IGenericDAO<Tree> treeDao; @Override public Tree getObjById(Long id) { // TODO Auto-generated method stub return this.treeDao.get(id); } @Override public boolean save(Tree instance) { // TODO Auto-generated method stub try { this.treeDao.save(instance); return true; } catch (Exception e) { // TODO Auto-generated catch block return false; } } @Override public boolean update(Tree instance) { // TODO Auto-generated method stub try { this.treeDao.update(instance); return true; } catch (Exception e) { // TODO Auto-generated catch block return false; } } @Override public IPageList list(IQueryObject properties) { // TODO Auto-generated method stub if(properties == null){ return null; } String query = properties.getQuery(); String construct = properties.getConstruct(); Map params = properties.getParameters(); GenericPageList pList = new GenericPageList(Tree.class, construct, query, params, this.treeDao); if(properties != null){ PageObject pageObj = properties.getPageObj(); if (pageObj != null) pList.doList(pageObj.getCurrentPage() == null ? 0 : pageObj .getCurrentPage(), pageObj.getPageSize() == null ? 0 : pageObj.getPageSize()); }else pList.doList(0, -1); return pList; } @Override public boolean delete(Long id) { // TODO Auto-generated method stub try { this.treeDao.remove(id); return true; } catch (Exception e) { // TODO Auto-generated catch block return false; } } @Override public List<Tree> query(String query, Map params, int begin, int max) { // TODO Auto-generated method stub return this.treeDao.query(query, params, begin, max); } }
package Example2; /** * 生产者——消费者 * @author yudong * @create 2019-11-07 19:22 */ public class ProducerConsumerSolution { public static void main(String[] args) { Product product = new Product(); Thread producer = new Thread(new Producer(product)); Thread consumer = new Thread(new Consumer(product)); producer.start(); consumer.start(); } }
package com.stk123.service.task; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; @Getter @Setter @AllArgsConstructor public class TaskBuilder { private Class task; private String[] args; public static TaskBuilder of(Class cls, String... args){ return new TaskBuilder(cls, args); } }
package org.example; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class CuentaCorrienteTest { CuentaCorriente cc1; CuentaCorriente cc2; @Test public void shouldAnswerWithTrue() { assertTrue(true); } @BeforeAll public void beforeAll() { cc1 = new CuentaCorriente("Cuenta1", 1234567890, 5); cc2 = new CuentaCorriente("Cuenta2", 234567, 2); } @BeforeEach public void setUp(){ cc1 = new CuentaCorriente("Cuenta1", 1234567890, 5); cc2 = new CuentaCorriente("Cuenta2", 234567, 2); //CuentaCorriente cc3 = new CuentaCorriente("Cuenta3", 13456, null); } @Test public void depositTest1(){ assertTrue(cc1.deposit(1)); } @Test public void depositTest2(){ assertFalse(cc1.deposit(-1)); } @Test public void withdrawTest11(){ assertTrue(cc1.withdraw(3,1F)); } @Test public void withdrawTest12(){ assertFalse(cc1.withdraw(3,3F)); } @Test public void withdrawTest13(){ assertFalse(cc1.withdraw(3,-1F)); } @Test public void withdrawTest14(){ assertFalse(cc1.withdraw(-3,1)); } @Test public void withdrawTest15(){ assertFalse(cc1.withdraw(-3,-1)); } @Test public void withdrawTest21(){ assertTrue(cc2.withdraw(3,1F)); } @Test public void withdrawTest22(){ assertFalse(cc2.withdraw(3,3F)); } @Test public void withdrawTest23(){ assertFalse(cc2.withdraw(3,-1F)); } @Test public void withdrawTest24(){ assertFalse(cc2.withdraw(-3,1)); } @Test public void withdrawTest25(){ assertFalse(cc2.withdraw(-3,-1)); } }
package io.github.seregaslm.jsonapi.simple.response; import io.github.seregaslm.jsonapi.simple.annotation.RequestJsonApiFieldSet; import io.github.seregaslm.jsonapi.simple.request.FieldSet; import io.github.seregaslm.jsonapi.simple.resolver.JsonApiSpreadFieldSetArgumentResolver; import lombok.NonNull; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.core.MethodParameter; import org.springframework.web.context.request.NativeWebRequest; import java.util.Collections; import java.util.Map; import java.util.Set; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.mockito.ArgumentMatchers.any; public class FieldSetTest { private static final String REQUEST_FIELD_SET_ARGUMENT_NAME = "fields"; private static final String TEST_FIELD_SET_RESOURCE_TYPE_1_NAME = "resource-type-1"; private static final Set<String> TEST_FIELD_SET_FIELDS_1 = Set.of("field_1", "field_2"); private static final String TEST_FIELD_SET_RESOURCE_TYPE_2_NAME = "resource-type-2"; private static final Set<String> TEST_FIELD_SET_FIELDS_2 = Set.of("field_3", "field_4", "field_5", "field_6"); private JsonApiSpreadFieldSetArgumentResolver jsonApiSpreadFieldSetArgumentResolver; @Mock private MethodParameter methodParameter; @Mock private RequestJsonApiFieldSet requestJsonApiFieldSet; @Mock private NativeWebRequest nativeWebRequest; @BeforeEach public void setUp() { MockitoAnnotations.openMocks(this); Mockito.when(methodParameter.getParameterAnnotation(any())) .thenReturn(requestJsonApiFieldSet); Mockito.when(requestJsonApiFieldSet.name()) .thenReturn(REQUEST_FIELD_SET_ARGUMENT_NAME); jsonApiSpreadFieldSetArgumentResolver = new JsonApiSpreadFieldSetArgumentResolver(); } @Test public void shouldReturnEmptyFieldSetsWhenArgumentNotPresent() { Mockito.when(nativeWebRequest.getParameterMap()) .thenReturn(Collections.emptyMap()); final FieldSet fieldSet = resolveFieldSet(); assertThat(fieldSet, is(notNullValue())); assertThat(fieldSet.getAllFields(), anEmptyMap()); assertThat(fieldSet.isEmpty(), is(true)); } @Test public void shouldParseFieldSetsWith1ResourceType() { final Map<String, String[]> fieldSetMap = prepareFieldSetMapWith1Resource(); Mockito.when(nativeWebRequest.getParameterMap()) .thenReturn(fieldSetMap); final FieldSet fieldSet = resolveFieldSet(); assertFieldsSet(fieldSet, TEST_FIELD_SET_RESOURCE_TYPE_1_NAME, TEST_FIELD_SET_FIELDS_1); } @Test public void shouldParseFieldSetsWith2ResourceTypes() { final Map<String, String[]> fieldSetMap = prepareFieldSetMapWith2Resources(); Mockito.when(nativeWebRequest.getParameterMap()) .thenReturn(fieldSetMap); final FieldSet fieldSet = resolveFieldSet(); assertFieldsSet(fieldSet, TEST_FIELD_SET_RESOURCE_TYPE_1_NAME, TEST_FIELD_SET_FIELDS_1); assertFieldsSet(fieldSet, TEST_FIELD_SET_RESOURCE_TYPE_2_NAME, TEST_FIELD_SET_FIELDS_2); } @Test public void shouldReturnTrueWhenFieldsSetContainsResourceTypeAndRequiredFields() { final Map<String, String[]> fieldSetMap = prepareFieldSetMapWith2Resources(); Mockito.when(nativeWebRequest.getParameterMap()) .thenReturn(fieldSetMap); final FieldSet fieldSet = resolveFieldSet(); assertThat(fieldSet, is(notNullValue())); assertThat(fieldSet.containsField(TEST_FIELD_SET_RESOURCE_TYPE_1_NAME, "field_3"), is(false)); assertThat(fieldSet.containsFields(TEST_FIELD_SET_RESOURCE_TYPE_1_NAME, Set.of("field_3", "field_5")), is(false)); assertThat(fieldSet.containsField(TEST_FIELD_SET_RESOURCE_TYPE_2_NAME, "field_3"), is(true)); assertThat(fieldSet.containsFields(TEST_FIELD_SET_RESOURCE_TYPE_2_NAME, Set.of("field_3", "field_5")), is(true)); } @Test public void shouldReturnValidAllFieldsWith2ResourceTypes() { final Map<String, String[]> fieldSetMap = prepareFieldSetMapWith2Resources(); Mockito.when(nativeWebRequest.getParameterMap()) .thenReturn(fieldSetMap); final FieldSet fieldSet = resolveFieldSet(); assertThat(fieldSet, is(notNullValue())); assertThat( fieldSet.getAllFields().keySet(), containsInAnyOrder(TEST_FIELD_SET_RESOURCE_TYPE_1_NAME, TEST_FIELD_SET_RESOURCE_TYPE_2_NAME) ); fieldSet.getAllFields().forEach((key, value) -> assertThat( fieldSet.getFieldsByResourceType(key), containsInAnyOrder(value.toArray()) )); } @Test public void shouldReturnFalseWhenFieldsSetNotContainsRequiredResourceType() { final Map<String, String[]> fieldSetMap = prepareFieldSetMapWith1Resource(); Mockito.when(nativeWebRequest.getParameterMap()) .thenReturn(fieldSetMap); final FieldSet fieldSet = resolveFieldSet(); assertThat(fieldSet, is(notNullValue())); assertThat(fieldSet.containsField(TEST_FIELD_SET_RESOURCE_TYPE_2_NAME, "field_1"), is(false)); } @Test public void shouldAddNewFieldsToExistingFieldSet() { final Map<String, String[]> fieldSetMap = prepareFieldSetMapWith1Resource(); Mockito.when(nativeWebRequest.getParameterMap()) .thenReturn(fieldSetMap); final FieldSet fieldSet = resolveFieldSet(); fieldSet.addFields(TEST_FIELD_SET_RESOURCE_TYPE_2_NAME, TEST_FIELD_SET_FIELDS_2); assertFieldsSet(fieldSet, TEST_FIELD_SET_RESOURCE_TYPE_1_NAME, TEST_FIELD_SET_FIELDS_1); assertFieldsSet(fieldSet, TEST_FIELD_SET_RESOURCE_TYPE_2_NAME, TEST_FIELD_SET_FIELDS_2); } @Test public void shouldThrowExceptionWhenArgumentInvalidFormat() { Assertions.assertThrows( IllegalArgumentException.class, () -> { final Map<String, String[]> fieldSetMap = Map.of(REQUEST_FIELD_SET_ARGUMENT_NAME + "[]", new String[0]); Mockito.when(nativeWebRequest.getParameterMap()) .thenReturn(fieldSetMap); resolveFieldSet(); } ); } private Map<String, String[]> prepareFieldSetMapWith1Resource() { return Map.of( REQUEST_FIELD_SET_ARGUMENT_NAME + "[" + TEST_FIELD_SET_RESOURCE_TYPE_1_NAME + "]", new String[] {String.join(",", TEST_FIELD_SET_FIELDS_1)} ); } private Map<String, String[]> prepareFieldSetMapWith2Resources() { return Map.of( REQUEST_FIELD_SET_ARGUMENT_NAME + "[" + TEST_FIELD_SET_RESOURCE_TYPE_1_NAME + "]", new String[] {String.join(",", TEST_FIELD_SET_FIELDS_1)}, REQUEST_FIELD_SET_ARGUMENT_NAME + "[" + TEST_FIELD_SET_RESOURCE_TYPE_2_NAME + "]", new String[] {String.join(",", TEST_FIELD_SET_FIELDS_2)} ); } private FieldSet resolveFieldSet() { return (FieldSet)jsonApiSpreadFieldSetArgumentResolver.resolveArgument( methodParameter, null, nativeWebRequest, null ); } private void assertFieldsSet(final FieldSet fieldSet, final @NonNull String resourceType, final @NonNull Set<String> requiredFields) { assertThat(fieldSet, is(notNullValue())); assertThat(fieldSet.hasResource(resourceType), is(true)); assertThat( fieldSet.getFieldsByResourceType(resourceType), containsInAnyOrder(requiredFields.toArray()) ); } }
public class Solution { public List<List<Integer>> allTriples(int[] array, int target) { List<List<Integer>> list = new ArrayList<>(); if (array == null) { return list; } Arrays.sort(array); for (int i = 0; i < array.length - 2; i++) { if (i > 0 && array[i] == array[i - 1]) { continue; } int j = i + 1; int k = array.length - 1; while (j < k) { if (j > i + 1 && array[j] == array[j - 1]) { j++; continue; } int cur = array[j] + array[k] + array[i]; if (cur == target) { list.add(Arrays.asList(array[i], array[j], array[k])); j++; k--; } else if (cur > target) { k--; } else { j++; } } } return list; } } 3 Sum is the same as 2 Sum, except setting the i pointer location first.
package com.kwik.repositories.product.dao; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; import br.com.caelum.vraptor.ioc.Component; import com.kwik.models.Product; import com.kwik.repositories.product.ProductRepository; @Component public class ProductDao implements ProductRepository { private EntityManager entityManager; public ProductDao(EntityManager entityManager) { this.entityManager = entityManager; } @Override public Product add(Product product) { Product result = product; entityManager.persist(result); return result; } @Override public Product update(Product product) { return entityManager.merge(product); } @Override public List<Product> listAll() { Query query = entityManager.createQuery("FROM " + Product.class.getName()); @SuppressWarnings("unchecked") List<Product> resultList = query.getResultList(); return resultList; } @Override public List<Product> findBy(List<Long> ids) { Query query = entityManager.createQuery("FROM " + Product.class.getName() + " p WHERE p.id IN :ids "); query.setParameter("ids", ids); @SuppressWarnings("unchecked") List<Product> resultList = query.getResultList(); return resultList; } @Override public Product findBy(Long id) { return entityManager.find(Product.class, id); } @Override public void destroy(Product product) { entityManager.remove(findBy(product.getId())); } }
/** * Copyright 2015 www.codereligion.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.codereligion.cherry.test.hamcrest; import org.hamcrest.Matcher; import org.hamcrest.core.SubstringMatcher; import static com.google.common.base.Preconditions.checkArgument; /** * A matcher which expects a string to contain a given string. This matcher basically does the same as Hamcrest's {@link org.hamcrest.core.StringContains}, with * the difference that it allows varargs which will be used to format the given string before the actual matching happens. * * @author Sebastian Gr&ouml;bler * @since 05.04.2015 */ public class StringContains extends SubstringMatcher { /** * Creates a matcher that matches if the examined {@link String} contains the specified {@link String} anywhere. Optional arguments can be provided which * will be used to format the given {@code substring}. * <p/> * Example usage: {@code assertThat("some string", containsString("some %s", "string"))} * * @param substring the substring that the returned matcher will expect to find within any examined string * @param args the arguments to use for formatting the given {@code substring} * @return a new matcher */ public static Matcher<String> containsString(final String substring, final Object... args) { checkArgument(substring != null, "substring must not be null."); return new StringContains(String.format(substring, args)); } private StringContains(final String substring) { super(substring); } @Override protected boolean evalSubstringOf(String s) { return s.indexOf(substring) >= 0; } @Override protected String relationship() { return "containing"; } }
package com.lsm.springboot.service.impl; import com.lsm.springboot.BaseTest; import com.lsm.springboot.config.RabbitMQConfig; import com.lsm.springboot.service.ISenderService; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Created by lishenming on 2017/6/12. */ public class SenderServiceImplTest extends BaseTest { @Autowired private ISenderService senderServiceImpl; @Test public void testSend(){ Map<String, String> massage = new HashMap<>(); massage.put("phoneNum", "18621949186"); massage.put("name", "lishenming"); massage.put("id", "1"); massage.put("date", new Date().toString()); senderServiceImpl.send(massage); /*testSend2(); testSendTopicMassage1(); testSendTopicMassage2(); testSendFanoutMassage();*/ } @Test public void testSend2(){ for (int i = 200; i < 250; i++) { if (i % 2 == 0){ String massage = "hi, i am MESSAGE" + i; senderServiceImpl.send(massage, RabbitMQConfig.STRING_QUEUE_NAME); }else{ String massage = "hi, i am MESSAGE to queue2" + i; senderServiceImpl.send(massage, RabbitMQConfig.STRING_QUEUE_NAME_2); } } } @Test public void testSendTopicMassage1(){ senderServiceImpl.sendTopicMassage1(); } @Test public void testSendTopicMassage2(){ senderServiceImpl.sendTopicMassage2(); } @Test public void testSendFanoutMassage() { senderServiceImpl.sendFanoutMassage(); } }
package com.myxh.developernews.ui.activity; import android.content.Intent; import android.os.Bundle; import android.provider.Settings; import android.support.v7.app.AlertDialog; import android.view.animation.Animation; import android.view.animation.ScaleAnimation; import android.widget.ImageView; import com.myxh.developernews.R; import com.myxh.developernews.ui.base.BaseActivity; import com.myxh.developernews.util.NetworkUtil; import butterknife.BindView; import butterknife.ButterKnife; public class SplashActivity extends BaseActivity { @BindView(R.id.splash_img) ImageView mSplashImg; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); ButterKnife.bind(this); initData(); } private void initData() { ScaleAnimation scaleAnimation = new ScaleAnimation(1.0f, 1.2f, 1.0f, 1.2f, Animation .RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); scaleAnimation.setFillAfter(true); scaleAnimation.setDuration(3000); scaleAnimation.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { startToMainActivity(); } @Override public void onAnimationRepeat(Animation animation) { } }); mSplashImg.startAnimation(scaleAnimation); } private void startToMainActivity() { if (NetworkUtil.isNetConnected(this)) { openActivityWithOutAnim(MainActivity.class); finish(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setTitle(R.string.tips); builder.setMessage(R.string.network_not_conntected); builder.setPositiveButton(R.string.dialog_ok, (dialog, which) -> { dialog.cancel(); Intent intent = new Intent(Settings.ACTION_SETTINGS); startActivity(intent); finish(); }); builder.setNegativeButton(R.string.dialog_cancel, (dialog, which) -> { dialog.cancel(); finish(); }); builder.create(); builder.show(); } } }
package com.uav.rof.activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.Toast; import com.rof.uav.adpater.ImageTextAdapter; import com.uav.rof.R; import com.uav.rof.constants.ApplicationConstant; import com.uav.rof.vo.DataAdapterVO; import java.util.ArrayList; public class setting extends AppCompatActivity { ImageView back_activity_button; ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_setting); getSupportActionBar().hide(); back_activity_button=(ImageView)findViewById(R.id.back_activity_button); listView=(ListView)findViewById(R.id.listview); back_activity_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); final ArrayList<DataAdapterVO> dataList = getDataList(); ImageTextAdapter myAdapter=new ImageTextAdapter(this, dataList, R.layout.listimagewithtextview); listView.setAdapter(myAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // String s=(String)parent.getItemAtPosition(position); int i=position; DataAdapterVO dataAdapterVO = (DataAdapterVO)dataList.get(position); if(dataAdapterVO.getAssociatedValue().equalsIgnoreCase(ApplicationConstant.MENU_SETTING_VERTICAL_KEY_IPSETTING)){ startActivity(new Intent(setting.this,IpAddressSetting.class)); } if(dataAdapterVO.getAssociatedValue().equalsIgnoreCase(ApplicationConstant.MENU_SETTING_CAMERA)){ startActivity(new Intent(setting.this,Camera_Preview_Setting.class)); } if(dataAdapterVO.getAssociatedValue().equalsIgnoreCase(ApplicationConstant.MENU_SETTING_VERTICAL_KEY_EXIT)){ Toast.makeText(setting.this, "Exit", Toast.LENGTH_SHORT).show(); } } }); } public ArrayList<DataAdapterVO> getDataList(){ ArrayList<DataAdapterVO> datalist = new ArrayList<>(); DataAdapterVO dataAdapterVO = new DataAdapterVO(); dataAdapterVO.setText("IP Address Setting"); dataAdapterVO.setAssociatedValue(ApplicationConstant.MENU_SETTING_VERTICAL_KEY_IPSETTING); dataAdapterVO.setImage(R.drawable.rof_ipaddress); datalist.add(dataAdapterVO); dataAdapterVO = new DataAdapterVO(); dataAdapterVO.setText("App Setting"); dataAdapterVO.setAssociatedValue(ApplicationConstant.MENU_SETTING_CAMERA); dataAdapterVO.setImage(R.drawable.rof_camera_btn_icon); datalist.add(dataAdapterVO); dataAdapterVO = new DataAdapterVO(); dataAdapterVO.setText("Exit"); dataAdapterVO.setAssociatedValue(ApplicationConstant.MENU_SETTING_VERTICAL_KEY_EXIT); dataAdapterVO.setImage(R.drawable.rof_exit); datalist.add(dataAdapterVO); return datalist; } }
package com.example.derrick.p03_classjournal; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { ListView lv; ArrayAdapter adapter; ArrayList<Module> moduleArrayList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv = findViewById(R.id.lvModules); moduleArrayList = new ArrayList<Module>(); moduleArrayList.add(new Module("C302","Web Services")); moduleArrayList.add(new Module("C347","Android Programming II")); adapter = new ModuleAdapter(this, R.layout.row_module, moduleArrayList); lv.setAdapter(adapter); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Module selectedModule = moduleArrayList.get(position); Intent i = new Intent(MainActivity.this, InfoActivity.class); i.putExtra("module_code",selectedModule.getCode()); startActivity(i); } }); } }