text
stringlengths 10
2.72M
|
|---|
package rouchuan.viewpagerlayoutmanager.circle;
import com.leochuan.CircleLayoutManager;
import rouchuan.viewpagerlayoutmanager.BaseActivity;
/**
* Created by Dajavu on 25/10/2017.
*/
public class CircleLayoutActivity extends BaseActivity<CircleLayoutManager, CirclePopUpWindow> {
@Override
protected CircleLayoutManager createLayoutManager() {
return new CircleLayoutManager(this);
}
@Override
protected CirclePopUpWindow createSettingPopUpWindow() {
return new CirclePopUpWindow(this, getViewPagerLayoutManager(), getRecyclerView());
}
}
|
package app.controlador;
//import app.entidad.Producto;
import app.entidad.Prueba;
import app.entidad.Personeros;
import app.entidad.partido;
import app.servicio.appServicio;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Carlos J
*/
@WebServlet(urlPatterns = {"/ControladorEL"})
public class ControladorEL extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String operacion = request.getParameter("operacion");
appServicio servicio = new appServicio();
if (operacion.equals("Menu")){//enviar al formulario de menu
response.sendRedirect("principal.jsp");
}
if (operacion.equals("Partido")){//enviar al formulario de menu
response.sendRedirect("formIngresarPartido.jsp");
}
if (operacion.equals("Cancelar")){//vuelve al principal
response.sendRedirect("principal.jsp");
}
if (operacion.equals("VotosTotales")){//enviar al formulario de menu
response.sendRedirect("formVotosTotales.jsp");
}
if (operacion.equals("Personeros")){//enviar al formulario de menu
response.sendRedirect("formRegistrarPersoneros.jsp");
}
if (operacion.equals("Registrar")) {//ejemplo de ingreso
try {
String nombre=request.getParameter("txtNombre");
String descripcion=request.getParameter("txtDescripcion");
Prueba prueba = new Prueba(nombre, descripcion);
request.setAttribute("producto", prueba);
servicio.registrarProducto(prueba);
} catch (Exception e) {
request.setAttribute("error", e.getMessage());
}
RequestDispatcher rd = request.getRequestDispatcher("principal.jsp");
rd.forward(request, response);
}
//************************************************************
//*************SECCION PERSONEROS***************************
if (operacion.equals("RegistrarPersonero")) {//Registrar Personero
try {
String departamento=request.getParameter("txtDepartamento");
String provincia=request.getParameter("txtProvincia");
String distrito=request.getParameter("txtDistrito");
String orgPolitica=request.getParameter("txtOrgPolitica");
String dniLT=request.getParameter("txtdniLT");
String apPaternoLT=request.getParameter("txtapellidopLT");
String apMaternoLT=request.getParameter("txtapellidomLT");
String nombresLT=request.getParameter("txtnombresLT");
String sexoLT=request.getParameter("txtsexoLT");
String fechaLT=request.getParameter("txtfechaLT");
String passLT=request.getParameter("txtpassLT");
String dniLA=request.getParameter("txtdniLA");
String apPaternoLA=request.getParameter("txtapellidopLA");
String apMaternoLA=request.getParameter("txtapellidomLA");
String nombresLA=request.getParameter("txtnombresLA");
String sexoLA=request.getParameter("txtsexoLA");
String fechaLA=request.getParameter("txtfechaLA");
String passLA=request.getParameter("txtpassLA");
String dniTT=request.getParameter("txtdniTT");
String apPaternoTT=request.getParameter("txtapellidopTT");
String apMaternoTT=request.getParameter("txtapellidomTT");
String nombresTT=request.getParameter("txtnombresTT");
String sexoTT=request.getParameter("txtsexoTT");
String fechaTT=request.getParameter("txtfechaTT");
String passTT=request.getParameter("txtpassTT");
Personeros personero = new Personeros(departamento,provincia,distrito,orgPolitica,dniLT,apPaternoLT,apMaternoLT,nombresLT,sexoLT,fechaLT,passLT,dniLA,apPaternoLA,apMaternoLA,nombresLA,sexoLA,fechaLA,passLA,dniTT,apPaternoTT,apMaternoTT,nombresTT,sexoTT,fechaTT,passTT);
request.setAttribute("personero", personero);
servicio.registrarPersoneros(personero);
} catch (Exception e) {
request.setAttribute("error", e.getMessage());
}
RequestDispatcher rd = request.getRequestDispatcher("Respuesta.jsp");
rd.forward(request, response);
}
// exportar a documento
if (operacion.equals("ExportarDoc")){
response.sendRedirect("Respuesta.jsp");
}
//*******************************************************
if (operacion.equals("ListarPersoneros")) {//Listar Personeros
try {
ArrayList<Personeros> personeros = servicio.listarPersoneros();
request.setAttribute("personeros", personeros);
} catch (Exception e) {
request.setAttribute("error", e.getMessage());
}
RequestDispatcher rd = request.getRequestDispatcher("ListarPersoneros.jsp");
rd.forward(request, response);
}
//*******************************EXPORTAR A EXCEL**************************+
if (operacion.equals("ExportarExcel")) {//Listar Personeros
try {
ArrayList<Personeros> personeros = servicio.listarPersoneros();
request.setAttribute("personeros", personeros);
} catch (Exception e) {
request.setAttribute("error", e.getMessage());
}
RequestDispatcher rd = request.getRequestDispatcher("PersonerosEXcel.jsp");
rd.forward(request, response);
}
//********************SECCION PARTIDOS**************************
if (operacion.equals("GuardarPartido")) {//Registrar Personero
try {
String nombre=request.getParameter("txtNombreP");
String ubicacion=request.getParameter("txtUbicacion");
String candidato=request.getParameter("txtCandidato");
partido partidos = new partido(nombre,ubicacion,candidato);
request.setAttribute("partidos", partidos);
servicio.GuardarPartidos(partidos);
} catch (Exception e) {
request.setAttribute("error", e.getMessage());
}
RequestDispatcher rd = request.getRequestDispatcher("Confirmacion.jsp");
rd.forward(request, response);
}
if (operacion.equals("ListarPartidos")) {//Listar Personeros
try {
ArrayList<partido> partidos = servicio.listarPartidos();
request.setAttribute("partidos", partidos);
} catch (Exception e) {
request.setAttribute("error", e.getMessage());
}
RequestDispatcher rd = request.getRequestDispatcher("ListarPartidos.jsp");
rd.forward(request, response);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
package BLL;
import DAL.BookInfo;
import DAL.BorrowerInfo;
import DAL.BorrowingInfo;
import java.util.ArrayList;
import java.util.Date;
public class ReturnBookController {
private ArrayList<BorrowingInfo> borrowing_list = new ArrayList<>();
private BorrowerInfo borrower = new BorrowerInfo();
public BorrowerInfo getBorrower() {
return borrower;
}
/**
* Get information of all borrowing that match keyword on a specific catalogue or all catalogues to borrowing_list
*
* @param keyword a string that input to look up data
* @param category a string that specifies catalogue on where to look up, can be "Borrowing Card" or "Copy number"
*/
public ArrayList<BorrowingInfo> getBorrowingInfo(String keyword, String category) {
borrowing_list.clear();
ArrayList<BorrowingInfo> lists;
lists = BorrowingInfo.getBorrowingInfo(keyword, category);
if (lists != null) {
if (!lists.isEmpty()) {
for (BorrowingInfo one : lists) {
if (one.getDueDate().after(new Date()) && !one.getDueDate().before(new Date())) {
if (one.getStatus().equals("Taken")){
borrowing_list.add(one);
}
}
}
lists.clear();
if (borrowing_list.isEmpty())
return null;
return borrowing_list;
}
}
return null;
}
/**
* Update returned book
*
* @param info
* @return true of success, false otherwise
*/
private boolean updateBookInfo(BorrowingInfo info) {
int copyNumber = info.getCopyNumber();
String bookNumber = info.getBookNumber();
BookInfo book = new BookInfo();
ArrayList<BookInfo> lists = BookInfo.getBookInfo(bookNumber, "bookNumber");
if (lists != null) {
for (BookInfo element : lists) {
if (element.getSequenceNumber() == copyNumber) {
book = element;
break;
}
}
book.setStatus("Available");
return book.updateQuery();
} else {
return false;
}
}
private boolean updateBorrowingInfo(BorrowingInfo info) {
info.setStatus("Returned");
return info.updateQuery();
}
public void setBorrower(BorrowingInfo info) {
int cardNumber = info.getCardNumber();
borrower = BorrowerInfo.getBorrower(Integer.toString(cardNumber), "cardID");
}
private boolean updateBorrowerStatus() {
if (!borrower.getBorrowerStatus()) {
borrower.setBorrowerStatus(true);
}
return borrower.updateQuery();
}
/**
* update single borrowing info
* @param info info of one borrowing
* @return true if update success, false otherwise
*/
public boolean update(BorrowingInfo info) {
if (info == null)
return false;
setBorrower(info);
if (!updateBorrowingInfo(info) || !updateBookInfo(info)) {
return false;
} else {
if (!borrower.getBorrowerStatus()) {
return updateBorrowerStatus();
}
}
return true;
}
/**
* get book from one borrowing info
* @param info info of one borrowing
* @return a bookInfo if found, null otherwise
*/
public BookInfo getBook(BorrowingInfo info){
ArrayList<BookInfo> bookInfos = BookInfo.getBookInfo(info.getBookNumber(), "bookNumber");
if (bookInfos != null){
if (!bookInfos.isEmpty()){
for (BookInfo one : bookInfos){
if (one.getSequenceNumber() == info.getCopyNumber())
return one;
}
}
}
return null;
}
}
|
/*
* Copyright 2019 iserge.
*
* 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.cleanlogic.rsc4j.format.primitives;
import com.google.gson.annotations.Expose;
import org.cleanlogic.rsc4j.format.enums.PrimitiveType;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
/**
* @author Serge Silaev aka iSergio <s.serge.b@gmail.com>
*/
public class SignPrimitive extends Primitive {
private int size;
private int ver;
private int hor;
private List<SignMask> masks = new ArrayList<>();
private int length;
public SignPrimitive(int incode) {
super(PrimitiveType.SIGN, null, incode);
}
@Override
public int getLength() {
return this.length;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int getVer() {
return ver;
}
public void setVer(int ver) {
this.ver = ver;
}
public int getHor() {
return hor;
}
public void setHor(int hor) {
this.hor = hor;
}
public List<SignMask> getMasks() {
return masks;
}
public void setMasks(List<SignMask> masks) {
this.masks = masks;
}
// @Override
// public void setLength(int length) {
// super.setLength(length);
// }
@Override
public SignPrimitive read(ByteBuffer buffer, boolean strict) {
// Buffer position before begin read
int pos = buffer.position();
this.length = buffer.getInt();
int count = buffer.getInt();
size = buffer.getInt();
ver = buffer.getInt();
hor = buffer.getInt();
for (int i = 0; i < count; i++) {
long color = buffer.getInt() & 0xFFFFFFFFL;
byte[] bits = new byte[128];
buffer.get(bits);
SignMask mask = new SignMask();
mask.setColor(color);
mask.setBits(bits);
masks.add(mask);
}
int length = buffer.position() - pos;
if (length != this.length) {
System.err.println(String.format("%s[%d]: something wrong with read primitive. Aspect/Actual: %d/%d", PrimitiveType.SIGN, incode, this.length, length));
}
return this;
}
}
|
package com.sjain.couponduniatask;
import android.app.Application;
import android.content.Context;
import com.sjain.couponduniatask.network.RestClient;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
/**
* Created by sjain on 31/10/17.
*/
public class MyApp extends Application {
public static String BASEURL = "http://www.coupondunia.in/";
//ApplicationContext
private static Context mContext;
//Restclient declartions
private static RestClient restClient;
private static OkHttpClient.Builder okHttpClient;
public static RestClient getRestClient(Context context) {
mContext = context.getApplicationContext();
if (restClient == null) {
restClient = new RestClient(mContext);
}
return restClient;
}
public static OkHttpClient getOkHttpClient() {
if (okHttpClient == null) {
okHttpClient = new OkHttpClient.Builder();
okHttpClient.connectTimeout(60, TimeUnit.SECONDS);
HttpLoggingInterceptor logger = new HttpLoggingInterceptor();
logger.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpClient.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder().addHeader("user-agent", "Mozilla/5.0 (Linux; Android 4.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Mobile Safari/537.36");
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
if (logger != null) {
okHttpClient.interceptors().add(logger);
}
}
return okHttpClient.build();
}
@Override
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
}
}
|
package queue.entity;
import java.util.*;
public class Queue {
private LinkedList<String> list;
private int currentIndex;
public Queue(LinkedList<String> list, int currentIndex) {
super();
this.list = list;
this.currentIndex = -1;
}
public Queue() {
list=new LinkedList<>();
this.currentIndex=-1;
}
/**
* @return the list
*/
public LinkedList<String> getList() {
return list;
}
/**
* @param list the list to set
*/
public void setList(LinkedList<String> list) {
this.list = list;
}
/**
* @return the currentIndex
*/
public int getCurrentIndex() {
return currentIndex;
}
/**
* @param currentIndex the currentIndex to set
*/
public void setCurrentIndex(int currentIndex) {
this.currentIndex = currentIndex;
}
}
|
package com.devinchen.library.common.consts;
/**
* CommonLibraryDemo
* com.devinchen.library.common.consts
* Created by Devin Chen on 2017/5/15 22:54.
* explain:本地存取的key
*/
public interface IoKeys {
}
|
package com.tencent.mm.plugin.game.ui;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.tencent.mm.bp.a;
import com.tencent.mm.plugin.game.d.ac;
import com.tencent.mm.plugin.game.e.c;
import com.tencent.mm.plugin.game.f;
import com.tencent.mm.plugin.game.f$c;
import com.tencent.mm.plugin.game.model.an;
import com.tencent.mm.plugin.game.model.e;
import com.tencent.mm.sdk.platformtools.bi;
public class GameFeedImageTextView extends LinearLayout implements OnClickListener {
private int hmV = 0;
private e jUA;
private GameFeedTitleDescView jXU;
private GameRoundImageView jXY;
private LinearLayout jYc;
private GameRoundImageView jYd;
private GameRoundImageView jYe;
private GameRoundImageView jYf;
private TextView jYg;
private GameFeedSubscriptView jYh;
private int jYi = 0;
private int jYj;
public GameFeedImageTextView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
protected void onFinishInflate() {
super.onFinishInflate();
this.jXU = (GameFeedTitleDescView) findViewById(f.e.game_feed_title_desc);
this.jXY = (GameRoundImageView) findViewById(f.e.big_image);
this.jYc = (LinearLayout) findViewById(f.e.small_image_layout);
this.jYd = (GameRoundImageView) findViewById(f.e.first_image);
this.jYe = (GameRoundImageView) findViewById(f.e.second_image);
this.jYf = (GameRoundImageView) findViewById(f.e.third_image);
this.jYg = (TextView) findViewById(f.e.more_image_text);
this.jYh = (GameFeedSubscriptView) findViewById(f.e.subscript);
setOnClickListener(this);
this.hmV = (c.getScreenWidth(getContext()) - getPaddingLeft()) - getPaddingRight();
this.jYi = (this.hmV - (a.fromDPToPix(getContext(), 10) * 2)) / 3;
this.jYj = a.fromDPToPix(getContext(), 105);
if (this.jYi < this.jYj) {
this.jYj = this.jYi;
}
LayoutParams layoutParams = this.jYd.getLayoutParams();
layoutParams.width = this.jYj;
layoutParams.height = this.jYj;
this.jYd.setLayoutParams(layoutParams);
this.jYe.setLayoutParams(layoutParams);
this.jYf.setLayoutParams(layoutParams);
}
public void setData(e eVar) {
if (eVar == null || eVar.jLz == null || eVar.jLz.jQr == null) {
setVisibility(8);
return;
}
this.jUA = eVar;
ac acVar = eVar.jLz;
setVisibility(0);
this.jXU.a(acVar.jQr.bHD, acVar.jQr.jSA, null);
if (bi.cX(acVar.jQr.jSB)) {
this.jXY.setVisibility(8);
this.jYc.setVisibility(8);
} else {
int size = acVar.jQr.jSB.size();
if (size == 1) {
this.jYc.setVisibility(8);
this.jXY.setVisibility(0);
com.tencent.mm.plugin.game.e.e.aVj().a(this.jXY, (String) acVar.jQr.jSB.get(0), getResources().getDimensionPixelSize(f$c.GameImageTextWidth), getResources().getDimensionPixelSize(f$c.GameImageTextHeight), (c.getScreenWidth(getContext()) - getPaddingLeft()) - getPaddingRight());
} else {
this.jXY.setVisibility(8);
this.jYc.setVisibility(0);
this.jYg.setVisibility(8);
com.tencent.mm.plugin.game.e.e.a.a aVar = new com.tencent.mm.plugin.game.e.e.a.a();
aVar.kdA = true;
com.tencent.mm.plugin.game.e.e.a aVk = aVar.aVk();
com.tencent.mm.plugin.game.e.e.aVj().a(this.jYd, (String) acVar.jQr.jSB.get(0), aVk);
com.tencent.mm.plugin.game.e.e.aVj().a(this.jYe, (String) acVar.jQr.jSB.get(1), aVk);
if (size > 2) {
com.tencent.mm.plugin.game.e.e.aVj().a(this.jYf, (String) acVar.jQr.jSB.get(2), aVk);
this.jYf.setVisibility(0);
if (size > 3) {
this.jYg.setVisibility(0);
this.jYg.setText(String.format("共%d张", new Object[]{Integer.valueOf(size)}));
}
} else {
this.jYf.setVisibility(4);
}
}
}
this.jYh.setData(acVar);
if (!this.jUA.jLB) {
an.a(getContext(), 10, 1024, this.jUA.position, this.jUA.jLz.jQb, GameIndexListView.getSourceScene(), an.Dx(this.jUA.jLz.jPA));
this.jUA.jLB = true;
}
}
public void onClick(View view) {
if (this.jUA != null && this.jUA.jLz != null && !bi.oW(this.jUA.jLz.jOU)) {
an.a(getContext(), 10, 1024, this.jUA.position, c.an(getContext(), this.jUA.jLz.jOU), this.jUA.jLz.jQb, GameIndexListView.getSourceScene(), an.Q(this.jUA.jLz.jPA, "clickType", "card"));
}
}
}
|
package com.isen.regardecommeilfaitbeau.api.conversion;
import android.os.Build;
import androidx.annotation.RequiresApi;
import com.isen.regardecommeilfaitbeau.api.meteo.Alert;
import com.isen.regardecommeilfaitbeau.typeData.Time;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.ArrayList;
public class ConvertionAlerts {
private String timeZone;
private JSONArray alertsJSON;
private ArrayList<Alert> alerts;
private boolean isMake;
@RequiresApi(api = Build.VERSION_CODES.O)
public ConvertionAlerts(JSONArray alertsJSON, Time time) throws JSONException {
this.alertsJSON = alertsJSON;
this.timeZone = time.getZoneIdS();
makeObject();
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void makeObject() throws JSONException {
makeArray();
isMake = true;
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void makeArray() throws JSONException {
alerts = new ArrayList<>();
for (int i = 0; i < alertsJSON.length(); i++){
Alert alert = new Alert(alertsJSON.getJSONObject(i), timeZone);
alerts.add(alert);
}
}
public ArrayList<Alert> getAlerts() {
return alerts;
}
public JSONArray getAlertsJSON() {
return alertsJSON;
}
public boolean isMake() {
return isMake;
}
}
|
package server.rest.controllers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import server.model.Contractor;
import server.rest.responses.ContractorsResponse;
import server.rest.responses.Response;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
class ContractorsControllerTest {
ContractorsController contractorController;
@BeforeEach
public void initController() {
contractorController = new ContractorsController();
}
@Test()
public void contractorsTest() {
ArrayList<Contractor> contractors = null;
try {
contractors = contractorController.getContractors();
} catch (SQLException e) {
fail(e.getMessage());
}
assertFalse(contractors.isEmpty());
}
@Test
public void addContractorsTest() {
List<Contractor> contractors = new ArrayList<Contractor>();
try {
contractors = contractorController.addContractor("Test first name" , "testSurname", "agency source", "active");
} catch (SQLException e) {
fail(e.getMessage());
}
assertFalse(contractors.isEmpty());
}
@Test
public void editContractorsTest() {
final int FIRST = 0;
Contractor contractor = null;
try {
contractor = contractorController.getContractors().get(FIRST);
} catch (SQLException e) {
fail(e.getMessage());
}
/*
contractor.setAgencySource("Test New Agency Source");
Response response = contractorController.editContractor(contractor.getId(), contractor.getFirstName(), contractor.getLastName(), contractor.getAgencySource(), contractor.getStatus());
assertFalse(response.isError());
*/
}
}
|
package lab_3.pkg2;
import java.util.Scanner;
/**
*
* @author sameeh boshra
*/
public class Lab_32 {
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
Lion l = new Lion();
String eat=input.next();
l.setEat(eat);
l.print();
}
}
|
package com.xhs.property.controller;
import com.xhs.property.jwt.JwtTokenUtils;
import com.xhs.property.pojo.ResultEntity;
import com.xhs.property.pojo.User;
import com.xhs.property.service.impl.UserServiceImpl;
import com.xhs.property.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping(value = "/user")
public class UserController {
@Autowired
UserServiceImpl userService;
@Autowired
JwtTokenUtils jwtTokenUtils;
@RequestMapping(value = "/register", method = RequestMethod.POST)
@ResponseBody
public ResultEntity register(@RequestBody User user) {
if (StringUtils.isEmpty(user.getName())) {
return ResultEntity.getErrorResult("用户姓名不能为空");
}
User userByPhone = userService.selectByPhone(user.getPhoneNumber());
if (userByPhone != null) {
return ResultEntity.getErrorResult("此用户已经存在");
}
boolean isInsert = userService.save(user);
if (isInsert) {
return ResultEntity.getSuccessResult("请求成功");
} else {
return ResultEntity.getErrorResult("插入失败");
}
}
@RequestMapping(value = "/getUser", method = RequestMethod.GET)
@ResponseBody
public ResultEntity getUser(int userId) {
User user = userService.selectById(userId);
if (user == null) {
return ResultEntity.getErrorResult("此用户不存在");
}
return ResultEntity.getSuccessResult(user);
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
@ResponseBody
public ResultEntity login(String phoneNumber, String password) {
User user = userService.selectByPhone(phoneNumber);
if (user == null) {
return ResultEntity.getErrorResult("此用户不存在");
}
if (!user.getPassword().equals(password)) {
return ResultEntity.getErrorResult("密码错误");
}
String token = jwtTokenUtils.createToken(user.getPhoneNumber(), user.getPassword());
return ResultEntity.getSuccessResult(token);
}
@RequestMapping(value = "/refreshToken", method = RequestMethod.GET)
@ResponseBody
public ResultEntity refreshToken(HttpServletRequest request) {
String token = request.getHeader("token");
String refreshToken = jwtTokenUtils.refreshToken(token);
return ResultEntity.getSuccessResult(refreshToken);
}
}
|
/*
* Copyright 2009 Kjetil Valstadsve
*
* 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 vanadis.core.collections;
import java.util.Enumeration;
import java.util.Hashtable;
/**
* An empty hashtable.
*
* @param <K> Type of the keys in this hashtable
* @param <V> Type of the values in this hashtable
*/
@SuppressWarnings({"SynchronizedMethod"}) // Sins of the fathers...
final class EmptyHashtable<K, V> extends Hashtable<K, V> {
private static final long serialVersionUID = 2569554589310719825L;
@Override
public synchronized int size() {
return 0;
}
@Override
public synchronized boolean isEmpty() {
return true;
}
@Override
public synchronized Enumeration<K> keys() {
return new EmptyEnumeration<K>();
}
@Override
public synchronized Enumeration<V> elements() {
return new EmptyEnumeration<V>();
}
@Override
public synchronized V get(Object key) {
return null;
}
@Override
public synchronized V put(K key, V value) {
throw new UnsupportedOperationException();
}
@Override
public synchronized V remove(Object key) {
throw new UnsupportedOperationException();
}
@Override
public synchronized int hashCode() {
return 1;
}
@Override
public synchronized boolean equals(Object obj) {
return obj instanceof EmptyHashtable;
}
@Override
public synchronized String toString() {
return getClass().getName() + "[EMPTY]";
}
}
|
package com.translator.application.test.doubles;
import com.translator.domain.model.numeral.Calculator;
import com.translator.domain.model.credits.Credits;
import com.translator.domain.model.numeral.Cost;
import java.util.ArrayList;
import java.util.List;
public class CalculatorSpy implements Calculator {
private Credits amount;
public List<List<? extends Cost>> romanNumeralAmountCalledWith;
public CalculatorSpy() {
this.romanNumeralAmountCalledWith = new ArrayList<List<? extends Cost>>();
}
public Credits calculate(List<? extends Cost> elements) {
romanNumeralAmountCalledWith.add(elements);
return amount;
}
public void setCreditsAmount(Credits amount) {
this.amount = amount;
}
}
|
package com.tencent.mm.plugin.aa.a.c;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.protocal.c.s;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.vending.c.a;
import com.tencent.mm.vending.g.b;
class f$2 implements a<Void, com.tencent.mm.ab.a.a<s>> {
final /* synthetic */ b eBj;
final /* synthetic */ f eBz;
f$2(f fVar, b bVar) {
this.eBz = fVar;
this.eBj = bVar;
}
public final /* synthetic */ Object call(Object obj) {
com.tencent.mm.ab.a.a aVar = (com.tencent.mm.ab.a.a) obj;
x.i("MicroMsg.PaylistAAInteractor", "on urgeAAPay finish, errType: %s, errCode: %s", new Object[]{Integer.valueOf(aVar.errType), Integer.valueOf(aVar.errCode)});
if (aVar.errType == 0 && aVar.errCode == 0) {
s sVar = (s) aVar.dIv;
x.i("MicroMsg.PaylistAAInteractor", "on urgeAAPay finish, retcode: %s, retmsg: %s", new Object[]{Integer.valueOf(sVar.hUm), sVar.hUn});
if (sVar.hUm == 0) {
x.i("MicroMsg.PaylistAAInteractor", "on urgeAAPay success");
com.tencent.mm.plugin.aa.a.ezo.vl();
this.eBj.v(new Object[]{Boolean.valueOf(true)});
h.mEJ.a(407, 24, 1, false);
} else {
if (sVar.hUm <= 0 || bi.oW(sVar.hUn)) {
this.eBj.ct(Boolean.valueOf(false));
} else {
this.eBj.ct(sVar.hUn);
}
h.mEJ.a(407, 26, 1, false);
}
} else {
this.eBj.ct(Boolean.valueOf(false));
h.mEJ.a(407, 25, 1, false);
}
return uQG;
}
}
|
/*
* 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 escuela.de.natacion;
import BaseDeDatos.ConexionMySQL;
import static BaseDeDatos.ConexionMySQL.Conexion;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
*
* @author Guillermo
*/
public class BuscarPago extends javax.swing.JFrame {
DefaultTableModel modelo;
/**
* Creates new form BuscarPago
*/
public BuscarPago() {
initComponents();
modelo = (DefaultTableModel) tablaBuscarClase.getModel();
modelo.addColumn("IdClase");
modelo.addColumn("Instructor");
modelo.addColumn("Inicio");
modelo.addColumn("Fin");
modelo.addColumn("Cupo");
modelo.addColumn("Cantidad");
}
public void limpiarClase() {
int filas = tablaBuscarClase.getRowCount();
for (int i = 0; filas > i; i++) {
modelo.removeRow(0);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
txtBuscarFolio = new javax.swing.JTextField();
btnBuscarFolio = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
txtHora = new javax.swing.JTextField();
lblHora = new javax.swing.JLabel();
txtFolio = new javax.swing.JTextField();
lblFolio = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
txtCliente = new javax.swing.JTextField();
jScrollPane2 = new javax.swing.JScrollPane();
tablaBuscarClase = new javax.swing.JTable();
jLabel5 = new javax.swing.JLabel();
txtTotal = new javax.swing.JTextField();
btnBuscarFolio.setText("Buscar Folio");
btnBuscarFolio.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBuscarFolioActionPerformed(evt);
}
});
jLabel4.setText("Buscar Folio:");
txtHora.setEditable(false);
txtHora.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
lblHora.setText("Hora:");
txtFolio.setEditable(false);
txtFolio.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblFolio.setText("Folio:");
jLabel3.setText("Cliente:");
txtCliente.setEditable(false);
txtCliente.setEnabled(false);
tablaBuscarClase.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
tablaBuscarClase.getTableHeader().setReorderingAllowed(false);
jScrollPane2.setViewportView(tablaBuscarClase);
jLabel5.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel5.setText("Total Pagado: ");
txtTotal.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N
txtTotal.setForeground(new java.awt.Color(255, 51, 51));
txtTotal.setEnabled(false);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txtBuscarFolio, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(53, 53, 53)
.addComponent(btnBuscarFolio))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txtCliente))
.addGroup(layout.createSequentialGroup()
.addComponent(lblFolio)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txtFolio, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(172, 172, 172)
.addComponent(lblHora)
.addGap(52, 52, 52)
.addComponent(txtHora, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(118, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 462, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txtTotal)
.addGap(28, 28, 28))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(txtBuscarFolio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnBuscarFolio))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblFolio)
.addComponent(txtFolio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblHora)
.addComponent(txtHora, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5)))
.addContainerGap(124, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnBuscarFolioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarFolioActionPerformed
// TODO add your handling code here
int total=0;
limpiarClase();
int contador = 0;
if (!txtBuscarFolio.getText().matches("^\\s*$")) {
String[] datos = new String[6];
try {
ConexionMySQL conexion = new ConexionMySQL();
conexion.MySQLConnection();
Statement st = Conexion.createStatement();
ResultSet rs = st.executeQuery("Select"
+ " pago.folio as fo, "
+ " pago.fecha as f, "
+ " pago.IdCliente as CLi, "
+ " pagodetalle.idclase, "
+ " c.idclase as id,"
+ " c.IdInstructor as inst,"
+ " c.HoraInicio as inicio,"
+ " c.HoraFinal as fin, "
+ " c.Cupo as cup, "
+ " pagodetalle.cantidad as cant"
+ " from pago"
+ " INNER Join pagodetalle ON pagodetalle.folio=pago.folio "
+ " INNER Join clase as c ON pagodetalle.IdClase=c.idclase "
+ " WHERE pagodetalle.folio=" + txtBuscarFolio.getText());
while (rs.next())
{
txtFolio.setText(""+rs.getInt("fo"));
txtHora.setText(rs.getString("f"));
txtCliente.setText(rs.getString("CLi"));
datos[0] = rs.getString("id");
datos[1] = rs.getString("inst");
datos[2] = rs.getString("inicio");
datos[3] = rs.getString("fin");
datos[4] = rs.getString("cup");
datos[5] = rs.getString("cant");
total+=Integer.parseInt(datos[5]);
modelo.addRow(datos);
contador++;
txtFolio.setText(datos[0]);
}
if (contador == 0) {
txtCliente.setText("");
limpiarClase();
}
txtTotal.setText(""+total);
} catch (SQLException ex) {
JOptionPane.showMessageDialog(rootPane, ex);
}
}
}//GEN-LAST:event_btnBuscarFolioActionPerformed
/**
* @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(BuscarPago.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(BuscarPago.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(BuscarPago.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(BuscarPago.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 BuscarPago().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnBuscarFolio;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JLabel lblFolio;
private javax.swing.JLabel lblHora;
private javax.swing.JTable tablaBuscarClase;
private javax.swing.JTextField txtBuscarFolio;
private javax.swing.JTextField txtCliente;
private javax.swing.JTextField txtFolio;
private javax.swing.JTextField txtHora;
private javax.swing.JTextField txtTotal;
// End of variables declaration//GEN-END:variables
}
|
package com.nolansherman.team_manager.repositories;
import java.util.List;
import com.nolansherman.team_manager.domains.Player;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PlayerRepository extends CrudRepository<Player, Long> {
List<Player> findById(long id);
List<Player> findByTeamID(long id);
}
|
/**
* Copyright (c) [2018] [ The Alienchain Developers ]
* Copyright (c) [2016] [ <ether.camp> ]
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.vm.program.invoke;
import java.math.BigInteger;
import java.util.Objects;
import org.ethereum.vm.DataWord;
import org.ethereum.vm.client.BlockStore;
import org.ethereum.vm.client.Repository;
import org.ethereum.vm.util.HexUtil;
public class ProgramInvokeImpl implements ProgramInvoke {
/**
* Transaction environment
*/
private final DataWord address, origin, caller, gasPrice, value;
private final byte[] data;
private final long gas;
/**
* Block environment
*/
private final DataWord prevHash, coinbase, timestamp, number, difficulty, gaslimit;
/**
* Database environment
*/
private final Repository repository;
private final Repository originalRepository;
private final BlockStore blockStore;
private int callDepth;
private boolean isStaticCall;
public ProgramInvokeImpl(DataWord address, DataWord origin, DataWord caller,
long gas, DataWord gasPrice, DataWord value, byte[] data, DataWord prevHash,
DataWord coinbase, DataWord timestamp, DataWord number, DataWord difficulty,
DataWord gasLimit, Repository repository, Repository originalRepository, BlockStore blockStore,
int callDepth, boolean isStaticCall) {
Objects.requireNonNull(address);
Objects.requireNonNull(origin);
Objects.requireNonNull(caller);
Objects.requireNonNull(gasPrice);
Objects.requireNonNull(value);
Objects.requireNonNull(data);
Objects.requireNonNull(prevHash);
Objects.requireNonNull(coinbase);
Objects.requireNonNull(timestamp);
Objects.requireNonNull(number);
Objects.requireNonNull(difficulty);
Objects.requireNonNull(gasLimit);
Objects.requireNonNull(repository);
Objects.requireNonNull(blockStore);
this.address = address;
this.origin = origin;
this.caller = caller;
this.gas = gas;
this.gasPrice = gasPrice;
this.value = value;
this.data = data;
this.prevHash = prevHash;
this.coinbase = coinbase;
this.timestamp = timestamp;
this.number = number;
this.difficulty = difficulty;
this.gaslimit = gasLimit;
this.repository = repository;
this.originalRepository = originalRepository;
this.blockStore = blockStore;
this.callDepth = callDepth;
this.isStaticCall = isStaticCall;
}
@Override
public DataWord getOwnerAddress() {
return address;
}
@Override
public DataWord getOriginAddress() {
return origin;
}
@Override
public DataWord getCallerAddress() {
return caller;
}
@Override
public long getGas() {
return gas;
}
@Override
public DataWord getGasPrice() {
return gasPrice;
}
@Override
public DataWord getValue() {
return value;
}
// open for testing
public byte[] getData() {
return data;
}
@Override
public DataWord getDataValue(DataWord indexData) {
byte[] data = getData();
BigInteger indexBI = indexData.value();
if (indexBI.compareTo(BigInteger.valueOf(data.length)) >= 0) {
return DataWord.ZERO;
}
int idx = indexBI.intValue();
int size = Math.min(data.length - idx, DataWord.SIZE);
byte[] buffer = new byte[DataWord.SIZE];
System.arraycopy(data, idx, buffer, 0, size); // left-aligned
return DataWord.of(buffer);
}
@Override
public DataWord getDataSize() {
byte[] data = getData();
return DataWord.of(data.length);
}
@Override
public byte[] getDataCopy(DataWord offsetData, DataWord lengthData) {
byte[] data = getData();
BigInteger offsetBI = offsetData.value();
BigInteger lengthBI = lengthData.value();
if (offsetBI.compareTo(BigInteger.valueOf(data.length)) >= 0) {
return new byte[0];
}
int offset = offsetBI.intValue();
int size = data.length - offset;
if (lengthBI.compareTo(BigInteger.valueOf(size)) < 0) {
size = lengthBI.intValue();
}
byte[] buffer = new byte[size];
System.arraycopy(data, offset, buffer, 0, size);
return buffer;
}
@Override
public DataWord getPrevHash() {
return prevHash;
}
@Override
public DataWord getCoinbase() {
return coinbase;
}
@Override
public DataWord getTimestamp() {
return timestamp;
}
@Override
public DataWord getNumber() {
return number;
}
@Override
public DataWord getDifficulty() {
return difficulty;
}
@Override
public DataWord getGaslimit() {
return gaslimit;
}
@Override
public Repository getRepository() {
return repository;
}
@Override
public Repository getOriginalRepository() {
return originalRepository;
}
@Override
public BlockStore getBlockStore() {
return blockStore;
}
@Override
public int getCallDepth() {
return this.callDepth;
}
@Override
public boolean isStaticCall() {
return isStaticCall;
}
@Override
public String toString() {
return "ProgramInvokeImpl{" +
"address=" + address +
", origin=" + origin +
", caller=" + caller +
", gas=" + gas +
", gasPrice=" + gasPrice +
", value=" + value +
", data=" + HexUtil.toHexString(data) +
", prevHash=" + prevHash +
", coinbase=" + coinbase +
", timestamp=" + timestamp +
", number=" + number +
", difficulty=" + difficulty +
", gaslimit=" + gaslimit +
", repository=" + repository +
", blockStore=" + blockStore +
", callDepth=" + callDepth +
", isStaticCall=" + isStaticCall +
'}';
}
}
|
package unalcol.types.collection.vector;
import unalcol.types.collection.Iterator;
import java.util.NoSuchElementException;
/**
* <p>Title: </p>
* <p>
* <p>Description: </p>
* <p>
* <p>Copyright: Copyright (c) 2009</p>
* <p>
* <p>Company: Kunsamu</p>
*
* @author Jonatan Gomez Perdomo
* @version 1.0
*/
public class VectorIterator<T> implements Iterator<T> {
protected int pos;
protected ImmutableVector<T> vector;
public VectorIterator(int pos, ImmutableVector<T> vector) {
this.vector = vector;
this.pos = pos;
}
public VectorIterator(VectorLocation<T> location) {
this.vector = location.vector;
this.pos = location.pos;
}
public boolean hasNext() {
return pos < vector.size;
}
public T next() throws NoSuchElementException {
try {
T d = vector.buffer[pos];
pos++;
return d;
} catch (Exception e) {
throw new NoSuchElementException("" + pos);
}
}
}
|
//package designpatterns.examples.strategy;
package com.headfirst.designpatterns.strategy;
public class MuteQuack implements QuackBehavior{
public void quack(){
System.out.println("<Silence>");
}
}
|
package it.unibz.testhunter;
import it.unibz.testhunter.model.TestResultModel;
import java.util.ArrayList;
import java.util.List;
public class AperMetric implements IMetric {
private List<TestResultModel> testSequence;
private List<Float> infoSeq;
private List<Float> timeSeq;
private Float T;
private Float I;
public AperMetric(List<TestResultModel> testSequence) {
this.testSequence = testSequence;
infoSeq = new ArrayList<Float>();
timeSeq = new ArrayList<Float>();
T = null;
I = null;
}
@Override
public float compute() {
infoSeq.add(new Float(0));
timeSeq.add(new Float(0));
float lastInfo = 0;
float lastTime = 0;
float aper = 0;
for (TestResultModel tr : testSequence) {
aper += (0.5*tr.getInfo()+lastInfo)*tr.getTime();
lastInfo += tr.getInfo();
lastTime += tr.getTime();
infoSeq.add(new Float(lastInfo));
timeSeq.add(new Float(lastTime));
}
I = lastInfo;
T = lastTime;
return (float) aper/(I*T);
}
@Override
public String getName() {
return "APER";
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.insat.gl5.crm_pfa.service;
import com.insat.gl5.crm_pfa.model.BackendUser;
import com.insat.gl5.crm_pfa.model.Contact;
import com.insat.gl5.crm_pfa.model.Notification;
import com.insat.gl5.crm_pfa.model.NotificationContact;
import java.util.List;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
/**
*
* @author Mu7ammed 3li -- mohamed.ali.affes@gmail.com --
*/
public class NotificationService extends GenericService{
private static final String SUCCESS = " with success";
/**
* Save new Notification
*
* @param notification
*/
public void saveNotification(Notification notification) throws Exception {
try {
persist(notification);
log.info("Create Notification " + getDisplayText(notification) + SUCCESS);
} catch (Exception ex) {
log.error("Error in Creating Notification "+getDisplayText(notification)+ " : -->", ex);
throw ex;
}
}
/**
* Save new NotificationContact
*
* @param notificationContact
*/
public void saveNotificationContact(NotificationContact notificationContact) throws Exception {
try {
persist(notificationContact);
} catch (Exception ex) {
log.error("Error in Creating NotificationContact : -->", ex);
throw ex;
}
}
/**
* Delete an Notification
*
* @param Notification
*/
public void deleteNotification(Notification notification) throws Exception {
try {
delete(notification);
log.info("Delete Notification " + getDisplayText(notification)+ SUCCESS);
} catch (Exception ex) {
log.error("Error in Deleting Notification "+getDisplayText(notification)+" : -->", ex);
throw ex;
}
}
/**
* Edit an Notification
*
* @param Notification
*/
public void editNotification(Notification notification) throws Exception {
try {
edit(notification);
log.info("Update Notification " + getDisplayText(notification) + SUCCESS);
} catch (Exception ex) {
log.error("Error in Updating Notification "+getDisplayText(notification)+" : -->", ex);
throw ex;
}
}
/**
* Get a list of notifications
*
* @return
*/
public List<Notification> getAllNotificationsByContact(Contact contact) {
TypedQuery query = em.createQuery("SELECT nc.notification FROM NotificationContact nc WHERE nc.contact=?1 AND nc.direction =1 ORDER BY nc.notification.createdOn DESC, nc.notification.readed", Notification.class).setParameter(1, contact);
return query.getResultList();
}
public List<Notification> getUnreadedNotificationsByContact(Contact contact) {
TypedQuery query = em.createQuery("SELECT nc.notification FROM NotificationContact nc WHERE nc.contact=?1 AND nc.notification.readed=false AND nc.direction =1 ORDER BY nc.notification.createdOn DESC", Notification.class).setParameter(1, contact);
return query.getResultList();
}
/**
* Get a list of notifications
*
* @return
*/
public List<Notification> getAllNotificationsByBackendUser(BackendUser backendUser) {
TypedQuery query = em.createQuery("SELECT nc.notification FROM NotificationContact nc WHERE nc.backendUser=?1 AND nc.direction =0 ORDER BY nc.notification.createdOn DESC, nc.notification.readed", Notification.class).setParameter(1, backendUser);
return query.getResultList();
}
public List<Notification> getUnreadedNotificationsByBackendUser(BackendUser backendUser) {
TypedQuery query = em.createQuery("SELECT nc.notification FROM NotificationContact nc WHERE nc.backendUser=?1 AND nc.notification.readed=false AND nc.direction =0 ORDER BY nc.notification.createdOn DESC", Notification.class).setParameter(1, backendUser);
return query.getResultList();
}
private String getDisplayText(Notification notification){
return notification.getType().getDisplayName()+" : "+notification.getContent() ;
}
//
// public int getNotificationsNumberByContact(Contact user){
// Query query = em.createQuery("SELECT COUNT(nc) FROM NotificationContact nc WHERE nc.contact=?1 AND nc.notification.readed=false AND nc.direction =1").setParameter(1, user);
// return query.getResultList().size();
// }
// public int getNotificationsNumberByBackendUser(BackendUser user){
// Query query = em.createQuery("SELECT COUNT(nc) FROM NotificationContact nc WHERE nc.backendUser=?1 AND nc.notification.readed=false AND nc.direction =2").setParameter(1, user);
// return query.getResultList().size();
// }
public Notification getNotificationByOpportunity(Long id){
TypedQuery query = em.createQuery("SELECT n FROM Notification n WHERE n.link=?1", Notification.class).setParameter(1, "/frontoffice/notifications/viewOpportunity?id="+id);
return (Notification) query.getResultList().get(0);
}
}
|
package com.gsonkeno.elasticsearch5_3;
import org.apache.commons.lang.math.RandomUtils;
import org.dom4j.DocumentException;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
/**
* Created by gaosong on 2017-04-05.
*/
public class SearchEngineTest {
public static void main(String[] args) {
SearchEngine engine = new SearchEngine("elasticsearch", "127.0.0.1", 9300);
//engine.createIndex("first",8,0);
System.out.println(engine.deleteIndex("first"));
}
@Test
public void createIndex(){
SearchEngine engine = new SearchEngine("elasticsearch", "127.0.0.1", 9300);
boolean b = engine.createIndex("first", 8, 0);
System.out.println(b);
}
@Test
public void deleteIndex(){
SearchEngine engine = new SearchEngine("elasticsearch", "127.0.0.1", 9300);
boolean b = engine.deleteIndex("first");
System.out.println(b);
}
//创建索引结构
@Test
public void loadSchema() throws IOException, DocumentException {
SearchEngine engine = new SearchEngine("elasticsearch", "127.0.0.1", 9300);
engine.loadSchema("first", "TYPE_NAME", "E:\\ideaProject\\summerProject\\summer\\src\\test\\resources\\bigdata_wifi.xml");
}
@Test
public void addDoc() throws IOException {
SearchEngine engine = new SearchEngine("elasticsearch","127.0.0.1",9300);
Map<String,Object> map = new HashMap<>();
map.put("INFO_ID", RandomUtils.nextLong());
map.put("MAC",425625 );
map.put("JGRQ","17231" );
map.put("DEVICE_ID","shadi7q" );
map.put("DEVICE_NAME","shadi7q");
engine.addDoc("first","TYPE_NAME",map,"INFO_ID");
}
//删除文档
@Test
public void deleteDoc(){
SearchEngine engine = new SearchEngine("elasticsearch","127.0.0.1",9300);
boolean b = engine.deleteDoc("first", "type", "1");
System.out.println(b);
}
//更新文档
@Test
public void updateDoc() throws IOException {
SearchEngine engine = new SearchEngine("elasticsearch","127.0.0.1",9300);
Map<String,Object> updateParams = new HashMap<String, Object>();
updateParams.put("MAC","abc");
boolean b = engine.updateDoc("first","type","1",updateParams);
for (int i =2;i<10;i++){
engine.updateDoc("first","type",""+i,updateParams);
}
System.out.println(b);
}
@Test
public void scrollQuery(){
SearchEngine engine = new SearchEngine("elasticsearch","127.0.0.1",9300);
QueryBuilder termQueryBuilder = termQuery("MAC", "abc");
ScrollRespContainer scrollRespContainer = engine.scrollQuery("first", termQueryBuilder, FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC, 2);
List<Map<String, Object>> next = scrollRespContainer.next();
System.out.println(next);
System.out.println(scrollRespContainer.next());
}
/**多条件查询**/
@Test
public void multiQuery(){
SearchEngine engine = new SearchEngine("elasticsearch","127.0.0.1",9300);
engine.multiQuery();
}
/**批量插入文档**/
@Test
public void bulkAdd() throws IOException {
SearchEngine engine = new SearchEngine("elasticsearch","127.0.0.1",9300);
List<Map<String,Object>> list = new ArrayList<>();
for (int i = 0; i <100 ; i++) {
Map<String,Object> map = new HashMap<>();
map.put("INFO_ID", RandomUtils.nextLong());
map.put("MAC",425625 + i);
map.put("JGRQ","17231" + i);
map.put("DEVICE_ID","shadi7q" + i);
map.put("DEVICE_NAME","shadi7q" + i);
list.add(map);
}
System.out.println(list.get(0).get("INFO_ID"));
System.out.println(list.get(99).get("INFO_ID"));
engine.bulkAddDoc("first","TYPE_NAME",list,"INFO_ID");
}
/**查询条件查询**/
@Test
public void testSearch(){
SearchEngine engine = new SearchEngine("elasticsearch","127.0.0.1",9300);
Query query = new Query(1,10);
query.addOrder("price",SortOrder.ASC);
// query.addRangeQuery("price",10000L,500000L);
// query.addPrefixQuery("color","g");
query.addFuzzyQuery("make","aoyotm",2);
String[] indices = new String[]{"cars"};
String[] types = new String[]{"transactions"};
List<Map<String, Object>> list = engine.searchForDocs(indices, types, query);
System.out.println(list.size());
System.out.println(list);
}
/**查询条件查询,测试string_query**/
@Test
public void testSearchStringQuery(){
SearchEngine engine = new SearchEngine("elasticsearch","127.0.0.1",9300);
Query query = new Query(1,10);
query.addStringQuery(new String[]{"name"},"中国美国", Operator.AND);
String[] indices = new String[]{"test_index"};
String[] types = new String[]{"test_type"};
List<Map<String, Object>> list = engine.searchForDocs(indices, types, query);
System.out.println(list.size());
System.out.println(list);
}
/**查询条件查询,测试wildcard**/
@Test
public void testSearchWildcardQuery(){
SearchEngine engine = new SearchEngine("elasticsearch","127.0.0.1",9300);
Query query = new Query(1,10);
// query.addWildcardQuery("name","中国美国");
String[] indices = new String[]{"test_index"};
String[] types = new String[]{"test_type"};
List<Map<String, Object>> list = engine.searchForDocs(indices, types, query);
System.out.println(list.size());
System.out.println(list);
}
/**测试terms桶聚合**/
@Test
public void testTermsAggregation(){
SearchEngine engine = new SearchEngine("elasticsearch","127.0.0.1",9300);
// engine.getClient().prepareSearch()
// .addAggregation(
// AggregationBuilders.terms("by_country").field("country")
// .subAggregation(AggregationBuilders.dateHistogram("by_year")
// .field("dateOfBirth")
// .dateHistogramInterval(DateHistogramInterval.YEAR)
// .subAggregation(AggregationBuilders.avg("avg_children").field("children"))
// )
// )
// .execute().actionGet();
String[] indices = new String[]{"cars"};
String[] types = new String[]{"transactions"};
Query query = new Query();
query.addRangeFromQuery("price",15000,false);
query.addAggregation(AggregationBuilders.terms("popular_color").field("color"));
SearchResponse searchResponse = engine.searchForStatistics(indices, types, query);
Map<Object, Long> statistics = ResponseHandler.responseToTermsStatistics(searchResponse, "popular_color");
System.out.println(statistics);
}
/**测试高亮字段**/
@Test
public void testHighlighting(){
SearchEngine engine = new SearchEngine("elasticsearch","127.0.0.1",9300);
String[] indices = new String[]{"test_index"};
String[] types = new String[]{"test_type"};
Query query = new Query(1,100);
query.addTermsQuery("name","中国");
query.addHighLighting("name");
List<Map<String, Object>> list = engine.searchForDocs(indices, types, query);
System.out.println(list);
}
}
|
package javaStudy.thread;
// 2. Runnable Interface를 구현해서 thread 만드는 방법
class Animal {
}
class Lion extends Animal implements Runnable {
@Override
public void run() { // thread의 작업 내용
Thread t = Thread.currentThread(); // 현재 이 문장을 실행하고 있는 thread를 알아내는 메소드
System.out.println("thread is running..." + t.getName());
}
}
public class LionTest {
public static void main(String[] args) {
Lion l1 = new Lion(); // Thread아님. Runnable 객체(run()메소드를 가지고 있는 객체)
Thread t1 = new Thread(new Tiger());
t1.start();
Lion l2 = new Lion(); // Thread아님. Runnable 객체(run()메소드를 가지고 있는 객체)
Thread t2 = new Thread(l2);
t2.start();
Lion l3 = new Lion(); // Thread아님. Runnable 객체(run()메소드를 가지고 있는 객체)
Thread t3 = new Thread(l3);
t3.start();
}
}
|
package com.neu.pojo;
import java.sql.Blob;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.OneToMany;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
@Entity
@Table
@PrimaryKeyJoinColumn(name="personID")
public class Jobseeker extends Person {
//@Column(name="currentPosition")
@Column(name="monthsOfExperience")
private String monthsOfExperience;
@Column(name="currentCompany")
private String currentCompany;
@Column(name="education")
private String education;
//private String resume;
@Column(name="currentDesignation")
private String currentDesignation;
// Attributes for file upload
/*@Column(name="name")
private String name;
@Column(name="description")
private String description;*/
@Column(name="filename")
private String filename;
@Column(name="content")
@Lob
private Blob content;
@Column(name="fileType")
private String fileType;
@Column
private String skills;
public String getSkills() {
return skills;
}
public void setSkills(String skills) {
this.skills = skills;
}
//Relationship and mapping with applied jobs
@OneToMany(mappedBy="jobseeker")
private Set<AppliedJobs> appliedJobs = new HashSet<AppliedJobs>();
public Jobseeker(){}
//Check*** if any parameters should be passed in this constructor
public Jobseeker(String monthsOfExperience,String currentCompany, String currentDesignation){
this.monthsOfExperience = monthsOfExperience;
this.currentCompany = currentCompany;
this.currentDesignation = currentDesignation;
}
public String getMonthsOfExperience() {
return monthsOfExperience;
}
public void setMonthsOfExperience(String monthsOfExperience) {
this.monthsOfExperience = monthsOfExperience;
}
public String getCurrentCompany() {
return currentCompany;
}
public void setCurrentCompany(String currentCompany) {
this.currentCompany = currentCompany;
}
public String getEducation() {
return education;
}
public void setEducation(String education) {
this.education = education;
}
/*
public String getResume() {
return resume;
}
public void setResume(String resume) {
this.resume = resume;
}
*/
public String getCurrentDesignation() {
return currentDesignation;
}
public void setCurrentDesignation(String currentDesignation) {
this.currentDesignation = currentDesignation;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public Blob getContent() {
return content;
}
public void setContent(Blob content) {
this.content = content;
}
public String getContentType() {
return fileType;
}
public void setContentType(String contentType) {
this.fileType = contentType;
}
public Set<AppliedJobs> getAppliedJobs() {
return appliedJobs;
}
public void setAppliedJobs(Set<AppliedJobs> appliedJobs) {
this.appliedJobs = appliedJobs;
}
}
|
package com.jk.jkproject.ui.dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import com.jk.jkproject.R;
import com.jk.jkproject.ui.entity.UpdateInfo;
import com.jk.jkproject.utils.ScreenUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
/**
* @author Zick
* @params
* @date 2020/7/27 1:41 PM
* @desc 版本更新弹窗
*/
public class DialogUpdateVersion extends BaseDialog {
private final Context mContext;
@BindView(R.id.tv_version)
TextView tvVersion;
@BindView(R.id.tv_1)
TextView tv1;
private UpdateInfo.DataBean data;
private Unbinder unbinder;
private DialogReturnListener listener;
public DialogUpdateVersion(Context mContext, UpdateInfo.DataBean data) {
super(mContext);
this.mContext = mContext;
this.data = data;
}
private void init() {
if (data != null) {
tvVersion.setText(data.getVersions());
tv1.setText(data.getContent());
}
}
protected void create(Bundle paramBundle) {
setContentView(R.layout.dialog_update_version);
unbinder = ButterKnife.bind(this);
setCanceledOnTouchOutside(false);
mWidthScale = 0.95F;
mDimAmount = 0.6F;
gravity = Gravity.CENTER;
}
protected void initView() {
init();
}
@Override
protected void onStart() {
super.onStart();
getWindow().setLayout(ScreenUtils.dp2px(getContext(), 315), ScreenUtils.dp2px(getContext(), 372));
}
public void setDialogClickListener(DialogReturnListener listener) {
this.listener = listener;
}
@OnClick({R.id.tv_btn_1, R.id.tv_btn_2})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.tv_btn_1:
dismiss();
break;
case R.id.tv_btn_2:
if (listener != null) {
listener.onDialogReturnClick(1);
dismiss();
}
break;
}
}
public static interface DialogReturnListener {
void onDialogReturnClick(int type);
}
}
|
package com.halilayyildiz.game.mancala;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MancalaPlayerTest
{
@Autowired
private MancalaPlayer mancalaPlayer;
@Autowired
private MancalaGame mancalaGame;
@Before
public void setUp()
{
}
@Test
public void whenMancalaPlayer()
{
assertNotNull(mancalaGame);
assertNotNull(mancalaPlayer);
assertNotNull(mancalaPlayer.getId());
}
@Test
public void whenMancalaPlayerJoinedGame()
{
assertNotNull(mancalaGame);
assertNotNull(mancalaPlayer);
mancalaPlayer.join(mancalaGame);
assertNotNull(mancalaPlayer.getGame());
assertNotNull(mancalaPlayer.getPlayerIndex());
}
@Test
public void whenMancalaPlayerMove()
{
assertNotNull(mancalaGame);
assertNotNull(mancalaPlayer);
int pitNum = 1;
mancalaPlayer.join(mancalaGame);
int pitStoneCount = mancalaGame.getBoard().getPlayerPits()[mancalaPlayer.getPlayerIndex()][pitNum - 1];
mancalaPlayer.move(new PlayerMove(mancalaGame, mancalaPlayer, pitNum));
assertNotEquals(pitStoneCount, mancalaGame.getBoard().getPlayerPits()[mancalaPlayer.getPlayerIndex()][pitNum - 1]);
}
}
|
package ru.kappers.convert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Service;
import ru.kappers.model.Event;
import ru.kappers.model.dto.EventDTO;
import ru.kappers.service.FixtureService;
import javax.annotation.Nullable;
/**
* Конвертер из {@link EventDTO} в {@link Event}
*/
@Service
public class EventDTOToEventConverter implements Converter<EventDTO, Event> {
private final FixtureService fixtureService;
@Autowired
public EventDTOToEventConverter(FixtureService fixtureService) {
this.fixtureService = fixtureService;
}
@Nullable
@Override
public Event convert(@Nullable EventDTO source) {
if (source == null) {
return null;
}
final Event event = Event.builder()
.fixture(fixtureService.getById(source.getF_id()))
.outcome(source.getOutcome())
.coefficient(source.getCoefficient())
.tokens(source.getTokens())
.price(source.getPrice())
.build();
return event;
}
}
|
package com.app.gnometown;
import android.app.Application;
import android.graphics.Bitmap;
import android.text.TextUtils;
import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;
import com.app.gnometown.connection.RequestManager;
import com.app.gnometown.connection.cache.ImageCacheManager;
import io.realm.Realm;
import io.realm.RealmConfiguration;
/**
* Created by andreinasarda on 17/4/16.
*/
public class GnomeTown extends Application{
private RequestQueue mRequestQueue;
private String TAG = GnomeTown.class.getSimpleName();
private static GnomeTown singleton;
private RealmConfiguration config;
private static int DISK_IMAGECACHE_SIZE = 1024*1024*50;
private static Bitmap.CompressFormat DISK_IMAGECACHE_COMPRESS_FORMAT = Bitmap.CompressFormat.PNG;
private static int DISK_IMAGECACHE_QUALITY = 100; //PNG is lossless so quality is ignored but must be provided
@Override
public void onCreate() {
super.onCreate();
singleton = this;
config = new RealmConfiguration.Builder(this)
.name("gnomes.realm")
.schemaVersion(1)
.deleteRealmIfMigrationNeeded()
.build();
Realm.setDefaultConfiguration(config);
init();
}
public static GnomeTown getInstance(){
return singleton;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024);
Network network = new BasicNetwork(new HurlStack());
mRequestQueue = new RequestQueue(cache, network);
mRequestQueue.start();
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
private void init() {
RequestManager.init(this);
createImageCache();
}
/*
* Creating image cache
* */
private void createImageCache(){
ImageCacheManager.getInstance().init(this,
this.getPackageCodePath()
, DISK_IMAGECACHE_SIZE
, DISK_IMAGECACHE_COMPRESS_FORMAT
, DISK_IMAGECACHE_QUALITY
, ImageCacheManager.CacheType.MEMORY);
}
}
|
package com.sye.kupps.calendarapp.login;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.sye.kupps.calendarapp.AppActivity;
import com.sye.kupps.calendarapp.R;
import com.sye.kupps.calendarapp.containers.User;
public class LoginActivity extends Activity {
private FragmentManager fragmentManager;
private LoginFragment loginFragment;
private RegisterFragment registerFragment;
// Used for verifying which fragment was last showing on rotation
private int lastFragment;
// Workaround for maintaining which fragment should appear on rotation after back stack
// has been popped.
private int lastBackStackCount;
// If true an async task is in progress and the wait screen should remain visible
private boolean taskInProgress;
// Tags
public static final String USER_OBJECT = "USER_OBJECT";
private static final String LOGIN_FRAGMENT_TAG = "LOGIN_FRAGMENT_KEY";
private static final String REGISTER_FRAGMENT_TAG = "REGISTER_FRAGMENT_KEY";
private static final String LAST_FRAGMENT_TAG = "LAST_FRAGMENT_TAG";
private static final String LAST_BACK_STACK_TAG = "LAST_BACK_STACK_TAG";
private static final String USER_STRING = "USER_STRING";
private static final String TASK_IN_PROGRESS_TAG = "TASK_IN_PROGRESS_TAG";
private static final String LOG_TAG = LoginActivity.class.getName();
@Override
protected void onCreate(Bundle savedInstanceState) {
String userString = getPreferences(MODE_PRIVATE).getString(USER_STRING, null);
if (userString != null) {
Intent app = new Intent(this, AppActivity.class);
app.putExtra(USER_STRING, userString);
startActivity(app);
finish();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
fragmentManager = getFragmentManager();
fragmentManager.addOnBackStackChangedListener(getBackStackListener());
if (savedInstanceState != null) {
recoverFragments(savedInstanceState);
checkForTask(savedInstanceState);
lastFragment = savedInstanceState.getInt(LAST_FRAGMENT_TAG);
lastBackStackCount = savedInstanceState.getInt(LAST_BACK_STACK_TAG);
if (!taskInProgress) {
switch (lastFragment) {
case 0:
goToLogin(false);
break;
case 1:
goToRegister(false);
break;
default:
goToLogin(false);
break;
}
}
} else {
instantiateFragments();
}
}
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt(LAST_FRAGMENT_TAG, lastFragment);
savedInstanceState.putInt(LAST_BACK_STACK_TAG, lastBackStackCount);
savedInstanceState.putBoolean(TASK_IN_PROGRESS_TAG, taskInProgress);
if (loginFragment != null)
fragmentManager.putFragment(savedInstanceState, LOGIN_FRAGMENT_TAG, loginFragment);
if (registerFragment != null)
fragmentManager.putFragment(savedInstanceState, REGISTER_FRAGMENT_TAG, registerFragment);
super.onSaveInstanceState(savedInstanceState);
}
private void recoverFragments(Bundle state) {
loginFragment =
(LoginFragment) fragmentManager.getFragment(state, LOGIN_FRAGMENT_TAG);
registerFragment =
(RegisterFragment) fragmentManager.getFragment(state, REGISTER_FRAGMENT_TAG);
}
private void instantiateFragments() {
loginFragment = new LoginFragment();
registerFragment = new RegisterFragment();
lastFragment = 0;
FragmentTransaction init = fragmentManager.beginTransaction();
init.add(R.id.login_activity_container, loginFragment, LOGIN_FRAGMENT_TAG);
init.add(R.id.login_activity_container, registerFragment, REGISTER_FRAGMENT_TAG);
init.hide(registerFragment);
init.commit();
}
protected void checkForTask(Bundle savedInstanceState) {
taskInProgress = savedInstanceState.getBoolean(TASK_IN_PROGRESS_TAG, false);
if (taskInProgress) {
if (loginFragment != null && loginFragment.isAdded()) {
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.hide(loginFragment);
transaction.commit();
}
if (registerFragment != null && registerFragment.isAdded()) {
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.hide(registerFragment);
transaction.commit();
}
View waitView = findViewById(R.id.login_wait_screen);
if (waitView.getVisibility() == View.GONE)
waitView.setVisibility(View.VISIBLE);
}
}
protected void goToLogin(boolean addToBackStack) {
lastFragment = 0;
FragmentTransaction swap = fragmentManager.beginTransaction();
if (!registerFragment.isHidden())
swap.hide(registerFragment);
if (loginFragment.isHidden())
swap.show(loginFragment);
if (addToBackStack) {
swap.addToBackStack(LOGIN_FRAGMENT_TAG);
lastBackStackCount++;
}
swap.commit();
}
protected void goToRegister(boolean addToBackStack) {
lastFragment = 1;
FragmentTransaction swap = fragmentManager.beginTransaction();
if (!loginFragment.isHidden())
swap.hide(loginFragment);
if (registerFragment.isHidden())
swap.show(registerFragment);
if (addToBackStack) {
swap.addToBackStack(REGISTER_FRAGMENT_TAG);
lastBackStackCount++;
}
swap.commit();
}
protected void onLoginAttempt() {
taskInProgress = true;
FragmentTransaction hide = fragmentManager.beginTransaction();
hide.hide(loginFragment);
hide.commit();
View waitView = findViewById(R.id.login_wait_screen);
waitView.setVisibility(View.VISIBLE);
}
protected void onLoginAttemptCompleted(User user) {
Log.i(LOG_TAG, "Login attempt completed");
taskInProgress = false;
if (user == null) {
View waitView = findViewById(R.id.login_wait_screen);
waitView.setVisibility(View.GONE);
goToLogin(false);
String message = "Username or password is incorrect";
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
} else {
Intent app = new Intent(this, AppActivity.class);
app.putExtra(USER_OBJECT, user);
startActivity(app);
finish();
}
}
protected void onRegistrationAttempt() {
taskInProgress = true;
FragmentTransaction hide = fragmentManager.beginTransaction();
hide.hide(registerFragment);
hide.commit();
View waitView = findViewById(R.id.login_wait_screen);
waitView.setVisibility(View.VISIBLE);
}
protected void onRegistrationAttemptCompleted(User user) {
Log.i(LOG_TAG, "Registration attempt completed");
taskInProgress = false;
if (user == null) {
View waitView = findViewById(R.id.login_wait_screen);
waitView.setVisibility(View.GONE);
goToRegister(false);
String message = "Username is already in use";
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
} else {
Intent app = new Intent(this, AppActivity.class);
app.putExtra(USER_OBJECT, user);
startActivity(app);
finish();
}
}
private FragmentManager.OnBackStackChangedListener getBackStackListener() {
return new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
int currentBackStackCount = fragmentManager.getBackStackEntryCount();
if (lastBackStackCount > currentBackStackCount)
lastFragment++;
lastBackStackCount = currentBackStackCount;
}
};
}
}
|
package com.example.shivam.tic_tac_toeonline;
import android.app.Dialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button btHost, btJoin;
EditText et_code;
Button bt_go;
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseReference = firebaseDatabase.getReference();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btHost = (Button) findViewById(R.id.bt_host);
btJoin = (Button) findViewById(R.id.bt_join);
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.dialog_generate_code);
dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
dialog.setTitle("Enter a unique code...");
et_code = (EditText) dialog.findViewById(R.id.et_code);
bt_go = dialog.findViewById(R.id.bt_enter);
btHost.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.show();
}
});
bt_go.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
Host host = new Host();
host.setTurn(false);
Away away = new Away();
away.setTurn(false);
Box box = new Box();
box.setTakenType(true); //true --> yellow false --> red
box.boxPosition = new ArrayList<Integer>(9) {{
add(-1);
add(-1);
add(-1);
add(-1);
add(-1);
add(-1);
add(-1);
add(-1);
add(-1);
}};
box.setBoxPosition(box.boxPosition);
box.setIstaken(false);
Game game = new Game();
game.setHost(host);
game.setAway(away);
game.setBox(box);
game.setLastMove(0);
game.setStarted(false);
game.setHostZero(true);
String hostNumber = et_code.getText().toString();
databaseReference.child(hostNumber).setValue(game);
Intent intent = new Intent(MainActivity.this, Game_PlayActivity.class);
intent.putExtra("isHost", true);
intent.putExtra("code", hostNumber);
startActivity(intent);
finish();
}
});
btJoin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, JoinActivity.class));
finish();
}
});
}
}
|
package cn.itcast.job.utils;
import java.util.*;
public class CollectionsUtils {
public static <T> List<T> getListFromArray(T[] array) {
List<T> resultList = new ArrayList<>(array.length);
Collections.addAll(resultList, array);
return resultList;
}
/**
* every step add one item
*
* @param i begin from 1 1,2,3,4。。。
* @param step
* @param list
* @param item
* @param <T>
*/
public static <T> void addItemInListEveryStep(int i, int step, List<T> list, T item) {
list.add(i * step - 1, item);
}
//https://blog.csdn.net/xujiangdong1992/article/details/79738717
//比较两个list
//取出存在menuOneList中,但不存在resourceList中的数据,差异数据放入differentList
public static <T> List<T> listCompare(List<T> menuOneList, List<T> resourceList) {
Map<T, Integer> map = new HashMap<T, Integer>(resourceList.size());
List<T> differentList = new ArrayList<T>();
for (T resource : resourceList) {
map.put(resource, 1);
}
for (T resource1 : menuOneList) {
if (map.get(resource1) == null) {
differentList.add(resource1);
}
}
return differentList;
}
public static <K, V> void mapTraversal(Map<K, V> map, MapTraversalCallback<K, V> mapTraversalCallback) {
Iterator<Map.Entry<K, V>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<K, V> entry = it.next();
if (mapTraversalCallback != null) {
mapTraversalCallback.visit(entry);
}
}
}
public static List<String> removeDuplicate(List<String> list) {
HashSet<String> h = new HashSet<String>(list);
list.clear();
list.addAll(h);
return list;
}
public interface MapTraversalCallback<K, V> {
void visit(Map.Entry<K, V> entry);
}
}
|
/*
* 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 practicos;
/**
*
* @author capacitacion16
*/
public class Ejercicio6 {
public static void main(String arg[]){
int [] array = { 2 , 18 , 6 ,- 4 , 5 , 1};
for(int i=0; i < array.length; i++){
array [ i ] = array [ i ] + ( array [ i ] / array [ 0 ]);
}
System.out.println("NUEVOS VALORES DEL VECTOR");
System.out.println("-------------------------");
System.out.print("array = { ");
for(int i=0; i<array.length; i++){
System.out.print(array[i] + ", ");
}
System.out.print("}");
}
}
|
/*
* Sonar PHP Plugin
* Copyright (C) 2010 Sonar PHP Plugin
* dev@sonar.codehaus.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.plugins.php.core;
import java.io.File;
import java.util.List;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.lang.SystemUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.BatchExtension;
import org.sonar.api.resources.Project;
/**
*
* Each php plugin should redefine properties names, it handles common properties initialization.
*/
public abstract class AbstractPhpPluginConfiguration implements BatchExtension {
/** The logger. */
private static final Logger LOG = LoggerFactory.getLogger(AbstractPhpPluginConfiguration.class);
/** Suffix used by windows for script files */
private static final String WINDOWS_BAT_SUFFIX = ".bat";
protected static final String SONAR_DYNAMIC_ANALYSIS = "sonar.dynamicAnalysis";
protected static final Boolean DEFAULT_SONAR_DYNAMIC_ANALYSIS = true;
protected Project project;
/** Indicates whether the plugin should only analyze results or launch tool. */
protected boolean analyzeOnly;
/** The tool argument line. */
private String argumentLine;
/** The report file name. */
private String reportFileName;
/** The report file relative path. */
private String reportFileRelativePath;
/**
* @param project
*/
protected AbstractPhpPluginConfiguration(Project project) {
this.project = project;
Configuration configuration = getProject().getConfiguration();
if (getReportFileNameKey() != null) {
this.reportFileName = configuration.getString(getReportFileNameKey(), getDefaultReportFileName());
}
if (getReportFileRelativePathKey() != null) {
this.reportFileRelativePath = configuration.getString(getReportFileRelativePathKey(), getDefaultReportFilePath());
String absolutePath = getProject().getFileSystem().getBuildDir().getAbsolutePath();
File reportDirectory = new File(absolutePath, reportFileRelativePath);
reportDirectory.mkdir();
}
if (getArgumentLineKey() != null) {
this.argumentLine = configuration.getString(getArgumentLineKey(), getDefaultArgumentLine());
}
if (getShouldAnalyzeOnlyKey() != null) {
this.analyzeOnly = configuration.getBoolean(getShouldAnalyzeOnlyKey(), shouldAnalyzeOnlyDefault());
}
}
/**
* Gets the argument line.
*
* @return the argument line
*/
public String getArgumentLine() {
return argumentLine;
}
/**
* Gets operating system dependent launching script name.
*
* <pre>
* As an example:
* For windows php unit launching script is : punit.bat
* For Unix php unit launching script is : punit
* </pre>
*
* @return the command line
*/
public String getOsDependentToolScriptName() {
// For Windows
if (isOsWindows()) {
return new StringBuilder(getCommandLine()).append(WINDOWS_BAT_SUFFIX).toString();
// For Unix like systems
} else {
return getCommandLine();
}
}
/**
* @return the created working directory.
*/
public File createWorkingDirectory() {
File target = getProject().getFileSystem().getBuildDir();
File logs = new File(target, getReportFileRelativePath());
synchronized (this) {
logs.mkdirs();
}
return logs;
}
/**
* Gets the report file.
*
* <pre>
* The path is construct as followed :
* {PORJECT_BUILD_DIR}\{CONFIG_RELATIVE_REPORT_FILE}\{CONFIG_REPORT_FILE_NAME}
* </pre>
*
* @return the report file
*/
public File getReportFile() {
StringBuilder fileName = new StringBuilder(reportFileRelativePath).append(File.separator);
fileName.append(reportFileName);
File reportFile = new File(getProject().getFileSystem().getBuildDir(), fileName.toString());
LOG.info("Report file for: " + getCommandLine() + " : " + reportFile);
return reportFile;
}
/**
* Gets the source directories.
*
* @return the source directories
*/
public List<File> getSourceDirectories() {
return getProject().getFileSystem().getSourceDirs();
}
/**
* Gets the project test source directories.
*
* @return List<File> A list of all test source folders
*/
public List<File> getTestDirectories() {
return getProject().getFileSystem().getTestDirs();
}
/**
* Checks if is analyze only.
*
* @return true, if is analyze only
*/
public boolean isAnalyseOnly() {
return analyzeOnly;
}
/**
* Checks if running os is windows.
*
* @return true, if os is windows
*/
public boolean isOsWindows() {
return SystemUtils.IS_OS_WINDOWS;
}
/**
* @return the project
*/
public Project getProject() {
return project;
}
/**
* Returns <code>true<code> if property is not null or empty.
* <pre>
* value.equals(null) return false
* value.equals("") return false
* value.equals(" ") return false
* value.equals(" toto ") return true
* </pre>
*
* @param key
* the property's key
* @return <code>true<code> if property is not null or empty; <code>false</code> any other way.
*/
public boolean isStringPropertySet(String key) {
return project.getConfiguration().containsKey(key);
}
/**
* Gets the argument line key.
*
* @return the argument line key
*/
protected abstract String getArgumentLineKey();
/**
* Gets the command line.
*
* @return the command line
*/
protected abstract String getCommandLine();
/**
* Gets the default argument line.
*
* @return the default argument line
*/
protected abstract String getDefaultArgumentLine();
/**
* Gets the default report file name.
*
* @return the default report file name
*/
protected abstract String getDefaultReportFileName();
/**
* Gets the default report file path.
*
* @return the default report file path
*/
protected abstract String getDefaultReportFilePath();
/**
* Gets the report file name key.
*
* @return the report file name key
*/
protected abstract String getReportFileNameKey();
/**
* Gets the report file relative path.
*
* @return the report file relative path
*/
public String getReportFileRelativePath() {
return reportFileRelativePath;
}
/**
* Gets the report file relative path key.
*
* @return the report file relative path key
*/
protected abstract String getReportFileRelativePathKey();
/**
* Gets the should analyze only key.
*
* @return the should analyze only key
*/
protected abstract String getShouldAnalyzeOnlyKey();
/**
* Gets the should run key.
*
* @return the should run key
*/
protected abstract String getShouldRunKey();
/**
* Should analyze only default.
*
* @return true, if successful
*/
protected abstract boolean shouldAnalyzeOnlyDefault();
/**
* Should run default.
*
* @deprecated
*
* @return true, if successful
*/
protected abstract boolean shouldRunDefault();
/**
* Skip the the tool execution default.
*
* @return bool
*/
protected abstract boolean skipDefault();
}
|
package com.xkzhangsan.time;
import java.time.DayOfWeek;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjuster;
/**
* TemporalAdjuster 扩展
* @author xkzhangsan
*
*/
public final class TemporalAdjusterExtension {
private TemporalAdjusterExtension() {
}
/**
* 下一个工作日
* next work day
* @return TemporalAdjuster
*/
public static TemporalAdjuster nextWorkDay(){
return (temporal) -> {
DayOfWeek dayOfWeek = DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK));
int add = 1;
if (dayOfWeek == DayOfWeek.FRIDAY){
add = 3;
}
if (dayOfWeek == DayOfWeek.SATURDAY){
add = 2;
}
return temporal.plus(add, ChronoUnit.DAYS);
};
}
}
|
/**
* Created with IntelliJ IDEA.
* User: Administrator
* Date: 02.03.14
* Time: 14:41
* To change this template use File | Settings | File Templates.
*/
public class WorkThread extends Thread {
private CompositeHashMap map;
WorkThread(CompositeHashMap map) {
this.map = map;
}
@Override
public void run() {
// put
for (int i = 0; i < 2000; i++) {
map.put(this.getId(), Integer.toString(i), 'v');
}
// remove
for (int i = 1000; i < 2000; i++) {
map.remove(this.getId(), Integer.toString(i));
}
}
}
|
package task3;
public class MainCalculator {
public static void main(String[] args) {
Calculator calculator = new Calculator();
boolean numberIsEven;
boolean numberIsOdd;
double circleField;
int powerVar;
numberIsEven = calculator.isEven(41);
System.out.println("Czy liczba jest parzysta: " + numberIsEven);
numberIsOdd = calculator.isOdd(41);
System.out.println("Czy liczba jest nieparzysta: " + numberIsOdd);
circleField = calculator.circleField(2.5);
System.out.println("Pole koła: " + circleField);
powerVar = calculator.power(5);
System.out.println("Liczna podniesiona do kwadratu to : " + powerVar);
}
}
|
/*
* 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 interfaces;
/**
*
* @author ESTUDIANTES
*/
public interface Productos {
public double calcularValorNeto();
public String categoria();
}
|
/**
* DNet eBusiness Suite
* Copyright: 2010-2013 Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
package net.nan21.dnet.module.bd.presenter.impl.currency.model;
import java.math.BigDecimal;
import java.util.Date;
import net.nan21.dnet.core.api.annotation.Ds;
import net.nan21.dnet.core.api.annotation.DsField;
import net.nan21.dnet.core.api.annotation.Param;
import net.nan21.dnet.core.api.annotation.RefLookup;
import net.nan21.dnet.core.api.annotation.RefLookups;
import net.nan21.dnet.core.api.annotation.SortField;
import net.nan21.dnet.core.presenter.model.AbstractAuditableDs;
import net.nan21.dnet.module.bd.domain.impl.currency.Currency;
import net.nan21.dnet.module.bd.domain.impl.currency.CurrencyXRate;
import net.nan21.dnet.module.bd.domain.impl.currency.CurrencyXRateProvider;
@Ds(entity = CurrencyXRate.class, sort = {
@SortField(field = CurrencyXRate_Ds.f_validAt, desc = true),
@SortField(field = CurrencyXRate_Ds.f_source),
@SortField(field = CurrencyXRate_Ds.f_target)})
@RefLookups({
@RefLookup(refId = CurrencyXRate_Ds.f_sourceId, namedQuery = Currency.NQ_FIND_BY_CODE, params = {@Param(name = "code", field = CurrencyXRate_Ds.f_source)}),
@RefLookup(refId = CurrencyXRate_Ds.f_targetId, namedQuery = Currency.NQ_FIND_BY_CODE, params = {@Param(name = "code", field = CurrencyXRate_Ds.f_target)}),
@RefLookup(refId = CurrencyXRate_Ds.f_providerId, namedQuery = CurrencyXRateProvider.NQ_FIND_BY_CODE, params = {@Param(name = "code", field = CurrencyXRate_Ds.f_provider)})})
public class CurrencyXRate_Ds extends AbstractAuditableDs<CurrencyXRate> {
public static final String f_validAt = "validAt";
public static final String f_value = "value";
public static final String f_sourceId = "sourceId";
public static final String f_source = "source";
public static final String f_targetId = "targetId";
public static final String f_target = "target";
public static final String f_providerId = "providerId";
public static final String f_provider = "provider";
@DsField
private Date validAt;
@DsField
private BigDecimal value;
@DsField(join = "left", path = "source.id")
private String sourceId;
@DsField(join = "left", path = "source.code")
private String source;
@DsField(join = "left", path = "target.id")
private String targetId;
@DsField(join = "left", path = "target.code")
private String target;
@DsField(join = "left", path = "provider.id")
private String providerId;
@DsField(join = "left", path = "provider.code")
private String provider;
public CurrencyXRate_Ds() {
super();
}
public CurrencyXRate_Ds(CurrencyXRate e) {
super(e);
}
public Date getValidAt() {
return this.validAt;
}
public void setValidAt(Date validAt) {
this.validAt = validAt;
}
public BigDecimal getValue() {
return this.value;
}
public void setValue(BigDecimal value) {
this.value = value;
}
public String getSourceId() {
return this.sourceId;
}
public void setSourceId(String sourceId) {
this.sourceId = sourceId;
}
public String getSource() {
return this.source;
}
public void setSource(String source) {
this.source = source;
}
public String getTargetId() {
return this.targetId;
}
public void setTargetId(String targetId) {
this.targetId = targetId;
}
public String getTarget() {
return this.target;
}
public void setTarget(String target) {
this.target = target;
}
public String getProviderId() {
return this.providerId;
}
public void setProviderId(String providerId) {
this.providerId = providerId;
}
public String getProvider() {
return this.provider;
}
public void setProvider(String provider) {
this.provider = provider;
}
}
|
package net.minecraft.command;
public class WrongUsageException extends SyntaxErrorException {
public WrongUsageException(String message, Object... replacements) {
super(message, replacements);
}
public synchronized Throwable fillInStackTrace() {
return this;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\command\WrongUsageException.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package br.com.senac.controller;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import br.com.senac.domain.EmailAdministrativo;
import br.com.senac.domain.Usuario;
import br.com.senac.service.EmailAdministrativoService;
import br.com.senac.service.FacebookService;
import br.com.senac.service.UsuarioService;
import br.com.senac.util.Security;
@RestController
@RequestMapping("/usuario")
public class UsuarioController {
@Autowired
FacebookService facebookService;
@Autowired
private UsuarioService service;
@Autowired
private EmailAdministrativoService mailService;
Security security = new Security();
@GetMapping("/adiciona")
public ModelAndView adiciona(RedirectAttributes redirectAttributes) {
ModelAndView mv = new ModelAndView("usuario/adiciona");
mv.addObject("usuario", new Usuario());
return mv;
}
@PostMapping("/insere")
public ModelAndView salva(Usuario usuario, RedirectAttributes redirectAttributes) {
ModelAndView mv = new ModelAndView("usuario/adiciona");
if (usuario.getEmail().equals("") || usuario.getSenha().equals("")) {
mv.addObject("mensagem", "Os campos de usuário e senha são obrigatórios.");
mv.addObject("alertClass", "alert-danger");
} else {
mv.addObject("mensagem", "Novo usuário autenticado com sucesso.");
mv.addObject("alertClass", "alert-success");
service.insere(usuario);
mv = new ModelAndView("usuario/autentica");
}
return mv;
}
@GetMapping("/autentica")
public ModelAndView autentica(RedirectAttributes redirectAttributes) {
ModelAndView mv = new ModelAndView("usuario/autentica");
mv.addObject("usuario", new Usuario());
return mv;
}
@PostMapping("/login")
public ModelAndView login(Usuario usuario, RedirectAttributes redirectAttributes) {
ModelAndView mv = new ModelAndView("home/home");
if (usuario.getEmail().equals("") || usuario.getSenha().equals("")) {
mv.addObject("mensagem", "Os campos de usuário e senha são obrigatórios.");
mv.addObject("alertClass", "alert-danger");
} else {
mv.addObject("mensagem", "Novo usuário criado com sucesso.");
mv.addObject("alertClass", "alert-success");
usuario = service.findUsuarioSenha(usuario);
if (usuario == null) {
mv = new ModelAndView("usuario/autentica");
mv.addObject("mensagem", "Nome de usuário ou senha inválidos.");
mv.addObject("alertClass", "alert-danger");
} else {
mv.addObject("email", usuario.getEmail());
mv.addObject("mensagem", "Novo usuário autenticado com sucesso.");
mv.addObject("alertClass", "alert-success");
}
}
return mv;
}
@GetMapping("/conectafacebook")
public ModelAndView conectaFacebook() {
return new ModelAndView("redirect:" + facebookService.createFacebookAuthorizationURL());
}
@GetMapping("/facebook")
public ModelAndView createFacebookAccessToken(@RequestParam("code") String code){
facebookService.createFacebookAccessToken(code);
ModelAndView mv = new ModelAndView("home/home");
mv.addObject("email", facebookService.getEmail());
return mv;
}
@PostMapping("/atualizasenha")
public ModelAndView atualizaSenha(Usuario usuario) {
usuario = service.atualizaSenha(usuario);
ModelAndView mv = new ModelAndView("usuario/autentica");
mv.addObject("usuario", new Usuario());
return mv;
}
@GetMapping("/recuperasenha")
public ModelAndView recuperaSenha(Usuario usuario) {
ModelAndView mv = new ModelAndView("usuario/recuperasenha");
mv.addObject("usuario", usuario);
return mv;
}
@GetMapping("/recuperasenha/decode")
public ModelAndView login(@RequestParam String chave) {
chave = security.decode(chave);
Usuario usuario = new Usuario();
usuario.setId(Integer.valueOf(chave.split("-")[0]));
usuario.setEmail(chave.split("-")[1]);
usuario = service.findIdEmail(usuario);
return recuperaSenha(usuario);
}
@GetMapping("/esquecisenha")
public ModelAndView exibeFormEsqueciSenha(Usuario usuario) {
ModelAndView mv = new ModelAndView("usuario/esquecisenha");
mv.addObject("usuario", usuario);
return mv;
}
@PostMapping("/enviaemailrecuperacaosenha")
private ModelAndView enviaEmailRecuperacaoSenha(Usuario usuario) {
usuario = service.findByEmail(usuario);
String token = security.encode(usuario.getId() + "-" + usuario.getEmail());
String url = "http://localhost:8080/usuario/recuperasenha/decode?chave=" + token;
EmailAdministrativo mail = mailService.busca(1);
Properties props = new Properties();
props.put("mail.smtp.host", mail.getHost());
props.put("mail.smtp.socketFactory.port", mail.getPorta());
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", mail.getPorta());
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(mail.getUsuario(), security.decode(mail.getSenha()));
}
});
Message message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(mail.getUsuario()));
Address[] toUser = InternetAddress.parse(usuario.getEmail());
message.setRecipients(Message.RecipientType.TO, toUser);
message.setSubject("Recuperação de senha");
message.setContent("<a href="+url+">Clique nesse link para recuperar sua senha.</a>", "text/html");
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
ModelAndView mv = new ModelAndView("usuario/autentica");
return mv;
}
}
|
package jwscert.jaxws.services;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.Source;
import javax.xml.ws.LogicalMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
public class SOAPHandler1 implements SOAPHandler<SOAPMessageContext> {
@Override
public boolean handleMessage(SOAPMessageContext ctx) {
if((boolean)ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)){
System.out.println("SOAPHandler1.handleMessage() - outbound");
}else {
System.out.println("SOAPHandler1.handleMessage() - inbound");
}
SOAPMessage msj = ctx.getMessage();
return true;
}
@Override
public boolean handleFault(SOAPMessageContext ctx) {
if((boolean)ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)){
System.out.println("SOAPHandler1.handleFault() - outbound");
}else {
System.out.println("SOAPHandler1.handleFault() - inbound");
}
return true;
}
@Override
public void close(MessageContext ctx) {
//System.out.println("SOAPHandler1.close()");
}
@Override
public Set<QName> getHeaders() {
System.out.println("SOAPHandler1.getHeaders()");
return null;
}
}
|
//Assignment 6 Program 1
//Justin Yang
//2/19/14
//.....
//.....
//.............
//Testing
public class Swap {
/**
* @param args
*/
public static void main(String[] args) {
//Input in array
;int array[] = new int [100000];
int array2[] = {3,2,4,6,1,0};
for (int i = 0 ; i < 100000 ; i++)
{
array [i] = (int) (Math.random () * 100);
}
System.out.println("Printing: ");
//binarySort(array2);
bubbleSort(array2);
for(int i=0; i < array2.length; i++)
System.out.println(array2[i]);
//selectionSort(array);
}
private static void selectionSort(int[] array) {
int i, j, first, temp;
for ( i = array.length - 1; i > 0; i -- )
{
first = 0;
for(j = 1; j <= i; j ++)
{
if( array[j] < array[first] )
first = j;
}
temp = array[first];
array[first] = array[i];
array[i] = temp;
}
}
private static void binarySort(int[] array){
for (int i=0;i<array.length - 1;++i){
int temp=array[i];
int left=0;
int right=i;
while (left<right){
int middle=(left+right)/2;
if (temp>=array[middle])
left=right+1;
else
right=middle;
}
for (int j=i;j>left;--j){
swap(array,j-1,j);
}
}
}
//Function to swap array elements from binarySort()
public static void swap(int array[],int i,int j){
int k=array[i];
array[i]=array[j];
array[j]=k;
}
public static void bubbleSort(int[] array)
{
int j, tmp;
boolean f= true;
while(f)
{
f = false;
for(j = 0; j < array.length - 1; j++)
{
if(array[j+1] < array[j])
{
tmp = array[j+1];
array[j+1] = array[j];
array[j] = tmp;
f = true;
}
}
}
}
}
|
package finger.print.atm;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
/*
* 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.
*/
/**
*
* @author vishal
*/
public class TransactionWindow extends javax.swing.JFrame {
/**
* Creates new form TransactionWindow
*/
public TransactionWindow() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
withdraw = new javax.swing.JLabel();
deposit = new javax.swing.JLabel();
getTransactionDetails = new javax.swing.JLabel();
updateInfo = new javax.swing.JLabel();
checkBalance = new javax.swing.JLabel();
changePin = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setUndecorated(true);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
withdraw.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
withdraw.setText("Withdraw");
withdraw.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
withdrawMouseClicked(evt);
}
});
getContentPane().add(withdraw, new org.netbeans.lib.awtextra.AbsoluteConstraints(547, 160, -1, -1));
deposit.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
deposit.setText("Deposit");
deposit.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
depositMouseClicked(evt);
}
});
getContentPane().add(deposit, new org.netbeans.lib.awtextra.AbsoluteConstraints(547, 217, -1, -1));
getTransactionDetails.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
getTransactionDetails.setText("Get Transaction Details");
getTransactionDetails.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
getTransactionDetailsMouseClicked(evt);
}
});
getContentPane().add(getTransactionDetails, new org.netbeans.lib.awtextra.AbsoluteConstraints(128, 160, -1, -1));
updateInfo.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
updateInfo.setText("Change Mobile Number");
updateInfo.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
updateInfoMouseClicked(evt);
}
});
getContentPane().add(updateInfo, new org.netbeans.lib.awtextra.AbsoluteConstraints(128, 217, -1, -1));
checkBalance.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
checkBalance.setText("Check Balance");
checkBalance.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
checkBalanceMouseClicked(evt);
}
});
getContentPane().add(checkBalance, new org.netbeans.lib.awtextra.AbsoluteConstraints(128, 284, -1, -1));
changePin.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
changePin.setText("Change Pin");
changePin.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
changePinMouseClicked(evt);
}
});
getContentPane().add(changePin, new org.netbeans.lib.awtextra.AbsoluteConstraints(547, 284, -1, -1));
jLabel8.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel8.setText("Select any one transaction : ");
jLabel8.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel8MouseClicked(evt);
}
});
getContentPane().add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(128, 92, -1, -1));
jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/bank.jpeg"))); // NOI18N
getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 760, 410));
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void withdrawMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_withdrawMouseClicked
// TODO add your handling code here:
new Withdraw().setVisible(true);
dispose();
}//GEN-LAST:event_withdrawMouseClicked
private void depositMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_depositMouseClicked
// TODO add your handling code here:
new Deposit().setVisible(true);
dispose();
}//GEN-LAST:event_depositMouseClicked
private void jLabel8MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel8MouseClicked
// TODO add your handling code here:
}//GEN-LAST:event_jLabel8MouseClicked
private void changePinMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_changePinMouseClicked
// TODO add your handling code here:
new ChangePin().setVisible(true);
dispose();
}//GEN-LAST:event_changePinMouseClicked
private void checkBalanceMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_checkBalanceMouseClicked
// TODO add your handling code here:
//new CheckBalance().setVisible(true);
//dispose();
String CardNo=LogIn.Card_No;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/atm","root","root");
PreparedStatement st=connection.prepareStatement("select balance from account where id=?");
st.setString(1,CardNo);
ResultSet rs=st.executeQuery();
if(rs.next())
{
JOptionPane.showMessageDialog(this,"Your Current Balance is : "+rs.getFloat(1));
}
}
catch(Exception ex){}
}//GEN-LAST:event_checkBalanceMouseClicked
private void updateInfoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_updateInfoMouseClicked
// TODO add your handling code here:
new UpdateMobile().setVisible(true);
dispose();
}//GEN-LAST:event_updateInfoMouseClicked
private void getTransactionDetailsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_getTransactionDetailsMouseClicked
// TODO add your handling code here:
new GetTransactionDetail().setVisible(true);
dispose();
}//GEN-LAST:event_getTransactionDetailsMouseClicked
/**
* @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(TransactionWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TransactionWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TransactionWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TransactionWindow.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 TransactionWindow().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel changePin;
private javax.swing.JLabel checkBalance;
private javax.swing.JLabel deposit;
private javax.swing.JLabel getTransactionDetails;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel updateInfo;
private javax.swing.JLabel withdraw;
// End of variables declaration//GEN-END:variables
}
|
package com.redscarf.admin.controller;
import com.baomidou.mybatisplus.plugins.Page;
import com.redscarf.admin.model.vo.UserVO;
import com.redscarf.admin.service.SysUserService;
import com.redscarf.admin.utils.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
/**
* @author lengleng
* @date 2017/10/28
*/
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
@Autowired
private SysUserService userService;
/**
* 通过用户名查询用户及其角色信息
*
* @param username 用户名
* @return UseVo 对象
*/
@GetMapping("/findUserByUsername/{username}")
public UserVO findUserByUsername(@PathVariable String username) {
return userService.findUserByUsername(username);
}
/**
* 分页查询用户
*
* @param params 参数集
* @param userVO 用户信息
* @return 用户集合
*/
@RequestMapping("/userPage")
public Page userPage(@RequestParam Map<String, Object> params, UserVO userVO) {
return userService.selectWithRolePage(new Query(params),userVO);
}
}
|
package diasporaTests;
import com.codeborne.selenide.Configuration;
import com.codeborne.selenide.Screenshots;
import com.google.common.io.Files;
import org.junit.Before;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;
import ru.yandex.qatools.allure.annotations.Attachment;
import java.io.File;
import java.io.IOException;
import static com.codeborne.selenide.CollectionCondition.texts;
import static com.codeborne.selenide.Selectors.byText;
import static com.codeborne.selenide.Condition.text;
import static com.codeborne.selenide.Condition.visible;
import static com.codeborne.selenide.Selenide.*;
import static helpers.Helpers.dropCreateSeedDiasporaDB;
import static pages.diaspora.*;
/**
* Created by yana on 30.05.15.
*/
public class AllDiasporaTests {
@Before
public void clearData() {
dropCreateSeedDiasporaDB();
open("http://localhost:3000/stream");
Configuration.timeout = 20000;
}
@Test
public void loginWritePostsLikePostTests() {
// log in
enterLogin("bob");
enterPassword("evankorth");
$(".user-name").shouldHave(text("Bob Grimm"));
//create activity
openMyActivity();
writeText("A from activity");
contentsList.find(text("A from activity"));
//create mentions
openMyMentions();
writeText("D from mentios");
contentsList.find(text("D from mentios"));
//create mark
openFollowedtags();
writeText("T from tags");
contentsList.find(text("T from tags"));
//my aspects
openMyAspects();
aspectsList.shouldHave(texts("Deselect all", "generic", "+ Add an aspect"));
// add new aspect
addNewAspects("B");
$(byText("Stream")).click();
openMyAspects();
aspectsList.shouldHave(texts("Select all", "generic", "B", "+ Add an aspect"));
//go to prifile
userPopupMenu("Profile");
contentsList.shouldHave(texts("T from tags", "D from mentios", "A from activity"));
//comment posts
contentsList.find(text("T from tags"));
commentPublic("M");
$(".comment.media").shouldHave(text("M"));
//delete post
deletePost("T from tags");
contentsList.shouldHave(texts("D from mentios", "A from activity"));
//cencel delete post
cencelDeletePost("D from mentios");
contentsList.shouldHave(texts("D from mentios", "A from activity"));
//like post
likePost("A from activity");
//log out
userPopupMenu("Log out");
}
@Test
public void popupChangePasswordCreatMes(){
// precondition
enterLogin("bob");
enterPassword("evankorth");
$(".user-name").shouldHave(text("Bob Grimm"));
//go to Contacts
userPopupMenu("Contacts");
$(byText("My contacts")).shouldBe(visible).click();
//open contact page
openContactPage("Alice Smith");
$("#name").shouldHave(text("Alice Smith")).click();
//press message icon in contact page
pressMessageIconInUsrPage();
$(byText("New conversation")).shouldBe(visible).click();
//create message
creatNewMessage("hi");
$(".last_message").shouldHave(text("hi"));
//go to settings
userPopupMenu("Settings");
$("#section_header>h2").shouldHave(text("Settings"));
//change password
changePassword("evankorth", "qwerty", "qwerty");
//login with new password
enterLogin("bob");
enterPassword("qwerty");
$(".user-name").shouldHave(text("Bob Grimm"));
//Change language
changeLanguage("Русский");
$("#section_header>h2").shouldHave(text("Настройки"));
//press button close account
$("#close_account").click();
$("#inner_account_delete>h1").shouldHave("Пожалуйста, не уходите!");
$(".close_image").click();
//go to Help
userPopupMenu("Помощь");
$(".help_header").shouldHave(text("Помощь"));
//go to admin
userPopupMenu("Администратор");
$(".user_search.span9>h3").shouldHave(text("Поиск пользователей"));
//Log out
userPopupMenu("Выйти");
}
@Test
public void editUserProfile(){
//precondition
enterLogin("bob");
enterPassword("evankorth");
$(".user-name").shouldHave(text("Bob Grimm"));
userPopupMenu("Profile");
//go to edit
$("#edit_profile").click();
//edit user name
editUserName("Boby");
//add
addDiscription("yoga");
addDiscription("theater");
//edit user bio
editUserBio("NEW edited");
//edit user local
editUserLocal("ZP edited");
//edit user gander
editUserGender("O edited");
//edit user birthday
editUserBerthday("1987", "June", "22");
// update edited
$("#update_profile").click();
$(".user-name").shouldHave(text("Boby Grimm"));
$$(".as-selection-item.blur").shouldHave(texts("yoga", "theater"));
$("#profile_bio").shouldHave(text("NEW edited"));
userPopupMenu("Profile");
userPopupMenu("Log out");
}
@After
public void tearDown ()throws IOException {
screenshot();
}
@Attachment(type = "image/png")
public byte[] screenshot ()throws IOException {
File screenshot = Screenshots.getScreenShotAsFile();
return Files.toByteArray(screenshot);
}
}
|
package com.tkb.elearning.dao.impl;
import java.util.ArrayList;
import java.util.List;
import com.tkb.elearning.dao.AppealDao;
import com.tkb.elearning.model.Appeal;
import sso.ojdbc.dao.impl.PagingDaoImpl;
public class AppealDaoImpl extends PagingDaoImpl implements AppealDao{
@SuppressWarnings("unchecked")
public List<Appeal> getList(int pageCount, int pageStart, Appeal appeal){
List<Object> args = new ArrayList<Object>();
String sql = "SELECT * FROM appeal";
if(appeal.getTransactor() != null && !"".equals(appeal.getTransactor())){
sql +="WHERE TRANSACTOR LIKE";
args.add("%" + appeal.getTransactor() + "%");
}
sql += " ORDER BY ID LIMIT ?, ?";
args.add(pageStart);//※注意pageStart和pageCount順序
args.add(pageCount);
return getJdbcTemplate().query(sql, args.toArray(), getRowMapper());
}
public Integer getCount(Appeal appeal){
List<Object> args = new ArrayList<Object>();
String sql = "SELECT COUNT(*) FROM appeal";
if(appeal.getTransactor() !=null && !"".equals(appeal.getTransactor())){
sql += "WHERE TRANSACTOR LIKE";
args.add("%" + appeal.getTransactor() + "%");
}
return getJdbcTemplate().queryForInt(sql, args.toArray());
}
public Appeal getData(Appeal appeal){
String sql = "SELECT * FROM appeal WHERE ID = ?";
return(Appeal)getJdbcTemplate().query(sql, new Object[]{appeal.getId()}, getRowMapper()).get(0);
}
public void add(Appeal appeal){
String sql = "INSERT INTO appeal(TRANSACTOR, HANDLE_DATE, HANDLE_CONTENT)"
+ "VALUE(?, NOW(), ?)";
getJdbcTemplate().update(sql, new Object[]{appeal.getTransactor(), appeal.getHandle_date(), appeal.getHandle_content()});
}
public void update(Appeal appeal){
String sql = "UPDATE appeal SET TRANSACTOR = ?, HANDLE_DATE, HANDLE_CONTENT = ? WHERE ID = ?";
getJdbcTemplate().update(sql, new Object[]{appeal.getTransactor(), appeal.getHandle_date(), appeal.getHandle_content()});
}
public void delete(Integer id){
String sql = "DELETE FROM appeal WHERE ID = ?";
getJdbcTemplate().update(sql, new Object[] {id});
}
// public Integer checkUsingPeriod(Active active) {
// String sql = "SELECT count(*) FROM active WHERE class_no = ? ";
// return getJdbcTemplate().queryForInt(sql, new Object[]{ active.getClass_no() });
// }
}
|
package com.zmyaro.ltd;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
public abstract class RotatingEnemy extends Enemy {
protected float mRotation;
protected float mRotationIncrement;
public RotatingEnemy() {
mRotation = (float) (Math.random() * 360);
mRotationIncrement = (float) (Math.random() * 0.5) + 0.5f;
}
@Override
public void update(long fps) {
super.update(fps);
mRotation += mRotationIncrement;
if (mRotation > 360) {
mRotation -= 360;
}
}
@Override
public void draw(Canvas canvas, Paint paint, float deviceScale) {
if (isDead() && mCurrentFrame >= mTotalFrames) {
return;
}
mCurrentFrame++;
if (!isDead() && mCurrentFrame >= mLoopLength) {
mCurrentFrame = 0;
}
Bitmap bitmap = BitmapManager.getBitmap(mBitmapName);
Rect cropRect = new Rect(
(int) (mCurrentFrame * getSpriteWidth()),
0,
(int) ((mCurrentFrame + 1) * getSpriteWidth()),
(int) getSpriteHeight());
Rect destRect = new Rect(
(int) (-getWidth(deviceScale) / 2),
(int) (-getHeight(deviceScale) / 2),
(int) (getWidth(deviceScale) / 2),
(int) (getHeight(deviceScale) / 2));
canvas.save();
canvas.translate(
getHitboxX(deviceScale) + getHitboxWidth(deviceScale) / 2,
getHitboxY(deviceScale) + getHitboxHeight(deviceScale) / 2);
canvas.rotate(mRotation);
canvas.drawBitmap(bitmap, cropRect, destRect, paint);
canvas.restore();
// Do not draw health bars for dead enemies.
if (isDead()) {
return;
}
drawHitbox(canvas, paint, deviceScale);
drawHealthBar(canvas, paint, deviceScale);
}
}
|
package com.tencent.mm.plugin.topstory.a;
public interface c {
void dM(int i, int i2);
}
|
package beans;
import lombok.Data;
import util.Default;
@Data
public class PurchasingCardForm {
private String id;
private String rowstamp;
private String companyPurchasing;
private String address;
private String city;
private String zipcode;
private String phone;
private String nameDeliver;
private String mocode;
private String approverName;
private String submittedBy;
private java.sql.Timestamp submitted;
private String isactive;
public PurchasingCardForm(){
rowstamp = Default.getInstance().getDefaultRawstramp();
isactive = Default.getInstance().getDefaultIsActive();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getRowstamp() {
return rowstamp;
}
public void setRowstamp(String rowstamp) {
this.rowstamp = rowstamp;
}
public String getCompanyPurchasing() {
return companyPurchasing;
}
public void setCompanyPurchasing(String companyPurchasing) {
this.companyPurchasing = companyPurchasing;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getNameDeliver() {
return nameDeliver;
}
public void setNameDeliver(String nameDeliver) {
this.nameDeliver = nameDeliver;
}
public String getMocode() {
return mocode;
}
public void setMocode(String mocode) {
this.mocode = mocode;
}
public String getApproverName() {
return approverName;
}
public void setApproverName(String approverName) {
this.approverName = approverName;
}
public String getSubmittedBy() {
return submittedBy;
}
public void setSubmittedBy(String submittedBy) {
this.submittedBy = submittedBy;
}
public java.sql.Timestamp getSubmitted() {
return submitted;
}
public void setSubmitted(java.sql.Timestamp submitted) {
this.submitted = submitted;
}
public String getIsactive() {
return isactive;
}
public void setIsactive(String isactive) {
this.isactive = isactive;
}
}
|
package org.terasoluna.gfw.examples.rest.api.common.error;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.terasoluna.gfw.common.exception.ExceptionCodeProvider;
import org.terasoluna.gfw.examples.rest.api.common.resource.hateoas.AbstractLinksSupportedResource;
public class ApiError extends AbstractLinksSupportedResource implements Serializable,
ExceptionCodeProvider {
private static final long serialVersionUID = 1L;
private final String code;
private final String message;
@JsonSerialize(include = Inclusion.NON_EMPTY)
private final String target;
@JsonSerialize(include = Inclusion.NON_EMPTY)
private final List<ApiError> details = new ArrayList<>();
public ApiError(String code, String message) {
this(code, message, null);
}
public ApiError(String code, String message, String target) {
this.code = code;
this.message = message;
this.target = target;
}
public String getCode() {
return code;
}
public String getMessage() {
return message;
}
public String getTarget() {
return target;
}
public List<ApiError> getDetails() {
return details;
}
public void setDetails(List<ApiError> details) {
this.details.clear();
this.details.addAll(details);
}
public void addDetail(ApiError detail) {
details.add(detail);
}
}
|
package com.minipg.fanster.armoury.adapter;
import android.content.Intent;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.minipg.fanster.armoury.R;
import com.minipg.fanster.armoury.activity.LoginActivity;
import com.minipg.fanster.armoury.activity.TopicListActivity;
import com.minipg.fanster.armoury.dao.CategoryItemDao;
import com.minipg.fanster.armoury.fragment.TabCategoryFragment;
import java.util.List;
import java.util.Locale;
/**
* Created by MFEC on 8/7/2017.
*/
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.CategoryListItemHolder>{
TabCategoryFragment fragmentCategory;
List<CategoryItemDao> categoryList;
TabCategoryFragment fragmentCategory1;
CategoryItemDao dao;
public CategoryAdapter(TabCategoryFragment fragmentCategory, List<CategoryItemDao> categoryList, TabCategoryFragment fragmentCategory1){
this.fragmentCategory = fragmentCategory;
this.categoryList = categoryList;
this.fragmentCategory1 = fragmentCategory1;
}
@Override
public CategoryListItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).
inflate(R.layout.list_category,parent,false);
return new CategoryListItemHolder(itemView);
}
@Override
public void onBindViewHolder(CategoryListItemHolder holder, final int position) {
if(categoryList!=null)
dao = categoryList.get(position);
if(dao!=null){
holder.tvCate.setText(dao.getName());
holder.tvAmount.setText(dao.getAmount()+" Topic");
}
else{
holder.tvCate.setText("IOS");
holder.tvAmount.setText("Unknow Topic");
}
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(fragmentCategory.getActivity(), TopicListActivity.class);
intent.putExtra("type_device" ,categoryList.get(position).getName());
fragmentCategory1.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
if(categoryList == null)
return 0;
return categoryList.size();
}
static class CategoryListItemHolder extends RecyclerView.ViewHolder {
private final TextView tvCate;
private final TextView tvAmount;
private final CardView cardView;
public CategoryListItemHolder(View itemView) {
super(itemView);
tvCate = (TextView) itemView.findViewById(R.id.tvCategory);
tvAmount = (TextView) itemView.findViewById(R.id.tvAmount);
cardView = (CardView) itemView.findViewById(R.id.cardViewCategory);
}
}
public void setData(List<CategoryItemDao> data){
if(data!=null) {
this.categoryList = data;
}
}
}
|
package forex.rates.api.controller;
import forex.rates.api.service.DateTimeProviderService;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public class ResponseEntityExceptionHandlerTest {
private @Mock DateTimeProviderService dateTimeProviderService;
private MockMvc mockMvc;
@RestController
private class DummyController {
@GetMapping("illegalArgumentException")
void throwException() {
throw new IllegalArgumentException("Some description");
}
}
@Before
public void before() {
MockitoAnnotations.initMocks(this);
DummyController dummyController = new DummyController();
ResponseEntityExceptionHandler exceptionHandler = new ResponseEntityExceptionHandler(dateTimeProviderService);
mockMvc = MockMvcBuilders.standaloneSetup(dummyController).setControllerAdvice(exceptionHandler).build();
}
@Test
public void shouldHandleExceptionAndReturnCustomJsonResponse() throws Exception {
when(dateTimeProviderService.getCurrentTimestamp()).thenReturn(1234L);
mockMvc.perform(get("/illegalArgumentException")
.accept(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isBadRequest())
.andExpect(content().json("{'error':true}"))
.andExpect(content().json("{'timestamp':1234}"))
.andExpect(content().json("{'httpStatus':400}"))
.andExpect(content().json("{'message':'Bad Request'}"))
.andExpect(content().json("{'description':'Some description'}"));
}
}
|
package com.lingnet.vocs.action.remotedebug;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.lang.xwork.StringUtils;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Controller;
import com.lingnet.common.action.BaseAction;
import com.lingnet.util.JsonUtil;
import com.lingnet.vocs.entity.Question;
import com.lingnet.vocs.entity.QuestionType;
import com.lingnet.vocs.service.remoteDebug.QuestionTypeService;
@Controller
public class QuestionTypeAction extends BaseAction {
private static final long serialVersionUID = 7111726885822373478L;
private QuestionType questionType;
private String formdata;
@Resource(name = "questionTypeService")
private QuestionTypeService questionTypeService;
public String add() {
return ADD;
}
public String saveOrUpdate() {
questionType = JsonUtil.toObject(formdata, QuestionType.class);
try {
String result = "";
result = questionTypeService.saveOrUpdate(questionType);
return ajax(Status.success, result);
} catch (Exception e) {
return ajax(Status.error, e.getMessage());
}
}
public String edit() {
questionType = questionTypeService.get(QuestionType.class, id);
if (questionType == null) {
questionType = new QuestionType();
}
QuestionType orc = questionTypeService.get(QuestionType.class,
questionType.getpId());
if (orc != null) {
questionType.setpName(orc.getTypeName());
}
return ADD;
}
public String remove() {
String message = "success";
ids = StringUtils.split(ids[0], ",");
List<Question> questions = questionTypeService.getList(Question.class,
Restrictions.in("typeId", ids));
if (questions.isEmpty() || questions == null) {
questionTypeService.delete(ids);
operate("记录问题现象", "删除", ids[0]);
} else {
message = "存在此类型问题,不能删除!!";
}
return ajax(Status.success, message);
}
public String getListData() {
String json = questionTypeService.getListData(pager);
return ajax(Status.success, JsonUtil.Encode(json));
}
public String list() {
return "list";
}
public String tree() {
return "tree";
}
public String getTreeData() {
String typeData = "[{id:\"1\",typename:\"设备故障\",describe:\"设备故障\",parentTypeId:\"\"},{id:\"2\",typename:\"脱附报警\",describe:\"脱附报警\",parentTypeId:\"\"},{id:\"10\",typename:\"设备运行故障\",describe:\"设备运行故障\",parentTypeId:\"1\"},{id:\"20\",typename:\"脱附异常\",describe:\"脱附异常\",parentTypeId:\"2\"}]";
return ajax(Status.success, typeData);
}
/****************************************************************************************/
public QuestionType getQuestionType() {
return questionType;
}
public void setQuestionType(QuestionType questionType) {
this.questionType = questionType;
}
public String getFormdata() {
return formdata;
}
public void setFormdata(String formdata) {
this.formdata = formdata;
}
public QuestionTypeService getQuestionTypeService() {
return questionTypeService;
}
public void setQuestionTypeService(QuestionTypeService questionTypeService) {
this.questionTypeService = questionTypeService;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
|
package com.website.views.pages;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import com.website.models.entities.Author;
import com.website.models.entities.Picture;
import com.website.persistence.AuthorService;
import com.website.persistence.PictureService;
import com.website.persistence.VisitService;
import com.website.tools.error.HttpErrorHandler;
import com.website.tools.navigation.ContextManager;
import com.website.tools.navigation.SessionManager;
import com.website.views.WebPages;
/**
* The picture report web page view.</br>
* This {@link Named} class is bound with the same named xhtml file.
*
* @author Jérémy Pansier
*/
@Named
@ViewScoped
public class PictureReport implements Serializable {
/** The serial version UID. */
private static final long serialVersionUID = 4582347711226573145L;
/** The service managing the visit persistence. */
@Inject
private VisitService visitService;
/** The service managing the picture persistence. */
@Inject
private PictureService pictureService;
/** The service managing the author persistence. */
@Inject
private AuthorService authorService;
/** The web page. */
public static final WebPages WEB_PAGE = WebPages.PICTURE_REPORT;
/** The id. */
private Long id;
/** The picture. */
private transient Picture picture;
/** The author. */
private transient Author author;
/** The session user name. */
private String sessionUserName;
/** The views count. */
private Long viewsCount;
/**
* Initializes the session user name and the author just after the construction.
*/
@PostConstruct
public void init() {
sessionUserName = SessionManager.getSessionUserNameOrRedirect();
author = authorService.findAuthorByAuthorName(sessionUserName);
}
/**
* Sets the picture and the views count on the web page loading, depending on the HTTP request parameter:
*/
public void load() {
try {
if (!pictureService.isPictureAuthor(id, sessionUserName)) {
return;
}
final String websiteURL = ContextManager.getWebsiteUrl();
picture = pictureService.findPictureByPictureId(id);
final String url = websiteURL + "/" + "FilesServlet" + "/" + picture.getFilename();
viewsCount = visitService.countVisitsByUrlGroupByUrl(url);
}
catch (final NumberFormatException numberFormatException) {
HttpErrorHandler.print404(
"The http parameter cannot be formatted to Integer. Method: " + Thread.currentThread().getStackTrace()[1].getMethodName() + " Class: " + this.getClass().getName(),
numberFormatException);
return;
}
catch (final IllegalStateException illegalStateException) {
HttpErrorHandler.print500("Forward issue", illegalStateException);
return;
}
}
/**
* Gets the web page.
*
* @return the web page
*/
public WebPages getWebPage() {
return WEB_PAGE;
}
/**
* Gets the id.
*
* @return the id
*/
public Long getId() {
return id;
}
/**
* Sets the id.
*
* @param id the new id
*/
public void setId(final Long id) {
this.id = id;
}
/**
* Gets the picture.
*
* @return the picture
*/
public Picture getPicture() {
return picture;
}
/**
* Gets the author.
*
* @return the author
*/
public Author getAuthor() {
return author;
}
/**
* Gets the views count.
*
* @return the views count
*/
public Long getViewsCount() {
return viewsCount;
}
}
|
package com.example.user.gallows;
/**
* Created by User on 29.11.2017.
*/
class GallowsModel {
private String secretWord;
private String guessedWord;
private int mistakesCount;
public GallowsModel() {
secretWord = "";
mistakesCount = 0;
}
public String getSecretWord() {
return secretWord;
}
public String getGuessedWord() {
return guessedWord;
}
public void setGuessedWord(String guessedWord) {
this.guessedWord = guessedWord;
}
public void setMistakesCount(int mistakesCount) {
this.mistakesCount = mistakesCount;
}
public int getMistakesCount() {
return mistakesCount;
}
public void setSecretWord(String secretWord) {
this.secretWord = secretWord;
}
}
|
package de.adesso.gitstalker.core.processors;
import de.adesso.gitstalker.core.config.Config;
import de.adesso.gitstalker.core.enums.RequestType;
import de.adesso.gitstalker.core.objects.Member;
import de.adesso.gitstalker.core.objects.OrganizationWrapper;
import de.adesso.gitstalker.core.objects.Query;
import de.adesso.gitstalker.core.objects.Repository;
import de.adesso.gitstalker.core.repositories.OrganizationRepository;
import de.adesso.gitstalker.core.repositories.ProcessingRepository;
import de.adesso.gitstalker.core.repositories.RequestRepository;
import de.adesso.gitstalker.core.resources.externalRepo_Resources.*;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
/**
* This is the response processor used for ExternalRepo Request.
*/
@Getter
@Setter
@NoArgsConstructor
public class ExternalRepoProcessor extends ResponseProcessor {
private RequestRepository requestRepository;
private OrganizationRepository organizationRepository;
private ProcessingRepository processingRepository;
private Query requestQuery;
private OrganizationWrapper organization;
private HashMap<String, Repository> repositoriesMap = new HashMap<>();
/**
* Setting up the necessary parameters for the response processing.
* @param requestQuery Query to be processed.
* @param requestRepository RequestRepository for accessing requests.
* @param organizationRepository OrganizationRepository for accessing organization.
*/
protected void setUp(Query requestQuery, RequestRepository requestRepository, OrganizationRepository organizationRepository, ProcessingRepository processingRepository) {
this.requestQuery = requestQuery;
this.requestRepository = requestRepository;
this.organizationRepository = organizationRepository;
this.processingRepository = processingRepository;
this.organization = this.organizationRepository.findByOrganizationName(requestQuery.getOrganizationName());
}
/**
* Performs the complete processing of an answer.
* @param requestQuery Query to be processed.
* @param requestRepository RequestRepository for accessing requests.
* @param organizationRepository OrganizationRepository for accessing organization.
*/
public void processResponse(Query requestQuery, RequestRepository requestRepository, OrganizationRepository organizationRepository, ProcessingRepository processingRepository) {
this.setUp(requestQuery, requestRepository, organizationRepository, processingRepository);
Data repositoriesData = ((ResponseExternalRepository) this.requestQuery.getQueryResponse()).getData();
super.updateRateLimit(repositoriesData.getRateLimit(), requestQuery.getQueryRequestType());
this.processQueryResponse(repositoriesData.getNodes());
this.processExternalReposAndFindContributors(organization, requestQuery);
super.doFinishingQueryProcedure(this.requestRepository, this.organizationRepository, this.processingRepository, organization, requestQuery, RequestType.EXTERNAL_REPO);
}
/**
* When all requests have been processed, a link is created to other collected information. This is done by linking the external repositories to the contributors.
* @param organization Complete organization object for other data.
* @param requestQuery Processed request query.
*/
protected void processExternalReposAndFindContributors(OrganizationWrapper organization, Query requestQuery) {
if (super.checkIfQueryIsLastOfRequestType(organization, requestQuery, RequestType.EXTERNAL_REPO, this.requestRepository)) {
this.organization.addExternalRepos(this.repositoriesMap);
HashMap<String, ArrayList<String>> externalRepos = super.calculateExternalRepoContributions(organization);
for (String externalRepoID : externalRepos.keySet()) {
for (String contributorID : externalRepos.get(externalRepoID)) {
Repository suitableExternalRepo = organization.getExternalRepos().getOrDefault(externalRepoID, null);
if (suitableExternalRepo != null) {
if (suitableExternalRepo.getContributors() != null) {
suitableExternalRepo.addContributor(organization.getMembers().getOrDefault(contributorID, null));
} else {
ArrayList<Member> contributors = new ArrayList<>();
contributors.add(organization.getMembers().getOrDefault(contributorID, null));
suitableExternalRepo.setContributors(contributors);
}
}
}
}
}
}
/**
* Processes the individual repositories that were returned as replies.
* @param repositories Repositories to be processed
*/
protected void processQueryResponse(ArrayList<NodesRepositories> repositories) {
for (NodesRepositories repo : repositories) {
ArrayList<Calendar> pullRequestDates = new ArrayList<>();
ArrayList<Calendar> issuesDates = new ArrayList<>();
ArrayList<Calendar> commitsDates = new ArrayList<>();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, cal.get(Calendar.DATE) - Config.PAST_DAYS_AMOUNT_TO_CRAWL);
for (NodesPullRequests nodesPullRequests : repo.getPullRequests().getNodes()) {
if (cal.before(nodesPullRequests.getCreatedAt())) {
pullRequestDates.add(nodesPullRequests.getCreatedAt());
}
}
for (NodesIssues nodesIssues : repo.getIssues().getNodes()) {
if (cal.before(nodesIssues.getCreatedAt())) {
issuesDates.add(nodesIssues.getCreatedAt());
}
}
if (repo.getDefaultBranchRef() != null) {
for (NodesHistory nodesHistory : repo.getDefaultBranchRef().getTarget().getHistory().getNodes()) {
commitsDates.add(nodesHistory.getCommittedDate());
}
}
this.repositoriesMap.put(repo.getId(), new Repository()
.setName(repo.getName())
.setUrl(repo.getUrl())
.setDescription(getDescription(repo))
.setProgrammingLanguage(getProgrammingLanguage(repo))
.setLicense(getLicense(repo))
.setForks(repo.getForkCount())
.setStars(repo.getStargazers().getTotalCount())
.setAmountPreviousCommits(commitsDates.size())
.setPreviousCommits(this.generateChartJSData(commitsDates))
.setAmountPreviousIssues(issuesDates.size())
.setPreviousIssues(this.generateChartJSData(issuesDates))
.setAmountPreviousPullRequests(pullRequestDates.size())
.setPreviousPullRequests(this.generateChartJSData(pullRequestDates)));
}
}
protected String getLicense(NodesRepositories repo) {
if (repo.getLicenseInfo() == null) return "No License deposited";
else return repo.getLicenseInfo().getName();
}
protected String getProgrammingLanguage(NodesRepositories repo) {
if (repo.getPrimaryLanguage() == null) return "/";
else return repo.getPrimaryLanguage().getName();
}
protected String getDescription(NodesRepositories repo) {
if (repo.getDescription() == null) return "No Description deposited";
else return repo.getDescription();
}
}
|
package com.fleet.postgis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author April Han
*/
@SpringBootApplication
public class PostGisApplication {
public static void main(String[] args) {
SpringApplication.run(PostGisApplication.class, args);
}
}
|
package com.tencent.mm.compatible.d;
public interface a$a {
void aL(long j);
}
|
package com.sula.service;
import com.fengpei.ioc.AutoInstance;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
@AutoInstance
public interface CreditScoreService {
/**
* 信用积分
*/
public Record getCreditObject();
public boolean modifyCreditObject(boolean flag , Record obj);
public Page<Record> getCreditUser(int page,int creditState);
public boolean modifyAccountState(int id,int state);
}
|
package com.zhowin.miyou.recommend.dialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import com.zhowin.base_library.base.BaseDialogFragment;
import com.zhowin.base_library.utils.ConstantValue;
import com.zhowin.miyou.R;
import com.zhowin.miyou.recommend.callback.OnReportAndAttentionListener;
/**
* author : zho
* date :2020/9/14
* desc : 举报或者关注的dialog
*/
public class ReportAndAttentionDialog extends BaseDialogFragment {
public static ReportAndAttentionDialog newInstance(String userNickNameAndId) {
ReportAndAttentionDialog dialog = new ReportAndAttentionDialog();
Bundle bundle = new Bundle();
bundle.putString(ConstantValue.NAME, userNickNameAndId);
dialog.setArguments(bundle);
return dialog;
}
private TextView tvUserNickNameAndId;
private OnReportAndAttentionListener onReportAndAttentionListener;
private String userNickNameAndId;
@Override
public int getLayoutId() {
return R.layout.include_report_and_attention_dialog;
}
public void setOnReportAndAttentionListener(OnReportAndAttentionListener onReportAndAttentionListener) {
this.onReportAndAttentionListener = onReportAndAttentionListener;
}
@Override
public void initView() {
tvUserNickNameAndId = get(R.id.tvUserNickNameAndId);
get(R.id.tvReport).setOnClickListener(this::onViewClick);
get(R.id.tvAttention).setOnClickListener(this::onViewClick);
get(R.id.tvPullBlack).setOnClickListener(this::onViewClick);
get(R.id.tvShare).setOnClickListener(this::onViewClick);
get(R.id.tvCancel).setOnClickListener(this::onViewClick);
}
@Override
public void initData() {
userNickNameAndId = getArguments().getString(ConstantValue.NAME);
if (!TextUtils.isEmpty(userNickNameAndId))
tvUserNickNameAndId.setText(userNickNameAndId);
}
@Override
public void onViewClick(View view) {
switch (view.getId()) {
case R.id.tvReport:
if (onReportAndAttentionListener != null) {
onReportAndAttentionListener.onItemClick(1);
}
break;
case R.id.tvAttention:
if (onReportAndAttentionListener != null) {
onReportAndAttentionListener.onItemClick(2);
}
break;
case R.id.tvPullBlack:
if (onReportAndAttentionListener != null) {
onReportAndAttentionListener.onItemClick(3);
}
break;
case R.id.tvShare:
if (onReportAndAttentionListener != null) {
onReportAndAttentionListener.onItemClick(4);
}
break;
case R.id.tvCancel:
break;
}
dismiss();
}
}
|
package com.jeecms.cms.manager.main;
import com.jeecms.cms.entity.main.Content;
import com.jeecms.cms.entity.main.ContentDoc;
import com.jeecms.core.entity.CmsUser;
public interface ContentDocMng {
public ContentDoc save(ContentDoc doc, Content content);
public ContentDoc update(ContentDoc doc, Content content);
public ContentDoc operateDocGrain(CmsUser downUser, ContentDoc doc);
public ContentDoc createSwfFile(ContentDoc doc);
}
|
package com.huawei.esdk.tp.professional.local.impl.utils;
public abstract class Base64Utils
{
/**
* 对数据进行Base64编码
*
* @param btData 数据
* @return 以Base64编码的数据
*/
public static String encode(byte[] btData)
{
int iLen = 0;
boolean l_bFlag;
int l_iGroup;
char[] l_szData;
byte[] l_btTmp;
int ii;
int jj;
int kk;
String l_stEncoding = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
if (btData == null)
{
return null;
}
if ((iLen <= 0) || (iLen > btData.length))
{
iLen = btData.length;
}
l_bFlag = ((iLen % 3) == 0);
l_iGroup = iLen / 3;
ii = l_iGroup;
if (!l_bFlag)
{
ii++;
}
l_szData = new char[4 * ii];
l_btTmp = new byte[3];
for (ii = 0, jj = 0, kk = 0; ii < l_iGroup; ii++)
{
l_btTmp[0] = btData[kk++];
l_btTmp[1] = btData[kk++];
l_btTmp[2] = btData[kk++];
l_szData[jj++] = l_stEncoding.charAt((l_btTmp[0] >> 2) & 0x3F);
l_szData[jj++] = l_stEncoding.charAt(((l_btTmp[0] & 0x03) << 4)
| ((l_btTmp[1] >> 4) & 0x0F));
l_szData[jj++] = l_stEncoding.charAt(((l_btTmp[1] & 0x0F) << 2)
| ((l_btTmp[2] >> 6) & 0x03));
l_szData[jj++] = l_stEncoding.charAt(l_btTmp[2] & 0x3F);
}
if (!l_bFlag)
{
l_btTmp[0] = btData[kk++];
l_szData[jj++] = l_stEncoding.charAt((l_btTmp[0] >> 2) & 0x3F);
l_szData[jj + 1] = '=';
l_szData[jj + 2] = '=';
if ((iLen % 3) == 1)
{
l_szData[jj] = l_stEncoding.charAt((l_btTmp[0] & 0x03) << 4);
}
else
// if ((iLen % 3) == 2)
{
l_btTmp[1] = btData[kk];
l_szData[jj++] = l_stEncoding.charAt(((l_btTmp[0] & 0x03) << 4)
| ((l_btTmp[1] >> 4) & 0x0F));
l_szData[jj] = l_stEncoding.charAt((l_btTmp[1] & 0x0F) << 2);
}
}
return new String(l_szData);
}
/**
* 对Base64数据进行解码, 转换失败返回 null
*
* @param stData 数据
* @return 解码后的数据
*/
public static byte[] getFromBASE64(String stData)
{
if (StringUtils.isNullOrEmpty(stData)) {
return null;
}
int l_iLen;
int l_iGroup;
int ii;
int jj;
int kk;
boolean l_bFlag;
char[] l_szTmp;
byte[] l_btData = new byte[0];
l_iLen = stData.length();
if ((l_iLen % 4) != 0)
{
return l_btData;
}
l_iGroup = l_iLen / 4;
ii = l_iGroup * 3;
l_bFlag = true;
l_szTmp = new char[4];
if (stData.charAt(l_iLen - 1) == '=')
{
l_iLen--;
ii--;
l_iGroup--;
l_bFlag = false;
if (stData.charAt(l_iLen - 1) == '=')
{
l_iLen--;
ii--;
}
}
for (jj = 0; jj < l_iLen; jj++)
{
l_szTmp[0] = stData.charAt(jj);
if (!((l_szTmp[0] == '+')
|| (('/' <= l_szTmp[0]) && (l_szTmp[0] <= '9'))
|| (('A' <= l_szTmp[0]) && (l_szTmp[0] <= 'Z')) || (('a' <= l_szTmp[0]) && (l_szTmp[0] <= 'z'))))
{
return l_btData;
}
}
l_btData = new byte[ii];
for (ii = 0, jj = 0, kk = 0; ii < l_iGroup; ii++)
{
l_szTmp[0] = returnToData(stData.charAt(kk++));
l_szTmp[1] = returnToData(stData.charAt(kk++));
l_szTmp[2] = returnToData(stData.charAt(kk++));
l_szTmp[3] = returnToData(stData.charAt(kk++));
l_btData[jj++] = (byte) ((l_szTmp[0] << 2) | ((l_szTmp[1] >> 4) & 0x03));
l_btData[jj++] = (byte) ((l_szTmp[1] << 4) | ((l_szTmp[2] >> 2) & 0x0F));
l_btData[jj++] = (byte) ((l_szTmp[2] << 6) | (l_szTmp[3] & 0x3F));
}
if (!l_bFlag)
{
l_szTmp[0] = returnToData(stData.charAt(kk++));
l_szTmp[1] = returnToData(stData.charAt(kk++));
l_btData[jj++] = (byte) ((l_szTmp[0] << 2) | ((l_szTmp[1] >> 4) & 0x03));
if ((l_iLen % 4) == 3)
{
l_szTmp[2] = returnToData(stData.charAt(kk));
l_btData[jj] = (byte) ((l_szTmp[1] << 4) | ((l_szTmp[2] >> 2) & 0x0F));
}
}
return l_btData;
}
private static char returnToData(char cChar) // cChar 的合法性由 getFromBASE64
// 中的代码保证了
{
if (('A' <= cChar) && (cChar <= 'Z'))
{
cChar -= 'A';
}
else if (('a' <= cChar) && (cChar <= 'z'))
{
cChar -= 'a';
cChar += 26;
}
else if (('0' <= cChar) && (cChar <= '9'))
{
cChar -= '0';
cChar += 52;
}
else if (cChar == '+')
{
cChar = 62;
}
else
// if (cChar == '/')
{
cChar = 63;
}
return cChar;
}
}
|
package com.duofei.command;
import com.duofei.service.ConsumerService;
import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCollapserProperties;
import com.netflix.hystrix.HystrixCommand;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
/**
* 请求合并命令
* @author duofei
* @date 2019/10/28
*/
public class HelloCollapseCommand extends HystrixCollapser<List<String>, String, String> {
private ConsumerService consumerService;
private String name;
public HelloCollapseCommand(ConsumerService consumerService, String name) {
super(Setter.withCollapserKey(HystrixCollapserKey.Factory.asKey("userCollapseCommand"))
.andCollapserPropertiesDefaults(HystrixCollapserProperties.Setter().withTimerDelayInMilliseconds(2000))
.andScope(Scope.GLOBAL)
);
this.consumerService = consumerService;
this.name = name;
}
@Override
public String getRequestArgument() {
return name;
}
@Override
protected HystrixCommand<List<String>> createCommand(Collection<CollapsedRequest<String, String>> collapsedRequests) {
/**
* collapsedRequests 保存了延迟时间窗中收集到的所有获取单个 name 的请求,
* 通过获取这些参数,来组织批量请求命令 HelloBatchCommand 实例
*/
return new HelloBatchCommand(consumerService, collapsedRequests.stream()
.map(CollapsedRequest::getArgument).collect(Collectors.toList()));
}
@Override
protected void mapResponseToRequests(List<String> batchResponse, Collection<CollapsedRequest<String, String>> collapsedRequests) {
int count = 0;
for (CollapsedRequest<String, String> collapsedRequest : collapsedRequests) {
collapsedRequest.setResponse(batchResponse.get(count++));
}
}
}
|
package com.jeysin.concurrency;
/**
* @Author: Jeysin
* @Date: 2019/4/16 12:07
* @Desc: 非公平锁的实现,可能存在线程饿死现象
*/
public class UnfairLock {
private volatile boolean isLocked = false;
private Thread lockingThread = null;
public synchronized void lock() throws InterruptedException{
while(isLocked){
wait();
}
isLocked = true;
lockingThread = Thread.currentThread();
}
public synchronized void unlock(){
if(this.lockingThread != Thread.currentThread()){
throw new IllegalMonitorStateException("Calling thread has not locked this lock");
}
isLocked = false;
lockingThread = null;
notify();
}
}
|
package model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import java.sql.Time;
import java.sql.Date;
@Setter
@Getter
public class Seance extends Entity<Integer> {
private Movie movie;
private Hall hall;
private Date seanceDate;
private Time seanceTime;
private int price;
public Seance(){}
public Seance(Movie movie, Hall hall, Date seanceDate, Time seanceTime, int price){
this.movie=movie;
this.seanceDate=seanceDate;
this.seanceTime=seanceTime;
this.hall=hall;
this.price=price;
}
}
|
package com.penzias.dao;
import com.penzias.core.interfaces.BasicMapper;
import com.penzias.entity.PhysiqueExamInfo;
import com.penzias.entity.PhysiqueExamInfoExample;
public interface PhysiqueExamInfoMapper extends BasicMapper<PhysiqueExamInfoExample, PhysiqueExamInfo>{
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.cmsitems.attributevalidators;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.cms2.servicelayer.services.AttributeDescriptorModelHelperService;
import de.hybris.platform.cmsfacades.common.validator.ValidationErrors;
import de.hybris.platform.cmsfacades.common.validator.ValidationErrorsProvider;
import de.hybris.platform.cmsfacades.uniqueidentifier.UniqueItemIdentifierService;
import de.hybris.platform.cmsfacades.validator.data.ValidationError;
import de.hybris.platform.core.model.ItemModel;
import de.hybris.platform.core.model.type.AttributeDescriptorModel;
import de.hybris.platform.core.model.type.TypeModel;
import java.util.List;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@UnitTest
@RunWith(MockitoJUnitRunner.class)
public class UniqueIdentifierAttributeContentValidatorTest
{
@Mock
private ValidationErrorsProvider validationErrorsProvider;
@Mock
private UniqueItemIdentifierService uniqueItemIdentifierService;
@Mock
private AttributeDescriptorModelHelperService attributeDescriptorModelHelperService;
@InjectMocks
private UniqueIdentifierAttributeContentValidator validator;
@Mock
private ItemModel itemModel;
@Mock
private AttributeDescriptorModel attributeDescriptor;
@Mock
private ValidationErrors validationErrors;
@Before
public void setup()
{
when(validationErrorsProvider.getCurrentValidationErrors()).thenReturn(validationErrors);
}
@Test
public void testWhenUUIDIsValid_shouldNotAddError()
{
when(uniqueItemIdentifierService.getItemModel(any(), any())).thenReturn(Optional.of(itemModel));
validator.validate("", attributeDescriptor);
verifyZeroInteractions(validationErrorsProvider);
}
@Test
public void testWhenUUIDIsInValid_shouldAddError()
{
when(uniqueItemIdentifierService.getItemModel(any(), any())).thenReturn(Optional.empty());
final List<ValidationError> errors = validator.validate("", attributeDescriptor);
assertThat(errors, not(empty()));
}
}
|
package ability.damageAbility;
import map.Square;
import map.Character;
import java.io.File;
import javax.sound.sampled.AudioSystem;
import ability.Ability;
public class Punch extends Ability {
private int damage;
// private String description;
public Punch() {
super("Punch");
setRadius(1);
this.setPaCost(3);
try {
this.setAbilitySound("Sound/PunchSound.wav");
} catch (Exception e) {
System.out.println("Erreur : Son de l'attaque " + this.getName() + " introuvable.");
}
}
public Punch(int damage) {
super("Punch");
this.damage = damage;
setRadius(1);
}
public String getCodex() {
return "ability.damageAbility.Punch" + "-" + damage;
}
public void setDamage(int dmg) {
this.damage = dmg;
}
public void setParameters(String[] parameters) {
if (parameters.length != 1)
System.out.println("Erreur dans setParameters de Punch");
setDamage(Integer.parseInt(parameters[0]));
}
public void use(Square userLocation, Square aim) {
if (range(userLocation, aim)) {
Character p = aim.getCharacter();
this.playAbilitySound();
if (p != null) {
physicalDamage(p, damage);
}
}
}
}
|
package com.tencent.mm.plugin.fav.ui.detail;
import android.widget.ImageView;
import com.tencent.mm.protocal.c.vx;
import com.tencent.mm.ui.tools.k;
class FavoriteImgDetailUI$a {
int bJr;
int bJs;
ImageView bOA;
vx bOz;
k fUH;
final /* synthetic */ FavoriteImgDetailUI jcT;
boolean jda;
String jdb;
private FavoriteImgDetailUI$a(FavoriteImgDetailUI favoriteImgDetailUI) {
this.jcT = favoriteImgDetailUI;
this.fUH = new k(this.jcT.mController.tml);
this.jda = false;
this.jdb = null;
this.bJr = 0;
this.bJs = 0;
}
/* synthetic */ FavoriteImgDetailUI$a(FavoriteImgDetailUI favoriteImgDetailUI, byte b) {
this(favoriteImgDetailUI);
}
}
|
package com.polaris.pay.ui.record;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.polaris.pay.R;
import com.polaris.pay.logic.model.RecordType;
import java.util.ArrayList;
/**
* @Date 2021/2/25 15:19
* @Author toPolaris
* @Description 记录界面中GridView的适配器
*/
public class GridViewAdapter extends BaseAdapter {
final Context context;
/**
* 需要加载的数据
* */
final ArrayList<RecordType> dataList;
/**
* 当前选中的位置,默认为0,即第一个
* */
private int positionSelected;
public GridViewAdapter(Context context, ArrayList<RecordType> dataList, int positionSelected) {
this.context = context;
this.dataList = dataList;
this.positionSelected = positionSelected;
}
public void setPositionSelected(int positionSelected) {
this.positionSelected = positionSelected;
}
@Override
public int getCount() {
return dataList.size();
}
@Override
public RecordType getItem(int position) {
return dataList.get(position);
}
@Override
public long getItemId(int position) {
return dataList.get(position).getId();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = LayoutInflater.from(context).inflate(R.layout.cell_record, parent, false);
TextView textView = convertView.findViewById(R.id.record_gv_item_tv);
ImageView imageView = convertView.findViewById(R.id.record_gv_item_iv);
RecordType recordType = dataList.get(position);
textView.setText(recordType.getTypeName());
if (positionSelected == position) {
imageView.setImageResource(recordType.getImgSelected());
} else {
imageView.setImageResource(recordType.getImg());
}
return convertView;
}
}
|
package com.flute.atp.share.resp;
import com.flute.atp.share.vo.RuleInfo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ObtainRuleGroupResp {
public String gitlab;
public String ruleGroupName;
public String creator;
public Date createTime;
//为简单起见,规则组容纳各种类别的规则
public List<RuleInfo> rules;
}
|
package com.ehootu.park.service.impl;
import com.ehootu.core.util.StringUtils;
import com.ehootu.park.dao.ChemicalsInspectionDao;
import com.ehootu.park.model.ChemicalsInspectionEntity;
import com.ehootu.park.model.PublicInformationEntity;
import com.ehootu.park.service.ChemicalsInspectionService;
import com.ehootu.park.service.PublicInformationService;
import com.ehootu.task.model.TaskExecution;
import com.ehootu.task.service.TaskService;
import com.ehootu.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 易制毒化学品检验表
*
* @author yinyujun
* @email
* @date 2017-09-26 16:27:31
*/
@Service("chemicalsInspectionService")
public class ChemicalsInspectionServiceImpl implements ChemicalsInspectionService {
@Autowired
private ChemicalsInspectionDao chemicalsInspectionDao;
@Autowired
private PublicInformationService publicInformationService;
@Autowired
private UserService userService;
@Autowired
private TaskService taskService;
@Override
public ChemicalsInspectionEntity queryObject(String id){
ChemicalsInspectionEntity entity = chemicalsInspectionDao.queryObject(id);
// 检查人员
String policeName = userService.findPoliceNameById(entity.getInspectors());
entity.setInspectorsName(policeName);
return entity;
}
@Override
public List<ChemicalsInspectionEntity> queryList(Map<String, Object> map){
return chemicalsInspectionDao.queryList(map);
}
@Override
public int queryTotal(Map<String, Object> map){
return chemicalsInspectionDao.queryTotal(map);
}
@Override
public void save(ChemicalsInspectionEntity chemicalsInspection){
chemicalsInspectionDao.save(chemicalsInspection);
}
@Override
public void update(ChemicalsInspectionEntity chemicalsInspection){
chemicalsInspectionDao.update(chemicalsInspection);
}
@Override
public void delete(String id){
chemicalsInspectionDao.delete(id);
}
@Override
public void deleteBatch(Integer[] ids){
chemicalsInspectionDao.deleteBatch(ids);
}
@Override
public List<ChemicalsInspectionEntity> select(String id) {
return chemicalsInspectionDao.select(id);
}
@Override
public List<ChemicalsInspectionEntity> selectOne(String dizhibianma) {
return chemicalsInspectionDao.selectOne(dizhibianma);
}
@Override
public List<ChemicalsInspectionEntity> selectAddress(String enterprise_address) {
return chemicalsInspectionDao.selectAddress(enterprise_address);
}
@Override
public void save(ChemicalsInspectionEntity chemicalsInspection, PublicInformationEntity publicInformation, String pageName) {
// 更新添加企业基本信息
String publicId = publicInformationService.saveUpdate(publicInformation);
// 添加 剧毒、易制毒化学品专项检查信息
chemicalsInspection.setInspectionTime(new Date());
chemicalsInspection.setDate(new Date());
chemicalsInspection.setPublicId(publicId);
// 将数组类型参数(检查人)转换为字符串
String inspectors = StringUtils.customConcat(chemicalsInspection.getInspectors());
chemicalsInspection.setInspectors(inspectors);
chemicalsInspectionDao.saveAndGetId(chemicalsInspection);
// 关联任务中间表
if (chemicalsInspection.getTaskId()!=null) {
TaskExecution taskExecution = new TaskExecution();
taskExecution.setTaskId(chemicalsInspection.getTaskId());
taskExecution.setTableId(chemicalsInspection.getId());
taskExecution.setTableName("chemicals_inspection");
taskExecution.setSonTaskName("剧毒、易制毒化学品专项检查");
taskExecution.setPageName(pageName);
taskExecution.setExecutorIds(chemicalsInspection.getInspectors());
taskExecution.setCreateTime(new Date());
taskService.createTaskExecution(taskExecution);
}
}
}
|
/*******************************************************************************
* Copyright (c) 2008-2010 Sonatype, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Sonatype, Inc. - initial API and implementation
*******************************************************************************/
package org.maven.ide.eclipse.pr.internal.sources;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import org.apache.maven.model.io.xpp3.MavenXpp3Writer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.m2e.core.project.IMavenProjectFacade;
import org.eclipse.m2e.core.project.MavenProjectManager;
import org.eclipse.osgi.util.NLS;
import org.maven.ide.eclipse.pr.IDataSource;
import org.maven.ide.eclipse.pr.internal.Messages;
import org.maven.ide.eclipse.pr.internal.ProblemReportingPlugin;
/**
* Returns the effective POM for a project.
*/
public class EffectivePomSource implements IDataSource {
private final MavenProjectManager mavenProjectManager;
private final IFile file;
private final IProgressMonitor monitor;
public EffectivePomSource(MavenProjectManager mavenProjectManager, IFile file, IProgressMonitor monitor) {
this.mavenProjectManager = mavenProjectManager;
this.file = file;
this.monitor = monitor;
}
public InputStream getInputStream() throws CoreException {
IMavenProjectFacade projectFacade;
try {
projectFacade = mavenProjectManager.create(file, true, monitor);
} catch(Exception ex) {
throw new CoreException(new Status(IStatus.ERROR, ProblemReportingPlugin.PLUGIN_ID, -1, //
NLS.bind(Messages.EffectivePomSource_error1, file.getLocation()), ex));
}
if(projectFacade == null) {
throw new CoreException(new Status(IStatus.ERROR, ProblemReportingPlugin.PLUGIN_ID, -1, //
NLS.bind(Messages.EffectivePomSource_error2, file.getLocation()), null));
}
StringWriter sw = new StringWriter();
try {
new MavenXpp3Writer().write(sw, projectFacade.getMavenProject(monitor).getModel());
} catch(IOException ex) {
throw new CoreException(new Status(IStatus.ERROR, ProblemReportingPlugin.PLUGIN_ID, -1, //
NLS.bind(Messages.EffectivePomSource_error3, file.getLocation()), ex));
}
return new ByteArrayInputStream(sw.getBuffer().toString().getBytes());
}
public String getName() {
return "pom-effective.pom"; //$NON-NLS-1$
}
}
|
public class PermutationOfString {
public void permutation(String str) {
doPermutation("", str);
}
private void doPermutation(String prefix, String str) {
int n = str.length();
if (n == 0) {
System.out.println(prefix);
} else {
for (int i = 0; i < n; i++) {
doPermutation(prefix+str.charAt(i),
str.substring(0, i) + str.substring(i+1, n));
}
}
}
public static void main(String[] args) {
PermutationOfString sol = new PermutationOfString();
String[] strs = {
"",
"a",
"abc",
"aac",
};
int count = strs.length;
for (int i = 0; i < count; i++) {
System.out.println("==== permutation of " + strs[i] + " ====");
sol.permutation(strs[i]);
}
}
}
|
package de.zarncke.lib.cache;
import java.util.Map;
final class StringMapUsage extends AbstractMapUsage {
private static final int BYTES_PER_STRING_OBJECT = 32;
StringMapUsage(final Map<?, String> map, final String name) {
super(map, name);
}
@Override
public int getTypicalObjectSize() {
int n = this.map.size();
if (n == 0) {
return BYTES_PER_STRING_OBJECT;
}
n = (int) Math.sqrt(n);
int t = 0;
int i = 0;
for (String s : ((Map<?, String>) this.map).values()) {
t += s.length() * 2 + BYTES_PER_STRING_OBJECT;
if (i++ > n) {
break;
}
}
return t / n;
}
}
|
package com.duanxr.yith.midium;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
/**
* @author 段然 2021/8/2
*/
public class NetworkDelayTime {
/**
* You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target.
*
* We will send a signal from a given node k. Return the time it takes for all the n nodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1.
*
*
*
* Example 1:
*
*
* Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
* Output: 2
* Example 2:
*
* Input: times = [[1,2,1]], n = 2, k = 1
* Output: 1
* Example 3:
*
* Input: times = [[1,2,1]], n = 2, k = 2
* Output: -1
*
*
* Constraints:
*
* 1 <= k <= n <= 100
* 1 <= times.length <= 6000
* times[i].length == 3
* 1 <= ui, vi <= n
* ui != vi
* 0 <= wi <= 100
* All the pairs (ui, vi) are unique. (i.e., no multiple edges.)
*
* 有 n 个网络节点,标记为 1 到 n。
*
* 给你一个列表 times,表示信号经过 有向 边的传递时间。 times[i] = (ui, vi, wi),其中 ui 是源节点,vi 是目标节点, wi 是一个信号从源节点传递到目标节点的时间。
*
* 现在,从某个节点 K 发出一个信号。需要多久才能使所有节点都收到信号?如果不能使所有节点收到信号,返回 -1 。
*
*
*
* 示例 1:
*
*
*
* 输入:times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
* 输出:2
* 示例 2:
*
* 输入:times = [[1,2,1]], n = 2, k = 1
* 输出:1
* 示例 3:
*
* 输入:times = [[1,2,1]], n = 2, k = 2
* 输出:-1
*
*
* 提示:
*
* 1 <= k <= n <= 100
* 1 <= times.length <= 6000
* times[i].length == 3
* 1 <= ui, vi <= n
* ui != vi
* 0 <= wi <= 100
* 所有 (ui, vi) 对都 互不相同(即,不含重复边)
*
*/
class Solution {
public int networkDelayTime(int[][] times, int n, int k) {
Map<Integer, List<int[]>> pathMap = new HashMap<>(times.length);
for (int[] time : times) {
pathMap.computeIfAbsent(time[0], key -> new ArrayList<>()).add(time);
}
int[] timeMap = new int[n + 1];
Arrays.fill(timeMap, Integer.MAX_VALUE);
int maxTime = 0;
Queue<Integer> currentNodes = new ArrayDeque<>();
currentNodes.add(k);
timeMap[k] = 0;
while (!currentNodes.isEmpty()) {
int size = currentNodes.size();
for (int i = 0; i < size; i++) {
Integer node = currentNodes.poll();
List<int[]> nextNodes = pathMap.get(node);
if (nextNodes != null) {
for (int[] nextNode : nextNodes) {
if (nextNode != null) {
int nt = nextNode[2] + timeMap[nextNode[0]];
if (nt < timeMap[nextNode[1]]) {
timeMap[nextNode[1]] = nt;
currentNodes.offer(nextNode[1]);
}
}
}
}
}
}
for (int i = 1; i < timeMap.length; i++) {
if (i != k) {
if (timeMap[i] == Integer.MAX_VALUE) {
return -1;
}
if (timeMap[i] > maxTime) {
maxTime = timeMap[i];
}
}
}
return maxTime;
}
}
}
|
package SukerEditor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.StyledTextPrintOptions;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.events.ShellListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.printing.Printer;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.wb.swt.SWTResourceManager;
import swing2swt.layout.BorderLayout;
public class SukerEditor_MainCls {
protected static Shell shell;
protected static CTabFolder tabEditFrame;
private String strOpenFolderPath;
private String strSaveFolderPath;
private ComboViewer comboViewer;
private Combo cbKeyWord;
private List<MenuItem> mMenuItemList = new ArrayList<MenuItem>();
private List<CTabItem> mTabItemList = new ArrayList<CTabItem>();
private SukerEditor_TabManager tabManager;
private SukerEditor_FileControl fileHandler;
private SukerEditor_MenuDlg menuDlg;
private Text text1;
private Text text2;
private Text text3;
private Text text4;
private Label lblCurrentFilePathName;
private Menu menu_Popup;
private MenuItem mntmPopupMenu_Save;
private MenuItem mntmPopupMenu_SaveAs;
private MenuItem mntmPopupMenu_Close;
private MenuItem mntmPopupMenu_CloseAll;
private StyledTextPrintOptions styledTextOptions;
private Printer printer;
/**
* Launch the application.
* @param args
*/
public static void main(String[] args) {
try {
SukerEditor_MainCls window = new SukerEditor_MainCls();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
* @throws Exception
*/
public void open() throws Exception {
Display display = Display.getDefault();
createContents();
initWindowSetting();
ShellListener shellListener = new ShellListener()
{
@Override
public void shellActivated(ShellEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void shellClosed(ShellEvent arg0) {
tabManager.refreshWorkedFilePathList();
__onDestoy();
}
@Override
public void shellDeactivated(ShellEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void shellDeiconified(ShellEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void shellIconified(ShellEvent arg0) {
// TODO Auto-generated method stub
}
};
shell.addShellListener(shellListener);
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
if (printer != null)
printer.dispose();
System.exit(0);
}
/**
* Create contents of the window.
*/
protected void createContents() {
shell = new Shell();
shell.setSize(1200, 800);
shell.setText("SWT Application");
shell.setLayout(new BorderLayout(0, 0));
{
//---------------------------------------------------Upper Group----------------------------------------------------------
Group grpKeywordInput = new Group(shell, SWT.NONE);
grpKeywordInput.setLayoutData(BorderLayout.NORTH);
grpKeywordInput.setLayout(new GridLayout(8, false));
Label lblSearchKeywords = new Label(grpKeywordInput, SWT.NONE);
lblSearchKeywords.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
lblSearchKeywords.setText("Search Keywords");
Button btnTextClear = new Button(grpKeywordInput, SWT.NONE);
btnTextClear.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
text1.setText("");
text2.setText("");
text3.setText("");
text4.setText("");
}
});
btnTextClear.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1));
btnTextClear.setText("Text Field Clear");
Button btnComboClear = new Button(grpKeywordInput, SWT.NONE);
btnComboClear.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
cbKeyWord.removeAll();
}
});
btnComboClear.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
btnComboClear.setText("ComboBox Clear");
Button btnDo = new Button(grpKeywordInput, SWT.NONE);
btnDo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String[] textList = {text1.getText(), text2.getText(), text3.getText(), text4.getText()};
updateComboList(textList);
SukerEditor_TextFieldControl textControl;
textControl = tabManager.getHashMapForCurrentWorkingStyledText(tabEditFrame.getSelection().getText());
textControl.setKeywords(textList);
textControl.refresh();
textControl.getCurrentTextHandle().setFocus();
}
});
btnDo.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, false, 1, 2));
btnDo.setText("Search Go");
Button btnCheckButton_ShowLineNum = new Button(grpKeywordInput, SWT.CHECK);
btnCheckButton_ShowLineNum.setEnabled(false);
btnCheckButton_ShowLineNum.setText("Show Line Number");
Button btnNewButton = new Button(grpKeywordInput, SWT.NONE);
btnNewButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
tabEditFrame.setSelection(tabManager.addTabList(tabEditFrame));
tabManager.setActiveTabIndex(tabEditFrame.getSelectionIndex());
SukerEditor_StatusBarDisplay.updateName("");
}
});
btnNewButton.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, false, false, 1, 2));
btnNewButton.setText("NewTab");
text1 = new Text(grpKeywordInput, SWT.BORDER);
text1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
text2 = new Text(grpKeywordInput, SWT.BORDER);
text2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
text3 = new Text(grpKeywordInput, SWT.BORDER);
text3.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
text4 = new Text(grpKeywordInput, SWT.BORDER);
text4.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
/*ModifyListener listener = new ModifyListener() {
public void modifyText(ModifyEvent e) {
}
};
text1.addModifyListener(listener);
text2.addModifyListener(listener);
text3.addModifyListener(listener);
text4.addModifyListener(listener);*/
comboViewer = new ComboViewer(grpKeywordInput, SWT.NONE);
cbKeyWord = comboViewer.getCombo();
cbKeyWord.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
int text1Length = text1.getText().length();
int text2Length = text2.getText().length();
int text3Length = text3.getText().length();
int text4Length = text4.getText().length();
int selectIndex = cbKeyWord.getSelectionIndex();
String selectStr = cbKeyWord.getItem(selectIndex);
if (text1Length < 1)
text1.setText(selectStr);
else if (text2Length < 1)
text2.setText(selectStr);
else if (text3Length < 1)
text3.setText(selectStr);
else if (text4Length < 1)
text4.setText(selectStr);
else
;
}
});
cbKeyWord.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
Button btnCheckButton = new Button(grpKeywordInput, SWT.CHECK);
btnCheckButton.setEnabled(false);
btnCheckButton.setText("TBD");
}
lblCurrentFilePathName = new Label(shell, SWT.NONE);
lblCurrentFilePathName.setLayoutData(BorderLayout.SOUTH);
lblCurrentFilePathName.setText("CurrentFilePath");
//---------------------------------------------------TabFolder----------------------------------------------------------
tabEditFrame = new CTabFolder(shell, SWT.BORDER);// | SWT.CLOSE | SWT.FLAT);
tabEditFrame.setFont(SWTResourceManager.getFont("Courier New", 10, SWT.NORMAL));
tabEditFrame.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
if (e.button == 3) { //right-click
CTabFolder tabFolder = (CTabFolder)e.widget;
CTabItem tabItem = tabFolder.getItem(new Point(e.x, e.y));
if (tabItem == null) {
mntmPopupMenu_Save.setEnabled(false);
mntmPopupMenu_SaveAs.setEnabled(false);
mntmPopupMenu_Close.setEnabled(false);
}
else {
mntmPopupMenu_Save.setEnabled(true);
mntmPopupMenu_SaveAs.setEnabled(true);
mntmPopupMenu_Close.setEnabled(true);
tabFolder.setSelection(tabItem);
if (!tabManager.getHashMapForCurrentWorkingFilesStatus(tabItem.getText()))
SukerEditor_StatusBarDisplay.updateName("");
else
SukerEditor_StatusBarDisplay.updateName(tabManager.getHashMapForCurrentWorkingFilesPath(tabItem.getText()));
}
} else { //left-click
int currentIndex = tabEditFrame.getSelectionIndex();
if (tabManager.getActiveTabIndex() != currentIndex) {
CTabItem tabItem = tabEditFrame.getSelection();
tabManager.setActiveTabIndex(currentIndex);
if (!tabManager.getHashMapForCurrentWorkingFilesStatus(tabItem.getText()))
SukerEditor_StatusBarDisplay.updateName("");
else
SukerEditor_StatusBarDisplay.updateName(tabManager.getHashMapForCurrentWorkingFilesPath(tabItem.getText()));
}
}
}
});
tabEditFrame.setLayoutData(BorderLayout.CENTER);
tabEditFrame.setSelectionBackground(Display.getCurrent().getSystemColor(SWT.COLOR_TITLE_INACTIVE_BACKGROUND_GRADIENT));
tabEditFrame.setSimple(false);
tabEditFrame.setUnselectedImageVisible(false);
tabEditFrame.setUnselectedCloseVisible(false);
tabEditFrame.setFocus();
/* CTabItem tbtmDefault = new CTabItem(tabEditFrame, SWT.CLOSE);
tbtmDefault.setFont(SWTResourceManager.getFont("±¼¸²", 10, SWT.BOLD));
tbtmDefault.setShowClose(true);
tbtmDefault.setText("Default");
StyledText styledText_default = new StyledText(tabEditFrame, SWT.MULTI | SWT.WRAP | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
styledText_default.setFont(SWTResourceManager.getFont("Courier New", 11, SWT.NORMAL));
styledText_default.setTopMargin(5);
styledText_default.setRightMargin(10);
styledText_default.setLeftMargin(5);
styledText_default.setText("test test");
styledText_default.setBlockSelection(true);
tbtmDefault.setControl(styledText_default);
mTabItemList.add(tbtmDefault);*/
//---------------------------------------------------Final----------------------------------------------------------
fileHandler = new SukerEditor_FileControl();
tabManager = new SukerEditor_TabManager(shell, mTabItemList, fileHandler, mMenuItemList);
tabManager.createDragTarget(tabEditFrame);
menuDlg = new SukerEditor_MenuDlg();
new SukerEditor_StatusBarDisplay(lblCurrentFilePathName);
//-----------------------------------------------------------------------------------------------------------------
//---------------------------------------------------Popup Menu----------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------
menu_Popup = new Menu(tabEditFrame);
//menu_Popup.setEnabled(false);
tabEditFrame.setMenu(menu_Popup);
mntmPopupMenu_Save = new MenuItem(menu_Popup, SWT.NONE);
mntmPopupMenu_Save.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
saveTab();
}
});
mntmPopupMenu_Save.setText("Save");
mntmPopupMenu_SaveAs = new MenuItem(menu_Popup, SWT.NONE);
mntmPopupMenu_SaveAs.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
saveAsTab();
}
});
mntmPopupMenu_SaveAs.setText("Save As ...");
new MenuItem(menu_Popup, SWT.SEPARATOR);
mntmPopupMenu_Close = new MenuItem(menu_Popup, SWT.NONE);
mntmPopupMenu_Close.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
tabManager.removeTabInList(tabEditFrame.getSelection().getText());
tabEditFrame.getSelection().getControl().dispose();
tabEditFrame.getSelection().dispose();
}
});
mntmPopupMenu_Close.setText("Close");
mntmPopupMenu_CloseAll = new MenuItem(menu_Popup, SWT.NONE);
mntmPopupMenu_CloseAll.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
tabManager.removeAllTabInList();
}
});
mntmPopupMenu_CloseAll.setText("Close All");
tabManager.setActiveTabIndex(-1);
//-----------------------------------------------------------------------------------------------------------------
//---------------------------------------------------Menu Bar------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------
Menu menu = new Menu(shell, SWT.BAR);
shell.setMenuBar(menu);
MenuItem mntmFile = new MenuItem(menu, SWT.CASCADE);
mntmFile.setText("File");
Menu menu_File = new Menu(mntmFile);
mntmFile.setMenu(menu_File);
MenuItem mntmFile_Open = new MenuItem(menu_File, SWT.NONE);
mntmFile_Open.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String temp;
temp = menuDlg.OpenFile(strOpenFolderPath);
if (temp != null && temp.length() > 1)
strOpenFolderPath = temp;
String textInitValue = null;
try {
textInitValue = fileHandler.readFileByBurst(strOpenFolderPath);
} catch (Exception e2) {
e2.printStackTrace();
}
tabEditFrame.setSelection(tabManager.addTabList(tabEditFrame, strOpenFolderPath, textInitValue, true));
SukerEditor_StatusBarDisplay.updateName(strOpenFolderPath);
}
});
mntmFile_Open.setText("Open File... Ctrl+O");
mntmFile_Open.setAccelerator(SWT.CTRL + 'o');
new MenuItem(menu_File, SWT.SEPARATOR);
MenuItem mntmFile_Close = new MenuItem(menu_File, SWT.NONE);
mntmFile_Close.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
tabManager.removeTabInList(tabEditFrame.getSelection().getText());
tabEditFrame.getSelection().getControl().dispose();
tabEditFrame.getSelection().dispose();
}
});
mntmFile_Close.setEnabled(false);
mntmFile_Close.setText("Close Ctrl+Q");
mntmFile_Close.setAccelerator(SWT.CTRL + 'q');
mMenuItemList.add(mntmFile_Close);
MenuItem mntmFile_CloseAll = new MenuItem(menu_File, SWT.NONE);
mntmFile_CloseAll.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
tabManager.removeAllTabInList();
}
});
mntmFile_CloseAll.setEnabled(false);
mntmFile_CloseAll.setText("Close All Ctrl+Alt+Q");
mMenuItemList.add(mntmFile_CloseAll);
new MenuItem(menu_File, SWT.SEPARATOR);
MenuItem mntmFile_Save = new MenuItem(menu_File, SWT.NONE);
mntmFile_Save.setEnabled(false);
mntmFile_Save.setAccelerator(SWT.CTRL + 's');
mntmFile_Save.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
saveTab();
}
});
mntmFile_Save.setText("Save Ctrl+S");
mMenuItemList.add(mntmFile_Save);
MenuItem mntmFile_SaveAs = new MenuItem(menu_File, SWT.NONE);
mntmFile_SaveAs.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
saveAsTab();
}
});
mntmFile_SaveAs.setEnabled(false);
mntmFile_SaveAs.setText("Save As...");
mMenuItemList.add(mntmFile_SaveAs);
new MenuItem(menu_File, SWT.SEPARATOR);
MenuItem mntmFile_Print = new MenuItem(menu_File, SWT.NONE);
mntmFile_Print.setEnabled(false);
mntmFile_Print.setText("Print... Ctrl+P");
mMenuItemList.add(mntmFile_Print);
new MenuItem(menu_File, SWT.SEPARATOR);
MenuItem mntmFile_Exit = new MenuItem(menu_File, SWT.NONE);
mntmFile_Exit.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
shell.close();
}
});
mntmFile_Exit.setText("E&xit");
mntmFile_Exit.setAccelerator(SWT.CTRL + 'x');
MenuItem mntmHelp = new MenuItem(menu, SWT.CASCADE);
mntmHelp.setText("Help");
Menu menu_Help = new Menu(mntmHelp);
mntmHelp.setMenu(menu_Help);
MenuItem mntmHelp_About = new MenuItem(menu_Help, SWT.NONE);
mntmHelp_About.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
SukerEditor_AboutDialog aboutDlg = new SukerEditor_AboutDialog(shell, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
aboutDlg.open();
}
});
mntmHelp_About.setText("About");
}
private void saveTab() {
CTabItem currentItem = tabEditFrame.getSelection();
String itemName = currentItem.getText();
Boolean isNewTab = !(tabManager.getHashMapForCurrentWorkingFilesStatus(itemName));
if (isNewTab) {
String temp = menuDlg.SaveFile(strSaveFolderPath);
if (temp != null && temp.length() > 1) {
SukerEditor_TextFieldControl sTextTemp;
strSaveFolderPath = temp;
sTextTemp = tabManager.getHashMapForCurrentWorkingStyledText(itemName);
tabManager.updateTabStatusInList(currentItem, strSaveFolderPath, itemName, SukerEditor_FileControl.getOnlyFileName(strSaveFolderPath), true, sTextTemp);
fileHandler.saveFileForText(shell, strSaveFolderPath, ((StyledText)currentItem.getControl()).getText());
tabManager.updateHashMapForCurrentWorkingEdited(currentItem, true);
}
} else {
String fullPath = tabManager.getHashMapForCurrentWorkingFilesPath(itemName);
fileHandler.saveFileForText(shell, fullPath, ((StyledText)currentItem.getControl()).getText());
tabManager.updateHashMapForCurrentWorkingEdited(currentItem, true);
}
}
private void saveAsTab() {
CTabItem currentItem = tabEditFrame.getSelection();
String itemName = currentItem.getText();
String temp = menuDlg.SaveFile(strSaveFolderPath);
if (temp != null && temp.length() > 1) {
SukerEditor_TextFieldControl sTextTemp;
strSaveFolderPath = temp;
sTextTemp = tabManager.getHashMapForCurrentWorkingStyledText(itemName);
tabManager.updateTabStatusInList(currentItem, strSaveFolderPath, itemName, SukerEditor_FileControl.getOnlyFileName(strSaveFolderPath), true, sTextTemp);
fileHandler.saveFileForText(shell, strSaveFolderPath, ((StyledText)currentItem.getControl()).getText());
tabManager.updateHashMapForCurrentWorkingEdited(currentItem, true);
}
}
/*public void print() {
SukerEditor_TextFieldControl sTextTemp;
CTabItem currentItem = tabEditFrame.getSelection();
String itemName = currentItem.getText();
sTextTemp = tabManager.getHashMapForCurrentWorkingStyledText(itemName);
styledTextOptions = new StyledTextPrintOptions();
styledTextOptions.footer = StyledTextPrintOptions.SEPARATOR + StyledTextPrintOptions.PAGE_TAG
+ StyledTextPrintOptions.SEPARATOR + "Confidential";
if (printer == null)
printer = new Printer();
styledTextOptions.header = StyledTextPrintOptions.SEPARATOR + filename + StyledTextPrintOptions.SEPARATOR;
(sTextTemp.getCurrentTextHandle()).print(printer, styledTextOptions).run();
}*/
public static Shell getShellInstance() {
return shell;
}
private void initWindowSetting() throws Exception {
String resultStr = "";
List<String> readList;
String[] comboFillList;
strOpenFolderPath = "";
strSaveFolderPath = "";
readList = SukerEditor_INIFile.readFile(SukerEditor_INIFile.INI_FILE_PATH);
if (readList != null){
strSaveFolderPath = SukerEditor_INIFile.readIniFile(readList, "LOGEDITOR_SAVE_FOLDER_PATH");
strOpenFolderPath = SukerEditor_INIFile.readIniFile(readList, "LOGEDITOR_OPEN_FOLDER_PATH");
resultStr = SukerEditor_INIFile.readIniFile(readList, "LOGEDITOR_KEYWORDS");
if (resultStr != null && resultStr.length() > 1) {
comboFillList = resultStr.split(",");
comboViewer.add(comboFillList);
//cbKeyWord.select(0);
}
/*if (SukerEditor_INIFile.readIniFile(readList, "LOGEDITOR_COMBOMULTISELECT").equals("true"))
comboSelectMultiOn = true;
else
comboSelectMultiOn = false;
btnCheckButton.setSelection(comboSelectMultiOn); */
int workedFileCount;
String temp = SukerEditor_INIFile.readIniFile(readList, "LOGEDITOR_WORKEDFILECOUNT");
if (temp == null || temp.length() < 1)
workedFileCount = 0;
else
workedFileCount = Integer.parseInt(temp);
for(int i = 0; i < workedFileCount; i++) {
resultStr = SukerEditor_INIFile.readIniFile(readList, "LOGEDITOR_WORKEDFILEPATHLIST"+i);
if (resultStr != null && resultStr.length() > 1) {
tabManager.setWorkedFilePathList(resultStr);
}
}
}
}
public void __onDestoy() {
List<String> writeList = new ArrayList<String>();
String comboStr;
if (strSaveFolderPath.length() <= 1)
strSaveFolderPath = "";
SukerEditor_INIFile.writeIniFile("LOGEDITOR_SAVE_FOLDER_PATH", fileHandler.getOnlyFolderName(strSaveFolderPath), writeList);
if (strOpenFolderPath.length() <= 1)
strOpenFolderPath = "";
SukerEditor_INIFile.writeIniFile("LOGEDITOR_OPEN_FOLDER_PATH", fileHandler.getOnlyFolderName(strOpenFolderPath), writeList);
//comboStr = LogViewer_INIFile.makeComboList(mComboList);
comboStr = SukerEditor_INIFile.makeComboList(cbKeyWord);
if (comboStr.length() > 0)
SukerEditor_INIFile.writeIniFile("LOGEDITOR_KEYWORDS", comboStr, writeList);
/*if (comboSelectMultiOn)
SukerEditor_INIFile.writeIniFile("LOGEDITOR_COMBOMULTISELECT", "true", writeList);
else
SukerEditor_INIFile.writeIniFile("LOGEDITOR_COMBOMULTISELECT", "false", writeList);*/
int workedFilePathListSize = tabManager.getWorkdedFilePathList().size();
SukerEditor_INIFile.writeIniFile("LOGEDITOR_WORKEDFILECOUNT", String.valueOf(workedFilePathListSize), writeList);
for (int i = 0; i < workedFilePathListSize; i++) {
String temp = "";
temp = tabManager.getWorkdedFilePathList().get(i).toString();
if (temp.length() > 0)
SukerEditor_INIFile.writeIniFile("LOGEDITOR_WORKEDFILEPATHLIST"+i, temp, writeList);
}
__finallyIniFileWrite(writeList);
}
private void __finallyIniFileWrite(List<String> writeList) {
try {
SukerEditor_INIFile.writeFile(writeList, SukerEditor_INIFile.INI_FILE_PATH);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void updateComboList(String[] textList) {
List<String> tempStrList = new ArrayList<String>();
int comboSize = this.cbKeyWord.getItemCount();
int nonEmptyTextCnt = textList.length;
for(int i = 0; i < comboSize; i++) {
tempStrList.add(i, this.cbKeyWord.getItem(i));
}
for(int i = 0; i < nonEmptyTextCnt; i++) {
if (textList[i].length() > 0) {
if (!tempStrList.contains(textList[i])) {
this.cbKeyWord.add(textList[i]);
}
}
}
}
}
|
package com.williamlabrum.cucumber;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;
/**
* use the following to run only specific tests from the command line:
* <ul>
* <li><strong>Test only desired tags:</strong>
* <pre>mvn test -Dskip.bdd.tests=false -Dcucumber.options="--tags @tagname1 @tagname2"</pre></li>
*
* <li><strong>Test only desired tags but not undesired tags:</strong>
* <pre>mvn test -Dskip.bdd.tests=false -Dcucumber.options="--tags @tagname1 --tags ~@tagname2"</pre>
*
* </li><li><strong>Test only desired features:</strong>
* <pre>mvn test -Dskip.bdd.tests=false -Dcucumber.options="--name featureName"</pre></li></ul>
*/
@RunWith(Cucumber.class)
@CucumberOptions(format = { "pretty", "html:target/cucumber", "json:target/cucumber.json" }, tags = { "~@in-progress", "~@skip"})
public class TestDriver {
}
|
package com.tyss.cg.repository;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Scanner;
public class test {
static void test() {
Users.UserTable();
BeanClass bean1 = new BeanClass();
Scanner scanner = new Scanner(System.in);
HashMap< String, Object> hsHashMap= new LinkedHashMap<String, Object>();
System.out.println("enter userid");
String userid = scanner.nextLine();
bean1.setUserid(userid);
hsHashMap.put("userid",userid );
Users.adminList.add(hsHashMap);
for (int i = 0; i < Users.adminList.size(); i++) {
System.out.println(Users.adminList.get(i));
}
}
public static void main(String[] args) {
test();
}
}
|
package app;
import javax.swing.*;
import java.io.Serializable;
public class Grade implements Serializable {
DefaultListModel<Double> grades;
public Grade (){
grades = new DefaultListModel<>();
}
public static double generateAverageGrade(DefaultListModel<Double> grades){
double avg=0;
for (int i=0; i<grades.size(); i++){
avg += grades.get(i);
}
avg = avg/grades.size();
return avg;
}
}
|
import java.util.concurrent.*;
public class Main {
static int hydrogenCount = 0;
static Phaser phaserBlock = new Phaser(4);
static int phase;
static boolean end = false;
public static void main(String[] args) {
ExecutorService HydrogenEX = Executors.newSingleThreadExecutor();
ExecutorService OxygenEx = Executors.newSingleThreadExecutor();
phase = phaserBlock.getPhase();
OxygenEx.execute(() -> releaseOxygen());
HydrogenEX.execute(() -> releaseHydrogen());
for (; ; ) {
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (phaserBlock.getArrivedParties() == 3) {
System.out.print(", ");
phaserBlock.arrive();
if (phase > 2) {
end = true;
break;
}
}
phase = phaserBlock.getPhase();
}
OxygenEx.shutdown();
HydrogenEX.shutdown();
}
static void releaseOxygen() {
for (; ; ) {
if (end) {
break;
}
System.out.print("O");
phaserBlock.arriveAndAwaitAdvance();
}
}
static void releaseHydrogen() {
for (; ; ) {
hydrogenCount++;
if (end) {
break;
}
if (hydrogenCount == 2) {
System.out.print("H");
hydrogenCount = 0;
phaserBlock.arriveAndAwaitAdvance();
} else {
System.out.print("H");
phaserBlock.arrive();
}
}
}
}
|
package theekransje.douaneapp.Domain;
import java.io.Serializable;
/**
* Created by Sander on 5/24/2018.
*/
public class Driver implements Serializable {
private static final String TAG = "Driver";
private String uid;
private String userName;
private String passwd;
private String IMEIHash;
private String lastName;
private String firstName;
private String token;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public String getIMEIHash() {
return IMEIHash;
}
public void setIMEIHash(String IMEIHash) {
this.IMEIHash = IMEIHash;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
}
|
package pl.finsys.helloWorld;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pl.finsys.testHello.TestHelloNumberGiver;
import static org.junit.Assert.assertEquals;
/**
*
*
* @author jarek@finsys.pl
*/
public class HelloWorldTest {
@BeforeClass()
public static void runBeforeClass() throws Exception {
}
@Before()
public void runBeforeTest() throws Exception {
}
@Test
public void testHelloWorld() throws Exception {
// given
ApplicationContext context = new ClassPathXmlApplicationContext("...");
TestHelloNumberGiver bean = (TestHelloNumberGiver) context.getBean("numberGiver");
// when
int a = bean.gimmeNumber();
//then
assertEquals(2014, a);
}
}
|
package org.firstinspires.ftc.teamcode;
/**
* Created by USER on 10/26/2016.
*/
/**@Autonomous(name="Autonomous Tester", group="Test")
public class AutonomousTest extends AutonomousBase{
public void gameState() {
super.gameState();
switch(gameState){
case 0:
if(!gyro.isCalibrating()){
gameState = 1;
}
break;
case 1:
map.setGoal(6,9);
if(linedUp()){
moveState = MoveState.FORWARD;
}else{
moveState = MoveState.TURN_TOWARDS_GOAL;
}
if(map.distanceToGoal() < DISTANCE_TOLERANCE){
gameState = 2;
}
break;
case 2:
map.setGoal(5,9);
if(linedUp()){
moveState = MoveState.LEFT;
}else{
moveState = MoveState.TURN_TOWARDS_GOAL;
}
if(map.distanceToGoal() < DISTANCE_TOLERANCE){
gameState = 3;
}
break;
case 3:
map.setGoal(6,8);
moveState = MoveState.STRAFE_TOWARDS_GOAL;
if(map.distanceToGoal() < DISTANCE_TOLERANCE){
moveState = MoveState.STOP;
gameState = 4;
}
break;
}
}
}
**/
|
package com.lbsp.promotion.entity.model;
import com.lbsp.promotion.entity.table.annotation.MyTable;
/**
* Created by Barry on 2015/2/17.
*/
@MyTable(value = "page_operate")
public class PageOperate extends BaseModel {
private String id;
private String code;
private String parent_id;
private String parent_code;
private String name;
private Integer sort_index;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getParent_id() {
return parent_id;
}
public void setParent_id(String parent_id) {
this.parent_id = parent_id;
}
public String getParent_code() {
return parent_code;
}
public void setParent_code(String parent_code) {
this.parent_code = parent_code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSort_index() {
return sort_index;
}
public void setSort_index(Integer sort_index) {
this.sort_index = sort_index;
}
}
|
package org.sbbs.app.security.dao.hibernate;
import java.util.List;
import org.sbbs.app.security.dao.MenuDao;
import org.sbbs.app.security.model.Menu;
import org.sbbs.base.dao.hibernate.BaseTreeDaoHibernate;
import org.springframework.stereotype.Repository;
@Repository("menuDao")
public class MenuDaoHibernate extends BaseTreeDaoHibernate<Menu, Long>
implements
MenuDao {
public MenuDaoHibernate() {
super(Menu.class);
}
@Override
public void initMenu(List menus) {
this.getHibernateTemplate().saveOrUpdateAll(menus);
}
}
|
package com.tt.miniapp.launchcache.meta;
import com.tt.miniapphost.entity.AppInfoEntity;
public interface AppInfoRequestListener {
void onAppInfoInvalid(AppInfoEntity paramAppInfoEntity, int paramInt);
void requestAppInfoFail(String paramString1, String paramString2);
void requestAppInfoSuccess(AppInfoEntity paramAppInfoEntity);
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\launchcache\meta\AppInfoRequestListener.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package things.entity;
import things.entity.singleton.FiredBullets;
import things.entity.template_method.DestroyableObject;
import java.awt.*;
/**
* This is an instantiable class called Barrier for creating a barrier entity.
* It is a sub-class of GameComponent therefore it inherits all of its
* attributes and abstract methods
*
* @author Darren Moriarty
* created on 11/11/2016.
*
* @version 2.0
*/
public class Barrier extends DestroyableObject {
private final int BARRIER_ROWS;
private final int BARRIER_COLUMNS;
//Class Attributes
// Two dimensional array of BarrierBlock objects
private DestroyableObject[][] barrierBlocks;
private FiredBullets alienBulls = FiredBullets.getAlienBullets();
/**
* 5 argument constructor
* @param topLeftXPos
* @param topLeftYPos
* @param width
* @param height
* @param color
*/
public Barrier(int topLeftXPos, int topLeftYPos, int width, int height, Color color) {
super(topLeftXPos, topLeftYPos, width, height, color);
BARRIER_ROWS = 7;
BARRIER_COLUMNS = 12;
// Instantiating the array of barrierBlocks
barrierBlocks = new BarrierBlock[BARRIER_ROWS][BARRIER_COLUMNS];
// Setting the dimensions of each barrier block in the array with a nested for loops to
// create a grid of block (5 x 6)
for (int i = 0; i < BARRIER_ROWS; i++) {
for (int j = 0; j < BARRIER_COLUMNS; j++) {
// Setting the dimensions of each block
// The position of each block is the width of the block wider relative to the block beside it
barrierBlocks[i][j] = new BarrierBlock(getTopLeftXPos() + j * (getWidth() / BARRIER_COLUMNS), getTopLeftYPos()
+ i * (getHeight() / BARRIER_ROWS), (getWidth() / BARRIER_COLUMNS), (getHeight() / BARRIER_ROWS), getColor(), false);
}
}
}
// This method decides what to do every time the screen refreshes
@Override
public void update() {
// checking for collisions with the barriers
collisionDecisions(barrierBlocks);
collisionsWithAliens();
}
private void collisionsWithAliens() {
// checking for collisions with alien bullets
for (int k = 0; k < alienBulls.size(); k++) {
Bullet alienBullet = alienBulls.getBullet(k);
for (int i = 0; i < BARRIER_ROWS; i++) {
for (int j = 0; j < BARRIER_COLUMNS; j++) {
if (alienBullet.collidesWith(barrierBlocks[i][j])) {
alienBulls.removeBullet(alienBullet);
barrierBlocks[i][j].setHeight(-1);
barrierBlocks[i][j].setWidth(-1);
barrierBlocks[i][j].setTopLeftXPos(-1);
barrierBlocks[i][j].setTopLeftYPos(-1);
barrierBlocks[i][j].setDestroyed(true);
try{
playSound("sounds/fastinvader2.wav");
}
catch (Exception e) { e.printStackTrace(); }
}
}
}
}
}
@Override
protected void performDestroyableObjectCollisionAction(DestroyableObject destroyableObject, Bullet tankBullet) {
System.out.println("There was a collision");
tankBullets.removeBullet(tankBullet);
destroyableObject.setHeight(-1);
destroyableObject.setWidth(-1);
destroyableObject.setTopLeftXPos(-1);
destroyableObject.setTopLeftYPos(-1);
destroyableObject.setDestroyed(true);
try{
playSound("sounds/fastinvader1.wav");
}
catch (Exception e) { e.printStackTrace(); }
}
@Override
public void draw(Graphics2D g) {
// Setting the dimensions of each barrier block in the array with a nested for loops to
// create a grid of block (7 x 12)
for (int i = 0; i < BARRIER_ROWS; i++) {
for (int j = 0; j < BARRIER_COLUMNS; j++) {
// Drawing the array of blocks to the screen
if(!barrierBlocks[i][j].isDestroyed()){
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.drawRect(barrierBlocks[i][j].getTopLeftXPos(),
barrierBlocks[i][j].getTopLeftYPos(),
barrierBlocks[i][j].getWidth(),
barrierBlocks[i][j].getHeight());
g.fillRect(barrierBlocks[i][j].getTopLeftXPos(),
barrierBlocks[i][j].getTopLeftYPos(),
barrierBlocks[i][j].getWidth(),
barrierBlocks[i][j].getHeight());
}
}
}
}
@Override
public String toString(){
return "Barrier class is working";
}
}
|
package edu.wayne.cs.severe.redress2.entity.refactoring.formulas.mm;
import edu.wayne.cs.severe.redress2.controller.HierarchyBuilder;
import edu.wayne.cs.severe.redress2.controller.MetricUtils;
import edu.wayne.cs.severe.redress2.controller.metric.CBOMetric;
import edu.wayne.cs.severe.redress2.controller.metric.CodeMetric;
import edu.wayne.cs.severe.redress2.entity.MethodDeclaration;
import edu.wayne.cs.severe.redress2.entity.TypeDeclaration;
import edu.wayne.cs.severe.redress2.entity.refactoring.RefactoringOperation;
import edu.wayne.cs.severe.redress2.utils.RefactoringUtils;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
public class CBOMoveMethodPF extends MoveMethodPredFormula {
private HierarchyBuilder builder;
public CBOMoveMethodPF(HierarchyBuilder builder) {
this.builder = builder;
}
@Override
public HashMap<String, Double> predictMetrVal(RefactoringOperation ref,
LinkedHashMap<String, LinkedHashMap<String, Double>> prevMetrics)
throws Exception {
TypeDeclaration srcCls = getSourceClass(ref);
MethodDeclaration method = getMethod(ref);
TypeDeclaration tgtCls = getTargetClass(ref);
CodeMetric metric = getMetric();
List<TypeDeclaration> superClasses = builder.getParentClasses().get(
srcCls.getQualifiedName());
LinkedHashSet<String> classesUsed = MetricUtils.getUsedClassesByMethod(
srcCls, superClasses, method);
HashMap<String, Double> predMetrs = new HashMap<String, Double>();
Double prevMetr = prevMetrics.get(srcCls.getQualifiedName()).get(
metric.getMetricAcronym());
Double deltaSrc = RefactoringUtils.getCBODelta(srcCls, method,
classesUsed, superClasses);
predMetrs.put(srcCls.getQualifiedName(), prevMetr - deltaSrc);
LinkedHashMap<String, Double> tgtMetrs = prevMetrics.get(tgtCls
.getQualifiedName());
Double prevMetrTgt = tgtMetrs == null ? 0.0 : tgtMetrs.get(metric
.getMetricAcronym());
List<TypeDeclaration> superClassesTgt = builder.getParentClasses().get(
tgtCls.getQualifiedName());
Double deltaTgt = RefactoringUtils.getCBODelta(tgtCls, method,
classesUsed, superClassesTgt);
predMetrs.put(tgtCls.getQualifiedName(), prevMetrTgt + deltaTgt);
return predMetrs;
}
@Override
public CodeMetric getMetric() {
return new CBOMetric();
}
}
|
package com.example.administrator.retrofitdemo;
import retrofit.Call;
import retrofit.http.GET;
import retrofit.http.POST;
import retrofit.http.Path;
import retrofit.http.Query;
/**
* Created by Administrator on 2017/8/29.
*/
public interface APIService {
// @POST("book/search")
// @GET("book/search")
// Call<Users> loadUsers();
@GET("book/search")
Call<Users> loadUsers(@Query("q") String name,
@Query("tag") String tag, @Query("start") int start,
@Query("count") int count);
}
|
//给你一个二叉树的根节点 root ,树中每个节点都存放有一个 0 到 9 之间的数字。
//
//
// 每条从根节点到叶节点的路径都代表一个数字:
//
//
// 例如,从根节点到叶节点的路径 1 -> 2 -> 3 表示数字 123 。
//
//
// 计算从根节点到叶节点生成的 所有数字之和 。
//
// 叶节点 是指没有子节点的节点。
//
//
//
// 示例 1:
//
//
//输入:root = [1,2,3]
//输出:25
//解释:
//从根到叶子节点路径 1->2 代表数字 12
//从根到叶子节点路径 1->3 代表数字 13
//因此,数字总和 = 12 + 13 = 25
//
// 示例 2:
//
//
//输入:root = [4,9,0,5,1]
//输出:1026
//解释:
//从根到叶子节点路径 4->9->5 代表数字 495
//从根到叶子节点路径 4->9->1 代表数字 491
//从根到叶子节点路径 4->0 代表数字 40
//因此,数字总和 = 495 + 491 + 40 = 1026
//
//
//
//
// 提示:
//
//
// 树中节点的数目在范围 [1, 1000] 内
// 0 <= Node.val <= 9
// 树的深度不超过 10
//
//
//
// Related Topics 树 深度优先搜索
// 👍 357 👎 0
package me.alvin.leetcode.editor.cn;
import support.TreeNode;
import support.TreeTools;
import java.util.LinkedList;
import java.util.List;
public class SumRootToLeafNumbers {
public static void main(String[] args) {
Solution solution = new SumRootToLeafNumbers().new Solution();
TreeNode root = null;
root = TreeTools.buildTree(new Integer[]{1, 2, 3}, root, 0);
System.out.println(solution.sumNumbers(root));
System.out.println(solution.travel(root,0));
}
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int sumNumbers(TreeNode root) {
List<Integer> nums = new LinkedList<>();
StringBuilder path = new StringBuilder();
travel(root, path, nums);
return nums.stream().mapToInt(Integer::intValue)
.sum();
}
private void travel(TreeNode root, StringBuilder path, List<Integer> nums) {
if (null == root) {
return;
}
path.append(root.val);
if (null == root.left && null == root.right) {
nums.add(Integer.parseInt(path.toString()));
}
travel(root.left, new StringBuilder(path), nums);
travel(root.right, new StringBuilder(path), nums);
}
/**
*
*
* @param root
* @param preSum
* @return
*/
public int travel(TreeNode root, int preSum) {
if (root == null) {
return 0;
}
int sum = preSum * 10 + root.val;
if (null == root.left && null == root.right) {
return sum;
}
return travel(root.left, sum) + travel(root.right, sum);
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
|
package lowOfDeteter.instance;
import java.lang.invoke.VarHandle;
/**
* @Author:Jack
* @Date: 2021/8/21 - 22:34
* @Description: lowOfDeteter.instance
* @Version: 1.0
*/
public class Client {
public static void main(String[] args) {
Installer installer = new Installer();
final Wizard wizard = new Wizard();
installer.install(wizard);
}
}
|
package JavaSE.OO.jihe;
import java.util.*;
/*collection中的方法:
* boolean add(Object element);向集合中添加元素
* int size();获取集合中元素的个数
* void clear();清空集合
* boolean isEmpty();判断集合是否为空
* Object[] toArray();将集合转换成数组
*
* Iterator<E> iterator;获取集合所依赖的迭代器对象
* boolean contains(Object o);判断集合中是否包含某个元素
* boolean remove(Object o);删除集合中某个元素
*/
class Customer{
String name;
int age;
Customer(String name,int age){
this.age=age;
this.name=name;
}
//重写Object中的toString方法
public String toString(){
return "Customer[name="+name+",age="+age+"]";
}
}
public class CollectionTest01 {
public static void main(String[] args) {
//创建集合
Collection c=new ArrayList();//多态
//添加元素
c.add(1);//自动装箱,会自动转换成Integer引用类型的引用
Object o=new Object();
c.add(o);//等同于下面
c.add(new Object());//保存的是引用,不是对象
Customer cus=new Customer("jack",20);
c.add(cus);
//获取元素个数
System.out.println(c.size());//4
System.out.println(c.isEmpty());//判断是否为空,false
//将集合转换成Object类型的数组
Object[] objs=c.toArray();
for(int i=0;i<objs.length;i++) {
System.out.println(objs[i]);
}
//清空
c.clear();
System.out.println(c.size());//0
System.out.println(c.isEmpty());//判断是否为空,true
}
}
|
package services;
import com.fasterxml.jackson.databind.JsonNode;
import models.ResponseToClient;
import play.libs.Json;
// TODO: 1/05/17
/**
* This class for any operation which makes changes on JIRA, that is, "writing operations".
* Currently not implemented at all.
*/
public class JiraWriterService {
/**
* This method calls appropriate method on run time based on the
* parameters (methodName and argName) passed and returns a value
* returned by that method.
*
* @param methodName
* @param issueKey
* @return
*/
// public static JsonNode questionMapping(String methodName, String issueKey, JsonNode responseBody) {
//
// TaskMap taskMap = new TaskMap();
//
// try {
// //call the method at runtime according to the argument "methodName"
// Method method = TaskMap.class.getMethod(methodName, String.class, JsonNode.class);
//
// return (JsonNode) method.invoke(taskMap, issueKey, responseBody);
// } catch (NoSuchMethodException
// | InvocationTargetException
// | IllegalAccessException
// | NullPointerException e) {
// return parseToJson("fail", e.getMessage());
// }
// }
/**
* This method gets the questions that POET was not able to answer in the past.
*
* @param issueKey is the IssueID of type string which was mentioned in the query by the user.
* @param responseBody is the JSON object received from JIRA Rest API.
* @return reply to the user in JSON format.
*/
public JsonNode QuestionsNotAnswered(String issueKey, JsonNode responseBody) {
String answer = "I have not saved any questions so far. Please wait for my next version update.";
System.out.println(answer);
return parseToJson("success", answer);
}
/**
* This method requests issues that are in progress and returns it to the calling method
*
* @param issueKey is the IssueID of type string which was mentioned in the query by the user.
* @param responseBody is the JSON object received from JIRA Rest API.
* @return reply to the user in JSON format.
*/
public JsonNode IssuesInProgress(String issueKey, JsonNode responseBody) {
String answer = "Code to find ISSUES IN PROGRESS has not been implemented yet. Please wait for our next version update.";
System.out.println(answer);
return parseToJson("success", answer);
}
/**
* This method requests issues that are completed and returns it to the calling method
*
* @param issueKey is the IssueID of type string which was mentioned in the query by the user.
* @param responseBody is the JSON object received from JIRA Rest API.
* @return reply to the user in JSON format.
*/
public JsonNode IssuesCompleted(String issueKey, JsonNode responseBody) {
String answer = "Code to find COMPLETED ISSUES has not been implemented yet. Please wait for our next version update.";
System.out.println(answer);
return parseToJson("success", answer);
}
/**
* This method requests issues that are stalled and returns it to the calling method
*
* @param issueKey is the IssueID of type string which was mentioned in the query by the user.
* @param responseBody is the JSON object received from JIRA Rest API.
* @return reply to the user in JSON format.
*/
public JsonNode StalledIssues(String issueKey, JsonNode responseBody) {
String answer = "Code to find STALLED ISSUES has not been implemented yet. Please wait for our next version update.";
System.out.println(answer);
return parseToJson("success", answer);
}
/**
* This method sets the project for a channel
*
* @param issueKey is the IssueID of type string which was mentioned in the query by the user.
* @param responseBody is the JSON object received from JIRA Rest API.
* @return reply to the user in JSON format.
*/
public JsonNode SetProject(String issueKey, JsonNode responseBody) {
String answer = "Code to SET PROJECT TO A CHANNEL has not been implemented yet. Please wait for our next version update.";
System.out.println(answer);
return parseToJson("success", answer);
}
/**
* This method sets the context for the conversations.
* It remembers the issue people are talking about.
*
* @param issueKey is the IssueID of type string which was mentioned in the query by the user.
* @param responseBody is the JSON object received from JIRA Rest API.
* @return reply to the user in JSON format.
*/
public JsonNode SetIssueContext(String issueKey, JsonNode responseBody) {
String answer = "Code to find SET CONTEXT has not been implemented yet. Please wait for our next version update.";
System.out.println(answer);
return parseToJson("success", answer);
}
/**
* This method sends one out of several greeting messages to the user.
*
* @param issueKey is the IssueID of type string which was mentioned in the query by the user.
* @param responseBody is the JSON object received from JIRA Rest API.
* @return reply to the user in JSON format.
*/
public JsonNode Greeting(String issueKey, JsonNode responseBody) {
String greetings[] = new String[3];
greetings[0] = "Hi, My name is POET. I can help you get information from JIRA or make modification in JIRA. " +
"What can I help you with today?";
greetings[1] = "Hello, I am POET. I am here to help you access information from JIRA or make modification in JIRA. " +
"What can I help you with today?";
greetings[2] = "Hi. People call me POET. Not that I write poems. Jokes apart, how can I help you?";
int index = (int) (Math.random() * 3);
String answer = greetings[index];
System.out.println(answer);
return parseToJson("success", answer);
}
/**
* This method takes String as an input as returns a JSON object in the required format
*
* @param message
* @return
*/
public static JsonNode parseToJson(String status, String message) {
ResponseToClient response = new ResponseToClient(status, message);
System.out.println("ResponseToClient: " + response.message);
return Json.toJson(response);
}
}
|
package com.todo.service;
import java.util.List;
import com.todo.model.TaskVO;
public interface TaskService {
public void insertData(TaskVO taskvo);
public List<TaskVO> retriveAll(int i);
public List<TaskVO> retriveInfo(TaskVO tvo);
public List<TaskVO> search(String t,int rid);
public List<TaskVO> sortByDate(int rid);
public List<TaskVO> sortByAllPriority(int rid);
public List<TaskVO> sortByPriority(int p,int rid);
}
|
package com.example.inheritance;
public class Test {
public static void main(String[] args) {
Surgeon surgeon = new Surgeon();
surgeon.personalDetails();
surgeon.toolsUsedForSurgery();
}
}
|
package webservice;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import utils.DescendantsCheck;
import data.Parents;
import data.TransactionsList;
@Path("/transactionservice")
public class TransactionApi {
@GET
@Path("/transaction/{transactionId}")
@Produces(MediaType.APPLICATION_JSON)
public Response getTransactionDetails(
@PathParam("transactionId") long transactionId)
throws JSONException {
if (TransactionsList.getTransactionById(transactionId) == null) {
return Response.status(200).entity("{}").build();
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("amount",
TransactionsList.getTransactionById(transactionId).getAmount());
jsonObject.put("type",
TransactionsList.getTransactionById(transactionId).getType());
if(TransactionsList.getTransactionById(transactionId).getParent_id() != null){
jsonObject.put("parent_id",
TransactionsList.getTransactionById(transactionId)
.getParent_id());
}
return Response.status(200).entity(jsonObject).build();
}
@GET
@Path("/types/{type}")
@Produces(MediaType.APPLICATION_JSON)
public Response getListOfTransactionTypes(@PathParam("type") String type)
throws JSONException {
JSONArray jsonArray = new JSONArray();
for (long key : TransactionsList.getTransactionMap().keySet()) {
String temporaryType = TransactionsList.getTransactionMap()
.get(key).getType();
if (temporaryType.equalsIgnoreCase(type)) {
jsonArray.put(key);
}
}
return Response.status(200).entity(jsonArray).build();
}
@GET
@Path("/sum/{transactionId}")
@Produces(MediaType.APPLICATION_JSON)
public Response getSumOfTransactionsById(
@PathParam("transactionId") long transactionId)
throws JSONException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("sum", calculateSumOftransactions(transactionId));
return Response.status(200).entity(jsonObject).build();
}
@PUT
@Path("/transaction/{transactionId}")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public Response addTransaction(
@PathParam("transactionId") long transactionId, String jsonUserInput)
throws JSONException {
String requestResult = "OK";
JSONObject jsonInput;
double amount;
String type;
long parentId;
try {
jsonInput = new JSONObject(jsonUserInput);
} catch (JSONException jsonEx) {
return Response.status(404).entity(jsonEx.getMessage()).build();
}
try {
amount = Double.parseDouble(jsonInput.get("amount").toString());
type = jsonInput.get("type").toString();
TransactionsList.addTransaction(transactionId, amount, type);
if (jsonInput.has("parent_id")) {
parentId = Long
.parseLong(jsonInput.get("parent_id").toString());
TransactionsList.addTransaction(transactionId, amount, type,
parentId);
}
} catch (NumberFormatException e) {
requestResult = "Transaction not added. Invalid type of argument";
;
} catch (Exception parentChildException) {
requestResult = parentChildException.getMessage();
}
JSONObject jsonOutput = new JSONObject();
jsonOutput.put("status", requestResult);
return Response.status(200).entity(jsonOutput).build();
}
private double calculateSumOftransactions(long transactionId) {
if (TransactionsList.getTransactionById(transactionId) == null) {
return 0;
}
Map<Long, Set<Long>> childrenParentsMap = Parents.getChildrenMap();
double sumAmount = 0;
Set<Long> allDescendantsIds = new LinkedHashSet<>();
if (childrenParentsMap.get(transactionId) != null) {
allDescendantsIds = new DescendantsCheck().findAllDescendants(
childrenParentsMap, transactionId);
for (Long sum : allDescendantsIds) {
sumAmount += TransactionsList.getTransactionById(sum)
.getAmount();
}
}
sumAmount += TransactionsList.getTransactionById(transactionId)
.getAmount();
return sumAmount;
}
}
|
package com.mahendra.library.app;
import java.util.Scanner;
import com.mahendra.library.dao.BookDAO;
import com.mahendra.library.dao.BookDAOImpl;
import com.mahendra.library.dao.BookIssueDAO;
import com.mahendra.library.dao.BookIssueDAOImpl;
import com.mahendra.library.dao.MemberDAO;
import com.mahendra.library.dao.MemberDAOImpl;
import com.mahendra.library.exceptions.ApplicationException;
import com.mahendra.library.models.Book;
import com.mahendra.library.services.BookIssueService;
import com.mahendra.library.services.BookIssueServiceImpl;
import com.mahendra.library.services.BookService;
import com.mahendra.library.services.BookServiceImpl;
import com.mahendra.library.services.MemberService;
import com.mahendra.library.services.MemberServiceImpl;
public class AppUI {
private Scanner sc = new Scanner(System.in);
private static boolean doQuit = false;
private BookDAO bookDao = new BookDAOImpl();
private MemberDAO memberDao = new MemberDAOImpl();
private BookIssueDAO issueDao = new BookIssueDAOImpl();
private BookService bookService = new BookServiceImpl(bookDao);
private MemberService memberService = new MemberServiceImpl(memberDao);
private BookIssueService issueService = new BookIssueServiceImpl(issueDao);
private static DataWriter dataWriter = new DataWriter();
public String input() {
System.out.println("COMMAND [Enter XX for Main Menu] : ");
String ln = sc.nextLine();
return ln;
}
public static void main(String[] args) {
AppUI ui = new AppUI();
dataWriter.loadData();
while (!doQuit) {
String ln = ui.input();
ui.action(ln);
}
}
public void closeApp() {
System.out.println("Are sure you want to QUIT ?");
System.out.println("Press N to continue application, any other key to QUIT");
String ln = sc.nextLine();
if (!ln.equalsIgnoreCase("N"))
AppUI.doQuit = true;
System.out.println("Writing changes to persistent file...");
dataWriter.writeData();
System.out.println("Bye....");
}
public void action(String command) {
command = command.toUpperCase();
switch (command) {
case "B":
showBookMenu();
break;
case "M":
showMemberMenu();
break;
case "I":
showIssuesMenu();
break;
case "Q":
closeApp();
break;
case "XX":
showMenu();
break;
case "NB":
addBook();
break;
case "FB":
findBookById();
}
}
public void showMenu() {
System.out.println("\n\n");
System.out.println("+------------------------Main Menu -----------------------+");
System.out.println("| Books Menu [B] |");
System.out.println("| Members Menu [M] |");
System.out.println("| Issues Menu [I] |");
System.out.println("| Quit App [Q] |");
System.out.println("+---------------------------------------MAHENDRA----------+");
System.out.println("\n\n");
}
public void showBookMenu() {
System.out.println("\n\n");
System.out.println("+------------------------Books Menu ----------------------+");
System.out.println("| Add new Book [NB] |");
System.out.println("| Find Book by ID [FB] |");
System.out.println("| Find by title [TB] |");
System.out.println("| Find by title (available only) [TA] |");
System.out.println("| Find by category (all books) [CA] |");
System.out.println("| Find by category (available only) [CB] |");
System.out.println("| Find by author (all Books) [AB] |");
System.out.println("| Find by author (available only) [AA] |");
System.out.println("| Find and update Book by ID [UB] |");
System.out.println("| RETURN TO MAIN MENU [XX] |");
System.out.println("+---------------------------------------MAHENDRA----------+");
System.out.println("\n\n");
}
public void showMemberMenu() {
System.out.println("\n\n");
System.out.println("+------------------------Members Menu ----------------------+");
System.out.println("| Add new Member [NM] |");
System.out.println("| Find Member by ID [FM] |");
System.out.println("| Find by Name [NM] |");
System.out.println("| List Members with no pending books [FE] |");
System.out.println("| Find and update Member by ID [UM] |");
System.out.println("| RETURN TO MAIN MENU [XX] |");
System.out.println("+---------------------------------------MAHENDRA----------+");
System.out.println("\n\n");
}
public void showIssuesMenu() {
System.out.println("\n\n");
System.out.println("+------------------------Issues Menu ---------------------+");
System.out.println("| Issue a Book [IB] |");
System.out.println("| Find Issue by ID [FI] |");
System.out.println("| List by Member ID [MI] |");
System.out.println("| List by Book ID [MB] |");
System.out.println("| List Pending books [LP] |");
System.out.println("| Find and update Issue by ID [UI] |");
System.out.println("| List all pending (due) Books [LD] |");
System.out.println("| RETURN TO MAIN MENU [XX] |");
System.out.println("+---------------------------------------MAHENDRA----------+");
System.out.println("\n\n");
}
public void addBook() {
Book book = new Book();
System.out.println("+--------- Adding new book ------------------------------+");
System.out.println("| Enter title : ");
book.setTitle(sc.nextLine());
System.out.println("| Enter author's name: ");
book.setAuthor(sc.nextLine());
System.out.println("| Enter catergory : ");
book.setCategory(sc.nextLine());
System.out.println("| Status set to 'A' [Available] for new book. ");
book.setStatus('A');
try {
Book temp = bookService.create(book);
System.out.println("Book created and assigned ID: " + temp.getId());
} catch (ApplicationException ex) {
System.out.println("Unable to add new book, " + ex.getMessage());
}
}
private void findBookById() {
System.out.println("+--------- Searching for book ------------------------------+");
System.out.println("| Enter ID : ");
int id = sc.nextInt();
try {
Book book = bookService.findById(id);
System.out.println("| Found book: ");
System.out.println("| title: " + book.getTitle());
System.out.println("| author: " + book.getAuthor());
System.out.println("| category: " + book.getCategory());
String status = book.getStatus() == 'A' ? "Yes" : "No";
System.out.println("| Available: " + status);
} catch (ApplicationException ex) {
System.out.println("| Cannot find book, " + ex.getMessage());
}
System.out.println("+-----------------------------------------------------------+");
}
}
|
package test;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
public static void main(String[] args) {
int count = 12;
String number = String.format("%04d", count);
System.out.println(number);
System.out.println("============");
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
System.out.println(sdf.format(date));
// System.out.println(sdf.format(date).replaceAll("-", ""));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.