text
stringlengths
10
2.72M
package com.tencent.mm.ui.contact; import android.database.Cursor; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.messenger.foundation.a.i; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.ab; import com.tencent.mm.ui.contact.a.a; import com.tencent.mm.ui.contact.a.d; import java.util.ArrayList; public final class z extends o { private Cursor eCC = ((i) g.l(i.class)).FR().d(this.ugF, "", this.gRN); private String ugF; public z(MMBaseSelectContactUI mMBaseSelectContactUI, String str) { super(mMBaseSelectContactUI, new ArrayList(), false, false); this.ugF = str; g.Ek(); } public final int getCount() { return this.eCC.getCount(); } protected final a iW(int i) { if (i < 0 || !this.eCC.moveToPosition(i)) { x.e("MicroMsg.SpecialContactAdapter", "create Data Item Error position=%d", new Object[]{Integer.valueOf(i)}); return null; } d dVar = new d(i); ab abVar = new ab(); abVar.d(this.eCC); dVar.guS = abVar; dVar.ujX = bwq(); return dVar; } public final void finish() { super.finish(); x.i("MicroMsg.SpecialContactAdapter", "finish!"); if (this.eCC != null) { this.eCC.close(); this.eCC = null; } } }
package com.goodhealth.algorithm.Jackson_FastJson; import com.fasterxml.jackson.annotation.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; /** * @ClassName Teacher * @Description TODO * @Author WDH * @Date 2019/8/15 8:14 * @Version 1.0 **/ @Data @NoArgsConstructor @AllArgsConstructor @JsonIgnoreProperties(value = {"password","realName"}) //@JsonInclude(JsonInclude.Include.NON_NULL) //属性为null不参与序列化。 @JsonInclude(JsonInclude.Include.NON_EMPTY) // 属性为空或者null都不参与序列化。 @JsonIgnoreType //当其他类中含有Teacher这个属性时,Teacher属性将不会参与序列化或反序列化 public class Teacher { @JsonProperty(value = "id") private Integer teacherId; private Integer age; @JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss",timezone="GMT+8") private Date birthday; // 不参与序列化 @JsonIgnore private String password; private String loginName; private String realName; private Student student; public Teacher(Integer teacherId, Integer age, Date birthday, String loginName, String realName, String password) { this.teacherId = teacherId; this.age = age; this.birthday = birthday; this.loginName = loginName; this.realName = realName; this.password = password; } public Teacher(String loginName, int age){ this.loginName = loginName; this.age = age; } }
package org.usfirst.frc.team6880.robot.driveTrain; import org.usfirst.frc.team6880.robot.FRCRobot; import org.usfirst.frc.team6880.robot.jsonReaders.*; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.SpeedControllerGroup; import edu.wpi.first.wpilibj.VictorSP; import edu.wpi.first.wpilibj.drive.DifferentialDrive; public class VictorSPDriveSystem implements DriveSystem { FRCRobot robot; VictorSP motorL1; VictorSP motorL2; SpeedControllerGroup motorLeft; VictorSP motorR1; VictorSP motorR2; SpeedControllerGroup motorRight; DifferentialDrive drive; Encoder leftEnc; Encoder rightEnc; DriveTrainReader configReader; WheelSpecsReader wheelSpecsReader; private double wheelDiameter; private double wheelCircumference; private double distancePerCount; /* * TODO * We will need to support at least 2 different drive trains: * 1) 4 Motor 4 VictorSP controller drive train (this is what the current off season robot uses) * 2) 4 Motor 4 Talon SRX controller drive train (this is what the new competition robot will use) * * The goal is to use object oriented concepts to organize the driveTrain package in * such a way that the users of DriveSystem class (Navigation, FRCRobot, Tasks, etc.) * do not have to know which specific drive train is being currently used. */ public VictorSPDriveSystem(FRCRobot robot, String driveSysName) { this.robot = robot; configReader = new DriveTrainReader(JsonReader.driveTrainsFile, driveSysName); String wheelType = configReader.getWheelType(); wheelSpecsReader = new WheelSpecsReader(JsonReader.wheelSpecsFile, wheelType); wheelDiameter = wheelSpecsReader.getDiameter(); wheelCircumference = Math.PI * wheelDiameter; // We will assume that the same encoder is used on both left and right sides of the drive train. distancePerCount = wheelCircumference / configReader.getEncoderValue("LeftEncoder", "CPR"); // TODO Use configReader.getChannelNum() method to identify the // channel numbers where each motor controller is plugged in motorL1 = new VictorSP(configReader.getChannelNum("Motor_L1")); motorL2 = new VictorSP(configReader.getChannelNum("Motor_L2")); motorLeft = new SpeedControllerGroup(motorL1, motorL2); motorR1 = new VictorSP(configReader.getChannelNum("Motor_R1")); motorR2 = new VictorSP(configReader.getChannelNum("Motor_R2")); motorRight = new SpeedControllerGroup(motorR1, motorR2); drive = new DifferentialDrive(motorLeft, motorRight); int[] encoderChannelsLeft = configReader.getEncoderChannels("LeftEncoder"); leftEnc = new Encoder(encoderChannelsLeft[0], encoderChannelsLeft[1], false, Encoder.EncodingType.k4X); leftEnc.setDistancePerPulse(distancePerCount); int[] encoderChannelsRight = configReader.getEncoderChannels("RightEncoder"); rightEnc = new Encoder(encoderChannelsRight[0], encoderChannelsRight[1], true, Encoder.EncodingType.k4X); rightEnc.setDistancePerPulse(distancePerCount); } public void tankDrive(double leftSpeed, double rightSpeed) { drive.tankDrive(leftSpeed, rightSpeed); } public void arcadeDrive(double speed, double rotationRate) { drive.arcadeDrive(speed, rotationRate); } public void resetEncoders() { leftEnc.reset(); rightEnc.reset(); } public double getEncoderDist() { return (leftEnc.getDistance() + rightEnc.getDistance()) / 2.0; } }
package at.fhv.team3.application; import at.fhv.team3.domain.dto.EmployeeDTO; public class LoggedInUser { private static LoggedInUser _loggedInUser; private EmployeeDTO _user; private LoggedInUser() { } public static LoggedInUser getInstance() { if (_loggedInUser == null) { _loggedInUser = new LoggedInUser(); } return _loggedInUser; } public void setUser(EmployeeDTO user) { _user = user; } public EmployeeDTO getUser() { return this._user; } public Boolean isLoggedIn() { if (_user != null) { return true; } return false; } }
/* * Copyright 2010 sdp.com, Inc. All rights reserved. * sdp.com PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * creator : jiangyixin.stephen * create time : 2013-2-25 下午5:33:57 */ package tools.invoker; import org.junit.Assert; import org.junit.Test; import tools.invoker.command.CommandDescriptor; import tools.invoker.command.FailFastCommand; import tools.invoker.command.FailSafeCommand; import java.util.List; import static org.hamcrest.CoreMatchers.is; /** * 功能描述: * * @author jiangyixin.stephen * time : 2013-2-25 下午5:33:57 */ public class InvokerTest { @Test public void testSyncInvoker() { Result result = Invokers.newSyncInvoker().addLogic("更新数据", new FailFastCommand<Integer>() { @Override public Integer execute() throws Exception { return 1; } }).execute().getResults(); List<CommandDescriptor> cmds = result.getCompletedCmds(); Assert.assertThat((Integer) cmds.get(0).getResult(), is(1)); } @Test public void testFailFastCommand() { Result result = Invokers.newSyncInvoker().addLogic("抛出异常", new FailFastCommand<Integer>() { @Override public Integer execute() throws Exception { throw new Exception("异常"); } }).addLogic("不会执行", new FailFastCommand<Integer>() { @Override public Integer execute() throws Exception { return 1; } }).execute().getResults(); List<CommandDescriptor> cmds = result.getCompletedCmds(); Assert.assertThat(cmds.size(), is(1)); Assert.assertThat(cmds.get(0).getName(), is("抛出异常")); } @Test public void testFailSafeCommand() { Result result = Invokers.newSyncInvoker().addLogic("抛出异常", new FailSafeCommand<Integer>() { @Override public Integer execute() throws Exception { throw new Exception("异常"); } }).addLogic("会被执行", new FailFastCommand<Integer>() { @Override public Integer execute() throws Exception { return 1; } }).execute().getResults(); List<CommandDescriptor> cmds = result.getCompletedCmds(); Assert.assertThat(cmds.size(), is(2)); Assert.assertThat(cmds.get(1).getName(), is("会被执行")); } @Test public void testAsyncInvoker() { long s = System.currentTimeMillis(); Result result = Invokers.newAsyncInvoker(4).addLogic("耗时操作1", new FailFastCommand<Integer>() { @Override public Integer execute() throws Exception { Thread.sleep(1000); return 1; } }).addLogic("耗时操作2", new FailFastCommand<Integer>() { @Override public Integer execute() throws Exception { Thread.sleep(1000); return 2; } }).addLogic("耗时操作3", new FailFastCommand<Integer>() { @Override public Integer execute() throws Exception { Thread.sleep(1000); return 3; } }).execute().getResults(); System.out.println(System.currentTimeMillis() - s); List<CommandDescriptor> cmds = result.getCompletedCmds(); Assert.assertThat(cmds.size(), is(3)); Assert.assertThat((Integer) cmds.get(1).getResult(), is(2)); } }
/* * Copyright © 2016, 2018 IBM Corp. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.ibm.cloudant.kafka.common; public class InterfaceConst { public final static String URL = "cloudant.db.url"; public final static String USER_NAME = "cloudant.db.username"; public final static String PASSWORD = "cloudant.db.password"; public final static String LAST_CHANGE_SEQ = "cloudant.db.since"; public final static String TOPIC = "topics"; public final static String TASKS_MAX = "tasks.max"; public final static String TASK_NUMBER = "task.number"; public final static String BATCH_SIZE = "batch.size"; public static final int DEFAULT_BATCH_SIZE = 1000; public static final int DEFAULT_TASKS_MAX = 1; public static final int DEFAULT_TASK_NUMBER = 0; public final static String REPLICATION = "replication"; public final static Boolean DEFAULT_REPLICATION = false; public final static String KC_SCHEMA = "kc_schema"; // Whether to omit design documents public final static String OMIT_DESIGN_DOCS = "cloudant.omit.design.docs"; // Whether to use a struct schema for the message values public final static String USE_VALUE_SCHEMA_STRUCT = "cloudant.value.schema.struct"; public final static String FLATTEN_VALUE_SCHEMA_STRUCT = "cloudant.value.schema.struct.flatten"; }
package com.base.crm.sign.entity; import java.util.Date; import java.util.Locale; import org.thymeleaf.util.DateUtils; import com.base.common.util.DateFormateType; import com.base.common.util.PageTools; public class UserSign { private Long id; private Long userId; private String userName; private String signDate; private String signTime; private String signExitTime; // query private String startDate = DateUtils.format(new Date(), "yyyyMM01", Locale.getDefault()); private String endDate = DateUtils.format(new Date(), DateFormateType.TIGHT_SHORT_FORMAT, Locale.getDefault()); private PageTools pageTools; public UserSign() { } public UserSign(Long id) { this.id = id; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getSignDate() { return signDate; } public void setSignDate(String signDate) { this.signDate = signDate; } public String getSignTime() { return signTime; } public void setSignTime(String signTime) { this.signTime = signTime; } public String getSignExitTime() { return signExitTime; } public void setSignExitTime(String signExitTime) { this.signExitTime = signExitTime; } public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public PageTools getPageTools() { return pageTools; } public void setPageTools(PageTools pageTools) { this.pageTools = pageTools; } @Override public String toString() { return String.format( "UserSign [id=%s, userId=%s, userName=%s, signDate=%s, signTime=%s, signExitTime=%s, startDate=%s, endDate=%s, pageTools=%s]", id, userId, userName, signDate, signTime, signExitTime, startDate, endDate, pageTools); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.solutec; /** * * @author esic */ public class EmployesConstantes { //Connection 1 public static final String url = "jdbc:derby://localhost:1527/BaseTP"; public static final String user = "jee"; public static final String mdp = "jee"; //Connection 2 public static final String url2 = "jdbc:derby://localhost:1527/solutec"; public static final String user2 = "test"; public static final String mdp2 = "test"; //Requêtes SQL public static final String REQ ="SELECT * FROM IDENTIFIANTS"; public static final String REQ2 ="SELECT * FROM EMPLOYES"; public static final String REQ3 ="DELETE FROM EMPLOYES WHERE ID=?"; public static final String REQ4 ="SELECT * FROM EMPLOYES WHERE ID=?"; public static final String REQ5 ="UPDATE EMPLOYES SET NOM=?, PRENOM=?, ADRESSE=?, EMAIL=? WHERE ID=?"; //Pages public static final String PAGE_INDEX = "index.jsp"; public static final String PAGE_CONTROLEUR = "Controleur"; public static final String PAGE_BIENVENUE = "bienvenue.jsp"; public static final String PAGE_DETAIL_EMPLOYE = "detailsEmployes.jsp"; //Messages d'erreur public static final String ERREUR_SAISIE_VIDE = "Vous devez renseigner les deux champs"; public static final String ERREUR_LOGIN_MDP = "Informations de connexion non valides. Réessayer svp"; //Actions public static final String ACTION_SUPPRIMER = "Supprimer"; public static final String ACTION_DETAILS = "Details"; public static final String ACTION_MODIFIER = "Modifier"; public static final String ACTION_VOIR_LISTE = "Voir liste"; }
package edu.cmu.lti.oaqa.openqa.test.team10.passage; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.solr.client.solrj.SolrServerException; import org.jsoup.Jsoup; import com.google.common.base.Function; import com.google.common.collect.Lists; import edu.cmu.lti.oaqa.framework.data.Keyterm; import edu.cmu.lti.oaqa.framework.data.PassageCandidate; import edu.cmu.lti.oaqa.framework.data.RetrievalResult; import edu.cmu.lti.oaqa.openqa.hello.passage.SimplePassageExtractor; //import edu.cmu.lti.oaqa.openqa.test.team10.passage.PassageCandidateFinder.PassageSpan; /** * This class set a threshold on the length of candidate passage * @author Yifei * */ public class CutSimpleBioPassageExtractor extends SimplePassageExtractor { @Override protected List<PassageCandidate> extractPassages(String question, List<Keyterm> keyterms, List<RetrievalResult> documents) { int gap = 3000; List<PassageCandidate> result = new ArrayList<PassageCandidate>(); for (RetrievalResult document : documents) { System.out.println("RetrievalResult: " + document.toString()); String id = document.getDocID(); try { String text= wrapper.getDocText(id); CutPassageCandidateFinder finder = new CutPassageCandidateFinder(id, text, new KeytermWindowScorerSum()); List<String> keytermStrings = Lists.transform(keyterms, new Function<Keyterm, String>() { public String apply(Keyterm keyterm) { return keyterm.getText(); } }); List<PassageCandidate> passageSpans = finder.extractPassages(keytermStrings .toArray(new String[0]),gap); for (PassageCandidate passageSpan : passageSpans) result.add(passageSpan); } catch (SolrServerException e) { e.printStackTrace(); } } return result; } }
package testDemo; import rabbitmq.MqManager; public class StartTest { public static void main(String[] args) { MqManager.start(); } }
package ru.otus.testframework; import java.util.ArrayList; import java.util.stream.IntStream; import ru.otus.testframework.framework.BeforeAll; import ru.otus.testframework.framework.AfterEach; import ru.otus.testframework.framework.AfterAll; import ru.otus.testframework.framework.BeforeEach; import ru.otus.testframework.framework.Test; import static ru.otus.testframework.framework.MyAsserts.*; public class TestClass { private final ArrayList<Integer> list = new ArrayList<>(4);; private final ArrayList<Integer> list2 = new ArrayList<>(4); private final ArrayList<Integer> array1 = new ArrayList<>(); private final ArrayList<Integer> array2 = new ArrayList<>(); @BeforeAll public static void init(){ System.out.println("Hello! TEST started. BeforeALL method called!\n"); } @BeforeEach public void addElementIntoList() { IntStream.range(15, 20).forEach(i -> array1.add(i)); IntStream.range(0, 10).forEach(i -> array2.add(i)); list.addAll(array1); list.addAll(array2); } @Test public void listEmpty() { list2.add(10); list2.add(20); list2.remove(0); list2.remove(0); assertTrue(list2.isEmpty()); } @Test public void getElementsByIndx() { assertEquals(15, list.get(0)); } @Test public void getIndexOfElement() { assertEquals(14, list.get(0)); } @AfterEach public void afterEach() { list.clear(); System.out.println("AfterEach method called!\n"); } @AfterAll public static void clearOther() { System.out.println("TEST finished. AfterAll method called!\n"); } }
package com.avogine.junkyard.scene.entity.collision; import org.ode4j.ode.DGeom; import org.ode4j.ode.DSpace; import org.ode4j.ode.DTriMeshData; import org.ode4j.ode.DWorld; import org.ode4j.ode.OdeHelper; import com.avogine.junkyard.scene.entity.Body; import com.avogine.junkyard.scene.entity.render.TerrainModel; public class TerrainCollider extends Collider { private DGeom plane; private DTriMeshData triMeshData; public TerrainCollider(int entity, DWorld world, DSpace space, Body entityBody, TerrainModel entityModel) { super(entity); body = OdeHelper.createBody(world); body.setPosition(entityBody.getPosition().x, entityBody.getPosition().y, entityBody.getPosition().z); body.setGravityMode(false); body.setKinematic(); // TODO Change this into a heightfield probably triMeshData = entityModel.getTriMeshData(); plane = OdeHelper.createTriMesh(space, triMeshData, null, null, null); //plane = OdeHelper.createPlane(space, 0, 1, 0, 0); plane.setBody(body); } }
/** * Copyright (c) 2016, 指端科技. */ package com.rofour.baseball.dao.user.mapper; import javax.inject.Named; import com.rofour.baseball.dao.user.bean.RandomCodeBean; /** * @ClassName: RandomCodeForUserMapper * @Description: 用户随机码mapper接口 * @author 周琦 * @date 2016年3月26日 下午3:22:59 * */ @Named("randomCodeMapper") public interface RandomCodeMapper { /** * 新增验证码信息 */ int insertSelective(RandomCodeBean randomCodeBean); /** * 获取当前用户有效验证码 */ RandomCodeBean getByParam(RandomCodeBean randomCodeBean); /** * 更新验证码状态 */ int updateCodeStatus(RandomCodeBean randomCodeBean); }
package com.spbsu.flamestream.core; import com.spbsu.flamestream.core.data.meta.LabelsPresence; import java.io.Serializable; import java.util.function.BiPredicate; public interface Equalz extends BiPredicate<DataItem, DataItem>, Serializable { static Equalz hashEqualz(HashFunction hashFunction) { return new Equalz() { private final HashFunction h = hashFunction; @Override public boolean testPayloads(DataItem dataItem, DataItem dataItem2) { return h.applyAsInt(dataItem) == h.applyAsInt(dataItem2); } }; } default LabelsPresence labels() { return LabelsPresence.EMPTY; } @Override default boolean test(DataItem dataItem, DataItem dataItem2) { return labels().stream().allMatch(label -> dataItem.meta().labels().get(label).equals(dataItem2.meta().labels().get(label)) ) && testPayloads(dataItem, dataItem2); } boolean testPayloads(DataItem dataItem, DataItem dataItem2); static Equalz allEqualz() { return (dataItem, dataItem2) -> true; } static <T> Equalz objectEqualz(Class<T> clazz) { return new Equalz() { private final Class<T> c = clazz; @Override public boolean testPayloads(DataItem dataItem, DataItem dataItem2) { return dataItem.payload(c).equals(dataItem2.payload(clazz)); } }; } }
package com.example.homestay_kha.Controller.Interface; import com.example.homestay_kha.Model.Tien_nghi_model; public interface Tien_nghi_Interface { void getTiennghi (Tien_nghi_model tien_nghi_model); }
package com.jpmc.portfolio.domain; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; public class Fund { private String name; private BigDecimal marketValue; private List<Fund> childFunds = new ArrayList<>(); private List<Fund> parentFunds = new ArrayList<>(); public Fund(String name, BigDecimal marketValue) { this.name = name; this.marketValue = marketValue; } public String getName() { return name; } public BigDecimal getMarketValue() { if(!childFunds.isEmpty()) { return childFunds.stream().map(Fund::getMarketValue).reduce(BigDecimal.ZERO, BigDecimal::add); } return marketValue; } public List<Fund> getChildFunds() { return childFunds; } public List<Fund> getParentFunds() { return parentFunds; } }
package com.ekniernairb.dicejobsearcher.networking; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import java.util.ArrayList; /* * All the pieces needed to do the following are in this class: * * URIBuilder * * Check internet connection * * HTTP GET connection * * Read from Stream * * */ public class NetworkStreaming { private NetworkStreaming() { } /* * ConverttoURL is needed because we have to convert the URL-string to URL-object. * */ public static URL ConverttoURL(String url_string) { URL urlString = null; try { urlString = new URL(url_string); } catch (MalformedURLException e) { e.printStackTrace(); } return urlString; } public static String BuildUriURL(String scheme, String authority, String resource, ArrayList<QueryURI> queryAL) { // Builds the complete URL for URI (in String format). // Input 'url_string' must be only the http://<domain> portion! // URL we want: //String URL_string = URL we want: https://content.guardianapis.com/us-news?api-key=431fa4f4-baa3-4b01-8584-6dfe2fa215fe /* * Do syntax checking on scheme. * */ String correctedScheme = scheme.trim(); correctedScheme = correctedScheme.replace(" ", ""); correctedScheme = correctedScheme.replace("/", ""); correctedScheme = correctedScheme.replace("/", ""); if (!correctedScheme.substring(correctedScheme.length() - 1).contentEquals(":")) { correctedScheme += ":"; } /* * Do syntax checking on authority. * */ String correctedAuthority = authority.trim(); correctedAuthority = correctedAuthority.replace(" ", ""); // remove 'slashes' should it have it..we'll add it programtically. correctedAuthority = correctedAuthority.replace("/", ""); if (!correctedScheme.substring(correctedScheme.length() - 1).contentEquals(":")) { correctedScheme += ":"; } /* * Do syntax checking on resource. * */ String correctedResource = resource.trim(); correctedResource = correctedResource.replace(" ", ""); if (correctedResource.length() != 0) { if (correctedResource.substring(correctedResource.length() - 1).contentEquals("/")) { correctedResource = correctedResource.substring(0, correctedResource.length() - 2); } } /* * Build the query. * */ String queryPath = ""; int i = 0; for (QueryURI curItem : queryAL) { i++; if (i == 1) { queryPath += "?"; } else if (i > 1) { queryPath += "&"; } queryPath += curItem.getKey() + "=" + curItem.getValue(); } Uri myURL = Uri.parse(correctedScheme + "//" + correctedAuthority + "/" + correctedResource + queryPath); /* Am not using because the builder is too limiting for our purposes. Uri.Builder builder = new Uri.Builder(); builder.scheme(scheme) .authority(authority) .appendPath("books") .appendPath("v1") .appendPath("volumes") .appendQueryParameter("q", this.mQueryText) .appendQueryParameter("maxResults", "40"); String myUrl = builder.build().toString();*/ return myURL.toString(); } public static String makeHttpRequest(URL url) { HttpURLConnection urlConnection = null; InputStream inputStream = null; String jsonResponse = ""; StringBuilder JsonResponseBuilder = new StringBuilder(); if (url == null) { // returns empty. return jsonResponse; } try { // Making an HTTP(s) Get connection. urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setReadTimeout(10000); // in milliseconds urlConnection.setConnectTimeout(15000); // in milliseconds urlConnection.connect(); // where it establishes the connection. if (urlConnection.getResponseCode() == 200) { inputStream = urlConnection.getInputStream(); jsonResponse = readFromStream(inputStream); JsonResponseBuilder.append(jsonResponse); } //TODO: Add response codes to inform the user. } catch (IOException e) { //TODO: Handle the exception Log.e("!myapp!", "Some IO exception when creating the connection"); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { // e.printStackTrace(); Log.e("!myapp!", "ioexception;" + e.getMessage()); } } } jsonResponse = JsonResponseBuilder.toString(); return jsonResponse; } private static String readFromStream(InputStream inputStream) { // In our case, returns a JSON response. StringBuilder output = new StringBuilder(); if (inputStream != null) { InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8")); BufferedReader reader = new BufferedReader(inputStreamReader); String line = null; try { // readLine() must be in a try/catch because there could be an unhandled eception. line = reader.readLine(); } catch (IOException e) { // e.printStackTrace(); } while (line != null) { output.append(line); try { line = reader.readLine(); } catch (IOException e) { // e.printStackTrace(); } } } return output.toString(); } public static boolean checkInternetConnection(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); return isConnected; } }
package com.mx.profuturo.bolsa.model.service.candidates.dto; public class GetDetailsCandidateRequestBean { private String idCandidato; public String getIdCandidato() { return idCandidato; } public void setIdCandidato(String idCandidato) { this.idCandidato = idCandidato; } }
/* ******************************************************************************** * システム:i-mode chat management * *==============================================================================* * モジュール:Uid.java * * クラス名 :Uid * * 概要   :NTTドコモ uid 取得クラス * * 作成   :2004/05/14 K.Katafuchi(affinity) * *------------------------------------------------------------------------------* * 更新  :2004/06/08 K.Katafuchi(affinity) * * ai-land i-mode より移植 * ******************************************************************************** */ /*-- パッケージ --------------------------------------------------------------*/ package manage.util; /*-- インポート --------------------------------------------------------------*/ import java.io.*; import javax.servlet.http.*; import manage.system.*; /*-- クラス定義 --------------------------------------------------------------*/ public class Uid { private String _Uid; public void setUid( String s ) { _Uid = s; } public String getUid() { return _Uid; } private HttpServletRequest _Request; //-------------------------------------------------------- // コンストラクタ //-------------------------------------------------------- public Uid() { clear(); } public Uid( HttpServletRequest request ) { setRequest( request ); clear(); } public void setRequest( HttpServletRequest request ) { _Request = request; } private void clear() { _Uid = ""; } //-------------------------------------------------------- // メソッド:uid 取得 12桁 // 戻り値 :uid(12桁) //-------------------------------------------------------- public String createID() { String UID = null; if( _Request != null ) UID = _Request.getParameter( "uid" ); if( UID == null || UID.equals("NULLGWDOCOMO")) UID = createID_dummy(); return( UID ); } /* テスト用にダミーuid発行メソッド */ public String createID_dummy() { String UID = ""; try { InputStreamReader _In = new InputStreamReader( new FileInputStream( Static.HomeDir + "uid.txt" ), "SJIS" ); BufferedReader _Buf = new BufferedReader( _In ); // EOFなら終了 if( _Buf.ready() ) { // 1行読込み UID = _Buf.readLine(); } } catch( Exception X ) { Static.Error.out( X.toString() ); } return( UID ); } }
class ForWhile { public static void main(String[] args) { /* * for (初始化语句;循环条件表达式;循环后的操作表达式) * { * 执行语句: * } */ for(int x = 0; x < 3; x++) { System.out.println("x="+x); } // 作用域问题,x在for循环中创建,只在for的大括号内有效, // 离开大括号,x就在内存中消失了 // System.out.println("x ======="+x); // //17-for-while.java:17: 错误: 找不到符号 int y = 0; while (y < 3) { System.out.println("y="+y); y++; } System.out.println("y====="+y); } } // 如果变量只为循环增量存在,那么用for更好,省内存,y占用内存,不会随着while结束而消失
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.charon3.impl.provider.resources; //Adding commeny to test git import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.HEAD; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import javax.ws.rs.ext.Provider; import javax.xml.bind.annotation.XmlRegistry; import org.json.JSONObject; import java.util.Arrays; import java.util.logging.Logger; import org.wso2.charon3.core.exceptions.CharonException; import org.wso2.charon3.core.exceptions.FormatNotSupportedException; import org.wso2.charon3.core.extensions.UserManager; import org.wso2.charon3.core.protocol.SCIMResponse; import org.wso2.charon3.core.protocol.endpoints.UserResourceManager; import org.wso2.charon3.impl.jaxrs.designator.PATCH; import org.wso2.charon3.impl.provider.util.SCIMProviderConstants; import org.wso2.charon3.utils.DefaultCharonManager; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import io.swagger.annotations.Contact; import io.swagger.annotations.Info; import io.swagger.annotations.License; import io.swagger.annotations.ResponseHeader; import io.swagger.annotations.SwaggerDefinition; /** * Endpoints of the UserResource in micro service. This will basically captures * the requests from the remote clients and hand over the request to respective operation performer. * */ @Api(value = "scim/v2/Users") @SwaggerDefinition( info = @Info( title = "/Users Endpoint Swagger Definition", version = "1.0", description = "SCIM 2.0 /Users endpoint", license = @License(name = "Apache 2.0", url = "http://www.apache.org/licenses/LICENSE-2.0"), contact = @Contact( name = "WSO2 Identity Server Team", email = "vindula@wso2.com", url = "http://wso2.com" )) ) @Path("/scim/v2/Users") public class UserResource extends AbstractResource { Logger logger = Logger.getLogger(UserResource.class.getName()); @GET @Path("/{id}") @Produces({"application/json", "application/scim+json"}) @ApiOperation( value = "Return the user with the given id", notes = "Returns HTTP 200 if the user is found.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Valid user is found"), @ApiResponse(code = 404, message = "Valid user is not found")}) public Response getUser(@ApiParam(value = SCIMProviderConstants.ID_DESC, required = true) @PathParam(SCIMProviderConstants.ID) String id, @ApiParam(value = SCIMProviderConstants.ATTRIBUTES_DESC, required = false) @QueryParam(SCIMProviderConstants.ATTRIBUTES) String attribute, @ApiParam(value = SCIMProviderConstants.EXCLUDED_ATTRIBUTES_DESC, required = false) @QueryParam(SCIMProviderConstants.EXCLUDE_ATTRIBUTES) String excludedAttributes) throws FormatNotSupportedException, CharonException { System.out.println("\n Get User by ID calls "); try { // obtain the user store manager UserManager userManager = DefaultCharonManager.getInstance().getUserManager(); // CreateUserManager userManager = (CreateUserManager) userManagerImpl; // create charon-SCIM user endpoint and hand-over the request. UserResourceManager userResourceManager = new UserResourceManager(); SCIMResponse scimResponse = userResourceManager.get(id, userManager, attribute, excludedAttributes); // needs to check the code of the response and return 200 0k or other error codes // appropriately. JSONObject object = new JSONObject(scimResponse); System.out.println("responce of getUserById = "+object.toString()); return buildResponse(scimResponse); } catch (CharonException e) { System.out.println("Charon exception got :: "+e.getMessage()); throw new CharonException(e.getDetail(), e); } } @ApiOperation( value = "Return the user which was created", notes = "Returns HTTP 201 if the user is successfully created.") @POST @Produces({"application/json", "application/scim+json"}) @Consumes("application/scim+json") @ApiResponses(value = { @ApiResponse(code = 201, message = "Valid user is created"), @ApiResponse(code = 404, message = "User is not found")}) public Response createUser(@ApiParam(value = SCIMProviderConstants.ATTRIBUTES_DESC, required = false) @QueryParam(SCIMProviderConstants.ATTRIBUTES) String attribute, @ApiParam(value = SCIMProviderConstants.EXCLUDED_ATTRIBUTES_DESC, required = false) @QueryParam(SCIMProviderConstants.EXCLUDE_ATTRIBUTES) String excludedAttributes, String resourceString) throws CharonException, FormatNotSupportedException { // System.out.println("\n /createUser callls.."); try { logger.info("Enter in /Users--->createUser "); System.out.println("Request for create user :: " + "\nattribute = "+attribute+ " :: " + "\nexcludedAttributes = "+ excludedAttributes+ " ::" + "\n resourceString = "+resourceString); // obtain the user store manager UserManager userManager = DefaultCharonManager.getInstance().getUserManager(); // CreateUserManager userManager = (CreateUserManager)userManager_1; //debug // CreateUserManager createUserManager = (CreateUserManager) DefaultCharonManager.getInstance().getUserManager(); // create charon-SCIM user endpoint and hand-over the request. UserResourceManager userResourceManager = new UserResourceManager(); // System.out.println("RESOURCE STRING :: "+resourceString); SCIMResponse response = userResourceManager.create(resourceString, userManager, attribute, excludedAttributes); JSONObject jsonObject = new JSONObject(response); System.out.println("Response of Create user "+jsonObject.toString()); return buildResponse(response); } catch (CharonException e) { throw new CharonException(e.getDetail(), e); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } @DELETE @Path("/{id}") @Produces({"application/json", "application/scim+json"}) @ApiOperation( value = "Delete the user with the given id", notes = "Returns HTTP 204 if the user is successfully deleted.") @ApiResponses(value = { @ApiResponse(code = 204, message = "User is deleted"), @ApiResponse(code = 404, message = "Valid user is not found")}) public Response deleteUser(@ApiParam(value = SCIMProviderConstants.ID_DESC, required = true) @PathParam(SCIMProviderConstants.ID) String id) throws FormatNotSupportedException, CharonException { try { // obtain the user store manager System.out.println("/delete (User)request"); System.out.println("id : "+id); UserManager userManager = DefaultCharonManager.getInstance().getUserManager(); // create charon-SCIM user resource manager and hand-over the request. UserResourceManager userResourceManager = new UserResourceManager(); SCIMResponse scimResponse = userResourceManager.delete(id, userManager); // needs to check the code of the response and return 200 0k or other error codes // appropriately. return buildResponse(scimResponse); } catch (CharonException e) { throw new CharonException(e.getDetail(), e); } } @GET @Produces({"application/json", "application/scim+json"}) @ApiOperation( value = "Return users according to the filter, sort and pagination parameters", notes = "Returns HTTP 404 if the users are not found.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Valid users are found"), @ApiResponse(code = 404, message = "Valid users are not found")}) public Response getUser(@ApiParam(value = SCIMProviderConstants.ATTRIBUTES_DESC, required = false) @QueryParam(SCIMProviderConstants.ATTRIBUTES) String attribute, @ApiParam(value = SCIMProviderConstants.EXCLUDED_ATTRIBUTES_DESC, required = false) @QueryParam(SCIMProviderConstants.EXCLUDE_ATTRIBUTES) String excludedAttributes, @ApiParam(value = SCIMProviderConstants.FILTER_DESC, required = false) @QueryParam(SCIMProviderConstants.FILTER) String filter, @ApiParam(value = SCIMProviderConstants.START_INDEX_DESC, required = false) @QueryParam(SCIMProviderConstants.START_INDEX) int startIndex, @ApiParam(value = SCIMProviderConstants.COUNT_DESC, required = false) @QueryParam(SCIMProviderConstants.COUNT) int count, @ApiParam(value = SCIMProviderConstants.SORT_BY_DESC, required = false) @QueryParam(SCIMProviderConstants.SORT_BY) String sortBy, @ApiParam(value = SCIMProviderConstants.SORT_ORDER_DESC, required = false) @QueryParam(SCIMProviderConstants.SORT_ORDER) String sortOrder) throws FormatNotSupportedException, CharonException { try { System.out.println("Filter = "+filter); // obtain the user store manager UserManager userManager = DefaultCharonManager.getInstance().getUserManager(); // create charon-SCIM user resource manager and hand-over the request. UserResourceManager userResourceManager = new UserResourceManager(); SCIMResponse scimResponse = userResourceManager.listWithGET(userManager, filter, startIndex, count, sortBy, sortOrder, attribute, excludedAttributes); JSONObject jsonObject = new JSONObject(scimResponse); System.out.println("Response of Get Users :: "+jsonObject.toString()); return buildResponse(scimResponse); } catch (CharonException e) { throw new CharonException(e.getDetail(), e); } } @POST @Path("/.search") @Produces({"application/json", "application/scim+json"}) @Consumes("application/scim+json") @ApiOperation( value = "Return users according to the filter, sort and pagination parameters", notes = "Returns HTTP 404 if the users are not found.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Valid users are found"), @ApiResponse(code = 404, message = "Valid users are not found")}) public Response getUsersByPost(String resourceString) throws FormatNotSupportedException, CharonException { try { // obtain the user store manager UserManager userManager = DefaultCharonManager.getInstance().getUserManager(); // create charon-SCIM user resource manager and hand-over the request. UserResourceManager userResourceManager = new UserResourceManager(); SCIMResponse scimResponse = userResourceManager.listWithPOST(resourceString, userManager); return buildResponse(scimResponse); } catch (CharonException e) { throw new CharonException(e.getDetail(), e); } } @PUT @Path("{id}") @Produces({"application/json", "application/scim+json"}) @Consumes("application/scim+json") @ApiOperation( value = "Return the updated user", notes = "Returns HTTP 404 if the user is not found.") @ApiResponses(value = { @ApiResponse(code = 200, message = "User is updated"), @ApiResponse(code = 404, message = "Valid user is not found")}) public Response updateUser(@ApiParam(value = SCIMProviderConstants.ID_DESC, required = true) @PathParam(SCIMProviderConstants.ID) String id, @ApiParam(value = SCIMProviderConstants.ATTRIBUTES_DESC, required = false) @QueryParam(SCIMProviderConstants.ATTRIBUTES) String attribute, @ApiParam(value = SCIMProviderConstants.EXCLUDED_ATTRIBUTES_DESC, required = false) @QueryParam(SCIMProviderConstants.EXCLUDE_ATTRIBUTES) String excludedAttributes, String resourceString) throws FormatNotSupportedException, CharonException { try { System.out.println("request /updateUser :: id ="+id+", attribute :: "+attribute+", ecludedeAttribute :: "+excludedAttributes+", resourceString :: "+resourceString); // obtain the user store manager UserManager userManager = DefaultCharonManager.getInstance().getUserManager(); // create charon-SCIM user endpoint and hand-over the request. UserResourceManager userResourceManager = new UserResourceManager(); SCIMResponse response = userResourceManager.updateWithPUT( id, resourceString, userManager, attribute, excludedAttributes); JSONObject object = new JSONObject(response); System.out.println("Responce of updateUser is :: "+object.toString()); return buildResponse(response); } catch (CharonException e) { throw new CharonException(e.getDetail(), e); } } @PATCH @Path("/{id}") @Produces({"application/json", "application/scim+json"}) @Consumes("application/scim+json") @ApiOperation( value = "Return the updated user", notes = "Returns HTTP 404 if the user is not found.") @ApiResponses(value = { @ApiResponse(code = 200, message = "User is updated"), @ApiResponse(code = 404, message = "Valid user is not found")}) public Response updateUserPatch(@ApiParam(value = SCIMProviderConstants.ID_DESC, required = true) @PathParam(SCIMProviderConstants.ID) String id, @ApiParam(value = SCIMProviderConstants.ATTRIBUTES_DESC, required = false) @QueryParam(SCIMProviderConstants.ATTRIBUTES) String attribute, @ApiParam(value = SCIMProviderConstants.EXCLUDED_ATTRIBUTES_DESC, required = false) @QueryParam(SCIMProviderConstants.EXCLUDE_ATTRIBUTES) String excludedAttributes, String resourceString) throws FormatNotSupportedException, CharonException { try { System.out.println("request /updateUser Patch :: id ="+id+", attribute :: "+attribute+", ecludedeAttribute :: "+excludedAttributes+", resourceString :: "+resourceString); // obtain the user store manager UserManager userManager = DefaultCharonManager.getInstance().getUserManager(); // create charon-SCIM user endpoint and hand-over the request. UserResourceManager userResourceManager = new UserResourceManager(); SCIMResponse response = userResourceManager.updateWithPATCH( id, resourceString, userManager, attribute, excludedAttributes); JSONObject object = new JSONObject(response); System.out.println("Responce of updateUserWithPatch is :: "+object.toString()); return buildResponse(response); } catch (CharonException e) { throw new CharonException(e.getDetail(), e); } } }
package com.mes.old.meta; // Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final import java.math.BigDecimal; /** * BOperatestep generated by hbm2java */ public class BOperatestep implements java.io.Serializable { private BOperatestepId id; private BigDecimal operationId; private String routing; private String stepname; private String processtime; private String notes; private String creator; private String createtime; private String BOperatestepOutUid; public BOperatestep() { } public BOperatestep(BOperatestepId id, BigDecimal operationId, String routing) { this.id = id; this.operationId = operationId; this.routing = routing; } public BOperatestep(BOperatestepId id, BigDecimal operationId, String routing, String stepname, String processtime, String notes, String creator, String createtime, String BOperatestepOutUid) { this.id = id; this.operationId = operationId; this.routing = routing; this.stepname = stepname; this.processtime = processtime; this.notes = notes; this.creator = creator; this.createtime = createtime; this.BOperatestepOutUid = BOperatestepOutUid; } public BOperatestepId getId() { return this.id; } public void setId(BOperatestepId id) { this.id = id; } public BigDecimal getOperationId() { return this.operationId; } public void setOperationId(BigDecimal operationId) { this.operationId = operationId; } public String getRouting() { return this.routing; } public void setRouting(String routing) { this.routing = routing; } public String getStepname() { return this.stepname; } public void setStepname(String stepname) { this.stepname = stepname; } public String getProcesstime() { return this.processtime; } public void setProcesstime(String processtime) { this.processtime = processtime; } public String getNotes() { return this.notes; } public void setNotes(String notes) { this.notes = notes; } public String getCreator() { return this.creator; } public void setCreator(String creator) { this.creator = creator; } public String getCreatetime() { return this.createtime; } public void setCreatetime(String createtime) { this.createtime = createtime; } public String getBOperatestepOutUid() { return this.BOperatestepOutUid; } public void setBOperatestepOutUid(String BOperatestepOutUid) { this.BOperatestepOutUid = BOperatestepOutUid; } }
package com.mystore.qa.pages; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import com.mystore.qa.base.TestBase; public class PaymentPage extends TestBase { @FindBy(xpath="//h1[contains(text(),'Please choose your payment method')]") @CacheLookup WebElement paymentTag; @FindBy(xpath="//*[@id=\"HOOK_PAYMENT\"]/div[2]/div/p/a") @CacheLookup WebElement paymentMethod; //Initialization public PaymentPage(){ PageFactory.initElements(driver, this); } public String validatePaymentPageTitle(){ return driver.getTitle(); } public boolean validatePaymentPage(){ return paymentTag.isDisplayed(); } public OrderSummaryPage proceedToCheckout() { paymentMethod.click(); return new OrderSummaryPage(); } }
/* * ********************************************************* * Copyright (c) 2019 @alxgcrz All rights reserved. * This code is licensed under the MIT license. * Images, graphics, audio and the rest of the assets be * outside this license and are copyrighted. * ********************************************************* */ package com.codessus.ecnaris.ambar.fragments; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import com.codessus.ecnaris.ambar.R; import com.codessus.ecnaris.ambar.activities.MainActivity; import com.codessus.ecnaris.ambar.helpers.AmbarManager; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.Unbinder; import static com.codessus.ecnaris.ambar.helpers.LogManager.log; public class CreditsFragment extends Fragment { private static final String TAG = CreditsFragment.class.getSimpleName(); // ID para recuperar el valor almacenado en el Bundle private static final String ARGS_FROM_HOME = "fromHome"; // NAVEGACIÓN (ocultos por defecto) @BindView(R.id.include_navigation_cancel) ImageButton cancelImageButton; // Variable recibida en un Bundle desde el fragment originario. // Permite saber a que pantalla regresar al pulsar el botón de 'CANCEL' private boolean fromHome; private Unbinder unbinder; // --- CONSTRUCTOR --- // public CreditsFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param fromHome Parameter 1. * @return A new instance of fragment AyudaSectionFragment. */ public static CreditsFragment newInstance( boolean fromHome ) { CreditsFragment fragment = new CreditsFragment(); Bundle args = new Bundle(); args.putBoolean( ARGS_FROM_HOME, fromHome ); fragment.setArguments( args ); return fragment; } @Override public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); if ( getArguments() != null ) { fromHome = getArguments().getBoolean( ARGS_FROM_HOME ); } } @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) { // Inflate the layout for this fragment View rootView = inflater.inflate( R.layout.fragment_credits, container, false ); // Inyectar las Views unbinder = ButterKnife.bind( this, rootView ); // Mostrar el botón 'CANCEL' cancelImageButton.setVisibility( View.VISIBLE ); return rootView; } /** * Método que se ejecuta al pulsar en el botón 'CANCEL' * * @param button pulsado */ @OnClick(R.id.include_navigation_cancel) public void navigation( View button ) { // Volver a la pantalla de ajustes enviando de vuelta la variable fromHome ((MainActivity) getActivity()).loadNextFragment( button, SettingsFragment.newInstance( fromHome ) ); } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } /** * onCreate -> onCreateView -> onResume */ @Override public void onResume() { super.onResume(); log( TAG + " --> onResume" ); // Reiniciar la reproducción (si ya se estuviera reproduciendo no pasa nada) AmbarManager.instance().playMusic( R.raw.main, true ); } }
package com.resource.iresource; import com.dto.DispatcherDto; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import java.util.List; @Component public interface IDispatcherResource { @RequestMapping(value = "/dispatcher", method = RequestMethod.POST, consumes = "application/json", produces = "application/json") ResponseEntity<?> addDispatcher(@RequestBody DispatcherDto dispatcherDto); @RequestMapping(value = "/dispatcher", method = RequestMethod.GET, produces = "application/json") List<DispatcherDto> getDispatchers(); @RequestMapping(value = "/dispatcher/{name}", method = RequestMethod.PUT, consumes = "application/json", produces = "application/json") ResponseEntity<?> updateDispatcher(@PathVariable("name") String name, @RequestBody DispatcherDto dispatcherDto); @RequestMapping(value = "/dispatcher/{name}", method = RequestMethod.DELETE, consumes = "application/json", produces = "application/json") ResponseEntity<?> deleteDispatcher(@PathVariable("name") String name); }
package classes; public class Pair { private Time timeInFirstStation; private Time timeInSecondStation; private int dayInFirstStation; private int dayInSecondStation; private Station firstStation; private Station secondStation; public Pair( Station firstStationName,Station secondStationName,Time firstStationTime,Time secondStationTime,int dayInFirst,int dayInSecond ) { this.timeInFirstStation = firstStationTime; this.timeInSecondStation = secondStationTime; this.dayInFirstStation = dayInFirst; this.dayInSecondStation=dayInSecond; this.firstStation = firstStationName; this.secondStation=secondStationName; } public Time getTimeInFirstStation() { return timeInFirstStation; } public Time getTimeInSecondStation() { return timeInSecondStation; } // public void setTimeInStation(Time timeInStation) { // this.timeInStation = timeInStation; // } public int getDayInFirstStation() { return dayInFirstStation; } public int getDayInSecondStation() { return dayInSecondStation; } // public void setDayInStation(int dayInStation) { // this.dayInStation = dayInStation; // } public Station getFirstStation() { return firstStation; } public Station getSecondStation() { return secondStation; } public void setTimeInFirstStation(Time timeInFirstStation) { this.timeInFirstStation = timeInFirstStation; } public void setTimeInSecondStation(Time timeInSecondStation) { this.timeInSecondStation = timeInSecondStation; } public void setDayInFirstStation(int dayInFirstStation) { this.dayInFirstStation = dayInFirstStation; } public void setDayInSecondStation(int dayInSecondStation) { this.dayInSecondStation = dayInSecondStation; } public void setFirstStation(Station firstStation) { this.firstStation = firstStation; } public void setSecondStation(Station secondStation) { this.secondStation = secondStation; } // public void setStationName(Station stationName) { // this.station = stationName; // } }
package com.demo.test.utils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.servlet.http.HttpServletRequest; import java.net.InetAddress; import java.net.UnknownHostException; /** * 获取发出request请求的客户端ip, 如果是自己发出的请求,那么获取的是自己的ip * 注意: * 如果使用此工具,获取到的不是客户端的ip地址;而是虚拟机的ip地址(d当客户端安装有VMware时,可能出现此情况); * 那么需要在客户端的[控制面板\网络和 Internet\网络连接]中禁用虚拟机网络适配器 * * @author Jack * @date 2019/05/30 15:32 PM */ public class IPUtils { static Logger logger = LogManager.getLogger(IPUtils.class); public static String getIpAddr(HttpServletRequest request) { String ipAddress = null; try { ipAddress = request.getHeader("x-forwarded-for"); if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("WL-Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getRemoteAddr(); if ("127.0.0.1".equals(ipAddress)) { // 根据网卡取本机配置的IP InetAddress inet = null; try { inet = InetAddress.getLocalHost(); LoggerUtils.logInfo(logger, "IP Address is :" + inet); } catch (UnknownHostException e) { LoggerUtils.logError(logger, "UnknownHostException happen in getIpAddr()", e.getStackTrace()); } ipAddress = inet.getHostAddress(); } } // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length() // = 15 if (ipAddress.indexOf(",") > 0) { ipAddress = ipAddress.substring(0, ipAddress.indexOf(",")); } } } catch (Exception e) { ipAddress = ""; LoggerUtils.logError(logger, "Exception happen in getIpAddr()", e.getStackTrace()); } return ipAddress; } }
package penktaPaskaita; import java.util.Random; public class penktaAntraUz { public static void main(String[] args) { Random random = new Random(); int a =random.nextInt(6); int b =random.nextInt(6); int c =random.nextInt(6); if (a==5||b==5||c==5) { System.out.println("Pralaimėjai..."); } else { System.out.println("Laimėjai!");} } }
package com.jyhd.black.dao; import com.jyhd.black.domain.ActivityData; import com.jyhd.black.domain.Admin; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import java.util.List; import java.util.Map; public interface ActivityDataDao extends JpaRepository<ActivityData, Long> { @Query(value = "SELECT * FROM activity_data WHERE user_id=?1 AND stage=?2",nativeQuery = true) ActivityData findByUserIdAndStage(String userId, int stage); Page<ActivityData> findByUserId(String userId,Pageable pageable); }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package control; import modelo.ProductoModelo; /** * * @author ADSI */ public class ProductoControl { public static String mensaje=""; public static float total=0; public static float calcular(ProductoModelo m){ if(m.getCantidad()<0 || m.getPrecios()<0){ mensaje="La cantidad o el precio no debe ser menor a 0(cero)"; return 0; }else{ mensaje="Operación realizada"; total=(m.getCantidad()*m.getPrecios()); } return total; } }
package com.ibeiliao.statement.api.dto.response; import java.util.List; import com.ibeiliao.pay.api.ApiCode; import com.ibeiliao.pay.api.ApiResultBase; /** * 幼儿园账户每日汇总表 * * @author liuying 2016/9/17. */ public class SchoolAccountDailySummaryResponse extends ApiResultBase { private static final long serialVersionUID = 1; private List<SchoolAccountDailySummary> summaries; public SchoolAccountDailySummaryResponse() {} public SchoolAccountDailySummaryResponse(int code, String message) { super(code, message); } public SchoolAccountDailySummaryResponse(List<SchoolAccountDailySummary> summaries) { super(ApiCode.SUCCESS, "success"); this.summaries = summaries; } public List<SchoolAccountDailySummary> getSummaries() { return summaries; } public void setSummaries(List<SchoolAccountDailySummary> summaries) { this.summaries = summaries; } }
package com.im.interfaces; import java.nio.channels.GatheringByteChannel; /** * Created by zhoulf on 2017/2/7. */ public abstract class Send extends Transmission { public abstract int writeTo(GatheringByteChannel channel); public int writeCompletely(GatheringByteChannel channel) { int totalWritten = 0; while (!complete) { int written = writeTo(channel); trace(written + " bytes written."); totalWritten += written; } return totalWritten; } }
package kr.hs.emirim.sookhee.redonorpets.adapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import kr.hs.emirim.sookhee.redonorpets.R; import kr.hs.emirim.sookhee.redonorpets.model.BadgeData; public class BadgeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public static class MyViewHolder extends RecyclerView.ViewHolder { ImageView ivBadge; TextView tvBadgeTitle; MyViewHolder(View view){ super(view); ivBadge = view.findViewById(R.id.BadgeImageView); tvBadgeTitle = view.findViewById(R.id.BadgeTitleTextView); } } public ArrayList<BadgeData> badgeDataArrayList; public BadgeAdapter(ArrayList<BadgeData> badgeDataArrayList){ this.badgeDataArrayList = badgeDataArrayList; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.mypage_badge_item, parent, false); return new MyViewHolder(v); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { MyViewHolder myViewHolder = (MyViewHolder) holder; myViewHolder.ivBadge.setImageResource(badgeDataArrayList.get(position).getBadgeId()); myViewHolder.tvBadgeTitle.setText(badgeDataArrayList.get(position).getBadgeTitle()); } @Override public int getItemCount() { return badgeDataArrayList.size(); } }
package fr.lteconsulting.servlet.action; import java.io.IOException; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import fr.lteconsulting.DonneesScope; import fr.lteconsulting.Joueur; import fr.lteconsulting.Partie; import fr.lteconsulting.dao.PartieDao; @WebServlet( "/creerPartie" ) public class CreerPartieServlet extends ActionServlet { private static final long serialVersionUID = 1L; @EJB private PartieDao partieDao; @Override protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { String nomPartie = request.getParameter( "nomPartie" ); int taillePlateau = Integer.parseInt( request.getParameter( "taillePlateau" ) ); Partie partie = new Partie( nomPartie, taillePlateau ); Joueur joueur = DonneesScope.getJoueurSession( request ); partie.ajouterJoueur( joueur ); partieDao.ajouterPartie( partie ); redirigerPartie( partie, response ); } }
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.builder; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.BeschichtungsInformationFolieListeType; import java.io.StringWriter; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.namespace.QName; public class BeschichtungsInformationFolieListeTypeBuilder { public static String marshal(BeschichtungsInformationFolieListeType beschichtungsInformationFolieListeType) throws JAXBException { JAXBElement<BeschichtungsInformationFolieListeType> jaxbElement = new JAXBElement<>(new QName("TESTING"), BeschichtungsInformationFolieListeType.class , beschichtungsInformationFolieListeType); StringWriter stringWriter = new StringWriter(); return stringWriter.toString(); } public BeschichtungsInformationFolieListeType build() { BeschichtungsInformationFolieListeType result = new BeschichtungsInformationFolieListeType(); return result; } }
package com.tencent.mm.plugin.account.security.a; import com.tencent.mm.ab.b; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.kernel.g; import com.tencent.mm.network.k; import com.tencent.mm.network.q; import com.tencent.mm.protocal.c.rl; import com.tencent.mm.protocal.c.rm; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; public final class a extends l implements k { private String byN; private b diG; private e diJ; public a(String str) { this.byN = str; com.tencent.mm.ab.b.a aVar = new com.tencent.mm.ab.b.a(); aVar.dIG = new rl(); aVar.dIH = new rm(); aVar.uri = "/cgi-bin/micromsg-bin/delsafedevice"; aVar.dIF = 362; aVar.dII = 0; aVar.dIJ = 0; this.diG = aVar.KT(); ((rl) this.diG.dID.dIL).rvq = str; } public final void a(int i, int i2, int i3, String str, q qVar, byte[] bArr) { x.d("MicroMsg.NetSceneDelSafeDevice", "NetSceneDelSafeDevice, errType= " + i2 + " errCode = " + i3); if (i2 == 0 && i3 == 0) { rm rmVar = (rm) this.diG.dIE.dIL; g.Ei().DT().set(64, Integer.valueOf(rmVar.raE)); x.d("MicroMsg.NetSceneDelSafeDevice", "NetSceneDelSafeDevice, get safedevice state = " + rmVar.raE); } this.diJ.a(i2, i3, str, this); } public final int getType() { return 362; } public final int a(com.tencent.mm.network.e eVar, e eVar2) { if (bi.oW(this.byN)) { x.e("MicroMsg.NetSceneDelSafeDevice", "null device id"); return -1; } this.diJ = eVar2; return a(eVar, this.diG, this); } }
package T; public class Audi extends Car{ public void start() { System.out.println("Automatic start"); } public void safety() { System.out.println("Safety"); } }
package net.minecraft.client.network; import net.minecraft.client.Minecraft; public class LanServerInfo { private final String lanServerMotd; private final String lanServerIpPort; private long timeLastSeen; public LanServerInfo(String p_i47130_1_, String p_i47130_2_) { this.lanServerMotd = p_i47130_1_; this.lanServerIpPort = p_i47130_2_; this.timeLastSeen = Minecraft.getSystemTime(); } public String getServerMotd() { return this.lanServerMotd; } public String getServerIpPort() { return this.lanServerIpPort; } public void updateLastSeen() { this.timeLastSeen = Minecraft.getSystemTime(); } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\client\network\LanServerInfo.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package View; import java.awt.Color; import java.awt.Font; import java.awt.font.FontRenderContext; import java.awt.geom.AffineTransform; import javax.swing.JTextArea; public class TextAreaHandler { public static JTextArea setAreaHightByText (JTextArea i_TextArea, String i_Text, int i_X, int i_Y, int i_MaxWidth, Font i_Font) { int textheight; int textwidth; i_TextArea.setText(i_Text); i_TextArea.setBackground(new Color(46,46,46)); i_TextArea.setForeground(new Color(255, 255, 255)); i_TextArea.setFont(new Font("Snap ITC", Font.PLAIN, 20)); i_TextArea.setLineWrap(true); i_TextArea.setWrapStyleWord(true); i_TextArea.setEditable(false); AffineTransform affinetransform = new AffineTransform(); FontRenderContext frc = new FontRenderContext(affinetransform,true,true); textwidth = (int)(i_Font.getStringBounds(i_Text, frc).getWidth()) / 2; if (textwidth / 300 != 0) { textheight = (textwidth / 300) * (int)(i_Font.getStringBounds(i_Text, frc).getHeight()); } else { textheight = (int)(i_Font.getStringBounds(i_Text, frc).getHeight()); } i_TextArea.setBounds(i_X, i_Y, i_MaxWidth,textheight); return i_TextArea; } }
package com.tencent.mm.console.a; import android.content.Context; import com.tencent.mm.plugin.emoji.model.i; public final class a implements com.tencent.mm.pluginsdk.cmd.a { public final boolean a(Context context, String[] strArr) { i.aEA().igI.aPm(); return true; } }
package Resources; public class RProjectors extends Resource { public RProjectors(String identification, String responsible) { super(identification, responsible); } }
package com.ifour.EmployeeManagement.Department; import javax.persistence.*; @Entity @Table public class Department { @Id @SequenceGenerator(name = "department_sequence", sequenceName = "department_sequence", allocationSize = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "department_sequence" ) private int dept_id; private String dept_name; public Department() { } public Department(int dept_id, String dept_name) { this.dept_id = dept_id; this.dept_name = dept_name; } public Department(String dept_name) { this.dept_name = dept_name; } public int getDept_id() { return dept_id; } public void setDept_id(int dept_id) { this.dept_id = dept_id; } public String getDept_name() { return dept_name; } public void setDept_name(String dept_name) { this.dept_name = dept_name; } @Override public String toString() { return "Department{" + "dept_id=" + dept_id + ", dept_name='" + dept_name + '\'' + '}'; } }
package datasource; import java.util.logging.Logger; import javax.annotation.sql.DataSourceDefinition; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.enterprise.inject.Produces; import javax.enterprise.inject.spi.InjectionPoint; @DataSourceDefinition( name = "java:app/jdbc/MyDS", className = "org.h2.jdbcx.JdbcDataSource", //url = "jdbc:h2:d:/aa/TestDatasource2/Data", url = "jdbc:h2:mem:test", user = "user", password = "pass" ) @Singleton @Startup public class DataSourceDefinitionConfig { @Produces public Logger produceLogger(InjectionPoint injectionPoint) { return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName()); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package figurasgeometricas; import javax.crypto.Mac; /** * * @author ESTUDIANTE */ public class Circulo extends Figura { private int radioCirc; public Circulo(int radioCirc) { this.radioCirc = radioCirc; } public int getRadioCirc() { return radioCirc; } public void setRadioCirc(int radioCirc) { this.radioCirc = radioCirc; } @Override public double calcularArea() { double totalArea = 0; totalArea = Math.PI * Math.pow(radioCirc, 2); return totalArea; } @Override public double calcularPerimetro() { double totalPerimetro = 0; totalPerimetro = 2 * (Math.PI*radioCirc); return totalPerimetro; } @Override public void ejecutarFigura() { System.out.println("Figura: " + getNombreFigura() + "\n"); System.out.println("Area del " + getNombreFigura() + ": " + calcularArea() + "\n"); System.out.println("Perimetro del " + getNombreFigura() + ": " + calcularPerimetro() + "\n"); } }
package step._04_WhileStatement; import java.util.Scanner; /* date : 2021-07-01 (목) * author : develiberta * number : 01110 * * [단계] * 04. While문 * while문을 사용해 봅시다. * [제목] * 03. 더하기 사이클 (01110) * 원래 수로 돌아올 때까지 연산을 반복하는 문제 * [문제] * 0보다 크거나 같고, 99보다 작거나 같은 정수가 주어질 때 다음과 같은 연산을 할 수 있다. * 먼저 주어진 수가 10보다 작다면 앞에 0을 붙여 두 자리 수로 만들고, 각 자리의 숫자를 더한다. * 그 다음, 주어진 수의 가장 오른쪽 자리 수와 앞에서 구한 합의 가장 오른쪽 자리 수를 이어 붙이면 새로운 수를 만들 수 있다. 다음 예를 보자. * 26부터 시작한다. 2+6 = 8이다. 새로운 수는 68이다. * 6+8 = 14이다. 새로운 수는 84이다. * 8+4 = 12이다. 새로운 수는 42이다. * 4+2 = 6이다. 새로운 수는 26이다. * 위의 예는 4번만에 원래 수로 돌아올 수 있다. 따라서 26의 사이클의 길이는 4이다. * N이 주어졌을 때, N의 사이클의 길이를 구하는 프로그램을 작성하시오. * [입력] * 첫째 줄에 N이 주어진다. N은 0보다 크거나 같고, 99보다 작거나 같은 정수이다. * [출력] * 첫째 줄에 N의 사이클 길이를 출력한다. * (예제 입력 1) * 26 * (예제 출력 1) * 4 * (예제 입력 2) * 55 * (예제 출력 2) * 3 * (예제 입력 3) * 1 * (예제 출력 3) * 60 * (예제 입력 4) * 0 * (예제 출력 4) * 1 */ public class _03_01110_PlusCycle { public static void main(String[] args) { Scanner in = new Scanner(System.in); int L = 1; int N = in.nextInt(); int M = N; while ((M = ((M % 10) * 10) + (((M / 10) + (M % 10)) % 10)) != N) { L++; } System.out.println(L); in.close(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.ez.model; /** * * @author purushothamanramraj */ public class Lang { private String htmlId; private String content; public String getHtmlId() { return htmlId; } public String getContent() { return content; } }
package com.credithc.libprocessor; import com.credithc.libannotation.PermissionDenied; import com.credithc.libannotation.PermissionGranted; import com.credithc.libannotation.PermissionRationale; import com.google.auto.service.AutoService; import java.lang.annotation.Annotation; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Filer; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; /** * @author liyong * @date 2019/9/27 15:57 * @description */ @AutoService(Processor.class) public class PermissionProcessor extends AbstractProcessor { private Elements elementUtil; private Types typeUtil; private Filer filer; private Messager messager; private HashMap<String, MethodInfo> clsMethodMap = new HashMap<>(); @Override public synchronized void init(ProcessingEnvironment processingEnv) { elementUtil = processingEnv.getElementUtils(); typeUtil = processingEnv.getTypeUtils(); filer = processingEnv.getFiler(); messager = processingEnv.getMessager(); } @Override public Set<String> getSupportedAnnotationTypes() { HashSet<String> supAnnotationTypes = new LinkedHashSet<>(); supAnnotationTypes.add(PermissionGranted.class.getCanonicalName()); supAnnotationTypes.add(PermissionDenied.class.getCanonicalName()); supAnnotationTypes.add(PermissionRationale.class.getCanonicalName()); return supAnnotationTypes; } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (annotations == null || annotations.size() == 0) { return true; } handleAnnotationInfo(roundEnv, PermissionGranted.class); handleAnnotationInfo(roundEnv, PermissionDenied.class); handleAnnotationInfo(roundEnv, PermissionRationale.class); for (String clsName : clsMethodMap.keySet()) { MethodInfo methodInfo = clsMethodMap.get(clsName); methodInfo.generateCode(); } return true; } private void handleAnnotationInfo(RoundEnvironment roundEnv, Class permissionClass) { Set<? extends Element> elementSet = roundEnv.getElementsAnnotatedWith(permissionClass); for (Element element : elementSet) { if (checkMethodValid(element)) { ExecutableElement executableElement = (ExecutableElement) element; TypeElement clsElement = (TypeElement) executableElement.getEnclosingElement(); String clsName = clsElement.getQualifiedName().toString(); MethodInfo methodInfo = clsMethodMap.get(clsName); if (methodInfo == null) { methodInfo = new MethodInfo(elementUtil, filer, messager, clsElement); clsMethodMap.put(clsName, methodInfo); } Annotation annotation = executableElement.getAnnotation(permissionClass); String methodName = executableElement.getSimpleName().toString(); List<? extends VariableElement> parameterElement = executableElement.getParameters(); if (parameterElement == null || parameterElement.size() == 0) { String msg = "method %s marked by %s must hava a parameter String[]"; throw new IllegalArgumentException(String.format(msg, methodName, annotation.getClass().getSimpleName())); } if (annotation instanceof PermissionGranted) { int requestCode = ((PermissionGranted) annotation).value(); methodInfo.grantedMap.put(requestCode, methodName); } else if (annotation instanceof PermissionDenied) { int requestCode = ((PermissionDenied) annotation).value(); methodInfo.deniedMap.put(requestCode, methodName); } else if (annotation instanceof PermissionRationale) { int requestCode = ((PermissionRationale) annotation).value(); methodInfo.rationaleMap.put(requestCode, methodName); } } } } private boolean checkMethodValid(Element element) { if (element.getKind() != ElementKind.METHOD) { return false; } if (element.getModifiers().contains(Modifier.PRIVATE)) { return false; } if (element.getModifiers().contains(Modifier.ABSTRACT)) { return false; } return true; } @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latest(); } }
/** * Javassonne * http://code.google.com/p/javassonne/ * * @author Hamilton Turner * @date Mar 24, 2009 * * Copyright 2009 Javassonne Team * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package org.javassonne.networking.impl; import java.util.Timer; import java.util.TimerTask; import org.javassonne.messaging.Notification; import org.javassonne.messaging.NotificationManager; import org.javassonne.ui.GameState; import org.javassonne.ui.GameState.Mode; /** * Represents a RemoteHost. Handles delivering all method calls in a new thread, * making it safe to call in a synchronous manner (which it is NOT safe to do on * a RemoteHost, any calls can block). * * @author Hamilton Turner * */ public class CachedHost implements RemoteHost { private String name_; private String uri_; private Mode status_; private CachedHostUpdater updater_; private boolean runningUpdater_; public CachedHost(RemoteHost host) { name_ = host.getName(); uri_ = host.getURI(); status_ = host.getStatus(); updater_ = new CachedHostUpdater(); runningUpdater_ = false; // Check the first game state to see if we need to be updating gameModeChanged(null); NotificationManager.getInstance().addObserver( Notification.GAME_MODE_CHANGED, this, "gameModeChanged"); } public CachedHost(CachedHost host, Boolean update) { name_ = new String(host.getName()); uri_ = new String(host.getURI()); status_ = GameState.Mode.values()[host.getStatus().ordinal()]; if (update){ updater_ = new CachedHostUpdater(); runningUpdater_ = false; } } public void gameModeChanged(Notification n) { if ((GameState.getInstance().getMode() == Mode.IN_LOBBY) && (runningUpdater_ == false)) { // Start a timer to update this hosts status ThreadPool.execute(updater_); runningUpdater_ = true; } else if (runningUpdater_) { // Cancel a previous timer updater_.cancel(); runningUpdater_ = false; } } /** * @return the name */ public String getName() { return name_; } /** * @return the desc_ */ public String getURI() { return uri_; } @Override public boolean equals(Object obj) { if (obj.getClass() != CachedHost.class) return false; CachedHost h = ((CachedHost)obj); if ((name_.equals(h.name_)) && (uri_.equals(h.uri_)) && (status_.equals(h.status_))) return true; return false; } /** * Polls the host every so often to update the status. Note that this is * already called from inside the ThreadPool, so there is no need to call * ThreadPool.execute inside of it, even though we are resolving a host */ public void update() { RemoteHost me = HostResolver.attemptToResolveHost(uri_); if (me == null) return; status_ = me.getStatus(); } /** * This is not guaranteed to get the exactly correct MODE, just the last * mode that we know about * * @return the mode_ */ public Mode getStatus() { return status_; } /** * @see org.javassonne.networking.impl.RemoteHost */ public void addClient(final String clientURI) { ThreadPool.execute(new Runnable() { public void run() { RemoteHost me = HostResolver.attemptToResolveHost(uri_); if (me == null) return; me.addClient(clientURI); } }); } /** * @see org.javassonne.networking.impl.RemoteHost */ public void resolveHost(final String hostURI) { ThreadPool.execute(new Runnable() { public void run() { RemoteHost me = HostResolver.attemptToResolveHost(uri_); if (me == null) return; me.resolveHost(hostURI); } }); } /** * @see org.javassonne.networking.impl.RemoteHost */ public void shareHost(final String hostURI) { ThreadPool.execute(new Runnable() { public void run() { RemoteHost me = HostResolver.attemptToResolveHost(uri_); if (me == null) return; me.shareHost(hostURI); } }); } /** * @see org.javassonne.networking.impl.RemoteHost */ public void receiveNotification(final String serializedNotification) { ThreadPool.execute(new Runnable() { public void run() { RemoteHost me = HostResolver.attemptToResolveHost(uri_); if (me == null) return; me.receiveNotification(serializedNotification); } }); } /** * @see org.javassonne.networking.impl.RemoteHost */ public void receiveNotificationFromClient( final String serializedNotification, final String clientURI) { ThreadPool.execute(new Runnable() { public void run() { RemoteHost me = HostResolver.attemptToResolveHost(uri_); if (me == null) return; me.receiveNotificationFromClient(serializedNotification, clientURI); } }); } /** * @see org.javassonne.networking.impl.RemoteHost */ public void removeClient(final String clientURI) { ThreadPool.execute(new Runnable() { public void run() { RemoteHost me = HostResolver.attemptToResolveHost(uri_); if (me == null) return; me.removeClient(clientURI); } }); } /** * @see org.javassonne.networking.impl.RemoteHost */ public void receiveACK(final String hostURI) { ThreadPool.execute(new Runnable() { public void run() { RemoteHost me = HostResolver.attemptToResolveHost(uri_); if (me == null) return; me.receiveACK(hostURI); } }); } private class CachedHostUpdater implements Runnable { private Timer t_; public void run() { t_ = new Timer("Cached Host Updater - " + uri_, true); t_.scheduleAtFixedRate(new TimerTask() { public void run() { update(); } }, 0, 1000); } public void cancel() { t_.cancel(); } } }
class Calculation1{ int c; public void addition(int a, int b){ c=a+b; System.out.println("The addition of a and b is "+c); } public void subtraction(int a, int b){ c=a-b; System.out.println("The subtraction of a and b is "+c); } } public class Calculation2 extends Calculation1{ public void subtraction(int a, int b){ c=a-b; System.out.println("subtraction of a,b: "+c); } public void multiplication(int a, int b){ c=a*b; System.out.println("The multiplication of a and b is "+c); } public void division(int a, int b){ c=a/b; System.out.println("The division of a and b is "+c); } public static void main(String args[]){ int a= 10, b= 5; Calculation2 s1= new Calculation2(); s1.addition(a,b); s1.subtraction(a,b); s1.multiplication(a,b); s1.division(a,b); } }
package com.tt.miniapp.msg; import android.text.TextUtils; import com.tt.frontendapiinterface.a; import com.tt.frontendapiinterface.b; import com.tt.miniapp.storage.filestorge.FileManager; import com.tt.miniapphost.AppBrandLogger; import com.tt.option.e.e; import java.io.File; import java.util.HashMap; import org.json.JSONException; import org.json.JSONObject; public class ApiGetFileInfoCtrl extends b { public ApiGetFileInfoCtrl(String paramString, int paramInt, e parame) { super(paramString, paramInt, parame); } public void act() { try { HashMap<Object, Object> hashMap; String str = (new JSONObject(this.mArgs)).optString("filePath"); File file = new File(FileManager.inst().getRealFilePath(str)); if (TextUtils.isEmpty(str)) { callbackFail(a.a(true, new String[] { getActionName(), str })); return; } if (FileManager.inst().canRead(file) && file.exists()) { hashMap = new HashMap<Object, Object>(); hashMap.put("size", Long.valueOf(file.length())); callbackOk(a.a(hashMap)); return; } callbackFail(a.b(new String[] { getActionName(), (String)hashMap })); return; } catch (JSONException jSONException) { AppBrandLogger.stacktrace(6, "ApiHandler", jSONException.getStackTrace()); callbackFail((Throwable)jSONException); return; } } public String getActionName() { return "getFileInfo"; } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\msg\ApiGetFileInfoCtrl.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.example.binlin.uielementsexamples; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.DragEvent; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private EditText editText; private TextView textView; private Button button; private Switch aSwitch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView2); editText = findViewById(R.id.editText); button = findViewById(R.id.button); aSwitch = findViewById(R.id.switch2); textView.setText("This Is Just A Test"); setListeners(); } private void setListeners() { button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // take input from editText and set as value for textView textView.setText(editText.getText()); } }); aSwitch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(aSwitch.isChecked()){ Toast.makeText(MainActivity.this, "IsOn", Toast.LENGTH_LONG).show(); }else{ Toast.makeText(MainActivity.this, "IsOff", Toast.LENGTH_LONG).show(); } } }); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package utilities; import java.text.ParseException; import java.util.Date; import java.text.SimpleDateFormat; import static java.time.temporal.ChronoUnit.*; import java.time.chrono.ChronoLocalDate; import java.time.chrono.ChronoPeriod; import java.time.format.DateTimeFormatter; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author william.alvarez */ public class Functions { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date fechaActual = new Date(); String sfa = format.format(fechaActual); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); public String getEdad(String fn) { ChronoLocalDate from = ChronoLocalDate.from(formatter.parse(fn)); ChronoLocalDate to = ChronoLocalDate.from(formatter.parse(sfa)); ChronoPeriod period = ChronoPeriod.between(from, to); String r = String.format("%d años, %d meses y %d días", period.get(YEARS), period.get(MONTHS), period.get(DAYS)); System.out.printf("%d años, %d meses y %d días", period.get(YEARS), period.get(MONTHS), period.get(DAYS)); return r; } public String getTiempoVinculacion(String fv) { ChronoLocalDate from = ChronoLocalDate.from(formatter.parse(fv)); ChronoLocalDate to = ChronoLocalDate.from(formatter.parse(sfa)); ChronoPeriod period = ChronoPeriod.between(from, to); String r = String.format("%d años, %d meses y %d días", period.get(YEARS), period.get(MONTHS), period.get(DAYS)); System.out.printf("%d años, %d meses y %d días", period.get(YEARS), period.get(MONTHS), period.get(DAYS)); return r; } public boolean esMayor(String fn) { ChronoLocalDate from = ChronoLocalDate.from(formatter.parse(fn)); ChronoLocalDate to = ChronoLocalDate.from(formatter.parse(sfa)); ChronoPeriod period = ChronoPeriod.between(from, to); return period.get(YEARS) >= 18; } public String strOracleFormat(String f) throws ParseException { SimpleDateFormat ft = new SimpleDateFormat("dd/MM/yyyy"); return ft.format(format.parse(f)); } }
package deals; import java.io.Serializable; import java.util.Date; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Deal implements Serializable { private Integer Id; private String name; private String description; private String company; private String img; private String link; private String regularPrice; private String salePrice; private String percentageOff; private String couponCode; private String note; private String shipping; private String saleType; public void setId(Integer Id) { this.Id = Id; } public Integer getId() { return Id; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setDescription(String description) { this.description = description; } public String getDescription() { return description; } public void setCompany(String company) { this.company = company; } public String getCompany() { return company; } public void setImg(String img) { this.img = img; } public String getImg() { return img; } public void setLink(String link) { this.link = link; } public String getLink() { return link; } public void setRegularPrice(String regularPrice) { this.regularPrice = regularPrice; } public String getRegularPrice() { return regularPrice; } public void setSalePrice(String salePrice) { this.salePrice = salePrice; } public String getSalePrice() { return salePrice; } public void setPercentageOff(String percentageOff) { this.percentageOff = percentageOff; } public String getPercentageOff() { return percentageOff; } public void setCouponCode(String couponCode) { this.couponCode = couponCode; } public String getCouponCode() { return couponCode; } public void setNote(String note) { this.note = note; } public String getNote() { return note; } public void setShipping(String shipping) { this.shipping = shipping; } public String getShipping() { return shipping; } public void setSaleType(String saleType) { this.saleType = saleType; } public String getSaleType() { return saleType; } }
/*Unique Paths II question: http://www.lintcode.com/en/problem/unique-paths-ii/ answer: http://www.jiuzhang.com/solutions/unique-paths-ii/ Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle and empty space is marked as 1 and 0 respectively in the grid. Example For example, There is one obstacle in the middle of a 3x3 grid as illustrated below. [ [0,0,0], [0,1,0], [0,0,0] ] The total number of unique paths is 2. Note m and n will be at most 100. */ package matrixDP; public class UniquePathII { public int uniquePathwithObstancles(int[][] obstanclegrid){ if (obstanclegrid == null || obstanclegrid.length == 0 || obstanclegrid[0] == null){ return 0; }//bug1: remember to list obstanclegrid[0] int m = obstanclegrid.length; int n = obstanclegrid[0].length; //1. state: path[i][j] means the count of unique paths from 0,0 to i,j int[][] count = new int[m][n]; //2. initialization: (1)row (2)collum for (int i = 0; i < m; i++){ if (obstanclegrid[i][0] == 1){ break; }else{ count[i][0] = 1; } } for (int i = 0; i < n; i++){ if (obstanclegrid[0][i] == 1){ break; }else{ count[0][i] = 1; } } //3. function for (int i = 1; i < m; i++){ for (int j = 1; j < n; i++){ if (obstanclegrid[i][i] == 1){ count[i][j] = 0; }else{ count[i][j] = count[i - 1][j] + count[i][j-1]; } } } //4.answer return count[m - 1][n - 1]; } public static void main(String[] args) { // TODO Auto-generated method stub int[][] obstanclegrid = new int[3][3]; obstanclegrid[0][0] = 0; obstanclegrid[0][1] = 0; obstanclegrid[0][2] = 0; obstanclegrid[1][0] = 0; obstanclegrid[1][1] = 1; obstanclegrid[1][2] = 0; obstanclegrid[2][0] = 0; obstanclegrid[2][1] = 0; obstanclegrid[2][2] = 0; } }
package com.smxknife.java2.thread.executorservice.demo06; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; /** * @author smxknife * 2020/7/31 */ public class _Run_WithExceptionThreadPoolExecutor_submit { public static void main(String[] args) { WithExceptionThreadPoolExecutor executor = new WithExceptionThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<>()); executor.submit(() -> { throw new RuntimeException(); }); } }
package com.xueqiu.servlet; import java.io.IOException; import java.net.URLDecoder; 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 org.apache.log4j.Logger; @WebServlet(name="getData", urlPatterns="/getData") public class Getdata extends HttpServlet { private static final long serialVersionUID = -8687400820173853188L; private static Logger logger = Logger.getLogger(Getdata.class); @Override protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { logger.warn("getting info"); String href = req.getParameter("href"); String cookie = req.getParameter("cookie"); if(null != href){ System.out.println(href); System.out.println(cookie); } res.getWriter().write(""); } }
import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class Solution { // Complete the minimumSwaps function below. static int minimumSwaps(int[] arr) { int minSwaps = 0; for(int i = 0; i < arr.length - 1; i++) { // take value of current int cur = arr[i]; // take the smallest value to the right int small2RightIndex = smallestToRight(arr, i); int smaller2Right = arr[small2RightIndex]; // if current is greater swap them and count the swap if (cur > smaller2Right) { int temp = arr[i]; arr[i] = arr[small2RightIndex]; arr[small2RightIndex] = temp; minSwaps++; } } return minSwaps; } static int smallestToRight(int[] arr, int index) { int minIndex = index + 1; int min = arr[minIndex]; for(int i = index+1; i < arr.length; i++) { if (arr[i] < min) { minIndex = i; min = arr[i]; } } return minIndex; } private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) throws IOException { BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); int n = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); int[] arr = new int[n]; String[] arrItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int i = 0; i < n; i++) { int arrItem = Integer.parseInt(arrItems[i]); arr[i] = arrItem; } int res = minimumSwaps(arr); bufferedWriter.write(String.valueOf(res)); bufferedWriter.newLine(); bufferedWriter.close(); scanner.close(); } }
package com.example.bratwurst.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.util.HtmlUtils; import org.unbescape.html.HtmlEscape; @Service public class SanitizingServiceImpl implements SanitizingService { @Override public String sanitizeString(String input) { return HtmlUtils.htmlEscape(input); } @Override public String sanitizeFilename(String input) { return input.replaceAll("[^\\p{IsDigit}\\p{IsAlphabetic}.]", ""); } }
package org.quarkchain.web3j.protocol.core; import java.math.BigInteger; import java.util.Arrays; import java.util.Collections; import org.quarkchain.web3j.protocol.Web3j; import org.quarkchain.web3j.protocol.Web3jService; import org.quarkchain.web3j.protocol.core.request.EthFilter; import org.quarkchain.web3j.protocol.core.request.TransactionReq; import org.quarkchain.web3j.protocol.core.request.TxData; import org.quarkchain.web3j.protocol.core.response.Call; import org.quarkchain.web3j.protocol.core.response.EstimateGas; import org.quarkchain.web3j.protocol.core.response.EthLog; import org.quarkchain.web3j.protocol.core.response.EthTransaction; import org.quarkchain.web3j.protocol.core.response.GasPrice; import org.quarkchain.web3j.protocol.core.response.GetAccountData; import org.quarkchain.web3j.protocol.core.response.GetBalances; import org.quarkchain.web3j.protocol.core.response.GetMinorBlock; import org.quarkchain.web3j.protocol.core.response.GetRootBlock; import org.quarkchain.web3j.protocol.core.response.GetRootHashConfirmingMinorBlockById; import org.quarkchain.web3j.protocol.core.response.GetTransactionConfirmedByNumberRootBlocks; import org.quarkchain.web3j.protocol.core.response.GetTransactionCount; import org.quarkchain.web3j.protocol.core.response.GetTransactionReceipt; import org.quarkchain.web3j.protocol.core.response.NetworkInfo; import org.quarkchain.web3j.protocol.core.response.SendTransaction; import org.quarkchain.web3j.utils.Numeric; /** * JSON-RPC 2.0 factory implementation. */ public class JsonRpcWeb3j implements Web3j { protected static final long ID = 1; protected Web3jService web3jService; public JsonRpcWeb3j(Web3jService web3jService) { this.web3jService = web3jService; } @Override public Request<?, NetworkInfo> networkInfo() { return new Request<>("networkInfo", Collections.<String>emptyList(), ID, web3jService, NetworkInfo.class); } @Override public Request<?, GasPrice> gasPrice(String fullShardKey, String tokenID) { return new Request<>("gasPrice", Arrays.asList(fullShardKey, tokenID), ID, web3jService, GasPrice.class); } @Override public Request<?, GetBalances> getBalances(String address) { return new Request<>("getBalances", Arrays.asList(address), ID, web3jService, GetBalances.class); } @Override public Request<?, GetTransactionCount> getTransactionCount(String address) { return new Request<>("getTransactionCount", Arrays.asList(address), ID, web3jService, GetTransactionCount.class); } @Override public Request<?, SendTransaction> sendTransaction(TransactionReq transaction) { return new Request<>("sendTransaction", Arrays.asList(transaction), ID, web3jService, SendTransaction.class); } @Override public Request<?, SendTransaction> sendRawTransaction(String signedTransactionData) { return new Request<>("sendRawTransaction", Arrays.asList(signedTransactionData), ID, web3jService, SendTransaction.class); } @Override public Request<?, Call> call(TransactionReq transaction, DefaultBlockParameter defaultBlockParameter) { return new Request<>("call", Arrays.asList(transaction, defaultBlockParameter), ID, web3jService, Call.class); } @Override public Request<?, EstimateGas> estimateGas(TransactionReq transaction) { return new Request<>("estimateGas", Arrays.asList(transaction), ID, web3jService, EstimateGas.class); } @Override public Request<?, GetRootBlock> getRootBlockByHeight(BigInteger blockNumber) { if (blockNumber == null) { return new Request<>("getRootBlockByHeight", Arrays.asList(), ID, web3jService, GetRootBlock.class); } return new Request<>("getRootBlockByHeight", Arrays.asList(Numeric.toHexStringWithPrefix(blockNumber)), ID, web3jService, GetRootBlock.class); } @Override public Request<?, GetRootBlock> getRootBlockById(String blockId) { return new Request<>("getRootBlockById", Arrays.asList(blockId), ID, web3jService, GetRootBlock.class); } @Override public Request<?, GetMinorBlock> getMinorBlockByHeight(BigInteger fullShardId, BigInteger blockNumber, boolean withTx) { String fullShardIdHex = Numeric.encodeQuantity(fullShardId); if (blockNumber == null) { return new Request<>("getMinorBlockByHeight", Arrays.asList(fullShardIdHex, null, withTx), ID, web3jService, GetMinorBlock.class); } return new Request<>("getMinorBlockByHeight", Arrays.asList(fullShardIdHex, Numeric.toHexStringWithPrefix(blockNumber), withTx), ID, web3jService, GetMinorBlock.class); } @Override public Request<?, GetMinorBlock> getMinorBlockById(String blockId, boolean withTx) { return new Request<>("getMinorBlockById", Arrays.asList(blockId, withTx), ID, web3jService, GetMinorBlock.class); } @Override public Request<?, EthTransaction> getTransactionById(String transactionHash) { return new Request<>("getTransactionById", Arrays.asList(transactionHash), ID, web3jService, EthTransaction.class); } @Override public Request<?, GetTransactionReceipt> getTransactionReceipt(String transactionHash) { return new Request<>("getTransactionReceipt", Arrays.asList(transactionHash), ID, web3jService, GetTransactionReceipt.class); } @Override public Request<?, EthLog> getLogs(EthFilter ethFilter, String fullShardKey) { return new Request<>("getLogs", Arrays.asList(ethFilter, fullShardKey), ID, web3jService, EthLog.class); } @Override public Request<?, GetAccountData> getAccountData(String address, DefaultBlockParameter defaultBlockParameter, boolean includeOtherShards) { return new Request<>("getAccountData", Arrays.asList(address, defaultBlockParameter, includeOtherShards), ID, web3jService, GetAccountData.class); } @Override public Request<?, GetRootHashConfirmingMinorBlockById> getRootHashConfirmingMinorBlockById(String minorBlockId) { return new Request<>("getRootHashConfirmingMinorBlockById", Arrays.asList(minorBlockId), ID, web3jService, GetRootHashConfirmingMinorBlockById.class); } @Override public Request<?, GetTransactionConfirmedByNumberRootBlocks> getTransactionConfirmedByNumberRootBlocks( String transactionId) { return new Request<>("getTransactionConfirmedByNumberRootBlocks", Arrays.asList(transactionId), ID, web3jService, GetTransactionConfirmedByNumberRootBlocks.class); } }
package org.mge.general; import java.util.Arrays; public class NextHighestNumberWithSameDigits { public static void main(String[] args) { String n = "4765"; char[] ch = n.toCharArray(); int i = n.length() - 1; while(i > 0 && ch[i] < ch[i-1]) { i--; } if(i == 0) { System.out.println("Not Possible"); return; } int x = ch[i-1], min = i; for(int j = i+1; j < n.length(); j++) { if(ch[j] > x && ch[j] < ch[min]) { min = j; } } char t = ch[min]; ch[min] = ch[i-1]; ch[i-1] = t; Arrays.sort(ch, i, n.length()); System.out.println(new String(ch)); } }
package com.tripad.cootrack.erpCommon.process; import com.tripad.cootrack.data.TmcDocumentUpdate; import com.tripad.cootrack.data.TmcDocumentUpdateLine; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.openbravo.dal.core.DalUtil; import org.openbravo.dal.core.OBContext; import org.openbravo.dal.service.OBDal; import org.openbravo.erpCommon.utility.OBError; import org.openbravo.scheduling.ProcessBundle; import org.openbravo.service.db.CallStoredProcedure; import org.openbravo.service.db.DalBaseProcess; public class UpdateCustomerMaintenanceActivities extends DalBaseProcess { public void doExecute(ProcessBundle bundle) throws Exception { try { // retrieve the parameters from the bundle final String strRecordId = (String) bundle.getParams().get("TMC_Documentupdateline_ID"); final String organizationId = (String) bundle.getParams().get("adOrgId"); final String tabId = (String) bundle.getParams().get("tabId"); final String p_gps_ditelpon = (String) bundle.getParams().get("p_gps_ditelpon"); final String p_gps_disms = (String) bundle.getParams().get("p_gps_disms"); final Date p_masa_aktif = (Date) bundle.getParams().get("p_masa_aktif"); final BigDecimal p_sisa_pulsa = (BigDecimal) bundle.getParams().get("p_sisa_pulsa"); final String p_sisa_quota = (String) bundle.getParams().get("p_sisa_quota"); final String p_analisa_problem = (String) bundle.getParams().get("p_analisa_problem"); final String p_solving_bysystem = (String) bundle.getParams().get("p_solving_bysystem"); final String p_result = (String) bundle.getParams().get("p_result"); final String p_by_phone = (String) bundle.getParams().get("p_by_phone"); final String p_by_sms = (String) bundle.getParams().get("p_by_sms"); final Date p_maintenancedate_from = (Date) bundle.getParams().get("p_maintenancedate_from"); final Date p_maintenancedate_to = (Date) bundle.getParams().get("p_maintenancedate_to"); final String p_jawaban_customer = (String) bundle.getParams().get("p_jawaban_customer"); final String p_keterangan = (String) bundle.getParams().get("p_keterangan"); /* (p_id character varying, p_gps_ditelpon character varying, p_gps_disms character varying, p_masa_aktif timestamp without time zone, p_sisa_pulsa numeric, p_sisa_quota character varying, p_analisa_problem character varying, p_solving_bysystem character varying, p_result character varying, p_by_phone character varying, p_by_sms character varying, p_maintenancedate_from timestamp without time zone, p_maintenancedate_to timestamp without time zone, p_jawaban_customer character varying, p_keterangan character varying) */ // implement your process here List<Object> params = new ArrayList<Object>(); params.add(strRecordId); params.add(p_gps_ditelpon); params.add(p_gps_disms); params.add(p_masa_aktif); params.add(p_sisa_pulsa); params.add(p_sisa_quota); params.add(p_analisa_problem); params.add(p_solving_bysystem); params.add(p_result); params.add(p_by_phone); params.add(p_by_sms); params.add(p_maintenancedate_from); params.add(p_maintenancedate_to); params.add(p_jawaban_customer); params.add(p_keterangan); CallStoredProcedure.getInstance().call("tmc_maintenanceprocess", params, null, true, false); // Show a result final StringBuilder sb = new StringBuilder(); sb.append("Read information:<br/>"); sb.append(bundle.getParamsDeflated()); // OBError is also used for successful results final OBError msg = new OBError(); msg.setType("Success"); msg.setTitle("Read parameters!"); msg.setMessage(sb.toString()); bundle.setResult(msg); } catch (final Exception e) { e.printStackTrace(System.err); final OBError msg = new OBError(); msg.setType("Error"); msg.setMessage(e.getMessage()); msg.setTitle("Error occurred"); bundle.setResult(msg); } } }
package org.buaa.ly.MyCar.logic; import lombok.extern.slf4j.Slf4j; import org.buaa.ly.MyCar.config.TestLoader; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; @Slf4j public class PayLogicTest extends TestLoader { @Autowired private PayLogic payLogic; }
package test0; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** How to skip the test case? use @Test(enabled = false) before the test method */ public class Ex4 { @Test public void test1() { System.out.println("running test1"); } @Test(enabled = false) public void test2() { System.out.println("running test2"); } @Test public void test3() { System.out.println("running test3"); } }
package pattern_test.proxy.static_proxy; /** * Description: 静态代理 * 缺点:一个代理类只能代理一个实现该接口的被代理类。假如要代理InterfaceAImpl1、InterfaceAImpl2、 * InterfaceAImpl3等,必须创建多个代理类。 * * @author Baltan * @date 2019-04-02 15:32 */ public class Test1 { public static void main(String[] args) { InterfaceA proxy = new InterfaceAProxy(); proxy.say(); } }
package com.fireblaze.foodiee.adapters; import android.content.Context; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.fireblaze.foodiee.UserOperations; import com.fireblaze.foodiee.models.FoodItem; import com.fireblaze.foodiee.viewholders.EventViewHolder; import com.google.firebase.database.Query; /** * Created by fireblaze on 9/12/16. */ public class EventListFragmentAdapter extends FirebaseRecyclerAdapter<FoodItem, EventViewHolder> { Context mContext; @Override protected void populateViewHolder(EventViewHolder viewHolder, final FoodItem model, int position) { if(model.getOrganizerID().equals(UserOperations.getUid())){ viewHolder.setOrganizer(true); } viewHolder.bindToPost(mContext, model, false); } public EventListFragmentAdapter(Class<FoodItem> modelClass, int modelLayout, Class<EventViewHolder> viewHolderClass, Query ref, Context c) { super(modelClass, modelLayout, viewHolderClass, ref); mContext = c; } }
package com.tkb.elearning.service; import java.util.List; import com.tkb.elearning.model.AboutWe; /** * 關於我們Service介面接口 * @author Admin * @version 創建時間:2016-04-21 */ public interface AboutWeService { /** * 取得關於我們資料清單(分頁) * @param pageCount * @param pageStart * @param aboutWe * @return List<AboutWe> */ public List<AboutWe> getList(int pageCount, int pageStart, AboutWe aboutWe); /** * 取得關於我們總筆數 * @param aboutWe * @return Integer */ public Integer getCount(AboutWe aboutWe); /** * 取得單筆關於我們 * @param aboutWe * @return AboutWe */ public AboutWe getData(AboutWe aboutWe); /** * 新增關於我們 * @param aboutWe */ public void add(AboutWe aboutWe); /** * 修改關於我們 * @param aboutWe */ public void update(AboutWe aboutWe); /** * 刪除關於我們 * @param id */ public void delete(Integer id); }
/** * From "Core Java, Vol 2" * * @version 1.20 1999-04-26 * @author Cay Horstmann * * Modified by Byron Weber Becker, 2012-03-22, to better indicate starting * multiple threads and to explicitly show the exceptions thrown by the * bad worker thread. */ import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; public class Demo4 { public static void main(String[] args) { JFrame frame = new SwingThreadFrame(); frame.setVisible(true); } } class SwingThreadFrame extends JFrame { private DefaultListModel model = new DefaultListModel(); DefaultListModel exceptions = new DefaultListModel(); private int numGoodWorkerThreads = 0; private int numBadWorkerThreads = 0; private JButton startGoodThread = new JButton("Start Good Thread"); private JLabel numGoodThreads = new JLabel("" + this.numGoodWorkerThreads); private JButton startBadThread = new JButton("Start Bad Thread"); private JLabel numBadThreads = new JLabel("" + this.numBadWorkerThreads); public SwingThreadFrame() { this.setTitle("SwingThread"); this.setSize(400, 300); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ExceptionHandler.registerExceptionHandler(this.exceptions); Box vert = Box.createVerticalBox(); Box good = Box.createHorizontalBox(); Box bad = Box.createHorizontalBox(); good.add(startGoodThread); good.add(Box.createHorizontalStrut(20)); good.add(numGoodThreads); bad.add(startBadThread); bad.add(Box.createHorizontalStrut(20)); bad.add(numBadThreads); JList list = new JList(this.model); // list.setPreferredSize(new Dimension(300, 300)); // list.setMinimumSize(new Dimension(300, 300)); JScrollPane scrollPane = new JScrollPane(list); JList excList = new JList(this.exceptions); JScrollPane excSP = new JScrollPane(excList); vert.add(good); vert.add(bad); vert.add(new JLabel("Model")); vert.add(scrollPane); vert.add(new JLabel("Exceptions")); vert.add(excSP); this.getContentPane().add(vert, BorderLayout.CENTER); startGoodThread.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { new GoodWorkerThread(model).start(); numGoodWorkerThreads += 1; numGoodThreads.setText("" + numGoodWorkerThreads); } }); startBadThread.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { new BadWorkerThread(model).start(); numBadWorkerThreads += 1; numBadThreads.setText("" + numBadWorkerThreads); } }); } } class BadWorkerThread extends Thread { private DefaultListModel model; private Random generator; public BadWorkerThread(DefaultListModel aModel) { model = aModel; generator = new Random(); } public void run() { while (true) { Integer i = new Integer(generator.nextInt(10)); if (model.contains(i)) model.removeElement(i); else model.addElement(i); //yield(); try { sleep(5); } catch (InterruptedException e ) {} } } } class GoodWorkerThread extends Thread { private DefaultListModel model; private Random generator; public GoodWorkerThread(DefaultListModel aModel) { model = aModel; generator = new Random(); } public void run() { while (true) { final Integer i = new Integer(generator.nextInt(10)); SwingUtilities.invokeLater(new Runnable() { public void run() { // Model updates the UI... if (model.contains(i)) model.removeElement(i); else model.addElement(i); } }); //yield(); try { sleep(5); } catch (InterruptedException e ) {} } } } /** * This class catches the AWT exceptions and makes sure they're actually * displayed in the application. */ class ExceptionHandler implements Thread.UncaughtExceptionHandler { private DefaultListModel exceptions; private ExceptionHandler(DefaultListModel exceptions) { this.exceptions = exceptions; } public void uncaughtException(Thread t, Throwable e) { handle(e); } public void handle(Throwable throwable) { try { final Throwable tCopy = new Throwable(throwable); SwingUtilities.invokeLater(new Runnable() { public void run() { exceptions.addElement(new Throwable(tCopy)); } }); } catch (Throwable t) { // don't let the exception get thrown out, will cause infinite // looping! } } public static void registerExceptionHandler(DefaultListModel exceptions) { Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(exceptions)); System.setProperty("sun.awt.exception.handler", ExceptionHandler.class.getName()); } }
package com.dxc.dao; import java.util.List; import com.dxc.pojos.Admin; import com.dxc.pojos.Customer; import com.dxc.pojos.Product; public interface IAdminDao { public boolean adminLogin(Admin a); public boolean addProduct(Product p); public List<Product> getAllProducts(); public void addCustomer(Customer c); public boolean removeCustomer(int i); public List<Customer>getAllCustomers(); public List<Product> getProduct(int i); }
/** * HW2 Part 2 - Coding with bitwise operators * * (Note the rules are different than in the other java file). * The only operators you are allowed to use in your code are the following * - The bitwise operators |, &, ~, ^, <<, >> * - Increment and Decrement ++, and --. You may also use add things with 1 or subtract things with 1. * - Boolean operators ||, &&, and ! only in if statements * - Conditional statements (if, if-else, switch-case, ? :). * - Equality comparisons (==, !=). * * Anything not in the above list you are not allowed to use. This includes the following but is not an exhaustive list: * - Multiplication & Division * - Addition & Subtraction with numbers other than 1. * - Modulus (%) * - Iteration (for, while, do-while loops, recursion) * - The unsigned right shift operator >>> (C does not provide this operator). * - Any functions found in Java libraries (especially the Math library) * - Example Math.pow, Integer.bitCount, etc. * - Greater than and less than comparisons (>, <, >=, <=) * - Casting (you should not have cast anywhere!) * * As a note all of these functions accept ints. Here is the reason * 1) If you pass in a number (which is of type int by default) into a function accepting a byte * the Java compiler will complain even if the number would fit into that type. * * Now keep in mind the return value is also an int. Please read the comments on how many bits * to return and make sure the other bits are not set or else you will not get any points for that * test case. i.e if I say to return 6 bits and you return 0xFFFFFFFF you will lose points. * * Definitions of types * nibble (nybble) - 4 bits * byte - 8 bits * short - 16 bits * int - 32 bits * * @author Harrison English * */ public class HW2Operations { public static void main(String[] args) { // Test your code here. // You should devise your own test cases here in addition to the ones in the comments. // Come up with one more test case than the ones given in the comments. //SetByte test cases 2 from comments + 1 self made System.out.println("---------Set Byte------------"); System.out.println("Expected value is 0x25093418"); int number = setByte(0x25093456, 0x18, 0); System.out.printf("Calculated value is 0x%x",number); System.out.println(); System.out.println("Expected value is 0x12370F25"); number = setByte(0x12374925, 0xF, 1); System.out.printf("Calculated value is 0x%x",number); System.out.println(); System.out.println("Expected value is 0xFFFFBAFF"); number = setByte(0xFFFFFFFF, 0xBA, 1); System.out.printf("Calculated value is 0x%x",number); System.out.println(); //GetByte test cases 2 from comments + 1 self made System.out.println("---------Get Byte------------"); System.out.println("Expected value is 0x78"); number = getByte(0x12345678, 0); System.out.printf("Calculated value is 0x%x",number); System.out.println(); System.out.println("Expected value is 0xFF"); number = getByte(0xA55AFF25, 1); System.out.printf("Calculated value is 0x%x",number); System.out.println(); System.out.println("Expected value is 0x6A"); number = getByte(0x456ADB0F, 2); System.out.printf("Calculated value is 0x%x",number); System.out.println(); //Pack test cases 2 from comments + 1 self made System.out.println("---------Pack------------"); System.out.println("Expected value is 0x34687723"); number = pack(0x3468, 0x7723); System.out.printf("Calculated value is 0x%x",number); System.out.println(); System.out.println("Expected value is 0xBAADBEEF"); number = pack(0xBAAD, 0xBEEF); System.out.printf("Calculated value is 0x%x",number); System.out.println(); System.out.println("Expected value is 0x876345AF"); number = pack(0x8763, 0x45AF); System.out.printf("Calculated value is 0x%x",number); System.out.println(); //Unpack test cases 1 from comments + 1 self made System.out.println("---------Unpack------------"); System.out.println("Expected value is 0x8, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1"); int[] numberArray = unpack(0x12345678); System.out.print("Calculated value is "); for(int i:numberArray) { System.out.printf("0x%x",i); System.out.print(" "); } System.out.println(); System.out.println("Expected value is 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF"); numberArray = unpack(0xFEDCBA98); System.out.print("Calculated value is "); for(int i:numberArray) { System.out.printf("0x%x",i); System.out.print(" "); } System.out.println(); //Negate test cases 4 from comments + 1 self made System.out.println("---------Negate------------"); System.out.println("Expected value is 0x7FFFFF"); number = negate(0x000001, 23); System.out.printf("Calculated value is 0x%x",number); System.out.println(); System.out.println("Expected value is 0x000001"); number = negate(0x7FFFFF, 23); System.out.printf("Calculated value is 0x%x",number); System.out.println(); System.out.println("Expected value is 0x000000"); number = negate(0x000000, 24); System.out.printf("Calculated value is 0x%x",number); System.out.println(); System.out.println("Expected value is 0x3"); number = negate(0x1, 2); System.out.printf("Calculated value is 0x%x",number); System.out.println(); System.out.println("Expected value is 0xF0000000"); number = negate(0x10000000, 32); System.out.printf("Calculated value is 0x%x",number); System.out.println(); //Sign Extend test cases 2 from comments + 1 self made System.out.println("---------Sign Extend------------"); System.out.println("Expected value is 0x000000D2"); number = signExtend(0x000000D2, 9, 32); System.out.printf("0x%x",number); System.out.println(); System.out.println("Expected value is 0xFFFFFFE4"); number = signExtend(0x000007E4, 11, 32); System.out.printf("0x%x",number); System.out.println(); System.out.println("Expected value is 0x7FFFFAE4"); number = signExtend(0x00001AE4, 13, 31); System.out.printf("0x%x",number); System.out.println(); } /** * Sets a byte in a integer * * Integers are made of four bytes, numbered like so: 33333333 22222222 11111111 00000000 * * For a graphical representation of this: * 3 2 1 * 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Byte3 | Byte2 | Byte1 | Byte0 | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * * Examples: * setByte(0x25093456, 0x18, 0) //=> 0x25093418 * setByte(0x12374925, 0xF, 1) //=> 0x12370F25 * * @param num integer that will be modified * @param b byte to insert into the integer * @param which determines which byte gets modified - 0 for least significant byte * * @return the modified integer */ public static int setByte(int num, int b, int which) { //switches which byte you alter based on variable which (0-3) switch(which){ //for each case it zeroes out the byte you want to alter //then it ORs it with the byte you want it to be creating that byte in the sequence case 0: num= num&0xFFFFFF00; num= num|b; break; //For cases 1-3 it shifts the byte you want to have over to the correct corresponding spots case 1: num= num&0xFFFF00FF; num= num|(b<<8); break; case 2: num= num&0xFF00FFFF; num= num|(b<<16); break; case 3: num= num&0x00FFFFFF; num= num|(b<<24); break; } //returns the new number you created return num; } /** * Gets a byte from an integer * * Other examples: i.e. * getByte(0x12345678, 0) //=> 0x78 * getByte(0xA55AFF25, 1) //=> 0xFF * * @param num an integer * @param which Determines which byte gets returned - 0 for least significant byte * * @return a byte corresponding */ public static int getByte(int num, int which) { //switches which byte you alter based on variable which (0-3) switch(which){ //for each case it zeroes out except for the byte you want case 0: num= num&0x000000FF; break; //For cases 1-3 it shifts the byte all the way down so there is a correct number of following zeroes case 1: num= num&0x0000FF00; num= num>>8; break; case 2: num= num&0x00FF0000; num= num>>16; break; case 3: num= num&0xFF000000; num= num>>24; break; } //returns Just the Byte you wanted return num; } /** * Packs 2 shorts (16 bits) into an int (32 bits) * * The shorts should be placed consecutively in the integer in the order * specified in the parameters. * * i.e. pack(0x3468, 0x7723) //=> 0x34687723 * pack(0xBAAD, 0xBEEF) //=> 0xBAADBEEF * * @param c1 most significant short (will always be an 16 bit number) * @param c2 2nd short (will always be an 16 bit number) * * @return an int formatted like so c1c2 */ public static int pack(int c1, int c2) { //Shifts c1 over 16 bits to be the most significant short c1 = c1<<16; //returns c1 ORed with c2 creating the new int return c1|c2; } /** * Unpacks an integer into 8 nibbles (4 bits) most significant nibble first. * * i.e unpack(0x12345678) //=> {0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8} * * @param num integer that needs to be unpacked * @return an array with each nibble of the integer most significant nibble first. */ public static int[] unpack(int num) { int[] answer = {0, 0, 0, 0, 0, 0, 0, 0}; //sets each element by zeroing all of the bits other than the appropriate nibble for the each place and then shifts it over //until it is in the spot of the least significant nibble at which point it places into the array answer[0] = num&0x0000000F; answer[1] = (num&0x000000F0)>>4; answer[2] = (num&0x00000F00)>>8; answer[3] = (num&0x0000F000)>>12; answer[4] = (num&0x000F0000)>>16; answer[5] = (num&0x00F00000)>>20; answer[6] = (num&0x0F000000)>>24; answer[7] = (num&0xF0000000)>>28; //makes it act as an unsigned shift so you dont have repeated 1s before the byte you want. if(answer[7] < 0x0) { answer[7] = answer[7]^0xFFFFFFF0; } //returns the array return answer; } /** * Negates an 'x' bit number. * * Examples: * negate(0x000001, 23) //=> 0x7FFFFF * negate(0x7FFFFF, 23) //=> 0x000001 * negate(0x000000, 24) //=> 0x000000 * negate(0x1, 2) //=> 0x3 * * @param num 2's complement 'x' bit number to negate. * @param 'x' number of bits num is * @return the negated version an 'x' bit binary number. */ public static int negate(int num, int x) { //verifies 0 stays 0 if(num == 0) return 0; //shifts all 1s over by the number of bits num is and then flips it so that there are only //1s for the number of bits num is. x= ~((0xFFFFFFFF<<(x-1))<<1); //Flips all of the bits in num and then adds 1 computing what is basically 2s compliment. return ((num^x)+0x1); } /** * Sign extends an 'x' bit value to a 'y' bit value * * Both the parameter and return value are ints, but the parameter only uses the least significant * x bits, and the return value only uses the least significant y bits (the rest are zeros) * * Examples: * signExtend(0x000000D2, 9, 32) results in 0x000000D2 * signExtend(0x000007E4, 11, 32) results in 0xFFFFFFE4 * * @param num an x bit 2's complement number * @param x the original bit length * @param y the new bit length * @warning You will be guaranteed y > x. If this precondition does not hold results are undefined. * @return a 'y' bit 2's complement number, the sign extended value of num. */ public static int signExtend(int num, int x, int y) { //creates a variable for the number created by have only a bit in the index int indexNum = (1<<(x-1)); //take all 1s and shift them y times then negate it so that there is only 1s the size of y int yNum = ~((0xFFFFFFFF<<(y-1))<<1); //XOR it with all 1s in the size of x which creates all 1s in front of the places of the original number int newNumSize = yNum^(~(0xFFFFFFFF<<x)); //test if the most sig bit is a 1 and there negative a which point it XORs it with the newNumSize creating all 1s //in front of the previous most sig bit if((num&indexNum)==indexNum) { return (num^newNumSize); } //else it places all 0s in front of the most sig bit (not really nessicary since java already places all leading bits //as zeroes to fill up the full space of an int) else { return num&(~newNumSize); } //return num; } }
/* * Copyright (c) 2011. Peter Lawrey * * "THE BEER-WARE LICENSE" (Revision 128) * As long as you retain this notice you can do whatever you want with this stuff. * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return * There is no warranty. */ package com.google.code.java.core.executor; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class ExecutorTestMain { public static void main(String... args) { int length = 1000 * 1000; final double[] a = generate(length); final double[] b = generate(length); final double[] c = new double[length]; int nThreads = Runtime.getRuntime().availableProcessors(); ExecutorService executor = Executors.newFixedThreadPool(nThreads); for (int i = 0; i < 5; i++) { // single threaded { long start = System.nanoTime(); geomean(a, b, c, 0, length); long time = System.nanoTime() - start; System.out.printf("Single threaded: Time to geomean %,d values was %.3f msecs. %n", length, time / 1e6); } // Too many tasks. doTest(length, a, b, c, executor, 1, "Too many tasks"); // Small number of tasks doTest(length, a, b, c, executor, length / nThreads, "One task per thread"); } executor.shutdown(); } private static void doTest(int length, final double[] a, final double[] b, final double[] c, ExecutorService executor, final int blockSize, String desc) { List<Future> futures = new ArrayList<Future>(); long start = System.nanoTime(); for (int j = 0; j < length; j += blockSize) { final int finalJ = j; futures.add(executor.submit(new Runnable() { @Override public void run() { geomean(a, b, c, finalJ, finalJ + blockSize); } })); } try { for (Future future : futures) { future.get(); } } catch (Exception e) { throw new AssertionError(e); } long time = System.nanoTime() - start; System.out.printf(desc + ": Time to geomean %,d values was %.3f msecs. %n", length, time / 1e6); } private static double[] generate(int length) { double[] d = new double[length]; for (int i = 0; i < length; i++) d[i] = Math.random() - Math.random(); return d; } public static void geomean(double[] a, double[] b, double[] c, int from, int to) { for (int i = from; i < to; i++) c[i] = Math.sqrt(a[i] * b[i]); } }
package chapter14; import javafx.application.Application; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.shape.Polygon; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.Stage; public class Exercise14_15 extends Application { @Override public void start(Stage primaryStage) throws Exception { StackPane pane = new StackPane(); pane.setPadding(new Insets(20)); Polygon polygon = new Polygon(); polygon.setStroke(Color.BLACK); polygon.setFill(Color.RED); ObservableList<Double> list = polygon.getPoints(); final double WIDTH = 200, HEIGHT = 200; double centerX = WIDTH / 2, centerY = HEIGHT / 2; double radius = Math.min(WIDTH, HEIGHT) * 0.4; for (int i = 0; i < 8; i++) { list.add(centerX + radius * Math.cos(2 * i * Math.PI / 8)); list.add(centerY - radius * Math.sin(2 * i * Math.PI / 8)); } polygon.setRotate(22.5); Text text = new Text("STOP"); text.setFill(Color.WHITE); text.setStrokeWidth(5); text.setFont(Font.font(30)); pane.getChildren().addAll(polygon, text); primaryStage.setTitle("Exercise14_15"); primaryStage.setScene(new Scene(pane)); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
package com.company; public class Mers extends Cars implements Print{ private String name; public Mers(String name) { this.name = name; } @Override public void print() { System.out.println(name); } }
package com.zzn.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.zzn.entity.City; import com.zzn.service.CityService; @Controller public class UserCtroller { @Autowired CityService cityService; @ResponseBody @RequestMapping("index") public PageInfo<City> index(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { PageHelper.startPage(pageNum, 5); List<City> cities = cityService.getCities(0); PageInfo<City> pageInfo = new PageInfo<City>(cities); //model.addAttribute("cities", pageInfo); return pageInfo; } @RequestMapping("list") public String list(Model model, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, String query) { System.out.print(query + "----------"); System.out.println(pageNum); PageHelper.startPage(pageNum, 5); List<City> cities = cityService.getCities(0); PageInfo<City> pageInfo = new PageInfo<City>(cities); model.addAttribute("page", pageInfo); model.addAttribute("query", query); return "add"; } }
package com.bingo.code.example.design.iterator.rewrite; /** * �������ӿڣ�������ʺͱ���Ԫ�صIJ��� */ public interface Iterator { /** * �ƶ����ۺ϶���ĵ�һ��λ�� */ public void first(); /** * �ƶ����ۺ϶������һ��λ�� */ public void next(); /** * �ж��Ƿ��Ѿ��ƶ��ۺ϶�������һ��λ�� * @return true��ʾ�Ѿ��ƶ��ۺ϶�������һ��λ�ã� * false��ʾ��û���ƶ����ۺ϶�������һ��λ�� */ public boolean isDone(); /** * ��ȡ�����ĵ�ǰԪ�� * @return �����ĵ�ǰԪ�� */ public Object currentItem(); }
package com.ceiba.parkingceiba.controller; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.ceiba.parkingceiba.exception.tipos.ParqueaderoErrorBuilderException; import com.ceiba.parkingceiba.model.entity.Parqueadero; import com.ceiba.parkingceiba.model.entity.Vehiculo; import com.ceiba.parkingceiba.service.IControlParqueaderoService; @CrossOrigin(origins = { "*" }) @RestController @RequestMapping("/parqueadero") public class ParqueaderoController { private static final Logger LOGGER = Logger.getLogger("loggerController"); @Autowired private IControlParqueaderoService controlParqueaderoService; public ParqueaderoController(IControlParqueaderoService controlParqueaderoService) { this.controlParqueaderoService = controlParqueaderoService; } @RequestMapping(value = "/registroEntrada") public ResponseEntity<Object> entradaVehiculo(@RequestBody Vehiculo vehiculo) { Parqueadero parqueadero; try { parqueadero = controlParqueaderoService.registroVehiculo(vehiculo); } catch (ParqueaderoErrorBuilderException e) { LOGGER.log(Level.INFO, e.getMensaje(), e); return new ResponseEntity<>(e.getMensaje(), HttpStatus.NOT_ACCEPTABLE); } return new ResponseEntity<>(parqueadero, HttpStatus.CREATED); } @RequestMapping(value = "/registroSalida") public ResponseEntity<Object> salidaVehiculo(@RequestBody String placa) { try { Parqueadero parqueadero = controlParqueaderoService.salidaVehiculo(placa); return new ResponseEntity<>(parqueadero, HttpStatus.OK); } catch (ParqueaderoErrorBuilderException e) { LOGGER.log(Level.INFO, e.getMensaje(), e); return new ResponseEntity<>(e.getMensaje(), HttpStatus.NOT_ACCEPTABLE); } } @GetMapping(value = "/buscarVehiculos") public ResponseEntity<Object> buscarTodosLosVehiculos() { List<Parqueadero> parqueadero; try { parqueadero = controlParqueaderoService.consultarTodosLosVehiculos(); } catch (ParqueaderoErrorBuilderException e) { LOGGER.log(Level.INFO, e.getMensaje(), e); return new ResponseEntity<>(e.getMensaje(), HttpStatus.NOT_ACCEPTABLE); } return new ResponseEntity<>(parqueadero, HttpStatus.OK); } }
package com.red.gotrade.fragment; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.ActivityOptionsCompat; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.red.gotrade.R; import com.red.gotrade.Utils; import com.red.gotrade.activity.MyGoodsActivity; import com.red.gotrade.activity.PublishActivity; import com.red.gotrade.activity.UpdateInfoActivity; import com.red.gotrade.db.DbHelper; import com.red.gotrade.db.gen.AuthorModelDao; import com.red.gotrade.model.AuthorModel; import com.vise.log.ViseLog; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.Unbinder; import es.dmoral.toasty.Toasty; import okhttp3.internal.Util; import static android.app.Activity.RESULT_OK; public class MyFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_TOKEN = "param1"; private static final String ARG_ROOT = "param2"; public static final int REQUEST_CODE_MODIFIED = 101; @BindView(R.id.tv_info) TextView tvInfo; @BindView(R.id.rl_improve_my_info) RelativeLayout rlImproveMyInfo; @BindView(R.id.tv_my_goods) TextView tvMyGoods; @BindView(R.id.rl_my_goods) RelativeLayout rlMyGoods; @BindView(R.id.player_user_avatar) ImageView playerUserAvatar; @BindView(R.id.tv_user_name) TextView tvUserName; @BindView(R.id.tv_sign_out) TextView tvSignOut; Unbinder unbinder; // TODO: Rename and change types of parameters private String mUserName; private String mToken; private int mRoot; private OnFragmentInteractionListener mListener; public MyFragment() { // Required empty public constructor } // /** // * Use this factory method to create a new instance of // * this fragment using the provided parameters. // * // * @param param1 Parameter 1. // * @param param2 Parameter 2. // * @return A new instance of fragment MyFragment. // */ // TODO: Rename and change types and number of parameters public static MyFragment newInstance(String token, int root) { MyFragment fragment = new MyFragment(); Bundle args = new Bundle(); args.putString(ARG_TOKEN, token); args.putInt(ARG_ROOT, root); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mToken = getArguments().getString(ARG_TOKEN); mRoot = getArguments().getInt(ARG_ROOT); } AuthorModel authorModel = DbHelper.getInstance().author().queryBuilder() .where(AuthorModelDao.Properties.Author_token.eq(mToken)) .build().list().get(0); mUserName = authorModel.getAuthor_nickname(); } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View parentView = inflater.inflate(R.layout.fragment_my, container, false); unbinder = ButterKnife.bind(this, parentView); tvUserName.setText(Utils.getRootName(mRoot)+ mUserName); if (mRoot==1||mRoot==2||mRoot==3) { tvInfo.setText("修改个人信息"); } if (mRoot==2) { tvMyGoods.setText("我发布的商品"); } if (mRoot==3) { tvMyGoods.setText("我订购的商品"); } return parentView; } @Override public void onActivityResult(int requestCode,int resultCode,Intent intent) { super.onActivityResult(requestCode,resultCode,intent); switch(requestCode){ case REQUEST_CODE_MODIFIED: if(resultCode == RESULT_OK){ ViseLog.d("修改密码后注销"); mListener.onUserSignOut(); } break; } } // // // TODO: Rename method, update argument and hook method into UI event // public void onButtonPressed(Uri uri) { // if (mListener != null) { // mListener.onFragmentInteraction(uri); // } // } // @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @OnClick({R.id.rl_improve_my_info, R.id.rl_my_goods, R.id.tv_user_name, R.id.tv_sign_out}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.rl_improve_my_info: if (mRoot==1||mRoot==2||mRoot==3) { Intent i = UpdateInfoActivity.newIntent(getActivity(), mToken, mRoot); startActivityForResult(i, REQUEST_CODE_MODIFIED); } break; case R.id.rl_my_goods: if (mRoot==2) { ActivityOptionsCompat oc = ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity()); Intent i = MyGoodsActivity.newIntent(getActivity(), mToken, mRoot); startActivity(i, oc.toBundle()); } if (mRoot==3) { ActivityOptionsCompat oc = ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity()); Intent i = MyGoodsActivity.newIntent(getActivity(), mToken, mRoot); startActivity(i, oc.toBundle()); } break; case R.id.tv_user_name: Toasty.info(view.getContext(), "用户昵称: " + mUserName, Toast.LENGTH_SHORT, true).show(); break; case R.id.tv_sign_out: mListener.onUserSignOut(); break; } } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onUserSignOut(); } }
package com.example.crm.service.impl; public class UserServiceImpl { }
package JogoDaVelha; public class Main { public static void main(String[] args) { Tabuleiro jogo = new Tabuleiro("X","O"); jogo.iniciar(); } }
package manage.teachergui; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Vector; import javax.swing.*; import manage.app.Application; import manage.bean.Grade; import manage.dbutil.ConnectionManager; import manage.service.impl.GradeServiceImpl; public class UpdateGradeFrame extends JFrame { //定义Vector private Vector rows; private Vector colHead; /** * 学号文本框 */ private JTextField txtId; private JButton btnQuery; private JButton btnBrowseAll; //定义服务实现类 private GradeServiceImpl gradeServiceImpl; //定义gui组件 private JTable table; private JScrollPane scroller; JPanel frame; JTextField idtext; JTextField nametext; JTextField classtext; JTextField chinesetext; JTextField mathtext; JTextField englishtext; JTextField physicstext; JTextField chemistrytext; JTextField biologtext; JButton bupdate; JButton brefresh; JButton bexit; //定义List private List<Grade> sets; //定义实体类 Grade grade; //设置构造方法 public UpdateGradeFrame(String title) { super(title); Start(); } //定义执行方法 public void Start(){ //vector实例化 rows=new Vector(); colHead=new Vector(); //gui界面设计 frame = (JPanel) getContentPane(); frame.setLayout(new BorderLayout()); JPanel southJPanel=new JPanel(); southJPanel.setLayout(new GridLayout(4,1)); JPanel p1=new JPanel(); JPanel p2=new JPanel(); JPanel p3=new JPanel(); JLabel label1=new JLabel("学号: "); JLabel label2=new JLabel("姓名: "); JLabel label3=new JLabel("班级: "); JLabel label4=new JLabel("语文: "); JLabel label5=new JLabel("数学: "); JLabel label6=new JLabel("英语: "); JLabel label7=new JLabel("物理: "); JLabel label8=new JLabel("化学: "); JLabel label9=new JLabel("生物: "); idtext=new JTextField(10); nametext=new JTextField(10); classtext=new JTextField(10); chinesetext=new JTextField(10); mathtext=new JTextField(10); englishtext=new JTextField(10); physicstext=new JTextField(10); chemistrytext=new JTextField(10); biologtext=new JTextField(10); idtext.setEditable(false); nametext.setEditable(false); classtext.setEditable(false); p1.add(label1); p1.add(idtext); p1.add(label2); p1.add(nametext); p1.add(label3); p1.add(classtext); p2.add(label4); p2.add(chinesetext); p2.add(label5); p2.add(mathtext); p2.add(label6); p2.add(englishtext); p3.add(label7); p3.add(physicstext); p3.add(label8); p3.add(chemistrytext); p3.add(label9); p3.add(biologtext); JPanel p4=new JPanel(); p4.setLayout(new FlowLayout(FlowLayout.CENTER)); bupdate=new JButton("更新"); brefresh=new JButton("刷新"); bexit=new JButton("退出"); p4.add(bupdate); p4.add(brefresh); p4.add(bexit); southJPanel.add(p1); southJPanel.add(p2); southJPanel.add(p3); southJPanel.add(p4); txtId = new JTextField(11); txtId.setHorizontalAlignment(JTextField.LEFT); btnQuery = new JButton("查询[Q]"); btnQuery.setMnemonic(KeyEvent.VK_Q); btnBrowseAll = new JButton("显示全部记录[A]"); btnBrowseAll.setMnemonic(KeyEvent.VK_A); JPanel pnlNorth=new JPanel(); JLabel lblInputId=new JLabel("输入学号:"); pnlNorth.add(lblInputId); pnlNorth.add(txtId); pnlNorth.add(btnQuery); pnlNorth.add(btnBrowseAll); frame.add(southJPanel,BorderLayout.SOUTH); frame.add(pnlNorth,BorderLayout.NORTH); gradeServiceImpl=new GradeServiceImpl(); sets=gradeServiceImpl.findgradeAll(); //显示结果集方法 fillTableData(); pack(); setSize(500,500); setLocationRelativeTo(null); setResizable(false); setVisible(true); // 重绘窗体 repaint(); //设计更新按钮事件 bupdate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { grade=new Grade(); grade.setStudent_id(Integer.parseInt(idtext.getText())); grade.setChinese(Integer.parseInt(chinesetext.getText())); grade.setMath(Integer.parseInt(mathtext.getText())); grade.setEnglish(Integer.parseInt(englishtext.getText())); grade.setPhysics(Integer.parseInt(physicstext.getText())); grade.setChemistry(Integer.parseInt(chemistrytext.getText())); grade.setBiolog(Integer.parseInt(biologtext.getText())); int count=gradeServiceImpl.updategrade(grade); if (count > 0) { JOptionPane.showMessageDialog(null, "成绩修改成功!", "提示", JOptionPane.INFORMATION_MESSAGE); // 重新获取全部学生列表 sets=gradeServiceImpl.findgradeAll(); // 清空待删学生学号文本框 idtext.setText(""); nametext.setText(""); classtext.setText(""); chinesetext.setText(""); mathtext.setText(""); englishtext.setText(""); physicstext.setText(""); chemistrytext.setText(""); biologtext.setText(""); // 填充数据 fillTableData(); } else { System.out.print(sets); System.out.print(count); JOptionPane.showMessageDialog(null, "成绩修改失败!", "警告", JOptionPane.WARNING_MESSAGE); } } }); //设计刷新按钮事件 brefresh.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { fillTableData(); } }); //设计退出按钮事件 bexit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { dispose(); } }); // 【显示全部记录】按钮单击事件 btnBrowseAll.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { // 获取全部学生记录 String classname=getClass_name(Application.id); sets=findgradeByClass_name(classname); // 填充表格数据 fillTableData(); } }); // 文本框按键事件 txtId.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == 10) { doQuery(); } } }); // 【查询】按钮单击事件 btnQuery.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { doQuery(); } }); //设计鼠标点击显示事件 table.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { // 获取当前行的行数 int row = table.rowAtPoint(e.getPoint()); // 选中鼠标单击的行 table.setRowSelectionInterval(row, row); // 设置文本框内容 txtId.setText(table.getValueAt(row,0).toString()); idtext.setText(table.getValueAt(row,0).toString()); nametext.setText(table.getValueAt(row,1).toString()); classtext.setText(table.getValueAt(row,2).toString()); chinesetext.setText(table.getValueAt(row,3).toString()); mathtext.setText(table.getValueAt(row,4).toString()); englishtext.setText(table.getValueAt(row,5).toString()); physicstext.setText(table.getValueAt(row,6).toString()); chemistrytext.setText(table.getValueAt(row,7).toString()); biologtext.setText(table.getValueAt(row,8).toString()); } }); } /** * 查询方法 */ private void doQuery() { // 获取查询学号 String id = txtId.getText().trim(); if (!id.equals("")) { sets.clear(); String classname=getClass_name(Application.id); sets=findgradeByClass_name(classname); // 填充表格 fillTableData(); } else { JOptionPane.showMessageDialog(this, "请输入待查学生学号!", "警告", JOptionPane.WARNING_MESSAGE); txtId.requestFocus(); } } //设计显示结果集方法 private void fillTableData() { // 填充表头 colHead.clear(); colHead.add("学号"); colHead.add("姓名"); colHead.add("班级"); colHead.add("语文"); colHead.add("数学"); colHead.add("英语"); colHead.add("物理"); colHead.add("化学"); colHead.add("生物"); //sets=setServiceImpl.findgrade(); // 填充表记录 rows.clear();//清空 for (Grade grade : sets) { Vector<String> currentRow = new Vector<String>(); currentRow.addElement(grade.getStudent_id()+""); currentRow.addElement(grade.getStudent_names()); currentRow.addElement(grade.getClass_names()); currentRow.addElement(grade.getChinese() + ""); currentRow.addElement(grade.getMath()+""); currentRow.addElement(grade.getEnglish()+""); currentRow.addElement(grade.getPhysics()+""); currentRow.addElement(grade.getChemistry()+""); currentRow.addElement(grade.getBiolog()+""); // 将当前行添加到记录行集 rows.add(currentRow); } // 创建表格(参数1:记录集;参数2:表头) table = new JTable(rows, colHead); // 定义滚动面板 scroller = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); // 设置此表是否始终大到足以填充封闭视口的高度。 table.setFillsViewportHeight(true); table.setAutoCreateRowSorter(true);//设置排序 // 将滚动面板添加到中心面板 frame.add(scroller, BorderLayout.CENTER); // 重绘窗体 repaint(); // 判断是否有记录行 if (rows.isEmpty()) { JOptionPane.showMessageDialog(this, "没有符合条件的记录!", "错误提示", JOptionPane.WARNING_MESSAGE); idtext.setText(""); nametext.setText(""); classtext.setText(""); chinesetext.setText(""); mathtext.setText(""); englishtext.setText(""); physicstext.setText(""); chemistrytext.setText(""); biologtext.setText(""); } else { // 让滚动条移到最上方 scroller.getVerticalScrollBar().setValue(0); } } public List<Grade> findgradeByClass_name(String classname){ List<Grade> sets=new ArrayList<Grade>(); // 获得数据库连接 Connection conn = ConnectionManager.getConnection(); // 定义SQL字符串 String strSQL = "select * from grade where class_name = ?"; try { // 创建预备语句对象 PreparedStatement pstmt = conn.prepareStatement(strSQL); // 设置占位符的值 pstmt.setString(1, classname); // 执行SQL查询,返回结果集 ResultSet rs = pstmt.executeQuery(); // 判断结果集是否有记录 while(rs.next()){ Grade grade=new Grade(); grade.setStudent_id(rs.getInt("student_id")); grade.setStudent_names(rs.getString("student_name")); grade.setClass_names(rs.getString("class_name")); grade.setChinese(rs.getInt("chinese")); grade.setMath(rs.getInt("math")); grade.setEnglish(rs.getInt("english")); grade.setPhysics(rs.getInt("physics")); grade.setChemistry(rs.getInt("chemistry")); grade.setBiolog(rs.getInt("biolog")); sets.add(grade); } rs.close(); pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } finally { ConnectionManager.closeConnection(conn); } // 返回删除记录数 return sets; } public String getClass_name(int id){ String getclass=null; Connection conn = ConnectionManager.getConnection(); String strSQL = "SELECT class_name FROM teacher join set_class using (class_id) WHERE teacher_id = ?"; PreparedStatement pstmt = null; try { pstmt = conn.prepareStatement(strSQL); pstmt.setInt(1, id); ResultSet rs; rs = pstmt.executeQuery(); if (rs.next()) { try { getclass=rs.getString("class_name"); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } return getclass; } }
package com.sinotao.business.dao; import tk.mybatis.mapper.common.Mapper; import com.sinotao.business.dao.entity.ClinicarItem; public interface ClinicarItemDao extends Mapper<ClinicarItem>{ }
package com.ireslab.sendx.electra.service; import com.ireslab.sendx.electra.model.ApprovelRequest; import com.ireslab.sendx.electra.model.ApprovelResponse; import com.ireslab.sendx.electra.model.TokenTransferRequest; import com.ireslab.sendx.electra.model.TokenTransferResponse; import com.ireslab.sendx.electra.model.TransactionHistoryResponse; import com.ireslab.sendx.electra.model.TransactionLimitRequest; import com.ireslab.sendx.electra.model.TransactionLimitResponse; import com.ireslab.sendx.electra.model.TransactionPurposeRequest; import com.ireslab.sendx.electra.model.TransactionPurposeResponse; /** * @author iRESlab * */ public interface TransactionManagementService { /** * @param clientCorrelationId * @param userCorrelationId * @return */ public TransactionHistoryResponse cashOutTokensHistory(String clientCorrelationId, String userCorrelationId); public TransactionLimitResponse getTransactionLimitData(); public ApprovelResponse ekycEkybApprovelList(); public ApprovelResponse approveEkycEkyb(ApprovelRequest approvelRequest); public TransactionLimitResponse updateTransactionLimit(TransactionLimitRequest transactionLimitRequest); public ApprovelResponse ekycEkybApprovedList(); public TransactionPurposeResponse getAllTransactionPurpose(String clientCorrelationId); public TokenTransferResponse transactionLimitsForAllowTransfer(TokenTransferRequest tokenTransferRequest); public TransactionPurposeResponse addAndUpdateTransactionPurpose( TransactionPurposeRequest transactionPurposeRequest); public TransactionPurposeResponse deleteTransactionPurpose(TransactionPurposeRequest transactionPurposeRequest); }
package com.shopping.Filter; import java.io.IOException; import java.net.URLDecoder; import java.sql.SQLException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.shopping.models.User; import com.shopping.service.UserService; import com.shopping.utils.CookieUtils; public class AutoLoginFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // 1、判断当前用户是否已经登陆 HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; if (httpServletRequest.getSession().getAttribute("user") == null) { // 未登录 // 2、判断对应cookie 是否存在 ---- 将cookie 查询写为工具类 Cookie cookie1 = CookieUtils.findCookie(httpServletRequest .getCookies(), "USERACCOUNT"); Cookie cookie2 = CookieUtils.findCookie(httpServletRequest .getCookies(), "USERPWD"); if (cookie1 != null && cookie2 != null) { // 找到了自动登陆cookie // 如果用户名中文,需要解密,详情见下文 String userAccount = URLDecoder.decode(cookie1.getValue(), "utf-8"); String password = URLDecoder.decode(cookie2.getValue(), "utf-8"); User u = null; UserService us = new UserService(); try { u = us.loginByAccount(userAccount, password); } catch (SQLException e) { e.printStackTrace(); } if(u==null){ try { u = us.loginByPhone(userAccount, password); } catch (SQLException e) { e.printStackTrace(); } } if(u!=null){ HttpSession session=httpServletRequest.getSession(); session.setAttribute("USER", u); System.out.println("AutoLoginFilter"); } chain.doFilter(request, response); } else { // 没有自动登陆信息 chain.doFilter(request, response); } } else { // 已经登陆,不需要自动登陆 chain.doFilter(request, response); } } public void init(FilterConfig filterConfig) throws ServletException { } }
package org.openfact.rest.idm; import io.swagger.annotations.ApiModel; @ApiModel(description = "Modelo para crear retenciones.") public class Retention extends PercepcionRetencion { }
package huawei; import java.math.BigInteger; import java.util.Scanner; /** * @author kangkang lou */ public class Main_45 { static String add(String a, String b) { BigInteger m = new BigInteger(a); BigInteger n = new BigInteger(b); return String.valueOf(m.add(n)); } public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { String a = in.next(); String b = in.next(); System.out.println(add(a, b)); } } }
package com.nearsoft.upiita.api.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import java.io.Serializable; @Entity @Table(name = "movie") public class Movie implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name = "origin_country") @Enumerated(EnumType.STRING) private Country country; @Enumerated(EnumType.STRING) private Genre genre; @ManyToOne @JoinColumn(name = "id_director") private Director director; private String title; private Long year; public Movie() {} public Movie(String title, Country country, Long year, Genre genre, Director director) { this.title = title; this.country = country; this.year = year; this.genre = genre; this.director = director; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Country getCountry() { return country; } public void setCountry(Country country) { this.country = country; } public Genre getGenre() { return genre; } public void setGenre(Genre genre) { this.genre = genre; } public Director getDirector() { return director; } public void setDirector(Director director) { this.director = director; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Long getYear() { return year; } public void setYear(Long year) { this.year = year; } }
package com.zoneigh.clappybird; import java.util.ArrayList; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer; import com.badlogic.gdx.physics.box2d.World; import com.zoneigh.clappybird.model.IClapListener; import com.zoneigh.clappybird.model.IGamer; import com.zoneigh.clappybird.render.Box2dRendering; import com.zoneigh.clappybird.render.SpriteRendering; public class ClappyBird implements ApplicationListener { public static final float VIEWPORT_WIDTH = 48; public static final float VIEWPORT_HEIGHT = 80; public static final float TIMESTEP = 1 / 24f; private IGamer gamer; private IClapListener clapListener; private int screenWidth; private int screenHeight; private OrthographicCamera camera; private SpriteBatch batch; public static World world; public static Box2DDebugRenderer renderer; public static int score; private int bestScore; public static boolean gameStarted; boolean gameEnded; public static boolean gamePlaying; private BitmapFont currentScoreFont; private BitmapFont bestScoreFont; private BitmapFont gameoverFont; private BitmapFont tapToRestartFont; private BitmapFont clapFont; public ClappyBird (IGamer gamer, IClapListener clapListener) { this.gamer = gamer; this.clapListener = clapListener; setBestScore(this.gamer.getBestScore()); this.clapListener.startListening(); } @Override public void create() { this.screenWidth = Gdx.graphics.getWidth(); this.screenHeight = Gdx.graphics.getHeight(); gameStarted = false; this.gameEnded = false; gamePlaying = false; this.batch = new SpriteBatch(); this.currentScoreFont = new BitmapFont(); this.bestScoreFont = new BitmapFont(); this.gameoverFont = new BitmapFont(); this.tapToRestartFont = new BitmapFont(); this.clapFont = new BitmapFont(); // create the camera and the SpriteBatch camera = new OrthographicCamera(); camera.setToOrtho(false, VIEWPORT_WIDTH, VIEWPORT_HEIGHT); Box2dRendering.createRendering(); world = Box2dRendering.world; renderer = Box2dRendering.renderer; score = 0; SpriteRendering.createSprites(); } @Override public void dispose() { batch.dispose(); SpriteRendering.disposeSprites(); } @Override public void render() { long currentTimestamp = System.currentTimeMillis(); // clear the screen with a dark blue color. The // arguments to glClearColor are the red, green // blue and alpha component in the range [0,1] // of the color to be used to clear the screen. Gdx.gl.glClearColor(0, 0, 0.2f, 1); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); renderer.render(world, camera.combined); if (this.clapListener.isManualAllowed() && Gdx.input.isTouched()) { this.clapListener.sendClap(); } if (this.clapListener.hasClap() && !this.gameEnded) { // TODO debug stuff. remove later Gdx.gl.glClearColor(1, 0, 0, 1); if (!gamePlaying) { // Start the game gameStarted = true; gamePlaying = true; Box2dRendering.createRendering(); world = Box2dRendering.world; renderer = Box2dRendering.renderer; Box2dRendering.createFirstObstacles(); } else { // Jump! Box2dRendering.jumpBird(); } this.clapListener.acknowledgeClap(); } if (this.gameEnded) { this.clapListener.stopListening(); //tap to resume if (Gdx.input.isTouched()) { this.clapListener.startListening(); this.gameEnded = false; gameStarted = false; gamePlaying = false; Box2dRendering.createRendering(); world = Box2dRendering.world; renderer = Box2dRendering.renderer; } } Box2dRendering.cycleObstacles(); Box2dRendering.checkScore(); //update best score automatically if (score > this.bestScore) { this.gamer.recordNewScore(score); setBestScore(this.gamer.getBestScore()); } Box2dRendering.hoverBird(!gamePlaying && !gameStarted); world.step(Box2dRendering.timeStep, 6, 2); batch.begin(); SpriteRendering.renderBackground(batch); //add all obstacles into a single list then render them ArrayList<Body> allObstacles = new ArrayList<Body>(); for (Body body : Box2dRendering.lastObstacles) { allObstacles.add(body); } for (Body body : Box2dRendering.scoreObstacles) { allObstacles.add(body); } for (Body body : Box2dRendering.obstacleList) { allObstacles.add(body); } SpriteRendering.renderObstacles(batch, allObstacles); SpriteRendering.renderGround(batch); SpriteRendering.renderBird(batch); if (!gamePlaying) { if (!gameStarted) { // Game hasn't started SpriteRendering.renderStartScreenBanner(batch); if ((currentTimestamp / 800) % 2 == 0) { // Blink this.clapFont.setScale(3); this.clapFont.draw(batch, "Clap to begin", this.screenWidth - 400, (this.screenHeight * 3.0f / 5.0f)); } } else { // Ended Game this.gamer.recordNewScore(score); setBestScore(this.gamer.getBestScore()); score = 0; this.gameEnded = true; this.gameoverFont.setScale(8); this.gameoverFont.setColor(0.8f, 0.2f, 0, 1); this.gameoverFont.draw(batch, "Game Over!", 40, (this.screenHeight * 5.0f / 7.0f)); if ((currentTimestamp / 800) % 2 == 0) { // Blink this.tapToRestartFont.setScale(3); this.tapToRestartFont.draw(batch, "tap to play again", this.screenWidth - 480, this.screenHeight - 500); } } } this.currentScoreFont.setScale(4); this.currentScoreFont.draw(batch, "" + score, 20, this.screenHeight - 20); // TODO relative position this.bestScoreFont.setScale(4); this.bestScoreFont.draw(batch, "Best: " + this.bestScore, this.screenWidth - 300, this.screenHeight - 20); // TODO relative position batch.end(); // tell the camera to update its matrices. camera.update(); } @Override public void resize(int width, int height) { } @Override public void pause() { // Box2dRendering.timeStep = 0; } @Override public void resume() { // Box2dRendering.timeStep = TIMESTEP; } private void setBestScore (int bestScore) { this.bestScore = bestScore; } }
package org.damienoreilly.zserv; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.damienoreilly.zserv.WadReader.WadType; import org.damienoreilly.zserv.config.ZservWebConfigService; import org.springframework.stereotype.Component; @Component public class ZservManagerImpl implements ZservManager { private ZservWebConfigService zservWebConfigService; @Override public Map<WadType, List<Wad>> getAvailableWads() throws IOException { WadReader wadreader = new WadReader(Paths.get(zservWebConfigService.getWadDir())); return wadreader.getAvailableWads(); } @Override public List<ZservProfile> getZservProfiles() { List<ZservProfile> servers = new ArrayList<>(); ZservProfile zservInstance = new ZservProfile(); zservInstance.setZservName("Test server #1"); Zserv zserv = new Zserv(); zserv.setPort(60001); zservInstance.setZserv(zserv); servers.add(zservInstance); zservInstance = new ZservProfile(); zservInstance.setZservName("Test server #2"); zserv = new Zserv(); zserv.setPort(60002); zservInstance.setZserv(zserv); servers.add(zservInstance); zservInstance = new ZservProfile(); zservInstance.setZservName("Test server #3"); zserv = new Zserv(); zserv.setPort(60003); zservInstance.setZserv(zserv); servers.add(zservInstance); return servers; } }
package br.univel.entrega; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Classe Java de entregar complex type. * * <p>O seguinte fragmento do esquema especifica o conteúdo esperado contido dentro desta classe. * * <pre> * &lt;complexType name="entregar"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="endereco_Entrega" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "entregar", propOrder = { "enderecoEntrega" }) public class Entregar { @XmlElement(name = "endereco_Entrega") protected String enderecoEntrega; /** * Obtém o valor da propriedade enderecoEntrega. * * @return * possible object is * {@link String } * */ public String getEnderecoEntrega() { return enderecoEntrega; } /** * Define o valor da propriedade enderecoEntrega. * * @param value * allowed object is * {@link String } * */ public void setEnderecoEntrega(String value) { this.enderecoEntrega = value; } }
package com.takshine.core.service.business; import java.util.List; import com.takshine.core.service.exception.CRMException; import com.takshine.wxcrm.domain.Schedule; import com.takshine.wxcrm.message.error.CrmError; import com.takshine.wxcrm.message.sugar.ScheduleAdd; /** * 日程服务 * @author yihailong * */ public interface CalendarService{ public List<ScheduleAdd> getScheduleList(Schedule sche)throws CRMException; public ScheduleAdd getSchedule(String rowid)throws CRMException; public void addSchedule(Schedule obj)throws CRMException; public void deleteSchedule(String rowid)throws CRMException; public void updateSchedule(Schedule obj)throws CRMException; }
package com.ivara.aravi.minimodulechat; import android.app.ProgressDialog; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.firebase.client.Firebase; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import org.w3c.dom.Text; public class MainActivity extends AppCompatActivity { FirebaseAuth pf; FirebaseAuth.AuthStateListener authStateListener; ProgressDialog pd; TextView e,p; Button r,s; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); pf = FirebaseAuth.getInstance(); pd = new ProgressDialog(this); e = (TextView)findViewById(R.id.eml); p = (TextView)findViewById(R.id.pws); r = (Button)findViewById(R.id.reg1); s = (Button)findViewById(R.id.login); r.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getApplicationContext(),Main2Activity.class)); } }); // final String[] c = new String[1]; final int[] tt = new int[2]; tt[0] = 0; tt[1] = 0; s.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pd.setMessage("Logging In . . ."); pd.show(); pf = FirebaseAuth.getInstance(); String em = e.getText().toString().trim(); String pw = p.getText().toString().trim(); check(); if (em.isEmpty()) { Toast.makeText(getApplicationContext(),"Email Field is Necessary !",Toast.LENGTH_SHORT).show(); return; } if (pw.isEmpty()) { Toast.makeText(getApplicationContext(),"Password Is Necessary !",Toast.LENGTH_SHORT).show(); return; } pf.signInWithEmailAndPassword(em,pw) .addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { Toast.makeText(getApplicationContext(),"Login Successful !",Toast.LENGTH_SHORT).show(); startActivity(new Intent(getApplicationContext(),Main3Activity.class)); } else { Toast.makeText(getApplicationContext(),"Credentials Mismatch !",Toast.LENGTH_SHORT).show(); } } }); pd.dismiss(); } }); } private void check() { pf.addAuthStateListener(authStateListener); authStateListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { if (pf.getCurrentUser()!=null) { Toast.makeText(getApplicationContext(),"Previous Login remembered !",Toast.LENGTH_SHORT).show(); startActivity(new Intent(getApplicationContext(),Main3Activity.class)); } } }; } @Override protected void onStart() { super.onStart(); } }
package fr.doranco.ecommerce.enums; public enum TypeUtilisateur { CLIENT ("C"), MAGASINIER ("M"), ADMIN ("A"); private String typeUtilisateur; private TypeUtilisateur(String typeUtilisateur) { this.typeUtilisateur = typeUtilisateur; } public String getTypeUtilisateur() { return this.typeUtilisateur; } }
package techquizapp.gui; import java.awt.Color; import java.awt.Font; import java.sql.SQLException; import javax.swing.JOptionPane; import techquizapp.dao.UserDAO; import techquizapp.pojo.User; import techquizapp.pojo.UserProfile; public class ChangePasswordFrame extends javax.swing.JFrame { private String username; private String password; private String rePassword; Color oldColor; public ChangePasswordFrame() { initComponents(); setTitle("THE TECH QUIZ APP"); setLocationRelativeTo(null); lblUserName.setText("Hello "+UserProfile.getUsername()); oldColor=lblLogout3.getForeground(); loadUserId(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); lblUserName = new javax.swing.JLabel(); lblLogout3 = new javax.swing.JLabel(); btnUpdPassword = new javax.swing.JButton(); btnBack = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); txtUserName = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); txtPassword = new javax.swing.JPasswordField(); jLabel3 = new javax.swing.JLabel(); txtRetypePassword = new javax.swing.JPasswordField(); setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); setResizable(false); jPanel1.setBackground(new java.awt.Color(0, 0, 0)); jLabel1.setBackground(new java.awt.Color(0, 0, 0)); jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 51, 51)); jLabel1.setText("Change Password"); lblUserName.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N lblUserName.setForeground(new java.awt.Color(255, 0, 0)); lblLogout3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N lblLogout3.setForeground(new java.awt.Color(255, 0, 0)); lblLogout3.setText("Logout"); lblLogout3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { lblLogout3MouseClicked(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { lblLogout3MouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { lblLogout3MouseExited(evt); } }); btnUpdPassword.setBackground(new java.awt.Color(255, 255, 255)); btnUpdPassword.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N btnUpdPassword.setForeground(new java.awt.Color(51, 51, 255)); btnUpdPassword.setText("Update Password"); btnUpdPassword.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnUpdPasswordActionPerformed(evt); } }); btnBack.setBackground(new java.awt.Color(255, 255, 255)); btnBack.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N btnBack.setForeground(new java.awt.Color(51, 51, 255)); btnBack.setText("Back"); btnBack.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnBackActionPerformed(evt); } }); jPanel2.setBackground(new java.awt.Color(51, 51, 51)); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 15)); // NOI18N jLabel2.setForeground(new java.awt.Color(0, 204, 0)); jLabel2.setText("UserId"); txtUserName.setEditable(false); txtUserName.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel4.setFont(new java.awt.Font("Tahoma", 1, 15)); // NOI18N jLabel4.setForeground(new java.awt.Color(0, 204, 0)); jLabel4.setText("Password"); txtPassword.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel3.setFont(new java.awt.Font("Tahoma", 1, 15)); // NOI18N jLabel3.setForeground(new java.awt.Color(0, 204, 0)); jLabel3.setText("ReType Password"); txtRetypePassword.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(71, 71, 71) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(jLabel2)) .addGap(66, 66, 66) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtRetypePassword, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(78, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(20, 20, 20) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(27, 27, 27) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addGap(28, 28, 28) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtRetypePassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addContainerGap(28, Short.MAX_VALUE)) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lblLogout3, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(103, 103, 103) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(148, 148, 148) .addComponent(btnUpdPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(58, 58, 58) .addComponent(btnBack, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 16, Short.MAX_VALUE))) .addContainerGap()) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(lblUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(491, Short.MAX_VALUE))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(lblLogout3) .addGap(19, 19, 19) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(43, 43, 43) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnUpdPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnBack)) .addContainerGap(44, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(lblUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(357, Short.MAX_VALUE))) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void lblLogout3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblLogout3MouseClicked LoginFrame loginFrame=new LoginFrame(); loginFrame.setVisible(true); this.dispose(); }//GEN-LAST:event_lblLogout3MouseClicked private void lblLogout3MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblLogout3MouseEntered lblLogout3.setForeground(Color.white); Font f =new Font("Tahoma",Font.ITALIC,12); lblLogout3.setFont(f); }//GEN-LAST:event_lblLogout3MouseEntered private void lblLogout3MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblLogout3MouseExited lblLogout3.setForeground(oldColor); Font f =new Font("Tahoma",Font.BOLD,12); lblLogout3.setFont(f); }//GEN-LAST:event_lblLogout3MouseExited private void btnUpdPasswordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdPasswordActionPerformed if(validateInputs()==false){ JOptionPane.showMessageDialog(null, "Please filled all inputs!", "Error!", JOptionPane.ERROR_MESSAGE); return; } if(password.equals(rePassword) == false){ JOptionPane.showMessageDialog(null, "Password and Retype-Password does not match!", "Error!", JOptionPane.ERROR_MESSAGE); return; } try{ User user=new User(username,password,"Student"); boolean isUser=UserDAO.updateStudent(user); if(!isUser){ JOptionPane.showMessageDialog(null,"Invalid, Student User cannot be created!", "Error!", JOptionPane.ERROR_MESSAGE); } else{ JOptionPane.showMessageDialog(null,"Password update successfully!", "Success!", JOptionPane.INFORMATION_MESSAGE); StudentOptionsFrame studFrame=new StudentOptionsFrame(); studFrame.setVisible(true); this.dispose(); } } catch(SQLException ex){ JOptionPane.showMessageDialog(null, "DB Error!", "Student Registration Error!", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } }//GEN-LAST:event_btnUpdPasswordActionPerformed private void btnBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBackActionPerformed StudentOptionsFrame studFrame=new StudentOptionsFrame(); studFrame.setVisible(true); this.dispose(); }//GEN-LAST:event_btnBackActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ChangePasswordFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ChangePasswordFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ChangePasswordFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ChangePasswordFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ChangePasswordFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnBack; private javax.swing.JButton btnUpdPassword; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JLabel lblLogout3; private javax.swing.JLabel lblUserName; private javax.swing.JPasswordField txtPassword; private javax.swing.JPasswordField txtRetypePassword; private javax.swing.JTextField txtUserName; // End of variables declaration//GEN-END:variables private void loadUserId() { txtUserName.setText(UserProfile.getUsername()); } private boolean validateInputs(){ username=txtUserName.getText(); char[] pwd=txtPassword.getPassword(); char[] repwd=txtRetypePassword.getPassword(); password=String.valueOf(pwd); rePassword=String.valueOf(repwd); if(username.isEmpty() || password.isEmpty() || rePassword.isEmpty()) return false; return true; } }
package com.tencent.mm.plugin.u; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.sdk.platformtools.bi; public final class g { public long aeq = 0; private boolean hEj; public long lcT = 0; public long lcU = 0; public long lcV = -1; public long lcW = 0; public long lcX = 0; public long lcY = 0; public long lcZ = 10; public boolean lda = true; public boolean ldb = true; public boolean ldc = false; public boolean ldd = false; boolean lde = false; boolean ldf = false; public g(boolean z) { this.hEj = z; } public final String avA() { return hashCode(); } public final void Hl(String str) { if (this.lda) { h.mEJ.a(354, 152, 1, false); h.mEJ.h(13836, new Object[]{Integer.valueOf(500), Long.valueOf(bi.VE()), str}); } } public final void Hm(String str) { if (this.lda) { h.mEJ.a(354, 153, 1, false); h.mEJ.h(13836, new Object[]{Integer.valueOf(501), Long.valueOf(bi.VE()), str}); } } public final void bdv() { if (this.lda) { h.mEJ.a(354, 155, 1, false); h.mEJ.h(13836, new Object[]{Integer.valueOf(503), Long.valueOf(bi.VE()), ""}); } } }
testing & hello
package com.vikastadge.hibernate.xml.service; import com.vikastadge.hibernate.xml.dao.PersonDAO; import com.vikastadge.hibernate.xml.dao.entity.PersonEntity; public class PersonService { public void save(PersonEntity personEntity){ System.out.println("In Service"); PersonDAO personDAO = new PersonDAO(); personDAO.save(personEntity); } }
package com.beiyelin.common.document; import lombok.Data; import org.apache.poi.POIXMLProperties; import org.apache.poi.hpsf.DocumentSummaryInformation; import org.apache.poi.hpsf.SummaryInformation; import javax.xml.bind.annotation.XmlType; import java.util.Date; /** * Created by newmann2017-09-12. */ @Data @XmlType(propOrder = {"category","contentStatus","contentType","creator","created","identifier","description","keywords","lastPrinted","modified","revision","subject","title","company","presentationFormat","manager","lineCount","parCount","sectionCount","applicationName","comments","editTime","osVersion","wordCount","pageCount"}) public abstract class OfficeInfo { private String category; private String contentStatus; private String contentType; private String creator; private Date created; private String identifier; private String description; private String keywords; private Date lastPrinted; private Date modified; private String revision; private String subject; private String title; private String company; private String presentationFormat; private String manager; private int lineCount; private int parCount; private int sectionCount; private String applicationName; private String comments; private long editTime; private int osVersion; private int wordCount; private int pageCount; public void addProperties(POIXMLProperties properties) { this.setCategory(properties.getCoreProperties().getCategory()); this.setContentStatus(properties.getCoreProperties().getContentStatus()); this.setContentType(properties.getCoreProperties().getContentType()); this.setCreated(properties.getCoreProperties().getCreated()); this.setCreator(properties.getCoreProperties().getCreator()); this.setDescription(properties.getCoreProperties().getDescription()); this.setIdentifier(properties.getCoreProperties().getIdentifier()); this.setKeywords(properties.getCoreProperties().getKeywords()); this.setLastPrinted(properties.getCoreProperties().getLastPrinted()); this.setModified(properties.getCoreProperties().getModified()); this.setRevision(properties.getCoreProperties().getRevision()); this.setSubject(properties.getCoreProperties().getSubject()); this.setTitle(properties.getCoreProperties().getTitle()); } public void addDocumentSummaryInformation(DocumentSummaryInformation dsi){ this.setCategory(dsi.getCategory()); this.setCompany(dsi.getCompany()); this.setManager(dsi.getManager()); this.setLineCount(dsi.getLineCount()); this.setParCount(dsi.getParCount()); this.setSectionCount(dsi.getSectionCount()); } public void addSummaryInformation(SummaryInformation summaryInformation) { this.setApplicationName(summaryInformation.getApplicationName()); this.setCreator(summaryInformation.getAuthor()); this.setComments(summaryInformation.getComments()); this.setCreated(summaryInformation.getCreateDateTime()); this.setEditTime(summaryInformation.getEditTime()); this.setKeywords(summaryInformation.getKeywords()); this.setLastPrinted(summaryInformation.getLastPrinted()); this.setOsVersion(summaryInformation.getOSVersion()); this.setPageCount(summaryInformation.getPageCount()); this.setSectionCount(summaryInformation.getSectionCount()); this.setWordCount(summaryInformation.getWordCount()); this.setRevision(summaryInformation.getRevNumber()); this.setSubject(summaryInformation.getSubject()); this.setTitle(summaryInformation.getTitle()); } }
/* * Copyright (C) 2014 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. */ package com.example.android.wearable.gridviewpager.fragments; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.android.wearable.gridviewpager.R; import com.example.android.wearable.gridviewpager.user.Contact; import com.example.android.wearable.gridviewpager.user.UserSettings; public class BuzzFragment extends Fragment { private Contact contact; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { int contactNumber = this.getArguments().getInt("contact_number"); contact = UserSettings.getInstance(getActivity()).getContacList().get(contactNumber); return inflater.inflate(R.layout.fragment_buzz, container, false); } @Override public void onViewCreated(View v, Bundle savedInstanceState) { super.onViewCreated(v, savedInstanceState); ((ImageView) getView().findViewById(R.id.buzz_button)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (contact.isAvailable()) Toast.makeText(getActivity(), "Buzz sent", Toast.LENGTH_SHORT).show(); else Toast.makeText(getActivity(), contact.getName()+" is busy", Toast.LENGTH_SHORT).show();} }); } }
package com.tencent.tencentmap.mapsdk.a; import org.apache.http.client.HttpRequestRetryHandler; class dq$a$1 implements HttpRequestRetryHandler { dq$a$1() { } }
package com.tibco.as.io.cli; import java.util.Collection; import java.util.Collections; import java.util.logging.Level; import java.util.logging.Logger; import com.beust.jcommander.Parameter; import com.tibco.as.io.BrowseConfig; import com.tibco.as.io.IChannel; import com.tibco.as.io.IDestination; import com.tibco.as.io.ITransfer; import com.tibco.as.io.cli.converters.BrowserDistributionScopeConverter; import com.tibco.as.io.cli.converters.BrowserTimeScopeConverter; import com.tibco.as.io.cli.converters.BrowserTypeConverter; import com.tibco.as.space.ASException; import com.tibco.as.space.browser.BrowserDef.BrowserType; import com.tibco.as.space.browser.BrowserDef.DistributionScope; import com.tibco.as.space.browser.BrowserDef.TimeScope; import com.tibco.as.util.log.LogFactory; public abstract class AbstractSpaceExportCommand extends AbstractExportCommand { private Logger log = LogFactory.getLog(AbstractSpaceExportCommand.class); @Parameter(names = "-browser_type", description = "Browser type", converter = BrowserTypeConverter.class, validateWith = BrowserTypeConverter.class) private BrowserType browserType; @Parameter(names = "-time_scope", description = "Browser time scope", converter = BrowserTimeScopeConverter.class, validateWith = BrowserTimeScopeConverter.class) private TimeScope timeScope; @Parameter(names = "-distribution_scope", description = "Browser distribution scope", converter = BrowserDistributionScopeConverter.class, validateWith = BrowserDistributionScopeConverter.class) private DistributionScope distributionScope; @Parameter(names = "-timeout", description = "Browser timeout") private Long timeout; @Parameter(names = "-prefetch", description = "Browser prefetch") private Long prefetch; @Parameter(names = "-query_limit", description = "Browser query limit") private Long queryLimit; @Parameter(names = "-filter", description = "Browser filter") private String filter; @Override protected Collection<String> getUserSpaceNames(IChannel channel) { try { return channel.getMetaspace().getUserSpaceNames(); } catch (ASException e) { log.log(Level.SEVERE, "Could not retrieve user space names", e); } return Collections.emptyList(); } @Override protected ITransfer getTransfer(IDestination destination) { BrowseConfig config = destination.getBrowseConfig(); if (browserType != null) { config.setBrowserType(browserType); } if (timeScope != null) { config.setTimeScope(timeScope); } if (distributionScope != null) { config.setDistributionScope(distributionScope); } if (timeout != null) { config.setTimeout(timeout); } if (prefetch != null) { config.setPrefetch(prefetch); } if (queryLimit != null) { config.setQueryLimit(queryLimit); } if (filter != null) { config.setFilter(filter); } return destination.getExport(); } }
package chatroom.serializer; import chatroom.model.message.*; import java.io.*; import java.util.HashMap; public class LoginResponseSerializer extends MessageSerializer { LoginResponsesDictionary responseDict = new LoginResponsesDictionary(); @Override public void serialize(OutputStream out, Message m) throws IOException { DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(out)); dataOut.writeByte(dict.getByte(MessageType.LOGINRESPONSEMSG)); dataOut.writeByte(responseDict.getByte(((LoginResponseMessage) m).getResponse())); dataOut.flush(); } @Override public Message deserialize(InputStream in) throws IOException { DataInputStream dataIn = new DataInputStream(new BufferedInputStream(in)); return new LoginResponseMessage(responseDict.getType(dataIn.readByte())); } }