blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
1b9550547413b6df3008b16035c27c7c41d7744e
Java
nuoyiai/tqsql
/core/src/main/java/tpsql/sql/mapping/SqlItemSet.java
UTF-8
490
2.21875
2
[ "BSD-2-Clause" ]
permissive
package tpsql.sql.mapping; import tpsql.sql.builder.SqlString; public class SqlItemSet extends SqlItemContent implements ISqlItemClone<SqlItemSet> { @Override public SqlString toString(SqlItemArgs arg) { arg.setHidePrepend(true); SqlString sql = super.toString(arg); return new SqlString(" set ").contact(sql); } @Override public SqlItemSet clone(Object args){ SqlItemSet set = new SqlItemSet(); set.map=this.map; set.parts=this.cloneParts(args); return set; } }
true
ad5f6356062eb581968f7a653e171921108e3a73
Java
CarlosBean/Backend-Parqueadero
/src/main/java/com/adsi/parqueadero/rest/services/PagosREST.java
UTF-8
5,382
2.234375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.adsi.parqueadero.rest.services; import com.adsi.parqueadero.jpa.entities.Carros; import com.adsi.parqueadero.jpa.entities.Pagos; import com.adsi.parqueadero.jpa.entities.Puestos; import com.adsi.parqueadero.jpa.entities.Tarifas; import com.adsi.parqueadero.jpa.sessions.CarrosFacade; import com.adsi.parqueadero.jpa.sessions.PagosFacade; import com.adsi.parqueadero.jpa.sessions.PuestosFacade; import com.adsi.parqueadero.jpa.sessions.TarifasFacade; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.Date; import java.util.List; import javax.ejb.EJB; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; /** * * @author carlos */ @Path("pagos") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class PagosREST { @EJB private CarrosFacade carroEJB; @EJB private TarifasFacade tarifaEJB; @EJB private PuestosFacade puestoEJB; @EJB private PagosFacade pagoEJB; @GET public List<Pagos> findAll() { return pagoEJB.findAll(); } /* */ @GET @Produces(MediaType.TEXT_PLAIN) @Path("totalIngresos") public Response consultarTotalIngresos() { GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); int total = 0; List<Pagos> pagos = pagoEJB.findAll(); for (Pagos pago : pagos) { total = total + pago.getTotalPrecio(); } Pagos pago = new Pagos(total); return Response.status(Response.Status.OK) .entity(gson.toJson(pago)) .build(); } /* Este metodo permite retirar un carro de un puesto y crear el pago correspondiente al tiempo que permanecio el automovil en el parqueadero. */ @POST public Response createPago(@QueryParam("placa") String placa) { GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); Tarifas tarifa = tarifaEJB.find(1); Pagos pago = new Pagos(); Date date = new Date(); if (carroEJB.findCarrosByPlaca(placa) != null) { Carros carro = carroEJB.findCarrosByPlaca(placa); Puestos puesto = puestoEJB.findPuestoByIdCarro(carro.getId()); if (puestoEJB.findPuestoByIdCarro(carro.getId()) != null) { pago.setIdTarifas(tarifa); pago.setHoraActual(date); pago.setTotalPrecio(calcularTotal(carro.getHoraLlegada(), pago.getIdTarifas().getValor())); pago.setIdCarros(carro); pagoEJB.create(pago); puesto.setIdCarros(null); puestoEJB.edit(puesto); carro.setHoraSalida(date); carroEJB.edit(carro); return Response.status(Response.Status.OK) .entity(gson.toJson("Carro removido exitosamente." + " Valor a pagar: " + pago.getTotalPrecio())) .build(); } else { return Response.status(Response.Status.BAD_REQUEST) .entity(gson.toJson("El auto no esta estacionado en ningun puesto.")) .build(); } } else { return Response.status(Response.Status.BAD_REQUEST) .entity(gson.toJson("El auto no existe.")) .build(); } } public int calcularTotal(Date horaLlegada, int valorTarifa) { Date date = new Date(); long minutosLlegada = (horaLlegada.getTime() / 1000) / 60; long minutosActual = (date.getTime() / 1000) / 60; int totalPrecio = (int) ((minutosActual - minutosLlegada) * (valorTarifa / 60)); return totalPrecio; } /* */ @GET @Path("consultarPrecio") @Produces(MediaType.APPLICATION_JSON) public Response consultarPrecio(@QueryParam("placa") String placa) { GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); Tarifas tarifa = tarifaEJB.find(1); if (carroEJB.findCarrosByPlaca(placa) != null) { Carros carro = carroEJB.findCarrosByPlaca(placa); if (puestoEJB.findPuestoByIdCarro(carro.getId()) != null) { int total = calcularTotal(carro.getHoraLlegada(), tarifa.getValor()); Carros obj = new Carros(total); return Response.status(Response.Status.OK) .entity(gson.toJson(obj)) .build(); }else{ return Response.status(Response.Status.BAD_REQUEST) .entity(gson.toJson("El vehiculo no se le ha asignado un puesto.")) .build(); } } else { return Response.status(Response.Status.BAD_REQUEST) .entity(gson.toJson("El vehiculo no esta registrado en el parqueadero.")) .build(); } } }
true
11aa8fb4a504f727f37cc770a3d7ae54f4d31979
Java
luiz158/monitoracoes
/src/main/java/planilhaAT/ComparadorPlanilha.java
UTF-8
3,695
2.5625
3
[]
no_license
package planilhaAT; public class ComparadorPlanilha implements java.util.Comparator { protected int m_sortCol; protected boolean m_sortAsc; public ComparadorPlanilha(int sortCol, boolean sortAsc) { this.m_sortCol = sortCol; this.m_sortAsc = sortAsc; } public int compare(Object o1, Object o2) { if ((!(o1 instanceof DadosPlanilha)) || (!(o2 instanceof DadosPlanilha))) return 0; DadosPlanilha s1 = (DadosPlanilha)o1; DadosPlanilha s2 = (DadosPlanilha)o2; int result = 0; switch (this.m_sortCol) { case 0: String str1 = (String)s1.getIcone().m_data; String str2 = (String)s2.getIcone().m_data; result = str1.compareTo(str2); break; case 1: double d1 = ((Double)s1.getVariacao().m_data).doubleValue(); double d2 = ((Double)s2.getVariacao().m_data).doubleValue(); result = d1 > d2 ? 1 : d1 < d2 ? -1 : 0; break; case 2: d1 = s1.getPreco().doubleValue(); d2 = s2.getPreco().doubleValue(); result = d1 > d2 ? 1 : d1 < d2 ? -1 : 0; break; case 3: d1 = ((Double)s1.getIfr().m_data).doubleValue(); d2 = ((Double)s2.getIfr().m_data).doubleValue(); result = d1 > d2 ? 1 : d1 < d2 ? -1 : 0; break; case 4: d1 = ((Double)s1.getStochastic().m_data).doubleValue(); d2 = ((Double)s2.getStochastic().m_data).doubleValue(); result = d1 > d2 ? 1 : d1 < d2 ? -1 : 0; break; case 5: d1 = ((Double)s1.getTopoAscen().m_data).doubleValue(); d2 = ((Double)s2.getTopoAscen().m_data).doubleValue(); result = d1 > d2 ? 1 : d1 < d2 ? -1 : 0; break; case 6: d1 = ((Double)s1.getFundoDescen().m_data).doubleValue(); d2 = ((Double)s2.getFundoDescen().m_data).doubleValue(); result = d1 > d2 ? 1 : d1 < d2 ? -1 : 0; break; case 7: result = s1.getSuportes().compareTo(s2.getSuportes()); break; case 8: result = s1.getResistencias().compareTo(s2.getResistencias()); break; case 9: d1 = ((Double)s1.getStop_loss_1().m_data).doubleValue(); d2 = ((Double)s2.getStop_loss_1().m_data).doubleValue(); result = d1 > d2 ? 1 : d1 < d2 ? -1 : 0; break; case 10: d1 = ((Double)s1.getStop_gain_1().m_data).doubleValue(); d2 = ((Double)s2.getStop_gain_1().m_data).doubleValue(); result = d1 > d2 ? 1 : d1 < d2 ? -1 : 0; break; case 11: d1 = ((Double)s1.getStop_loss_2().m_data).doubleValue(); d2 = ((Double)s2.getStop_loss_2().m_data).doubleValue(); result = d1 > d2 ? 1 : d1 < d2 ? -1 : 0; break; case 12: d1 = ((Double)s1.getStop_gain_2().m_data).doubleValue(); d2 = ((Double)s2.getStop_gain_2().m_data).doubleValue(); result = d1 > d2 ? 1 : d1 < d2 ? -1 : 0; break; case 13: d1 = ((Double)s1.getStop_loss_3().m_data).doubleValue(); d2 = ((Double)s2.getStop_loss_3().m_data).doubleValue(); result = d1 > d2 ? 1 : d1 < d2 ? -1 : 0; break; case 14: d1 = ((Double)s1.getStop_gain_3().m_data).doubleValue(); d2 = ((Double)s2.getStop_gain_3().m_data).doubleValue(); result = d1 > d2 ? 1 : d1 < d2 ? -1 : 0; } if (!this.m_sortAsc) result = -result; return result; } public boolean equals(Object obj) { if ((obj instanceof ComparadorPlanilha)) { ComparadorPlanilha compObj = (ComparadorPlanilha)obj; return (compObj.m_sortCol == this.m_sortCol) && (compObj.m_sortAsc == this.m_sortAsc); } return false; } }
true
e4a9e8fc09e4536c966f5f7c11705b3c327b9174
Java
grazianiborcai/Agenda_WS
/src/br/com/mind5/business/orderSearch/info/OrdarchCopier.java
UTF-8
1,026
2.265625
2
[]
no_license
package br.com.mind5.business.orderSearch.info; import java.util.List; import br.com.mind5.info.InfoCopier; import br.com.mind5.payment.payOrder.info.PayordInfo; import br.com.mind5.payment.refundOrderItem.info.RefemInfo; public final class OrdarchCopier { public static OrdarchInfo copyFromPayord(PayordInfo source) { InfoCopier<OrdarchInfo, PayordInfo> copier = new OrdarchCopyPayord(); return copier.makeCopy(source); } public static List<OrdarchInfo> copyFromPayord(List<PayordInfo> sources) { InfoCopier<OrdarchInfo, PayordInfo> copier = new OrdarchCopyPayord(); return copier.makeCopy(sources); } public static OrdarchInfo copyFromRefem(RefemInfo source) { InfoCopier<OrdarchInfo, RefemInfo> copier = new OrdarchCopyRefem(); return copier.makeCopy(source); } public static List<OrdarchInfo> copyFromRefem(List<RefemInfo> sources) { InfoCopier<OrdarchInfo, RefemInfo> copier = new OrdarchCopyRefem(); return copier.makeCopy(sources); } }
true
b8de57f2293d78e114b077e7718e85f4ee86a2f9
Java
likeyewan/Demo
/app/src/main/java/com/shoulashou/demo/tcp/ApplicationUtil.java
UTF-8
1,104
2.515625
3
[]
no_license
package com.shoulashou.demo.tcp; /** * Created by likeye on 2020/7/23 9:59. **/ import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; import android.app.Application; public class ApplicationUtil extends Application{ private Socket socket; private DataOutputStream out = null; private DataInputStream in = null; public void init() throws IOException, Exception{ this.socket = new Socket("192.168.3.240",9987); this.out = new DataOutputStream(socket.getOutputStream()); this.in = new DataInputStream(socket.getInputStream()); } public Socket getSocket() { return socket; } public void setSocket(Socket socket) { this.socket = socket; } public DataOutputStream getOut() { return out; } public void setOut(DataOutputStream out) { this.out = out; } public DataInputStream getIn() { return in; } public void setIn(DataInputStream in) { this.in = in; } }
true
3954c7ff7f4d49575958a6e3ad4e9200a3785a61
Java
MHarbi/algorithm-design
/Assignment4/MergesortRecord.java
UTF-8
972
3.3125
3
[]
no_license
/*************************************************************************************** ************ Defines Objects to be used by the non-recursive Mergesort routine ********* ************ Programmed by Olac Fuentes ********* ************ Last modified September 12, 2011 ********* ****************************************************************************************/ import java.util.*; public class MergesortRecord { public boolean sorted; //Indicates if the first and second half of the array have already been sorted public int first; public int last; public MergesortRecord(boolean s, int f, int l){ sorted = s; first = f; last = l; } /*public int getfirst() { return first; } public boolean getsorted() { return sorted; } public int getlast() { return last; }*/ public void print(){ System.out.println(sorted + " " + first + " " + last); } }
true
bf5e8769e008e152f6d25825b79258fda6c338e1
Java
NewbieFlyOver/zbm
/zbm/src/main/java/wmq/fly/thread/concurrent/CyclicBarrierDemo.java
UTF-8
1,059
3.71875
4
[]
no_license
package wmq.fly.thread.concurrent; import java.util.concurrent.CyclicBarrier; class ThreadDemo extends Thread{ CyclicBarrier cyclicBarrier; public ThreadDemo(CyclicBarrier cyclicBarrier) { this.cyclicBarrier = cyclicBarrier; } @Override public void run() { System.out.println("开始处理数据喽喽喽.........."); try { sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("处理数据结束.........."); try { cyclicBarrier.await(); } catch (Exception e) { e.printStackTrace(); } System.out.println("唤醒并并行执行.........."); } } /** * CyclicBarrier初始化时规定一个数目,然后计算调用了CyclicBarrier.await()进入等待的线程数。 * 当线程数达到了这个数目时,所有进入等待状态的线程被唤醒并继续。  * */ public class CyclicBarrierDemo { public static void main(String[] args) { CyclicBarrier cyclicBarrier = new CyclicBarrier(5); for(int i=0; i<5; i++) { new ThreadDemo(cyclicBarrier).start(); } } }
true
1dd89a3a6b30ee00055cff564c7000b3f9a9dba1
Java
indraoct/sgo_android
/app/src/main/java/com/indraoctamaindra/library/UrlHit.java
UTF-8
1,011
2.140625
2
[]
no_license
package com.indraoctamaindra.library; import android.content.Context; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; /** * Created by Indra Octama on 7/16/2015. */ public class UrlHit { private static final String AIRLINES_URL = ParamConst.airlinesMainUrl; private static AsyncHttpClient client = new AsyncHttpClient(); public static void get( RequestParams params, AsyncHttpResponseHandler responseHandler) { client.setTimeout(ParamConst.setTimeout); client.get(AIRLINES_URL, params, responseHandler); } public static void post(Context context,String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { client.setTimeout(ParamConst.setTimeout); client.post(context,getAbsoluteUrl(url), params, responseHandler); } private static String getAbsoluteUrl(String relativeUrl) { return AIRLINES_URL + relativeUrl; } }
true
1a4cb5c54718dc26dbe22e3f2ad8f0b4b1c2390a
Java
imflyn/Location
/TestLocation/src/com/flyn/location/service/MyItemizedOverlay.java
UTF-8
1,391
2.234375
2
[]
no_license
package com.flyn.location.service; import java.util.ArrayList; import java.util.List; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import com.google.android.maps.GeoPoint; import com.google.android.maps.ItemizedOverlay; import com.google.android.maps.MapView; import com.google.android.maps.OverlayItem; public class MyItemizedOverlay extends ItemizedOverlay { private List<OverlayItem> overlays = new ArrayList<OverlayItem>(); public MyItemizedOverlay(Drawable defaultMarker) { super(boundCenterBottom(defaultMarker)); } @Override protected OverlayItem createItem(int i) { return overlays.get(i); } @Override public int size() { return overlays.size(); } public void addOverlay(OverlayItem item) { overlays.add(item); populate(); } public void removeOverlay(int location) { overlays.remove(location); } @Override public boolean onTap(GeoPoint p, MapView mapView) { return super.onTap(p, mapView); } @Override protected boolean onTap(int index) { return super.onTap(index); } @Override public void draw(Canvas canvas, MapView mapView, boolean shadow) { super.draw(canvas, mapView, shadow); } }
true
e28c16211f7a1b6246fe6516838bc920f1e19470
Java
BeyondSkyCoder/BeyondCoder
/leetcode/java/DataStructureStrArrayDeque/EncodeAndDecode_STR.java
UTF-8
2,312
4.09375
4
[ "Apache-2.0" ]
permissive
package DataStructureStrArrayDeque; import java.util.ArrayList; import java.util.List; public class EncodeAndDecode_STR { /** * Design an algorithm to encode a list of strings to a string. * The encoded string is then sent over the network and is decoded back to * the original list of strings. * Machine 1 (sender) has the function: * string encode(vector<string> strs) { * // ... your code * return encoded_string; * } * Machine 2 (receiver) has the function: * vector<string> decode(string s) { * //... your code * return strs; * } * So Machine 1 does: string encoded_string = encode(strs); * and Machine 2 does: vector<string> strs2 = decode(encoded_string); * strs2 in Machine 2 should be the same as strs in Machine 1. * Implement the encode and decode methods. * Note: * The string may contain any possible characters out of 256 valid ascii characters. * Your algorithm should be generalized enough to work on any possible characters. * Do not use class member/global/static variables to store states. * Your encode and decode algorithms should be stateless. * Do not rely on any library method such as eval or serialize methods. * You should implement your own encode/decode algorithm. */ // Algorithm: encoding with tuple (length+delimiter+string) // Encodes a list of strings to a single string. public String encode(List<String> strs) { StringBuilder res = new StringBuilder(); for (String s : strs) { res.append(s.length()).append("/").append(s); } return res.toString(); } // Decodes a single string to a list of strings. public List<String> decode(String s) { List<String> res = new ArrayList<>(); int i = 0; int n = s.length(); // parse tuple by tuple while (i < n) { int j = i + 1; // find delimiter '/' while (j < n && s.charAt(j) != '/') j++; // j is at delimiter. Front is length and after is string int len = Integer.parseInt(s.substring(i, j)); res.add(s.substring(j + 1, j + 1 + len)); i = j + len + 1; } return res; } }
true
f76f5487ab767cdbebe49e19c80f2836a7493874
Java
jselbie/ScheduleBuilder
/src/com/selbie/schedulebuilder/Resolver.java
UTF-8
14,162
2.15625
2
[]
no_license
package com.selbie.schedulebuilder; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; public class Resolver { static final String LONGBOARD_ICON_URL = "http://www.selbie.com/wrek/LB3.png"; static final String THELOCALS_ICON_URL = "http://www.selbie.com/wrek/locals.png"; static final String TAPAS_ICON_URL = "http://www.selbie.com/wrek/tapas.png"; static final String POPUP_ICON_URL = "http://www.selbie.com/wrek/pop.png"; static final String BROADWAY_ICON_URL = "http://www.selbie.com/wrek/broadway.png"; static final String FREAKERS_ICON_URL = "http://www.selbie.com/wrek/freakers.png"; static final String STORYTIME_ICON_URL = "http://www.selbie.com/wrek/storytime.png"; static final String LIO_ICON_URL = "http://www.selbie.com/wrek/lio.png"; static final String LIVE_STREAM_128KBS_URL = "http://streaming.wrek.org:8000/wrek_live-128kb.m3u"; static final String LIVE_STREAM_24KBS_URL = "http://streaming.wrek.org:8000/wrek_live-24kb-mono.m3u"; static final String LIVE_STREAM_ICON_URL = "http://www.selbie.com/wrek/radio2.png"; static final String SUBNET_STREAM_128KBS_URL = "http://streaming.wrek.org:8000/wrek_HD-2.m3u"; static final String SUBNET_STREAM_ICON_URL = "http://www.selbie.com/wrek/hd.png"; static final String LOGO_URL_ATMOSPHERICS = "http://www.selbie.com/wrek/atmospherics.png"; static final String LOGO_URL_CLASSICS = "http://www.selbie.com/wrek/classics.png"; static final String LOGO_URL_JUSTJAZZ = "http://www.selbie.com/wrek/justjazz.png"; static final String LOGO_URL_BLUEPLATE = "http://www.selbie.com/wrek/blueplate.png"; static final String LOGO_URL_RRR = "http://www.selbie.com/wrek/rrr.png"; static final String TECHNIQUES_ICON_URL = "http://www.selbie.com/wrek/techniques.png"; static final String SLOWRIOT_ICON_URL = "http://www.selbie.com/wrek/slowriot.png"; public Resolver() { } private ArrayList<String> CrackM3U(String m3uURL) { ArrayList<String> urls = new ArrayList<String>(); URL url = null; StringBuilder stringBuilder = new StringBuilder(); if ((m3uURL == null) || m3uURL.isEmpty()) { return urls; } System.out.println("Cracking " + m3uURL + " into component parts"); try { url = new URL(m3uURL); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); return urls; } try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); char [] buffer = new char[5000]; while (true) { int result = reader.read(buffer); if (result < 0) { break; } stringBuilder.append(buffer, 0, result); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return urls; } String str = stringBuilder.toString(); String [] lines = str.split("\\r?\\n"); for (String line : lines) { line = line.trim(); if (line.length() > 0) { urls.add(line); System.out.println(" " + line); } } return urls; } private void mergeDescriptionsIntoShows(ArrayList<Show> shows, ArrayList<ShowDescription> descriptions) { HashMap<String, ShowDescription> mapDescriptions = new HashMap<String, ShowDescription>(); for (ShowDescription desc : descriptions) { mapDescriptions.put(desc.Title, desc); } for (Show show : shows) { ShowDescription desc = mapDescriptions.get(show.Title); if (desc != null) { show.Genres = desc.Genres; show.LogoURL = desc.LogoURL; } } } ArrayList<Show> getLiveShows() { Show s1 = new Show(); Show s2 = new Show(); s1.Title = "Live air stream"; s1.Genres = "What's on the air right now"; s1.LiveStream = true; s1.M3U_High = LIVE_STREAM_128KBS_URL; s1.M3U_Low = LIVE_STREAM_24KBS_URL; s1.LogoURL = LIVE_STREAM_ICON_URL; s1.TypeOfShow = Show.ShowType.Live; s1.HasIcyMetaInt = true; s2.Title = "HD2 Subchannel"; s2.Genres = "Alternate programming"; s2.LiveStream = true; s2.M3U_High = SUBNET_STREAM_128KBS_URL; s2.LogoURL = SUBNET_STREAM_ICON_URL; s2.TypeOfShow = Show.ShowType.Live; s2.HasIcyMetaInt = true; ArrayList<Show> shows = new ArrayList<Show>(); shows.add(s1); shows.add(s2); return shows; } public void fixupDates(Show show) { String dayOfWeek = ""; String datePart = ""; int month = 0; int day = 0; if (show.DayText.isEmpty()) { return; } String [] splits = show.DayText.split(" "); if (splits.length >= 2) { dayOfWeek = splits[0]; datePart = splits[1]; String [] subsplit = datePart.split("/"); if (subsplit.length >= 2) { month = Integer.parseInt(subsplit[0]); day = Integer.parseInt(subsplit[1]); } } if ((month != 0) && (day != 0)) { show.DayText = dayOfWeek; show.MonthInt = month; show.DayInt = day; } } public void fixupGenreAndLogos(Show show, HashMap<String, Show> showMap) { String [] titles = {"atmospherics", "the classics", "just jazz", "rock, rhythm, and roll", "blue plate special", "the locals", "tapas and tunes", "pop up show", "a bit off broadway", "freaker's ball", "storytime", "slow riot", "techniques"}; String [] genres = {"Ambient, drone, spaced-out", "Classical (Traditional and contemporary)", "Jazz", "Indie rock, Blues, Hip-Hop, and more", "Diverse", "Atlanta area music", "Latin and Spanish", "New show", "Musical", "Classic Rock", "Concept album", "Post rock, instrumental, math rock", "Turntablism, Instrumental Hip Hop, Chopped and Screwed", }; String [] logos = {LOGO_URL_ATMOSPHERICS, LOGO_URL_CLASSICS, LOGO_URL_JUSTJAZZ, LOGO_URL_RRR, LOGO_URL_BLUEPLATE, THELOCALS_ICON_URL, TAPAS_ICON_URL, POPUP_ICON_URL, BROADWAY_ICON_URL, FREAKERS_ICON_URL, STORYTIME_ICON_URL, SLOWRIOT_ICON_URL, TECHNIQUES_ICON_URL }; // try to resolve show descriptions and logos using the map file (if available) if (showMap != null) { if (show.Genres.isEmpty() && showMap.containsKey(show.Title.toLowerCase())) { Show entry = showMap.get(show.Title.toLowerCase()); show.Genres = entry.Genres; } if (show.LogoURL.isEmpty() && showMap.containsKey(show.Title.toLowerCase())) { Show entry = showMap.get(show.Title.toLowerCase()); show.LogoURL = entry.LogoURL; } } if (show.Genres.isEmpty()) { for (int x = 0; x < titles.length; x++) { if (show.Title.toLowerCase().equals(titles[x])) { show.Genres = genres[x]; } } } if (show.LogoURL.isEmpty()) { for (int x = 0; x < titles.length; x++) { if (show.Title.toLowerCase().equals(titles[x])) { show.LogoURL = logos[x]; } } } // The Longboards show has been missing a show logo. So let's give it one. if (show.Title.toLowerCase().equals("the longboards show") && show.LogoURL.isEmpty()) { show.LogoURL = LONGBOARD_ICON_URL; } } public void resolve(ArrayList<Show> shows, ArrayList<ShowDescription> descriptions, HashMap<String, Show> showMap) { mergeDescriptionsIntoShows(shows, descriptions); // add in the live shows - they get their M3Us cracked as well ArrayList<Show> showsLive = this.getLiveShows(); for (int x = showsLive.size()-1; x >= 0; x--) { // prepend the live shows to the show list since they get shown first shows.add(0, showsLive.get(x)); } // turn each M3U into a playlist for (Show s : shows) { if (!s.M3U_High.isEmpty() && !s.M3U_High.contains("http")) { s.M3U_High = "https://www.wrek.org" + s.M3U_High; } if (!s.M3U_Low.isEmpty() && !s.M3U_Low.contains("http")) { s.M3U_Low = "https://www.wrek.org" + s.M3U_Low; } s.urls_High = CrackM3U(s.M3U_High); s.urls_Low = CrackM3U(s.M3U_Low); } // do fixups for (Show s : shows) { fixupDates(s); fixupGenreAndLogos(s, showMap); } for (Show show : shows) { System.out.println("\n============================================"); System.out.println(show.Title); System.out.println(show.TypeOfShow.toString()); System.out.println(show.Genres); System.out.println(show.LogoURL); System.out.println(show.DayText + " (" + show.MonthInt + "/" + show.DayInt + ")"); System.out.println(show.Time); System.out.println(show.M3U_High); for (String url : show.urls_High) System.out.println(" " + url); System.out.println(show.M3U_Low); for (String url : show.urls_Low) System.out.println(" " + url); } } public ArrayList<Show> filterForToday(ArrayList<Show> shows) { // Cull out of the show list anything that isn't a specialty show or live stream // But do include the latest versions of "Atmospherics", "Just Jazz", "The Classics", "Rock, Rhythm, and Roll" into the schedule // let's figure out what today it is today Calendar calendar = Calendar.getInstance(); int dayofweek = calendar.get(Calendar.DAY_OF_WEEK); Show justjazz = null; Show classics = null; Show atmospherics = null; Show rockroll = null; // roll back to Friday if it's the weekend if (dayofweek == Calendar.SATURDAY) { calendar.add(Calendar.DAY_OF_WEEK, -1); } else if (dayofweek == Calendar.SUNDAY) { calendar.add(Calendar.DAY_OF_WEEK, -2); } int targetMonth = calendar.get(Calendar.MONTH) + 1; // months are zero-indexed. DAY_OF_MONTH is 1 based. go figure... int targetDay = calendar.get(Calendar.DAY_OF_MONTH); for (Show show : shows) { if ((show.MonthInt == targetMonth) && (show.DayInt == targetDay)) { String title = show.Title.toLowerCase(); if (title.equals("just jazz")) { justjazz = show; } else if (title.equals("the classics")) { classics = show; } else if (title.equals("atmospherics")) { atmospherics = show; } else if (title.equals("rock, rhythm, and roll")) { rockroll = show; } } } ArrayList<Show> newlist = new ArrayList<Show>(); // copy over the live streams for (Show show : shows) { if (show.LiveStream) { newlist.add(show); } } // now add the format blocks for today if (atmospherics != null) { newlist.add(atmospherics); } if (classics != null) { newlist.add(classics); } if (justjazz != null) { newlist.add(justjazz); } if (rockroll != null) { newlist.add(rockroll); } // now copy over all the specialty shows for (Show show : shows) { if ((show.TypeOfShow == Show.ShowType.SpecialtyShow) && !show.Title.equalsIgnoreCase("the best of our knowledge")) { newlist.add(show); } } return newlist; } }
true
6592a61424d8b0e5b017a13e2772abcbbb7ebd0a
Java
jemoii/je-veri
/src/main/java/me/voler/jeveri/controller/IndexController.java
UTF-8
3,299
2.171875
2
[]
no_license
package me.voler.jeveri.controller; import javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import me.voler.jeveri.service.Verification; import me.voler.jeveri.service.VerificationService; import me.voler.jeveri.util.enumeration.SendError; import me.voler.jeveri.util.enumeration.VerifyError; import me.voler.jeveri.util.ticket.SignatureUtil; @Controller public class IndexController { @Autowired @Qualifier("emailVerification") private VerificationService EmailVerification; @Autowired @Qualifier("messageVerification") private VerificationService MessageVerification; @Resource private SignatureUtil SignatureUtil; @ResponseBody @RequestMapping(value = "/delivery", method = RequestMethod.POST) public JSONResponse send(DeliveryInput input) { if (!SignatureUtil.checkSign(input)) { return new JSONResponse(false, SendError.SIGNATURE_ERROR); } SendError sendError = SendError.NONE_ERROR; Verification verification = new Verification(); BeanUtils.copyProperties(input, verification); if (verification.getIdentity().indexOf('@') == -1) { sendError = MessageVerification.send(verification); } else { sendError = EmailVerification.send(verification); } if (sendError.getErrCode() < 0) { return new JSONResponse(false, sendError); } else { return new JSONResponse(sendError); } } /** * * @param identity * 手机号 * @param token * 短信验证码 * @return */ @ResponseBody @RequestMapping(value = "/matching", method = RequestMethod.GET) public JSONResponse verify(@RequestParam String identity, @RequestParam String token) { Verification verification = new Verification(); verification.setIdentity(identity); verification.setToken(token); VerifyError verifyError = MessageVerification.verify(verification); if (verifyError.getErrCode() < 0) { return new JSONResponse(false, verifyError); } else { return new JSONResponse(verifyError); } } /** * 邮箱验证成功且设置了应用回调链接,重定向至回调链接;否则返回空白页 * * @param token * 邮箱验证token * @return */ @ResponseBody @RequestMapping(value = "/check", method = RequestMethod.GET) public ModelAndView verify(@RequestParam String token) { Verification verification = EmailVerification.verify(token); ModelAndView mv = new ModelAndView("check"); if (verification == null || StringUtils.isEmpty(verification.getCallback())) { mv.addObject("verify", false); mv.addObject("callback", "http://duapp.voler.me/jeadmin/"); } else { mv.addObject("verify", true); mv.addObject("callback", String.format("%s?id=%s&res=true", verification.getCallback(), verification.getIdentity())); } return mv; } }
true
8af8ff30ab329634a36a116b5e806fb5016bca82
Java
bingoohuang/spring-redis-cache
/src/main/java/com/github/bingoohuang/springrediscache/RedisCacheNameGenerator.java
UTF-8
206
1.898438
2
[ "Apache-2.0" ]
permissive
package com.github.bingoohuang.springrediscache; import org.aopalliance.intercept.MethodInvocation; public interface RedisCacheNameGenerator { String generateCacheName(MethodInvocation invocation); }
true
801182373b61d8680706ac8d87afeccb0a79edca
Java
ChinnaVishnu/CORE
/CORE/src/test/java/com/jocata/core/existingfuctions/AddruleChangesFuctionaltiy.java
UTF-8
20,744
1.90625
2
[]
no_license
package com.jocata.core.existingfuctions; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.FluentWait; import org.openqa.selenium.support.ui.Wait; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.Test; import com.google.common.base.Function; import com.jocata.core.basescripts.ExtentTestManager; import com.jocata.core.basescripts.GetScreenshort; import com.jocata.core.basescripts.mainbaseLatest; import com.relevantcodes.extentreports.LogStatus; public class AddruleChangesFuctionaltiy extends mainbaseLatest { public void clickComboItem(WebElement input, String target) { input.click(); // click input to pop up the combo list List<WebElement> comboItems = driver.findElements( By.xpath("//div[@id='ruleBldrVOThreshholdTransDetList[7].thresholdTransDetFilterSubValitem-innerCt']")); for (int i = 1; i <= comboItems.size(); i++) { WebElement item = comboItems.get(i); System.out.println(item.getText()); if (item.getText().equals(target)) { item.click(); break; } } } public WebElement fluentWait(final By locator) { Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(50, TimeUnit.SECONDS) .pollingEvery(5, TimeUnit.SECONDS).ignoring(NoSuchElementException.class); WebElement foo = wait.until(new Function<WebDriver, WebElement>() { public WebElement apply(WebDriver driver) { return driver.findElement(locator); } }); return foo; }; public void sleep(int seconds) { try { Thread.sleep(seconds * 1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test(priority = 29) public void loginNew() throws InterruptedException { ExtentTestManager.startTest(" Create New Rule : Using All Threshold Parameters "); // Newcreateruleexcel ruleSheet =new Newcreateruleexcel("Frist"); // driver.findElement(By.xpath("//input[@id='userName']")).sendKeys("l3_user"); // driver.findElement(By.xpath("//input[@id='password']")).sendKeys("Star@123"); // driver.findElement(By.xpath("//span[@id='loginButtonExt-btnIconEl']")).click(); // sleep(10); String ruleName = "rule"; for (int i = 2; i < 3; i++) { // for(String ruleName:ruleSheet.getData()){ /* * int ruleNameincrementor = 0;--Databahasse * * connect to database to the table that has this value fetch the * the updated value * * ruleNameincrementor = updated value; * * ruleNameincrementor++; ruleName = ruleName + ruleNameincrementor; * updATE THIS VALUE TO DB AGAIN */ ruleName = ruleName + new Date().getTime(); System.out.println("ruleName" + ruleName); ExtentTestManager.getTest().log(LogStatus.PASS, ruleName); ExtentTestManager.getTest().log(LogStatus.INFO, "New Rule "); // System.out.println(); sleep(1); clickDashboard(ruleName); } /* * if(){ * * } */ // String name = "Vishnuvaradhanyadav"+count; // count++; // new // StringBuilder().append("Vishnuvaradhanyadav").append("Vishnuvaradhanyadav"+count).toString(); // clickDashboard(name); } public void clickDashboard(String name) throws InterruptedException { try { sleep(12); driver.findElement(By.xpath("//span[text()='Rules and Patterns']")).click(); sleep(6); driver.findElement(By.xpath("//a[text()='Rule Builder']")).click(); sleep(6); fluentWait(By.xpath("//a[@class='add-icon icon']")).click(); sleep(6); fluentWait(By.xpath("//input[@id='ruleTemplateCombo-inputEl']")).click(); fluentWait(By.xpath("//div[@data-qtip='Transaction Determination']")).click(); fluentWait(By.xpath("//input[@id='ruleModel-inputEl']")).click(); fluentWait(By.xpath("//li[text()='Cash and Structuring']")).click(); /* * WebElement element * =driver.findElement(By.xpath("//input[@id='ruleModel-inputEl']")) * ; Select select=new Select(element); select.selectByVisibleText( * "Cash and Structuring"); * * */ // ..................................................Rule // Name..................................................................// fluentWait(By.xpath("//input[@id='ruleName']")).sendKeys(name); // clicking Desception// fluentWait(By.xpath("//textarea[@id='ruleDescription']")).sendKeys(" how are you"); // clicking the Referencenumber// fluentWait(By.xpath("//input[@id='ruleReferenceNmbr']")).sendKeys("1234455"); // selecting the level// fluentWait(By.xpath("//input[@id='investigationLevel-inputEl']")).click(); fluentWait(By.xpath("//li[text()='L1 User']")).click(); // fluentWait(By.xpath("//li[text()='Analyst']")).click(); // clicking the priority levels // fluentWait(By.xpath("//input[@id='rulePriority-inputEl']")).click(); fluentWait(By.xpath("//li[text()='4']")).click(); fluentWait(By.xpath("//input[@id='valDetRulePeriod']")).sendKeys("23"); // clickcing the key parameter// fluentWait(By.xpath("//input[@id='keyParameter-inputEl']")).click(); // ...................................Key // Parameter......................................................................// sleep(9); fluentWait(By.xpath("//div[@data-qtip='Tran. Amount']")).click(); // clicking the status// fluentWait(By.xpath("//input[@id='ruleStatus-inputEl']")).click(); fluentWait(By.xpath("//li[text()='Inactive']")).click(); // ..................................................Customer/Account // Filter...................................................// fluentWait( By.xpath(".//*[@id='temp_ruleBldrVOAccCusTransDetList[0].custAccTransDetFilterVal-triggerWrap']")) .click(); // ............................................................Account // Age.................................................// fluentWait(By.xpath("//div[contains(@id,'boundlist-')][7]//li[2]")).click(); fluentWait(By.xpath(".//*[@id='ruleBldrVOAccCusTransDetList[0].custAccTransDetFilterFromVal']")) .sendKeys("23"); fluentWait(By.xpath(".//*[@id='ruleBldrVOAccCusTransDetList[0].custAccTransDetFilterToVal']")) .sendKeys("34"); fluentWait(By.xpath("(//a[contains(text(),'Add Condition')])[3]")).click(); fluentWait(By.xpath("//input[@id='temp_ruleBldrVOAccCusTransDetList[1].custAccTransDetFilterVal-inputEl']")) .click(); // .........................................................Account // Balance..................................................// /* * Thread.sleep(9000); //fluentWait(By.xpath( * "//div[contains(@id,'boundlist-')][8]//li[3]")).click(); * * fluentWait(By.xpath("//div[@id='boundlist-1033-listEl']//li[3]")) * .click(); * * * fluentWait(By.xpath( * ".//*[@id='ruleBldrVOAccCusTransDetList[1].custAccTransDetFilterFromVal']" * )).sendKeys("66"); * * * fluentWait(By.xpath( * ".//*[@id='ruleBldrVOAccCusTransDetList[1].custAccTransDetFilterToVal']" * )).sendKeys("77"); */ // ................................... Threshold // Parameters........................................................................// WebDriverWait wait = new WebDriverWait(driver, 60); wait.until(ExpectedConditions.visibilityOfElementLocated( By.id("temp_ruleBldrVOThreshholdTransDetList[0].thresholdTransDetFilterVal-inputEl"))); fluentWait(By.id("temp_ruleBldrVOThreshholdTransDetList[0].thresholdTransDetFilterVal-inputEl")).click(); fluentWait(By.xpath("//li[text()='Tran. Amount']")).click(); WebElement elementTothreshold = fluentWait( By.xpath("//input[@id='ruleBldrVOThreshholdTransDetList[0].thresholdTransDetFilterFromVal']")); // Scroll the browser to the element's Y position ((JavascriptExecutor) driver) .executeScript("window.scrollTo(0," + elementTothreshold.getLocation().y + ")"); // Click the element elementTothreshold.sendKeys("32"); WebElement elementTothresholdsecond = fluentWait( By.xpath("//input[@id='ruleBldrVOThreshholdTransDetList[0].thresholdTransDetFilterToVal']")); // Scroll the browser to the element's Y position ((JavascriptExecutor) driver) .executeScript("window.scrollTo(0," + elementTothresholdsecond.getLocation().y + ")"); // Click the element elementTothresholdsecond.sendKeys("47"); fluentWait(By.xpath("(//a[contains(text(),'Add Condition')])[4]")).click(); fluentWait(By .xpath("//table[@id='temp_ruleBldrVOThreshholdTransDetList[1].thresholdTransDetFilterVal-triggerWrap']//following::div[1]")) .click(); // fluentWait(By.xpath(".//*[@id='temp_ruleBldrVOThreshholdTransDetList[1].thresholdTransDetFilterVal-inputEl']")).click(); // fluentWait(By.xpath("//div[contains(@id,'boundlist-')][3]//li[2]")).click(); fluentWait(By.xpath("//div[@id='boundlist-1035-listEl']//li[2]")).click(); // fluentWait(By.xpath("//div[@id='boundlist-1035-listEl']//li[2]")).click(); fluentWait(By .xpath("//input[@id='ruleBldrVOThreshholdTransDetList[1].thresholdTransDetFilterSubVal-inputEl']")) .click(); fluentWait(By.xpath("//div[@data-qtip='Debit Card']")).click(); // fluentWait(By.xpath("//b[text()='Threshold // Parameters']")).click(); fluentWait(By.xpath("(//a[contains(text(),'Add Condition')])[4]")).click(); // .........................................................ThridType............................................................// fluentWait(By .xpath("//table[@id='temp_ruleBldrVOThreshholdTransDetList[2].thresholdTransDetFilterVal']//following::div[2]")) .click(); fluentWait(By.xpath("//div[@id='boundlist-1037-listEl']//li[3]")).click(); fluentWait(By .xpath("//input[@id='ruleBldrVOThreshholdTransDetList[2].thresholdTransDetFilterSubVal-inputEl']")) .click(); fluentWait(By.xpath("//div[@data-qtip='ATM']")).click(); fluentWait(By.xpath("(//a[contains(text(),'Add Condition')])[4]")).click(); // ..................................................FourthType................................................................// // .................................................CounterCountry.............................................................// fluentWait(By .xpath("//table[@id='temp_ruleBldrVOThreshholdTransDetList[3].thresholdTransDetFilterVal-triggerWrap']//following::div")) .click(); fluentWait(By.xpath("//div[@id='boundlist-1039-listEl']//li[4]")).click(); fluentWait(By .xpath("//input[@id='ruleBldrVOThreshholdTransDetList[3].thresholdTransDetFilterSubVal-inputEl']")) .click(); fluentWait(By.xpath("//div[@data-qtip='Angola']")).click(); fluentWait(By.xpath("(//a[contains(text(),'Add Condition')])[4]")).click(); // ....................................................FiveType................................................................// // ...................................................CounteryRisk.................................................................// fluentWait(By .xpath("//table[@id='temp_ruleBldrVOThreshholdTransDetList[4].thresholdTransDetFilterVal-triggerWrap']//following::div")) .click(); fluentWait(By.xpath("//div[@id='boundlist-1041-listEl']//li[5]")).click(); fluentWait(By .xpath("//input[@id='ruleBldrVOThreshholdTransDetList[4].thresholdTransDetFilterSubVal-inputEl']")) .click(); fluentWait(By.xpath("//div[@data-qtip='Low']")).click(); fluentWait(By.xpath("(//a[contains(text(),'Add Condition')])[4]")).click(); // ..................................................SixType................................................................// // ..................................................CR or // DR................................................................// fluentWait(By .xpath("//table[@id='temp_ruleBldrVOThreshholdTransDetList[5].thresholdTransDetFilterVal-triggerWrap']//following::div")) .click(); fluentWait(By.xpath("//div[@id='boundlist-1043-listEl']//li[6]")).click(); fluentWait(By .xpath("//input[@id='ruleBldrVOThreshholdTransDetList[5].thresholdTransDetFilterSubVal-inputEl']")) .click(); fluentWait(By.xpath("//div[@data-qtip='Cr']")).click(); fluentWait(By.xpath("(//a[contains(text(),'Add Condition')])[4]")).click(); // ..................................................SixType................................................................// // ......................................................In // stumentType.........................................................// fluentWait(By .xpath("//table[@id='temp_ruleBldrVOThreshholdTransDetList[6].thresholdTransDetFilterVal-triggerWrap']//following::div")) .click(); fluentWait(By.xpath("//div[@id='boundlist-1045-listEl']//li[7]")).click(); fluentWait(By .xpath("//input[@id='ruleBldrVOThreshholdTransDetList[6].thresholdTransDetFilterSubVal-inputEl']")) .click(); fluentWait(By.xpath("//div[@data-qtip='0']")).click(); fluentWait(By.xpath("(//a[contains(text(),'Add Condition')])[4]")).click(); // ..................................................SevenType................................................................// fluentWait(By .xpath("//table[@id='temp_ruleBldrVOThreshholdTransDetList[7].thresholdTransDetFilterVal-triggerWrap']//following::div")) .click(); fluentWait(By.xpath("//div[@id='boundlist-1047-listEl']//li[8]")).click(); // Thread.sleep(8000); /* * WebElement Marchemntty= fluentWait(By.xpath( * "//div[@data-qtip='MERCHANT TYPE 10']")); * * Actions action=new Actions(driver); * * action.moveToElement(Marchemntty).sendKeys(Keys.ENTER).build(). * perform(); */ // driver.findElement(By.cssSelector("li.x-boundlist-item.x-boundlist-item-over")).click(); Thread.sleep(8000); driver.findElement(By.xpath("//li[4]/div")).click(); /* * Thread.sleep(4000); * * //fluentWait(By.xpath("//div[@data-qtip='MERCHANT TYPE 10']" * )).click(); * * fluentWait(By.xpath("//ul[@class='x-list-plain']//li[2]")).click( * ); * * Thread.sleep(19000); * * WebElement input= driver.findElement(By.xpath( * "//div[@data-qtip='MERCHANT TYPE 10']")); * * String target=" MERCHANT TYPE 10"; * * clickComboItem(input, target); */ Thread.sleep(19000); fluentWait(By.xpath("(//a[contains(text(),'Add Condition')])[4]")).click(); // ..................................................PurposeCode.................................................................. Thread.sleep(2000); fluentWait(By .xpath("//table[@id='temp_ruleBldrVOThreshholdTransDetList[8].thresholdTransDetFilterVal']//following::div[2]")) .click(); fluentWait(By.xpath("//div[@id='boundlist-1050-listEl']//li[9]")).click(); fluentWait(By .xpath("//input[@id='ruleBldrVOThreshholdTransDetList[8].thresholdTransDetFilterSubVal-inputEl']")) .click(); Thread.sleep(2000); fluentWait(By.xpath("//div[@data-qtip='P0001']")).click(); Thread.sleep(3000); fluentWait(By.xpath("(//a[contains(text(),'Add Condition')])[4]")).click(); // ..................................................ReportCode.................................................................. fluentWait(By .xpath("//table[@id='temp_ruleBldrVOThreshholdTransDetList[9].thresholdTransDetFilterVal-triggerWrap']//following::div")) .click(); fluentWait(By.xpath("//div[@id='boundlist-1052-listEl']//li[10]")).click(); fluentWait(By .xpath("//input[@id='ruleBldrVOThreshholdTransDetList[9].thresholdTransDetFilterSubVal-inputEl']")) .click(); fluentWait(By.xpath("//div[@data-qtip='Report Code1']")).click(); Thread.sleep(3000); fluentWait(By.xpath("(//a[contains(text(),'Add Condition')])[4]")).click(); // ............................................Trans.SubType.......................................................................// fluentWait(By .xpath("//table[@id='temp_ruleBldrVOThreshholdTransDetList[10].thresholdTransDetFilterVal-triggerWrap']//following::div")) .click(); fluentWait(By.xpath("//div[@id='boundlist-1054-listEl']//li[12]")).click(); fluentWait(By .xpath("//input[@id='ruleBldrVOThreshholdTransDetList[10].thresholdTransDetFilterSubVal-inputEl']")) .click(); fluentWait(By.xpath("//div[@data-qtip='Cash - Cash']")).click(); Thread.sleep(3000); fluentWait(By.xpath("(//a[contains(text(),'Add Condition')])[4]")).click(); // ............................................Trans.Type.......................................................................// ExtentTestManager.getTest().log(LogStatus.INFO, "Screenshortbelow :" + ExtentTestManager.getTest() .addScreenCapture(GetScreenshort.capture(driver, "ScreenshortForExtentReport"))); fluentWait(By .xpath("//table[@id='temp_ruleBldrVOThreshholdTransDetList[11].thresholdTransDetFilterVal-triggerWrap']//following::div")) .click(); fluentWait(By.xpath("//div[@id='boundlist-1056-listEl']//li[13]")).click(); fluentWait(By .xpath("//input[@id='ruleBldrVOThreshholdTransDetList[11].thresholdTransDetFilterSubVal-inputEl']")) .click(); fluentWait(By.xpath("//div[@data-qtip='Cash']")).click(); Thread.sleep(3000); fluentWait(By.xpath("(//a[contains(text(),'Add Condition')])[4]")).click(); // ............................................TransCation // .Branch.......................................................................// fluentWait(By .xpath("//table[@id='temp_ruleBldrVOThreshholdTransDetList[12].thresholdTransDetFilterVal-triggerWrap']//following::div")) .click(); fluentWait(By.xpath("//div[@id='boundlist-1058-listEl']//li[14]")).click(); fluentWait(By .xpath("//input[@id='ruleBldrVOThreshholdTransDetList[12].thresholdTransDetFilterSubVal-inputEl']")) .click(); fluentWait(By.xpath("//div[@data-qtip='Dilsukhnagar']")).click(); sleep(10); fluentWait(By.xpath("(//a[contains(text(),'Add Condition')])[4]")).click(); ExtentTestManager.getTest().log(LogStatus.INFO, "Screenshortbelow :" + ExtentTestManager.getTest() .addScreenCapture(GetScreenshort.capture(driver, "ScreenshortForExtentReport"))); sleep(10); // clicking the Save rule// fluentWait(By.xpath("//div[@id='createRuleTransDet']//span")).click(); ExtentTestManager.getTest().log(LogStatus.INFO, "Screenshortbelow :" + ExtentTestManager.getTest() .addScreenCapture(GetScreenshort.capture(driver, "ScreenshortForExtentReport"))); // sucessfully created sleep(10); ExtentTestManager.getTest().log(LogStatus.INFO, "Screenshortbelow :" + ExtentTestManager.getTest() .addScreenCapture(GetScreenshort.capture(driver, "ScreenshortForExtentReport"))); fluentWait(By.xpath("//img[@class='x-tool-img x-tool-close']")).click(); sleep(10); ExtentTestManager.getTest().log(LogStatus.INFO, "Screenshortbelow :" + ExtentTestManager.getTest() .addScreenCapture(GetScreenshort.capture(driver, "ScreenshortForExtentReport"))); sleep(9); System.out.println("Sucess"); ExtentTestManager.getTest().log(LogStatus.INFO, " Create Rule Successfully "); } catch (Exception e) { sleep(19); ExtentTestManager.getTest().log(LogStatus.INFO, "Screenshortbelow :" + ExtentTestManager.getTest() .addScreenCapture(GetScreenshort.capture(driver, "ScreenshortForExtentReport"))); driver.navigate().refresh(); System.out.println("referesh................"); ExtentTestManager.getTest().log(LogStatus.FAIL, "missing modules of the Threshold parameters"); } } }
true
25321021a13da614a9826572262a4ac361fe94e4
Java
asaow/FlightServer
/src/main/java/com/mycompany/flightserver/service/BookingServices.java
UTF-8
1,218
2.484375
2
[]
no_license
package com.mycompany.flightserver.service; import com.mycompany.flightserver.hibernate.HibernateQueries; import com.mycompany.flightserver.model.Booking; import java.util.List; /** * * @author Grupp 2 */ public class BookingServices { HibernateQueries hibernateQueries = new HibernateQueries(); public BookingServices() { } /** * Metoden getBooking hämtar en bokning. * * @param bookingId * @return en bokning */ public Booking getBooking(int bookingId) { return hibernateQueries.getBooking(bookingId); } /** * Metoden getBookings hämtar en lista med alla bokningar. * * @return en lista med alla bokningar */ public List<Booking> getBookings() { return hibernateQueries.getBookings(); } /** * Metoden createBooking skapar en bokning. * * @param b * @return en bokning */ public Booking createBooking(Booking b) { return hibernateQueries.createBooking(b); } /** * Metoden deleteBooking tar bort en bokning. * * @param bookingId */ public void deleteBooking(int bookingId) { hibernateQueries.deleteBooking(bookingId); } }
true
f7cba4ca3ac3a1e74a97a40c03a23a20e73d2040
Java
AndroidTVDeveloper/com.google.android.tvlauncher
/HOLD/sources/defpackage/atr.java
UTF-8
1,095
1.90625
2
[]
no_license
package defpackage; import android.media.MediaCodecInfo; import android.media.MediaCodecList; /* renamed from: atr reason: default package */ /* compiled from: PG */ final class atr implements atp { private final int a; private MediaCodecInfo[] b; public atr(boolean z, boolean z2) { int i = 1; if (!z && !z2) { i = 0; } this.a = i; } public final boolean b() { return true; } private final void c() { if (this.b == null) { this.b = new MediaCodecList(this.a).getCodecInfos(); } } public final int a() { c(); return this.b.length; } public final MediaCodecInfo a(int i) { c(); return this.b[i]; } public final boolean a(String str, MediaCodecInfo.CodecCapabilities codecCapabilities) { return codecCapabilities.isFeatureRequired(str); } public final boolean a(String str, String str2, MediaCodecInfo.CodecCapabilities codecCapabilities) { return codecCapabilities.isFeatureSupported(str); } }
true
4451ab7bf6c399f58b0a6d381c14929eb9b394ed
Java
pombredanne/lsh-for-source-code
/Big_Clone_Bench_files_used/bcb_reduced/3/selected/797815.java
UTF-8
14,175
2.03125
2
[ "MIT" ]
permissive
package com.entelience.tomcat; import java.io.IOException; import java.util.Hashtable; import java.util.Enumeration; import java.util.ArrayList; import java.util.List; import java.util.Iterator; import java.util.Map; import java.util.HashMap; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.FilterChain; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Cookie; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import jcifs.Config; import jcifs.smb.NtlmPasswordAuthentication; /** * This is an J2EE filter to authenticate user with NTLM and grant access based on groups memberships. It extends the Samba JCIFS * <a href="http://jcifs.samba.org/src/docs/ntlmhttpauth.html">NtlmHttpFilter</a>. * * The following parameters can be defined within the <code>web.xml</code>: * <ul><li>com.entelience.tomcat.debug : to activate debug logs</li> * <li>com.entelience.tomcat.denyPage : to define the deny login page</li> * <li>com.entelience.tomcat.paranoid : to activate the NTLM/AD check for every request</li> * <li>com.entelience.tomcat.autoRedirect : to activate the redirection to the first allowed url</li> * <li>url: to define the url to be protected, the AD group is the value</li> * <li>com.entelience.tomcat.ad_base : AD base CN</li> * </ul> * * It uses cookies to ensure the persistent of the session. The HttpSession seems to break things with Axis. */ public class ExtNtlmHttpFilter extends jcifs.http.NtlmHttpFilter { private FilterConfig filterConfig = null; private Map<String, String> urlToProtect = null; private String denyPage = "deny.html"; private boolean DEBUG = false; private boolean PARANOID = false; private boolean REDIRECT = false; private static final int max_queries = 1000; private int queries = 0; private static final String COOKIE_NAME = "ntlm_signon"; private Double salt = null; /** * Filter public constructor. Fetches the config parameter from the web.xml file */ public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; urlToProtect = new HashMap<String, String>(); Enumeration e = filterConfig.getInitParameterNames(); String name = ""; String value = null; while (e.hasMoreElements()) { name = (String) e.nextElement(); value = filterConfig.getInitParameter(name); if (name.startsWith("com.entelience.tomcat")) { Config.setProperty(name, value); filterConfig.getServletContext().log(this.getClass().getName() + " setting " + name + " to " + value); } else if (name.startsWith("url:") && value != null) { urlToProtect.put(value, name.substring(4)); filterConfig.getServletContext().log(this.getClass().getName() + " limiting access to " + name + " to users from group " + value); } } if (Config.getProperty("com.entelience.tomcat.denyPage") == null) { filterConfig.getServletContext().log(this.getClass().getName() + " no deny page configured"); } else { denyPage = Config.getProperty("com.entelience.tomcat.denyPage"); } if (Config.getProperty("com.entelience.tomcat.debug") != null) { DEBUG = true; } if (Config.getProperty("com.entelience.tomcat.paranoid") != null) { PARANOID = true; } if (Config.getProperty("com.entelience.tomcat.autoRedirect") != null) { REDIRECT = true; } salt = new Double(Math.random() * 1000000); super.init(filterConfig); filterConfig.getServletContext().log(this.getClass().getName() + " is configured"); } /** * This is called by Tomcat to purge the filter, for instance * on restart or shutdown */ public void destroy() { this.filterConfig = null; super.destroy(); } /** * This is the only method that we need to overwrite */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (filterConfig == null) { return; } if (++queries > max_queries) { queries = 0; salt = new Double(Math.random() * 1000000); if (DEBUG) filterConfig.getServletContext().log(this.getClass().getName() + " resetting salt"); } HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; String url = req.getRequestURI(); if (!isUrlProtected(url)) { if (DEBUG) filterConfig.getServletContext().log(this.getClass().getName() + " unprotected url " + url); chain.doFilter(request, response); } if (DEBUG) filterConfig.getServletContext().log(this.getClass().getName() + " filtering " + url); if (checkCookie(request) && !PARANOID) { if (DEBUG) filterConfig.getServletContext().log(this.getClass().getName() + " pass-through"); chain.doFilter(request, response); return; } NtlmPasswordAuthentication ntlm; if ((ntlm = negotiate(req, resp, false)) == null) { filterConfig.getServletContext().log(this.getClass().getName() + " NTLM negotiate failure"); filterConfig.getServletContext().getRequestDispatcher("/" + denyPage).forward(request, response); return; } String userName = ntlm.getName(); filterConfig.getServletContext().log(this.getClass().getName() + " NTLM authenticated user is " + userName); List<String> e = adLookup(userName); Iterator<String> ie = e.iterator(); boolean authorized = false; String group = ""; String alternateUrl = ""; while (ie.hasNext() && !authorized) { group = ie.next(); if (DEBUG) filterConfig.getServletContext().log(this.getClass().getName() + " user " + userName + " is part of group " + group); if (urlToProtect.containsKey(group)) { alternateUrl = (String) urlToProtect.get(group); if ((url.startsWith(alternateUrl))) { validateSignOn(request, response, alternateUrl); authorized = true; } } } if (!authorized) { if (!"".equals(alternateUrl) && REDIRECT) { filterConfig.getServletContext().log(this.getClass().getName() + " redirecting user " + userName + " to a url he is allowed to " + alternateUrl); filterConfig.getServletContext().getRequestDispatcher(alternateUrl).forward(request, response); } else { filterConfig.getServletContext().log(this.getClass().getName() + " denying url " + url + " for user " + userName); filterConfig.getServletContext().getRequestDispatcher("/" + denyPage).forward(request, response); } return; } if (DEBUG) filterConfig.getServletContext().log(this.getClass().getName() + " url " + url + " is ok for user " + userName); chain.doFilter(request, response); } /** * Returns true if the url is one that is protected by * this filter. */ private boolean isUrlProtected(String url) { Iterator<String> ie = urlToProtect.values().iterator(); while (ie.hasNext()) { if (url.startsWith(ie.next())) return true; } return false; } /** * Returns null or the url to protect */ private String getUrlProtected(String url) { Iterator<String> ie = urlToProtect.values().iterator(); String urlTP = null; while (ie.hasNext()) { urlTP = ie.next(); if (url.startsWith(urlTP)) return urlTP; } return null; } /** * Sessions are stored within a cookie. I tried using the HttpSession but somehow it is screwing up what * Axis is doing...need to revisit this later on. */ private void validateSignOn(ServletRequest request, ServletResponse response, String url) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; Cookie cookie = new Cookie(COOKIE_NAME, cookieString(url, req.getRemoteAddr())); cookie.setMaxAge(-1); cookie.setPath(url); res.addCookie(cookie); if (DEBUG) filterConfig.getServletContext().log(this.getClass().getName() + " cookie "); } /** * Returns the cookie string which contains a random part * that is generated each time the filter is (re)started. * * Cookies can be stolen/sniffed... so turning on SSL would be a * great idea. This version lacks something unique to the user that * can be retrieved without relaunching the NTLM. Any ideas ? */ private String cookieString(String url, String ip) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); md.update((url + "&&" + ip + "&&" + salt.toString()).getBytes()); java.math.BigInteger hash = new java.math.BigInteger(1, md.digest()); return hash.toString(16); } catch (NoSuchAlgorithmException e) { filterConfig.getServletContext().log(this.getClass().getName() + " error " + e); return null; } } /** * Checks it a cookie exists for this request */ private boolean checkCookie(ServletRequest request) { HttpServletRequest req = (HttpServletRequest) request; Cookie[] cookies = req.getCookies(); if (cookies != null) { for (int loop = 0; loop < cookies.length; loop++) { if (DEBUG) filterConfig.getServletContext().log(this.getClass().getName() + " cookie = " + cookies[loop].getName()); if (cookies[loop].getName().equals(COOKIE_NAME)) { String cookie = cookieString(getUrlProtected(req.getRequestURI()), req.getRemoteAddr()); if (cookie.equals(cookies[loop].getValue())) return true; } } } return false; } /** * Lookup the groups of user in a domain */ private List<String> adLookup(String userName) { List<String> groups = new ArrayList<String>(); try { String DOMAIN_CONTROLER = Config.getProperty("jcifs.http.domainController"); String DOMAIN_USER = Config.getProperty("jcifs.smb.client.username"); String DOMAIN_PWD = Config.getProperty("jcifs.smb.client.password"); String DOMAIN = Config.getProperty("jcifs.smb.client.domain"); String userLogon = userName.substring(DOMAIN.length() + 1); String AD_BASE = Config.getProperty("com.entelience.tomcat.ad_base"); String AD_SEARCH = Config.getProperty("com.entelience.tomcat.ad_search", "(&(objectClass=user)(CN=" + userLogon + "))"); Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, DOMAIN + "\\" + DOMAIN_USER); env.put(Context.SECURITY_CREDENTIALS, DOMAIN_PWD); String url = "ldap://" + DOMAIN_CONTROLER + ":389"; env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, url); if (DEBUG) filterConfig.getServletContext().log("Connecting to " + url); DirContext ctx; ctx = new InitialDirContext(env); SearchControls ctls = new SearchControls(); String returnedAtts[] = { "memberOf" }; ctls.setReturningObjFlag(false); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setReturningAttributes(returnedAtts); NamingEnumeration answer = ctx.search(AD_BASE, AD_SEARCH, ctls); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); Attributes attrs = sr.getAttributes(); if (attrs != null) { try { for (NamingEnumeration ae = attrs.getAll(); ae.hasMore(); ) { Attribute attr = (Attribute) ae.next(); if (DEBUG) filterConfig.getServletContext().log("Attribute: " + attr.getID()); for (NamingEnumeration e = attr.getAll(); e.hasMore(); ) { String group[] = (e.next().toString()).split(","); if (group[0].startsWith("CN=")) { groups.add(group[0].substring(3)); } else { filterConfig.getServletContext().log("Expecting a CN in " + group); } } } } catch (NamingException e) { filterConfig.getServletContext().log(this.getClass().getName() + " Problem listing membership: " + e); } } } ctx.close(); } catch (Exception e) { filterConfig.getServletContext().log(this.getClass().getName() + " error " + e); } return groups; } }
true
4d0a054877a25c7464f1ecc9f63ad6c439eba212
Java
zely20/java-developer-test-azelenko
/src/main/java/com/vizor/mobile/ConfigTweet.java
UTF-8
1,342
2.578125
3
[]
no_license
package com.vizor.mobile; import com.google.gson.annotations.SerializedName; import com.vizor.mobile.twitter.Rule; import com.vizor.mobile.twitter.Tweet; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class ConfigTweet implements Tweet { private String text; private List<Rule> matchingRules = new ArrayList<>(); @Override public String toString() { return "ConfigTweet{" + "text='" + text + '\'' + ", rules=" + matchingRules + '}'; } @Override public String getText() { return text; } @Override public List<Rule> getMatchingRules() { return matchingRules; } @Override public void setText(String text) { this.text = text; } @Override public void setMatchingRules(List<Rule> matchingRules) { this.matchingRules = matchingRules; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ConfigTweet tweet = (ConfigTweet) o; return Objects.equals(text, tweet.text) && Objects.equals(matchingRules, tweet.matchingRules); } @Override public int hashCode() { return Objects.hash(text, matchingRules); } }
true
2866ed2c465dba0636ed825f4dc82a23096b39cf
Java
AndreasNiederschick/weckdengeparden
/src/main/java/com/gepardec/wdg/guiRunner/RestGUI.java
UTF-8
11,837
2.265625
2
[]
no_license
package com.gepardec.wdg.guiRunner; import com.fasterxml.jackson.databind.ObjectMapper; import com.gepardec.wdg.challenge.model.ConstraintViolationResponse; import com.gepardec.wdg.client.personio.Source; import org.jboss.logging.Logger; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import static javax.swing.WindowConstants.EXIT_ON_CLOSE; public class RestGUI extends JFrame { private JPanel basic; private JLabel jobIdLabel; private JLabel vornameLabel; private JLabel nachnameLabel; private JLabel emailLabel; private JLabel gitHubLinkLabel; private JLabel sourceLabel; private JLabel messageToGepardecLabel; private JLabel titelLabel; private JLabel otherSourceLabel; private JLabel telefonLabel; private JLabel linkedInLabel; private JTextField jobIdTextField; private JTextField vornameTextField; private JTextField nachnameTextField; private JTextField emailTextField; private JTextField gitHubTextField; private JTextField sourceTextField; private JTextField titelTextField; private JTextField otherSourceTextField; private JTextField telefonTextField; private JTextField linkedInTextField; private JTextField xingTextField; private JTextField cvTextField; private JLabel cvLabel; private JLabel xingLabel; private JButton submitButton; private JTextArea messageTextArea; private JComboBox sourceComboBox; final static String utf8 = "utf-8"; final static String WDG_ITANDTEL = "https://weckdengeparden-57-services.cloud.itandtel.at"; private static final org.jboss.logging.Logger log = Logger.getLogger(RestGUI.class.getName()); public static void main(String[] args) { JFrame frame = new JFrame("Bewerbung Formular"); ImageIcon pic = new ImageIcon("gepardec_icon.jpg"); frame.setIconImage(pic.getImage()); frame.setContentPane(new RestGUI().basic); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setSize(475, 500); frame.setResizable(false); frame.setVisible(true); } public RestGUI() { sourceComboBox.setModel(new DefaultComboBoxModel(Source.values())); submitButton.addActionListener(e -> { URL url; try { url = new URL(WDG_ITANDTEL+"/challenge/2/url/"); } catch (MalformedURLException malformedURLException) { log.error("Error while assign the URL." + malformedURLException.getMessage(), malformedURLException); JOptionPane.showMessageDialog(null, "Es ist ein Fehler beim Verbindungsaufbau aufgetreten\n"+malformedURLException.getMessage()); return; } HttpURLConnection con; try { con = (HttpURLConnection) url.openConnection(); } catch (IOException ioException) { log.error("Error while opening the HttpURLConnection." + ioException.getMessage(), ioException); JOptionPane.showMessageDialog(null, "Es ist ein Fehler beim Verbindungsaufbau aufgetreten\n"+ioException.getMessage()); return; } try { con.setRequestMethod("POST"); } catch (ProtocolException protocolException) { log.error("Error while setting the request Method of the HttpURLConnection to 'POST'." + protocolException.getMessage(), protocolException); return; } con.setRequestProperty("Content-Type", "application/json; utf-8"); con.setRequestProperty("Accept", "application/json"); con.setDoOutput(true); String jsonInputString = "{\r\n \"jobId\": \"" + jobIdTextField.getText().trim() + "\"," + "\r\n \"firstName\": \"" + vornameTextField.getText().trim() + "\"," + "\r\n \"lastName\": \"" + nachnameTextField.getText().trim() + "\"," + "\r\n \"email\": \"" + emailTextField.getText().trim() + "\"," + "\r\n \"url\": \"" + gitHubTextField.getText().trim() + "\"," + "\r\n \"source\": \"" + sourceComboBox.getSelectedItem() + "\"," + "\r\n \"messageToGepardec\": \"" + messageTextArea.getText().trim() + "\"," + "\r\n \"otherSource\": \"" + otherSourceTextField.getText().trim() + "\"," + "\r\n \"title\": \"" + titelTextField.getText().trim() + "\"," + "\r\n \"phone\": \"" + telefonTextField.getText().trim() + "\"," + "\r\n \"linkedInLink\": \"" + linkedInTextField.getText().trim() + "\"," + "\r\n \"xingLink\": \"" + xingTextField.getText().trim() + "\"," + "\r\n \"cv\": \"" + cvTextField.getText().trim() + "\"\r\n}"; try (OutputStream os = con.getOutputStream()) { byte[] input = jsonInputString.getBytes(utf8); os.write(input, 0, input.length); } catch (IOException ioException) { log.error("Error while trying to get the OutputStream from the HttpURLConnection." + ioException.getMessage(), ioException); return; } String response = ""; try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), utf8))) { String responseLine; while ((responseLine = br.readLine()) != null) { response = response + responseLine.trim(); } JOptionPane.showMessageDialog(null, response.toString()); } catch (IOException ioException) { String errorResponse = ""; try { String inputLine; BufferedReader br = new BufferedReader(new InputStreamReader(con.getErrorStream(), utf8)); while ((inputLine = br.readLine()) != null) { response = response + inputLine; } br.close(); ObjectMapper objectMapper = new ObjectMapper(); ConstraintViolationResponse constraintViolationResponse = objectMapper.readValue(response, ConstraintViolationResponse.class); for (String message : constraintViolationResponse.getViolations()) { errorResponse = errorResponse + message + "\n"; } JOptionPane.showMessageDialog(null, errorResponse); } catch (UnsupportedEncodingException unsupportedEncodingException) { log.error("Error while trying to get the ErrorStream." + unsupportedEncodingException.getMessage(), unsupportedEncodingException); return; } catch (IOException exception) { log.error("Error while trying to get the ErrorStream." + exception.getMessage(), exception); return; } } }); jobIdTextField.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { super.focusGained(e); if (jobIdTextField.getText().equalsIgnoreCase("<JobId der Website>")) { jobIdTextField.setText(""); } } }); vornameTextField.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { super.focusGained(e); if (vornameTextField.getText().equalsIgnoreCase("<Vorname>")) { vornameTextField.setText(""); } } }); nachnameTextField.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { super.focusGained(e); if (nachnameTextField.getText().equalsIgnoreCase("<Nachname>")) { nachnameTextField.setText(""); } } }); emailTextField.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { super.focusGained(e); if (emailTextField.getText().equalsIgnoreCase("<E-Mail Adresse>")) { emailTextField.setText(""); } } }); gitHubTextField.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { super.focusGained(e); if (gitHubTextField.getText().equalsIgnoreCase("<Github-Link>")) { gitHubTextField.setText(""); } } }); titelTextField.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { super.focusGained(e); if (titelTextField.getText().equalsIgnoreCase("<Titel vorangestellt>")) { titelTextField.setText(""); } } }); messageTextArea.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { super.focusGained(e); if (messageTextArea.getText().equalsIgnoreCase("<Was kann dein Beitrag zur Umsetzung der Vision von gepardec sein?>")) { messageTextArea.setText(""); } } }); otherSourceTextField.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { super.focusGained(e); if (otherSourceTextField.getText().equalsIgnoreCase("<Wenn Source auf EMPFEHLUNG oder SONSTIGES gesetzt ist, dann hier Details angeben>")) { otherSourceTextField.setText(""); } } }); telefonTextField.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { super.focusGained(e); if (telefonTextField.getText().equalsIgnoreCase("<Telefonnummer>")) { telefonTextField.setText(""); } } }); linkedInTextField.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { super.focusGained(e); if (linkedInTextField.getText().equalsIgnoreCase("<LinkedIn Profil URL>")) { linkedInTextField.setText(""); } } }); xingTextField.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { super.focusGained(e); if (xingTextField.getText().equalsIgnoreCase("<Xing Profil URL>")) { xingTextField.setText(""); } } }); cvTextField.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { super.focusGained(e); if (cvTextField.getText().equalsIgnoreCase("<Lebenslauf in Base64 encodiert>")) { cvTextField.setText(""); } } }); } }
true
ed45b933bc101568cc5ec68e4bcae2ee28266155
Java
tungbkit/TSP-genetic-algorithm
/src/com/tungbk/tsp/Population.java
UTF-8
836
2.890625
3
[]
no_license
package com.tungbk.tsp; public class Population { private static final int POP_SIZE = 200; public Individual[] ins; private int minDistance; private Individual bestInv; public Population(boolean init) { ins = new Individual[POP_SIZE]; if (init) { for (int i = 0; i < POP_SIZE; i++) { Individual newInv = new Individual(); newInv.generateGenes(); ins[i] = newInv; } } } public void setAllEval() { for (int i = 0; i < POP_SIZE; ++i) ins[i].setEval(); } public void setMinDistance() { minDistance = ins[0].getDistance(); bestInv = ins[0]; for (Individual i : ins) { if (i.getDistance() < minDistance) { minDistance = i.getDistance(); bestInv = i; } } } public int getMinDistance() { return minDistance; } public Individual getBestInv() { return bestInv; } }
true
b1292b2cb0afe2ec2a82aa112b2b9d4819b7f3b1
Java
lesps/Voice
/Voice/src/edu/upenn/cis350/voice/ConfirmationActivity.java
UTF-8
875
2.28125
2
[]
no_license
package edu.upenn.cis350.voice; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class ConfirmationActivity extends Activity{ @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.confirmation); } public void onBackButtonClick(View view){ Intent i = new Intent(); i.putExtra("Submit", false); setResult(RESULT_OK, i); finish(); } /** * Override hardware back button functionality */ @Override public void onBackPressed(){ Intent i = new Intent(); i.putExtra("Submit", false); setResult(RESULT_OK, i); finish(); } public void onSubmitButtonClick(View view){ Intent i = new Intent(); i.putExtra("Submit", true); setResult(RESULT_OK, i); finish(); } }
true
0b3903b236032a0dac4890a2aabd7178af57e8a0
Java
praveenmunagapati/ms-registration-server
/server/modules/commonAssays/luminex/src/org/labkey/luminex/AnalyteImportHelper.java
UTF-8
1,793
1.9375
2
[ "MIT" ]
permissive
/* * Copyright (c) 2007-2018 LabKey Corporation * * 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.labkey.luminex; import org.labkey.api.exp.OntologyManager; import org.labkey.luminex.model.Analyte; import java.util.Map; import java.util.Collection; import java.sql.SQLException; /** * User: jeckels * Date: Jul 19, 2007 */ public class AnalyteImportHelper implements OntologyManager.ImportHelper { private final Collection<Analyte> _analytes; private final String _namePropertyURI; public AnalyteImportHelper(Collection<Analyte> analytes, String namePropertyURI) { _analytes = analytes; _namePropertyURI = namePropertyURI; } public String beforeImportObject(Map<String, Object> map) { String name = (String)map.get(_namePropertyURI); for (Analyte analyte : _analytes) { if (analyte.getName().equals(name)) { // return analyte.getLSID(); } } throw new IllegalStateException("Could not find LSID for Analyte with name " + name); } public void afterBatchInsert(int currentRow) { } public void updateStatistics(int currentRow) { } }
true
5561ac9ae4306c38700be6ca350ff976d9092d4c
Java
olegs-volaks/java2_thursday_online_2020_autumn
/team_healthy_tooth/src/main/java/dental_clinic/core/services/ContainsDatabaseIdService.java
UTF-8
1,317
2.4375
2
[]
no_license
package dental_clinic.core.services; import dental_clinic.core.requests.ContainsDatabaseIdRequest; import dental_clinic.core.responses.ContainsDatabaseIdResponse; import dental_clinic.core.responses.CoreError; import dental_clinic.core.validators.ContainsDatabaseIdValidator; import dental_clinic.core.database.patient.PatientRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; @Component public class ContainsDatabaseIdService { @Autowired private PatientRepository patientRepository; @Autowired private ContainsDatabaseIdValidator containsDatabaseIdValidator; public ContainsDatabaseIdResponse execute(ContainsDatabaseIdRequest containsDatabaseIdRequest){ List<CoreError> errors = containsDatabaseIdValidator.validate(containsDatabaseIdRequest); if (!errors.isEmpty()){ return new ContainsDatabaseIdResponse(errors); } if (patientRepository.containsPatientWithSpecificId(containsDatabaseIdRequest.getId())){ return new ContainsDatabaseIdResponse(containsDatabaseIdRequest.getId()); } errors.add(new CoreError("id", "Database doesn't contain patient with id")); return new ContainsDatabaseIdResponse(errors); } }
true
6a09bd9f26bad2c5fe7fb6dc1d6a8e1c0d0d67df
Java
KeKeKuKi/IACAA30
/base/support-jpa/src/main/java/com/gapache/jpa/OpByRecordEntity.java
UTF-8
870
2.03125
2
[]
no_license
package com.gapache.jpa; import lombok.Getter; import lombok.Setter; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.Column; import javax.persistence.EntityListeners; import javax.persistence.MappedSuperclass; import java.io.Serializable; /** * @author HuSen * create on 2020/4/29 3:33 下午 */ @Getter @Setter @MappedSuperclass @EntityListeners(AuditingEntityListener.class) public class OpByRecordEntity<OP_MAN extends Serializable> { /** * 被谁创建 */ @CreatedBy @Column(name = "create_user_id") private OP_MAN createBy; /** * 最近一次被谁修改 */ @LastModifiedBy @Column(name = "last_modified_by") private OP_MAN lastModifiedBy; }
true
a739610b2acbdd00cf63af70c82f772a7b7ba0f7
Java
Caaarlowsz/StyleSkills
/src/me/liu/Listeners/KillStreaks.java
WINDOWS-1252
5,713
2.78125
3
[]
no_license
package me.liu.Listeners; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerLevelChangeEvent; import org.bukkit.inventory.ItemStack; import me.liu.Main; public class KillStreaks implements Listener { Main plugin; public KillStreaks(final Main plugin) { this.plugin = plugin; } @EventHandler public void onKillLevel(final PlayerDeathEvent event) { if (!(event.getEntity().getKiller() instanceof Player)) { return; } if (event.getEntity().getKiller() == null) { return; } final Player p = event.getEntity(); final Player k = p.getKiller(); k.setLevel(k.getLevel() + 1); p.setLevel(0); } @EventHandler public void onLevel(final PlayerLevelChangeEvent e) { final Player p = e.getPlayer(); if (e.getNewLevel() == 5) { Bukkit.getServer() .broadcastMessage(ChatColor.RED + p.getDisplayName() + " 7conseguiu um Killstreak de c56!"); p.getInventory().setBoots(new ItemStack(Material.LEATHER_BOOTS)); p.sendMessage("bVoce ganhou uma bota por ter feito um killstreak de 5!"); } if (e.getNewLevel() == 10) { Bukkit.getServer() .broadcastMessage(ChatColor.RED + p.getDisplayName() + " 7conseguiu um Killstreak de c107!"); } if (e.getNewLevel() == 15) { Bukkit.getServer() .broadcastMessage(ChatColor.RED + p.getDisplayName() + " 7conseguiu um Killstreak de c156!"); p.getInventory().setHelmet(new ItemStack(Material.LEATHER_HELMET)); p.sendMessage("bVoce ganhou um capacete por ter feito um killstreak de 15!"); } if (e.getNewLevel() == 20) { Bukkit.getServer() .broadcastMessage(ChatColor.RED + p.getDisplayName() + " 7conseguiu um Killstreak de c207!"); } if (e.getNewLevel() == 30) { Bukkit.getServer() .broadcastMessage(ChatColor.RED + p.getDisplayName() + " 7conseguiu um Killstreak de c307!"); p.getInventory().setLeggings(new ItemStack(Material.LEATHER_LEGGINGS)); p.sendMessage("bVoce ganhou uma cal\u00e7a por ter feito um killstreak de 30!"); } if (e.getNewLevel() == 40) { Bukkit.getServer() .broadcastMessage(ChatColor.RED + p.getDisplayName() + " 7conseguiu um Killstreak de c407!"); } if (e.getNewLevel() == 50) { Bukkit.getServer() .broadcastMessage(ChatColor.RED + p.getDisplayName() + " 7conseguiu um Killstreak de c507!"); } if (e.getNewLevel() == 60) { Bukkit.getServer() .broadcastMessage(ChatColor.RED + p.getDisplayName() + " 7conseguiu um Killstreak de c607!"); p.getInventory().setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE)); p.sendMessage("bVoce ganhou um peitoral por ter feito um killstreak de 60!"); } if (e.getNewLevel() == 70) { Bukkit.getServer() .broadcastMessage(ChatColor.RED + p.getDisplayName() + " 7conseguiu um Killstreak de c707!"); } if (e.getNewLevel() == 80) { Bukkit.getServer() .broadcastMessage(ChatColor.RED + p.getDisplayName() + " 7conseguiu um Killstreak de c807!"); } if (e.getNewLevel() == 90) { Bukkit.getServer() .broadcastMessage(ChatColor.RED + p.getDisplayName() + " 7conseguiu um Killstreak de c907!"); } if (e.getNewLevel() == 100) { Bukkit.getServer() .broadcastMessage(ChatColor.RED + p.getDisplayName() + " 7conseguiu um Killstreak de c1007!"); } if (e.getNewLevel() == 150) { Bukkit.getServer() .broadcastMessage(ChatColor.RED + p.getDisplayName() + " 7conseguiu um Killstreak de c1507!"); } if (e.getNewLevel() == 200) { Bukkit.getServer() .broadcastMessage(ChatColor.RED + p.getDisplayName() + " 7conseguiu um Killstreak de c2007!"); } if (e.getNewLevel() == 250) { Bukkit.getServer() .broadcastMessage(ChatColor.RED + p.getDisplayName() + " 7conseguiu um Killstreak de c2507!"); } if (e.getNewLevel() == 300) { Bukkit.getServer() .broadcastMessage(ChatColor.RED + p.getDisplayName() + " 7conseguiu um Killstreak de c3007!"); } if (e.getNewLevel() == 350) { Bukkit.getServer() .broadcastMessage(ChatColor.RED + p.getDisplayName() + " 7conseguiu um Killstreak de c3507!"); } if (e.getNewLevel() == 400) { Bukkit.getServer() .broadcastMessage(ChatColor.RED + p.getDisplayName() + " 7conseguiu um Killstreak de c4007!"); } if (e.getNewLevel() == 450) { Bukkit.getServer() .broadcastMessage(ChatColor.RED + p.getDisplayName() + " 7conseguiu um Killstreak de c4507!"); } if (e.getNewLevel() == 500) { Bukkit.getServer() .broadcastMessage(ChatColor.RED + p.getDisplayName() + " 7conseguiu um Killstreak de c5007!"); p.getInventory().setHelmet(new ItemStack(Material.LEATHER_HELMET)); p.getInventory().setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE)); p.getInventory().setLeggings(new ItemStack(Material.LEATHER_LEGGINGS)); p.getInventory().setBoots(new ItemStack(Material.LEATHER_BOOTS)); p.sendMessage("bVoce ganhou um FULL COURO por ter feito um killstreak de 500!"); } if (e.getNewLevel() == 1000) { Bukkit.getServer() .broadcastMessage(ChatColor.RED + p.getDisplayName() + " 7conseguiu um Killstreak de c10007!"); } if (e.getNewLevel() == 1500) { Bukkit.getServer() .broadcastMessage(ChatColor.RED + p.getDisplayName() + " 7conseguiu um Killstreak de c15007!"); } if (e.getNewLevel() == 2000) { Bukkit.getServer() .broadcastMessage(ChatColor.RED + p.getDisplayName() + " 7conseguiu um Killstreak de c20007!"); } } }
true
5fab6ff0470c433ebad0e2615237583776ca62c9
Java
xm-online/xm-lep
/xm-lep-api/src/main/java/com/icthh/xm/lep/api/LepProcessingListener.java
UTF-8
205
1.59375
2
[ "Apache-2.0" ]
permissive
package com.icthh.xm.lep.api; import java.util.function.Consumer; /** * The {@link LepProcessingListener} interface. */ public interface LepProcessingListener extends Consumer<LepProcessingEvent> { }
true
b10f30d894731c7922ead13cbfee534cfda25e99
Java
xly8482/sw-table-edit
/sw-table-edit/src/main/java/com/example/demo/util/PoiExcelReport.java
UTF-8
8,524
2.59375
3
[]
no_license
package com.example.demo.util; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.math.BigDecimal; import java.util.Date; import java.util.Map; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** * 产生Excel报表文档,使用Apache POI * * @author hewenfa * */ public class PoiExcelReport { protected Workbook wb; /** * 读取报表构造方法 * * @param filePath * 源报表路径或报表模板路径 */ public PoiExcelReport(final String filePath) { FileInputStream inp = null; try { inp = new FileInputStream(filePath); if (filePath.substring(filePath.lastIndexOf(".")).equals("xlsx")) { wb = new XSSFWorkbook(inp); } else { wb = WorkbookFactory.create(inp); } inp.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (EncryptedDocumentException e) { e.printStackTrace(); } catch (InvalidFormatException e) { e.printStackTrace(); } finally { if (null != inp) { try { inp.close(); } catch (Exception e) { } } } } /** * 导出报表 */ public void export(String outputFile) { FileOutputStream out = null; try { FileUtil.makeDirs(FileUtil.getFolderName(outputFile)); out = new FileOutputStream(outputFile); wb.write(out); close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 关闭Excel */ public void close() { if (wb != null) { try { wb.close(); } catch (IOException e) { } } } /** * 获取Workbook * * @return */ public Workbook getWorkbook() { return this.wb; } // ========================================================================== // Sheet 获取、创建、删除 // ========================================================================== public Sheet getSheet(int index) { if (wb != null) { return wb.getSheetAt(index); } return null; } public Sheet getSheet(String sheetName) { if (wb != null) { return wb.getSheet(sheetName); } return null; } public Sheet createSheet(String sheetName) { if (wb != null) { return wb.createSheet(sheetName); } return null; } public Sheet createSheet() { if (wb != null) { return wb.createSheet(); } return null; } public void removeSheet(int idx) { if (wb != null) { if (wb.getSheetAt(idx) != null) { wb.removeSheetAt(idx); } } } public void removeSheet(String name) { if (wb != null) { int idx = wb.getSheetIndex(name); if (idx > -1) { wb.removeSheetAt(idx); } } } public void removeSheet(Sheet sheet) { if (wb != null) { int idx = wb.getSheetIndex(sheet); if (idx > -1) { wb.removeSheetAt(idx); } } } // ========================================================================== // Row 获取与创建 // ========================================================================== public Row getRow(int sheetIndex, int rowIndex) { Sheet sheet = this.getSheet(sheetIndex); if (sheet != null) { return sheet.getRow(rowIndex); } return null; } public Row getRow(String sheetName, int rowIndex) { Sheet sheet = this.getSheet(sheetName); if (sheet != null) { return sheet.getRow(rowIndex); } return null; } public Row getRow(final Sheet sheet, final int rowIndex) { Row row = sheet.getRow(rowIndex); if (row == null) { row = sheet.createRow(rowIndex); } return row; } public Row createRow(final Sheet sheet, final int rowIndex) { if (sheet != null) { return sheet.createRow(rowIndex); } return null; } // ========================================================================== // Cell 获取与创建 // ========================================================================== public Cell getCell(final Row row, final int cellIndex) { Cell cell = row.getCell(cellIndex); if (cell == null) { cell = row.createCell(cellIndex); } return cell; } public Cell getCell(final Row row, final int cellIndex, final CellStyle style) { Cell cell = row.getCell(cellIndex); if (cell == null) { cell = row.createCell(cellIndex); } cell.setCellStyle(style); return cell; } public Cell createCell(final Row row, final int cellIndex) { if (row != null) { return row.createCell(cellIndex); } return null; } public Cell createCell(final Row row, final int cellIndex, final CellStyle style) { if (row != null) { Cell cell = row.createCell(cellIndex); cell.setCellStyle(style); return cell; } return null; } // ========================================================================== // 设置单元格值 // ========================================================================== /** * 参数方式设置单元格值 * * @param sheet * @param paramMap */ @SuppressWarnings("deprecation") public void setSheetParams(final Sheet sheet, final Map<Object, Object> paramMap) { int startRowIdx = 0; int endRowIdx = sheet.getLastRowNum(); for (int i = startRowIdx; i <= endRowIdx; i++) { final Row row = getRow(sheet, i); if (row == null) { continue; } for (int j = 0; j < row.getLastCellNum(); j++) { Cell cell = getCell(row, j); if (cell != null && Cell.CELL_TYPE_STRING == cell.getCellType()) { final String cellValue = cell.getStringCellValue(); if (paramMap.containsKey(cellValue)) { setCellValue(cell, paramMap.get(cellValue)); } } } } } @SuppressWarnings("unchecked") public <T> T getCellValue(Cell cell) { if (cell != null) { int type = cell.getCellType(); switch (type) { case Cell.CELL_TYPE_BLANK: return (T) ""; case Cell.CELL_TYPE_STRING: return (T) cell.getStringCellValue(); case Cell.CELL_TYPE_BOOLEAN: return (T) (Boolean) cell.getBooleanCellValue(); case Cell.CELL_TYPE_NUMERIC: return (T) (Double) cell.getNumericCellValue(); default: break; } } return null; } public String getCellValueStr(Cell cell) { if (cell != null) { int type = cell.getCellType(); switch (type) { case Cell.CELL_TYPE_BLANK: return ""; case Cell.CELL_TYPE_STRING: return cell.getStringCellValue(); case Cell.CELL_TYPE_BOOLEAN: return cell.getBooleanCellValue() + ""; case Cell.CELL_TYPE_NUMERIC: String strVal = (Double) cell.getNumericCellValue() + ""; return strVal; default: break; } } return null; } /** * 根据数据类型,设置单元格值 * * @param cell * @param value */ public void setCellValue(Cell cell, Object value) { if (cell != null) { if (value == null) { cell.setCellType(Cell.CELL_TYPE_BLANK); cell.setCellValue(""); } else if (value instanceof String) { cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellValue((String) value); } else if (value instanceof Date) { cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellValue((Date) value); } else if (value instanceof Double) { cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue((Double) value); } else if (value instanceof Float) { cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue((Float) value); } else if (value instanceof BigDecimal) { cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue(((BigDecimal) value).doubleValue()); } else if (value instanceof Integer) { cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue((Integer) value); } else { cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellValue(value.toString()); } } } }
true
3e4823b5fe91c8ba3d014351e0f0fd738d5d8052
Java
unclebryan719/design-pattern
/src/main/java/com/unclebryan/builder/House.java
UTF-8
283
2.1875
2
[ "Apache-2.0" ]
permissive
package com.unclebryan.builder; import lombok.Data; /** * @program: design-pattern * @description: 房子-->Product * @author: UncleBryan * @created: 2021/05/29 20:41 */ @Data public class House { private String basic; private String wall; private String roof; }
true
d48dc76716ca01151df1033023ae3037493157d7
Java
adaptris/interlok
/interlok-core/src/test/java/com/adaptris/naming/adapter/ContextFactoryTest.java
UTF-8
2,950
2.015625
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2017 Adaptris Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.adaptris.naming.adapter; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Hashtable; import javax.naming.ConfigurationException; import javax.naming.Context; import javax.naming.NamingException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.adaptris.core.JndiContextFactory; public class ContextFactoryTest { @BeforeEach public void setUp() throws Exception { } @AfterEach public void tearDown() throws Exception { } private Context createContext() throws NamingException { JndiContextFactory factory = new JndiContextFactory(); return factory.getInitialContext(new Hashtable<>()); } @Test public void testGetObjectInstance_String() throws Exception { Context ctx = createContext(); Object bindObject = new Object(); ctx.bind("testGetObjectInstance_String", bindObject); adapterURLContextFactory factory = new adapterURLContextFactory(); assertEquals(bindObject, factory.getObjectInstance("testGetObjectInstance_String", null, null, new Hashtable())); ctx.unbind("testGetObjectInstance_String"); } @Test public void testGetObjectInstance_Object() throws Exception { Assertions.assertThrows(IllegalArgumentException.class, () -> { adapterURLContextFactory factory = new adapterURLContextFactory(); factory.getObjectInstance(new Object(), null, null, new Hashtable()); }); } @Test public void testGetObjectInstance_EmptyStringArray() throws Exception { Assertions.assertThrows(ConfigurationException.class, () -> { adapterURLContextFactory factory = new adapterURLContextFactory(); factory.getObjectInstance(new String[0], null, null, new Hashtable()); }); } @Test public void testGetObjectInstance_StringArray() throws Exception { Context ctx = createContext(); Object bindObject = new Object(); ctx.bind("testGetObjectInstance_StringArray", bindObject); adapterURLContextFactory factory = new adapterURLContextFactory(); assertEquals(bindObject, factory.getObjectInstance( new String[] { "adapter:comp/env/xxx", "adapter:comp/env/yyy", "testGetObjectInstance_StringArray" }, null, null, new Hashtable())); } }
true
d567de5c478f3e02c934e7d50facdb1161f1e60c
Java
gmazzali/com.common.util
/code/src/main/java/com/common/util/domain/model/entity/AuditablePersistence.java
ISO-8859-1
1,564
2.5
2
[]
no_license
package com.common.util.domain.model.entity; import java.io.Serializable; import java.util.Date; /** * La interfaz que extiende {@link ActivePersistence} y que define las entidades auditables. * * @see Persistence * @see ActivePersistence * * @since 02/07/2014 * @author Guillermo Mazzali * @version 1.0 * * @param <PK> * La clase que va a representar el identificador de las entidades auditables. */ public interface AuditablePersistence<PK extends Serializable> extends ActivePersistence<PK> { /** * Permite retornar la fecha de creacin de la entidad. * * @return La fecha de creacin de la entidad. */ public Date getCreateDate(); /** * Permite cargar la fecha de creacin de la entidad. * * @param createDate * La fecha de creacin de la entidad. */ public void setCreateDate(Date createDate); /** * Permite retornar la fecha de modificacin de la entidad. * * @return La fecha de modificacin de la entidad. */ public Date getModifyDate(); /** * Permite cargar la fecha de modificacin de la entidad. * * @param modifyDate * La fecha de modificacin de la entidad. */ public void setModifyDate(Date modifyDate); /** * Permite retornar la fecha de borrado lgico de la entidad. * * @return La fecha de borrado lgico de la entidad. */ public Date getDeleteDate(); /** * Permite cargar la fecha de baja de la entidad. * * @param deleteDate * La fecha de baja de la entidad. */ public void setDeleteDate(Date deleteDate); }
true
c5f8d7b64131d696d40f3d8a694e67b16736679b
Java
garfieldua/google-appengine-training
/000_Hello_Endpoints/src/main/java/com/google/training/helloworld/Time.java
UTF-8
330
2.4375
2
[ "Apache-2.0" ]
permissive
package com.google.training.helloworld; import java.text.SimpleDateFormat; import java.util.Calendar; public class Time { public String timeFormatted = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(Calendar.getInstance().getTime()); public Time() { } public String getTimeFormatted() { return timeFormatted; } }
true
4ad8357d3eb54d0727de974e55c1a8ec259dbcdb
Java
xxxiaom/bluewhite
/src/main/java/com/bluewhite/product/primecost/tailor/service/TailorService.java
UTF-8
1,186
1.851563
2
[]
no_license
package com.bluewhite.product.primecost.tailor.service; import java.util.List; import org.springframework.stereotype.Service; import com.bluewhite.base.BaseCRUDService; import com.bluewhite.common.entity.PageParameter; import com.bluewhite.common.entity.PageResult; import com.bluewhite.product.primecost.tailor.entity.OrdinaryLaser; import com.bluewhite.product.primecost.tailor.entity.Tailor; @Service public interface TailorService extends BaseCRUDService<Tailor,Long> { /** * * 新增裁剪 * @param tailor * @return */ public Tailor saveTailor(Tailor tailor) ; /** * 分页查询裁剪 * @param tailor * @param page * @return */ public PageResult<Tailor> findPages(Tailor tailor, PageParameter page); /** * 获取裁剪页面所需要的数据 * @param tailor * @return */ public OrdinaryLaser getOrdinaryLaserDate(Tailor tailor,OrdinaryLaser prams); /** * 获取各种裁剪方式页面所需要的数据 * @param tailor * @return */ public Tailor getTailorDate(Tailor tailor,OrdinaryLaser ordinaryLaser); public List<Tailor> findByProductId(Long productId); }
true
a6004759977c0727305f54811b67ddc61478e4b8
Java
wedgithubming/testDemo
/src/yaninst.java
UTF-8
269
2.046875
2
[]
no_license
/** * fileName:yaninst * description: * author:zz * createTime:2019/3/8 11:07 */ public class yaninst { public static void main(String[] args) { System.out.println("郭启明行健分子"); System.out.println("郭启明行健分子1"); } }
true
26ca897a72e16d1482f5e5ac2c8f7340b164e27e
Java
bellmit/seed-project
/system/src/main/java/com/cody/seed/modules/system/entity/SysUser.java
UTF-8
2,366
1.96875
2
[]
no_license
package com.cody.seed.modules.system.entity; import com.baomidou.mybatisplus.annotation.FieldStrategy; import com.baomidou.mybatisplus.annotation.TableField; import com.cody.common.aspect.annotation.Stringify; import com.cody.common.entity.SysLogicDeleteModel; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import org.springframework.format.annotation.DateTimeFormat; import javax.validation.constraints.NotBlank; import java.io.Serializable; import java.time.LocalDateTime; /** * @author Administrator * @Description: 系统用户表 * @date: 2020年06月16日 18:27 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class SysUser extends SysLogicDeleteModel<SysUser> implements Serializable { private static final long serialVersionUID = 1L; /** * 用户昵称 */ @NotBlank(message = "登录账号为空") private String userName; /** * 昵称 */ @NotBlank(message = "昵称不能为空") private String nickName; /** * 用户邮箱 */ @TableField(updateStrategy = FieldStrategy.IGNORED) private String email; /** * 手机号码 */ @TableField(updateStrategy = FieldStrategy.IGNORED) private String phone; /** * 生日 */ @TableField(updateStrategy = FieldStrategy.IGNORED) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private LocalDateTime birthday; /** * 性别 */ private Integer sex; /** * 用户头像 */ private String avatar; /** * 密码 */ @NotBlank(message = "密码不能为空") private String password; /** * 帐号状态:1正常,0禁用 */ private Boolean enabled; /** * 部门id */ @Stringify private Long deptId; /** * 岗位id */ @Stringify private Long jobId; /** * 最后登录ip */ private String loginIp; /** * 最后登录时间 */ @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private LocalDateTime loginTime; /** * 备注 */ private String remark; }
true
1ec328ec5813118e6875dfb66655da502e18e10e
Java
OuFungWah/FungWahToolsDemo
/app/src/main/java/com/example/fungwahtoolsdemo/animdemo/frament/Tween1Fragment.java
UTF-8
1,812
2.078125
2
[]
no_license
package com.example.fungwahtoolsdemo.animdemo.frament; import android.support.design.widget.FloatingActionButton; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import com.example.fungwahtools.fragment.BaseFragment; import com.example.fungwahtoolsdemo.R; /** * Created by 区枫华 on 2017/9/6. */ public class Tween1Fragment extends BaseFragment implements View.OnClickListener { private ImageView imageView; private FloatingActionButton floatingActionButton; private Animation disappearAnim; private Animation appearAnim; private boolean flag = false; @Override protected int setLayoutId() { return R.layout.anim_tween1_fragment; } @Override protected void initView(View parent) { imageView = findView(R.id.tween_img); floatingActionButton = findView(R.id.fab); //加载动画XML disappearAnim = AnimationUtils.loadAnimation(getContext(), R.anim.tween_disappear); //加载动画XML appearAnim = AnimationUtils.loadAnimation(getContext(), R.anim.tween_appear); } @Override protected void setView() { } @Override protected void initListener() { floatingActionButton.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.fab: if (flag) { //开始动画 imageView.startAnimation(appearAnim); flag = !flag; } else { //开始动画 imageView.startAnimation(disappearAnim); flag = !flag; } break; } } }
true
00e5dcccef3109063f04607a04bad59c6b0c934d
Java
merbauraya/lportal6.2
/Eis-portlet/docroot/WEB-INF/src/com/idetronic/eis/model/impl/MasterFileCacheModel.java
UTF-8
4,927
1.804688
2
[]
no_license
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library 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 2.1 of the License, or (at your option) * any later version. * * This library 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. */ package com.idetronic.eis.model.impl; import com.idetronic.eis.model.MasterFile; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.model.CacheModel; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; /** * The cache model class for representing MasterFile in entity cache. * * @author Mazlan Mat * @see MasterFile * @generated */ public class MasterFileCacheModel implements CacheModel<MasterFile>, Externalizable { @Override public String toString() { StringBundler sb = new StringBundler(29); sb.append("{masterFileId="); sb.append(masterFileId); sb.append(", masterTypeId="); sb.append(masterTypeId); sb.append(", parentId1="); sb.append(parentId1); sb.append(", parentId2="); sb.append(parentId2); sb.append(", masterFileName="); sb.append(masterFileName); sb.append(", status1="); sb.append(status1); sb.append(", status2="); sb.append(status2); sb.append(", status3="); sb.append(status3); sb.append(", status4="); sb.append(status4); sb.append(", status5="); sb.append(status5); sb.append(", masterCode="); sb.append(masterCode); sb.append(", oldId="); sb.append(oldId); sb.append(", note="); sb.append(note); sb.append(", inActive="); sb.append(inActive); sb.append("}"); return sb.toString(); } @Override public MasterFile toEntityModel() { MasterFileImpl masterFileImpl = new MasterFileImpl(); masterFileImpl.setMasterFileId(masterFileId); masterFileImpl.setMasterTypeId(masterTypeId); masterFileImpl.setParentId1(parentId1); masterFileImpl.setParentId2(parentId2); if (masterFileName == null) { masterFileImpl.setMasterFileName(StringPool.BLANK); } else { masterFileImpl.setMasterFileName(masterFileName); } masterFileImpl.setStatus1(status1); masterFileImpl.setStatus2(status2); masterFileImpl.setStatus3(status3); masterFileImpl.setStatus4(status4); masterFileImpl.setStatus5(status5); if (masterCode == null) { masterFileImpl.setMasterCode(StringPool.BLANK); } else { masterFileImpl.setMasterCode(masterCode); } masterFileImpl.setOldId(oldId); if (note == null) { masterFileImpl.setNote(StringPool.BLANK); } else { masterFileImpl.setNote(note); } masterFileImpl.setInActive(inActive); masterFileImpl.resetOriginalValues(); return masterFileImpl; } @Override public void readExternal(ObjectInput objectInput) throws IOException { masterFileId = objectInput.readLong(); masterTypeId = objectInput.readLong(); parentId1 = objectInput.readLong(); parentId2 = objectInput.readLong(); masterFileName = objectInput.readUTF(); status1 = objectInput.readBoolean(); status2 = objectInput.readBoolean(); status3 = objectInput.readBoolean(); status4 = objectInput.readBoolean(); status5 = objectInput.readBoolean(); masterCode = objectInput.readUTF(); oldId = objectInput.readLong(); note = objectInput.readUTF(); inActive = objectInput.readBoolean(); } @Override public void writeExternal(ObjectOutput objectOutput) throws IOException { objectOutput.writeLong(masterFileId); objectOutput.writeLong(masterTypeId); objectOutput.writeLong(parentId1); objectOutput.writeLong(parentId2); if (masterFileName == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(masterFileName); } objectOutput.writeBoolean(status1); objectOutput.writeBoolean(status2); objectOutput.writeBoolean(status3); objectOutput.writeBoolean(status4); objectOutput.writeBoolean(status5); if (masterCode == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(masterCode); } objectOutput.writeLong(oldId); if (note == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(note); } objectOutput.writeBoolean(inActive); } public long masterFileId; public long masterTypeId; public long parentId1; public long parentId2; public String masterFileName; public boolean status1; public boolean status2; public boolean status3; public boolean status4; public boolean status5; public String masterCode; public long oldId; public String note; public boolean inActive; }
true
607c295ca87ea6db911677bfa77d2b8809acad89
Java
xpoll/qxx
/gui/src/main/java/cn/blmdz/search/Hits.java
UTF-8
292
1.6875
2
[]
no_license
package cn.blmdz.search; import java.io.Serializable; import java.util.List; import lombok.Data; @Data public class Hits implements Serializable { private static final long serialVersionUID = -8033128358999935071L; private Long total; private Float max_score; private List<Hit> hits; }
true
68a8cb64a83956c293456f38e43aac2290dec1eb
Java
M4TH1EU/Flan-s-Mod-Updater
/src/main/java/ch/m4th1eu/flansupdater/Logger.java
UTF-8
867
2.921875
3
[]
no_license
package ch.m4th1eu.flansupdater; public class Logger { public static final String ANSI_RESET = "\u001B[0m"; public static final String ANSI_RED = "\u001B[31m"; public static final String ANSI_GREEN = "\u001B[32m"; public static final String ANSI_YELLOW = "\u001B[33m"; public static final String RED_BOLD = "\033[1;31m"; // RED public static void error(String message) { System.out.println(ANSI_RED + "[ERROR] " + message + ANSI_RESET); } public static void info(String message) { System.out.println(ANSI_GREEN + "[INFO] " + message + ANSI_RESET); } public static void warn(String message) { System.out.println(ANSI_YELLOW + "[WARN] " + message + ANSI_RESET); } public static void fatal(String message) { System.out.println(RED_BOLD + "[FATAL] " + message + ANSI_RESET); } }
true
611907431b429be2041cbc1e1d24e5d575b75f1f
Java
lucasreginato/DiffApi
/src/main/java/com/assignment/rest/v1/EndpointV1.java
UTF-8
9,540
2.6875
3
[]
no_license
package com.assignment.rest.v1; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; 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.apache.log4j.Logger; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import com.assignment.task.Task; import com.assignment.task.TaskFactory; import com.assignment.task.impl.TaskFactoryImpl; import com.assignment.utils.DataEnum; import com.assignment.utils.JSONUtils; import com.assignment.utils.Utils; /** * Represents the REST API V1.<br/> * This API has 3 endpoints (right, left and diff).<br/> * The right and left endpoints accepts a JSON base64 encoded binary data. * The diff endpoint returns the following information:<br/> * A) If data are equals return that they are equal.<br/> * B) If data are not equal in size return that they are not equal in size.<br/> * C) If data has the same size, but has differences, the endpoint provide * insight in where the differences are (offsets + length in the data).<br/> * * @author lucas.reginato@gmail.com */ @Path("/v1/diff/") public class EndpointV1 { // logger of the class. private Logger log = Logger.getLogger("com.assignment.rest.v1.EndpointV1"); /** * The left endpoint, which is a HTTP POST.<br/> * It accepts a JSON base64 encoded binary data.<br/> * This value will be used later in the diff endpoint.<br/> * <br/> * @param id The id of the request. This id will be used to save a file on the disk and keep the "left" data. * @param inputData JSON base64 encoded binary data. * @return A HTTP response: 500 in case of failure, or 204 in case of success. */ @Path("/{id}/left") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response left(@PathParam("id") String id, String inputData) { log.info("EndpointV1.left is executing, id is (" + id + ") and inputData is (" + inputData + ")"); try { // if the path param ID is null or empty then return an error // if inputData is not a valid JSON array then return an error if (!validInputs(id, inputData)) { return Response.status(Utils.INTERNAL_SERVER_ERROR).build(); } // the input data is a JSON array, it can contains chunks // of Base64 encoded binary data. // encapsulates all data into a StringBuilder. StringBuilder stringBuilder = encapsulateInputData(inputData); if (stringBuilder == null) { return Response.status(Utils.INTERNAL_SERVER_ERROR).build(); } // saves the data in a file which name is the {ID} value. // today this is a synchronous job, but it should be asynchronous // and the data should be saved in a database. TaskFactory taskFactory = new TaskFactoryImpl(); Task task = taskFactory.createSaveDataTask(id, DataEnum.LEFT.name(), stringBuilder.toString()); task.executeTask(); } catch (Exception exc) { log.debug("Exception during EndpointV1.left execution: " + exc.getMessage()); return Response.status(Utils.INTERNAL_SERVER_ERROR).build(); } log.info("EndpointV1.left execution ended with success."); return Response.status(Utils.OK_WITH_NO_CONTENT).build(); } /** * The right endpoint, which is a HTTP POST.<br/> * It accepts a JSON base64 encoded binary data.<br/> * This value will be used later in the diff endpoint.<br/> * <br/> * @param id The id of the request. This id will be used to save a file on the disk and keep the "right" data. * @param inputData JSON base64 encoded binary data. * @return A HTTP response: 500 in case of failure, or 204 in case of success. */ @Path("/{id}/right") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response right(@PathParam("id") String id, String inputData) { log.info("EndpointV1.right is executing, id is (" + id + ") and inputData is (" + inputData + ")"); try { // if the path param ID is null or empty then return an error // if inputData is not a valid JSON array then return an error if (!validInputs(id, inputData)) { return Response.status(Utils.INTERNAL_SERVER_ERROR).build(); } // the input data is a JSON array, it can contains chunks // of Base64 encoded binary data. // encapsulates all data into a StringBuilder. StringBuilder stringBuilder = encapsulateInputData(inputData); if (stringBuilder == null) { return Response.status(Utils.INTERNAL_SERVER_ERROR).build(); } // saves the data in a file which name is the {ID} value // today this is a synchronous job, but it should be asynchronous // and the data should be saved in a database. TaskFactory taskFactory = new TaskFactoryImpl(); Task task = taskFactory.createSaveDataTask(id, DataEnum.RIGHT.name(), stringBuilder.toString()); task.executeTask(); } catch (Exception exc) { log.debug("Exception during EndpointV1.right execution: " + exc.getMessage()); return Response.status(Utils.INTERNAL_SERVER_ERROR).build(); } log.info("EndpointV1.right execution ended with success."); return Response.status(Utils.OK_WITH_NO_CONTENT).build(); } /** * The diff endpoint, which is a HTTP GET.<br/> * <br/> * It executes a diff over the rigth and left data and returns a JSON result to the user.<br/> * The diff endpoint returns the following information:<br/> * A) If data are equals return that they are equal:<br/> * { "Result":[ "The right and left data are equals."] }<br/> * <br/> * B) If data are not equal in size return that they are not equal in size:<br/> * { "Result":[ "The right and left data does not have the same length." ] }<br/> * <br/> * C) If data has the same size, but has differences, the endpoint provide * insight in where the differences are (offsets + length in the data):<br/> * { "Result":"The right and left data have the same length, but differences were found.", * "Differences":[ { * "Offset":0, * "Length":4 }, * { * "Offset":21, * "Length":5 }] * }<br/> * * @param id String that represents the ID of the request. * @return A HTTP response: 500 in case of failure, or 200 in case of success with a JSON result. */ @Path("/{id}") @GET @Produces(MediaType.APPLICATION_JSON) public Response diff(@PathParam("id") String id) { log.info("EndpointV1.diff is executing, id is (" + id + ")."); try { // validating if id is not null or empty. if((id == null) || (id.isEmpty())) { log.info("Id is null or empty, returning internal error."); return Response.status(Utils.INTERNAL_SERVER_ERROR).build(); } // generates the diff between the 2 data (right and left). // this is a synchronous job TaskFactory taskFactory = new TaskFactoryImpl(); Task task = taskFactory.createGetDiffTask(id); JSONObject jsonObject = task.executeTask(); if (jsonObject == null) { log.info("Error while executing diff algorithm, returning internal error."); return Response.status(Utils.INTERNAL_SERVER_ERROR).build(); } log.info("Result is: " + jsonObject.toString()); return Response.ok().entity(jsonObject.toString()).build(); } catch(Exception exc) { log.debug("Exception: " + exc.getMessage() + " returning internal error...", exc); return Response.status(Utils.INTERNAL_SERVER_ERROR).build(); } } /** * Validate the inputs of the endpoints right and left.<br/> * The id input is an string and cannot be null or empty.<br/> * The inputData input is a JSONArray and cannot be null, empty or valid JSON.<br/> * * @param id The id of the request. * @param inputData The JSON string that contains base64 encoded binary data. * @return True in case the inputs are valid, otherwise false. */ public boolean validInputs(String id, String inputData) { // validates if the path param ID is null or empty then return an error // path param ID is key for the execution of this assignment if((id == null) || (id.isEmpty())) { log.info("Invalid id, returning false."); return false; } // validates if inputData is NOT a JSON string, then return an error JSONUtils jsonUtils = new JSONUtils(); if (!jsonUtils.isValidJSONArray(inputData)) { log.info("Invalid JSON, returning false."); return false; } return true; } /** * Encapsulate the InputData into a single String.<br/> * The nputData can be a JSONArray object, which has different values in the array.<br/> * All the values are concatenated into a unique string.<br/> * * @param inputData The JSON string that contains base64 encoded binary data. * @return StringBuilder Which contains all the Strings inside the JSONArray (inputdata). */ public StringBuilder encapsulateInputData(String inputData) { log.info("Parsing inputData (" + inputData + ") into JSONArray object"); try { StringBuilder stringBuilder = new StringBuilder(); JSONArray jsonArray = new JSONArray(inputData); for(int index = 0; index < jsonArray.length(); index++) { // saves the JSON into a new StringBuilder for later processing. stringBuilder.append(jsonArray.get(index)); } log.info("Returning String (" + stringBuilder.toString()+ ")."); return stringBuilder; } catch (JSONException jsonExc) { log.debug("Exception encapsulating data: " + jsonExc.getMessage(), jsonExc); return null; } } }
true
b28986f6b498563561050012113bbf155fce1e04
Java
Krassimir-ILLIEV/Programming101-Java
/week03/1.Monday/Week03Monday_3011/src/_04_SummationFunction/SummationFunction.java
UTF-8
430
3.484375
3
[]
no_license
package _04_SummationFunction; public class SummationFunction { public static <T1 extends Number, T2 extends Number> double add(T1 first, T2 second){ //return first.doubleValue()+second.doubleValue(); return (Double) first+(Double) second; } public static void main(String[] args){ SummationFunction sf=new SummationFunction(); System.out.println(sf.<Double, Double>add(new Double(234.0), new Double(132.0))); } }
true
de2d918c483d5dbe70ac50e27f6bf690a5f23827
Java
lanye123/litemall-master
/litemall-wx-api/src/main/java/org/linlinjava/litemall/wx/web/CsTestController.java
UTF-8
10,142
2.015625
2
[ "MIT" ]
permissive
package org.linlinjava.litemall.wx.web; import org.apache.commons.lang3.StringUtils; import org.apache.ibatis.annotations.Param; import org.linlinjava.litemall.db.domain.*; import org.linlinjava.litemall.db.service.*; import org.linlinjava.litemall.db.util.ResponseUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.*; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 趣味测试接口 * leiq * 2018-7-16 11:07:37 */ @RestController @RequestMapping("/wx/cstest") public class CsTestController { @Autowired private CsTestService csTestService; @Autowired private CsDetailService csDetailService; @Autowired private CsTitleService csTitleService; @Autowired private CsOptionService csOptionService; @Autowired private CsResultService csResultService; @Autowired private LitemallUserService litemallUserService; @Autowired private IntegretionDetailService integretionDetailService; @Autowired private CsJieguoService csJieguoService; private BufferedImage image; private int csimageWidth=750; private int csimageHeight=1161; @Value("${web.upload-path}") private String webUploadPath; @Value("${serverurl}") private String serverurl; //普通类型测试列表 @GetMapping("list") public List<CsTest> list(Integer isHot){ Map<String,Object> data=new HashMap<>(); List<CsTest> testList=csTestService.list(isHot); return testList; } //根据测试题ID返回对应记录 @GetMapping("read") public CsTest read(Integer id){ return csTestService.read(id); } //根据测试题ID级联返回测试题目及选项信息 @GetMapping("option") public CsTest option(Integer id){ return csTestService.cascate(id); } /** * @Author leiqiang * @Description //TODO 保存用户做题结果流水记录 * @Date 2018/7/16 11:30 * @Param [detail] * @return void **/ @PostMapping("addDetail") public void addDetail(@RequestBody CsDetail detail){ CsDetail detail1=csDetailService.retrieve(detail.getUserId(),detail.getTestId(),detail.getTitleId()); if(detail1==null) csDetailService.addDetail(detail);//不存在记录则创建 else{ //存在记录则检查选项是否一致,否则更新记录 if(detail.getOptionId()!=detail1.getOptionId()){ detail1.setOptionId(detail.getOptionId()); detail1.setAccount(detail.getAccount()); csDetailService.update(detail1); } } } /** * @Author leiqiang * @Description //TODO 根据选项不同动态显示下一题趣味测试内容接口 * @Date 2018/7/16 11:49 * @Param [title_id] * @return void **/ @GetMapping("title") public CsTitle title(Integer pid){ return csTitleService.option(pid); } @GetMapping("optionDync") public CsTest optionDync(Integer id){ return csTestService.cascateDync(id); } /** * @Author leiqiang * @Description //TODO 检查该项测试用户是否已经测试,如果已经测试则直接返回测试结果 * @Date 2018/7/18 16:07 * @Param [testId, userId] * @return java.lang.Object **/ @GetMapping("check") public Object check(Integer testId,Integer userId){ Map data = new HashMap(); CsTest test=csTestService.findById(testId); if(test!=null&&StringUtils.isNotEmpty(test.getInfo())) data.put("info",test.getInfo()); CsJieguo jg=csJieguoService.queryById(testId,userId); if(jg!=null){ data.put("checked",1); data.put("CsJieguo",jg); }else data.put("checked",0); return ResponseUtil.ok(data); } /** * @Author leiqiang * @Description //TODO 根据用户ID和测试ID查看测试结果 * @Date 2018/7/16 17:56 * @Param [testId, userId] * @return java.lang.Object **/ @GetMapping("look") public Object look(Integer testId,Integer userId){ Map data = new HashMap(); CsTest test=csTestService.findById(testId); if(test!=null&&StringUtils.isNotEmpty(test.getInfo())) data.put("info",test.getInfo()); Integer account=0; account=csDetailService.sumAccount(testId,userId);//统计该用户该项测试最终得分情况 if(account!=0){ CsResult result= csResultService.getPicUrl(testId,account);//根据用户测试得分和测试ID得出背景图片url String imgurl= result.getPicUrl(); //根据图片url及用户ID生成最终图片 LitemallUser user = litemallUserService.findById(userId); String nickname=user.getNickname(); String avatar=user.getAvatar(); image = new BufferedImage(csimageWidth, csimageHeight, BufferedImage.TYPE_INT_RGB); //设置图片的背景色 Graphics2D main = image.createGraphics(); main.fillRect(0, 0, csimageWidth, csimageHeight); //***********************插入背景图 Graphics mainPic = image.getGraphics(); BufferedImage bimg = null; try { URL url2 = new URL(imgurl); URLConnection con2 = url2.openConnection(); //不超时 con2.setConnectTimeout(0); //不允许缓存 con2.setUseCaches(false); con2.setDefaultUseCaches(false); InputStream is2 = con2.getInputStream(); //先读入内存 ByteArrayOutputStream buf2 = new ByteArrayOutputStream(8192); byte[] b2 = new byte[1024]; int len2; while ((len2 = is2.read(b2)) != -1) { buf2.write(b2, 0, len2); } //读图像 is2 = new ByteArrayInputStream(buf2.toByteArray()); bimg = javax.imageio.ImageIO.read(is2); } catch (Exception e) { e.printStackTrace(); } if (bimg != null) { mainPic.drawImage(bimg, 0, 0, csimageWidth, csimageHeight, null); mainPic.dispose(); } //***********************插入用户头像 if (StringUtils.isNotEmpty(avatar)) { Graphics mainPic3 = image.getGraphics(); BufferedImage bimg3 = null; try { URL url3 = new URL(avatar); URLConnection con3 = url3.openConnection(); //不超时 con3.setConnectTimeout(0); //不允许缓存 con3.setUseCaches(false); con3.setDefaultUseCaches(false); InputStream is3 = con3.getInputStream(); //先读入内存 ByteArrayOutputStream buf3 = new ByteArrayOutputStream(8192); byte[] b3 = new byte[1024]; int len3; while ((len3 = is3.read(b3)) != -1) { buf3.write(b3, 0, len3); } //读图像 is3 = new ByteArrayInputStream(buf3.toByteArray()); bimg3 = ImageIO.read(is3); } catch (Exception e) { e.printStackTrace(); } if (bimg3 != null) { mainPic3.drawImage(bimg3, 65, csimageHeight - 120, 60, 60, null); mainPic3.dispose(); } } Graphics2D tip4 = image.createGraphics(); Font tipFont4 = new Font("苹方 常规", Font.PLAIN, 16); //tip4.setColor(new Color(51, 129, 246)); tip4.setFont(tipFont4); tip4.drawString(nickname, 135, csimageHeight - 95); Graphics2D tip5 = image.createGraphics(); Font tipFont5 = new Font("苹方 常规", Font.PLAIN, 16); //tip4.setColor(new Color(51, 129, 246)); tip5.setFont(tipFont5); tip5.drawString("一本书,一视界", 135, csimageHeight - 75); String temp = "images" + File.separator + "temp" + File.separator; // 新的图片文件名 = 获取时间戳+"."图片扩展名 String newFileName = String.valueOf(System.currentTimeMillis()) + ".jpg"; // 文件路径 String filePath = webUploadPath.concat(temp); File dest = new File(filePath, newFileName); if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } createImage(filePath + newFileName); System.out.println(filePath + newFileName); // 将反斜杠转换为正斜杠 String dataPath = temp.replaceAll("\\\\", "/") + newFileName; data.put("imgUrl", serverurl + dataPath); data.put("desk_url", filePath + newFileName); //首次测试加10积分 Integer integretionCount=0; integretionCount=integretionDetailService.queryByTest(testId,userId); if(integretionCount==0){ IntegretionDetail detail=new IntegretionDetail(); detail.setType((byte) 22); detail.setUserId(String.valueOf(userId)); detail.setIntegretionId(String.valueOf(testId)); detail.setAmount(10);//趣味测试完成后获得10积分 integretionDetailService.add(detail); } //将结果保存进csjieguo中 CsJieguo jg=csJieguoService.queryById(testId,userId); if(jg==null){ CsJieguo csjg=new CsJieguo(); csjg.setAccount(account); csjg.setTestId(testId); csjg.setUserId(userId); csjg.setImgUrl(serverurl + dataPath); csJieguoService.add(csjg); }else{ jg.setAccount(account); jg.setImgUrl(serverurl + dataPath); csJieguoService.update(jg); } } return ResponseUtil.ok(data); } public void createImage(String fileLocation) { if(image != null){ try { String formatName = fileLocation.substring(fileLocation.lastIndexOf(".") + 1); ImageIO.write(image, /*"GIF"*/ formatName /* format desired */ , new File(fileLocation) /* target */ ); /*FileOutputStream fos = new FileOutputStream(fileLocation); bos = new BufferedOutputStream(fos); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos); encoder.encode(image);*/ } catch (Exception e) { e.printStackTrace(); } } } }
true
433634335a5f8467a4544104e145f2c45fbb5de2
Java
christinakornilova/hillel-qa-auto-hometasks
/src/main/java/hometask03/ReplaceLastDCharacter.java
UTF-8
1,621
3.109375
3
[]
no_license
package hometask03; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import utils.Utils; import java.io.*; import java.util.List; public class ReplaceLastDCharacter { private static Logger log = LogManager.getLogger(ReplaceLastDCharacter.class); private final static String dDFindRgx = "[Dd](?=[^Dd]*$)"; private final static String path = "src/test/resources/regex/d.txt"; public static String readFileContentToString(File input) { List<String> list = null; try { //read file content to string FileInputStream fileInputStream = new FileInputStream(input); list = Utils.addSingleFileContentToList(fileInputStream); } catch (Exception e) { log.error("Error :)", e); } return String.join(" ", list); } //replace last Dd symbol to "" public static String replaceLastDdChar(String s) { return s.replaceAll(dDFindRgx,""); } // write new string with replaced line OVER the same file public static void overwriteFile(String inputStr, String path) { try { FileOutputStream fileOut = new FileOutputStream(path); fileOut.write(inputStr.getBytes()); fileOut.close(); } catch (Exception e) { log.error("Error reading file", e); } } public static void main(String[] args) { File input = new File(path); String s = readFileContentToString(input); s = replaceLastDdChar(s); // System.out.println(s); overwriteFile(s, path); } }
true
f5727241529daae0f99a0a8998f80c36ba18071a
Java
ArrenBryan/TasksReminders_V2
/app/src/main/java/com/example/tasksreminders/ui/tasks/TasksListAdapter.java
UTF-8
1,415
2.671875
3
[]
no_license
package com.example.tasksreminders.ui.tasks; import androidx.annotation.NonNull; import androidx.recyclerview.widget.DiffUtil; import androidx.recyclerview.widget.ListAdapter; import android.view.ViewGroup; public class TasksListAdapter extends ListAdapter<Tasks, TasksViewHolder> { private OnNoteListener onNoteListener; public TasksListAdapter(@NonNull DiffUtil.ItemCallback<Tasks> diffCallback, OnNoteListener onNoteListener) { super(diffCallback); this.onNoteListener = onNoteListener; } @Override public void onBindViewHolder(TasksViewHolder holder, int position) { Tasks current = getItem(position); holder.bind(current.getName(), current.getDescription(), current.getDeadline()); } @Override public TasksViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return TasksViewHolder.create(parent, onNoteListener); } static class TasksDiff extends DiffUtil.ItemCallback<Tasks> { @Override public boolean areItemsTheSame(@NonNull Tasks oldItem, @NonNull Tasks newItem) { return oldItem == newItem; } @Override public boolean areContentsTheSame(@NonNull Tasks oldItem, @NonNull Tasks newItem) { return oldItem.getName().equals(newItem.getName()); } } public interface OnNoteListener { void onNoteClick(int position); } }
true
89dd6ca7812c58d0415d389c16304de5e0a99830
Java
sanyaade-speechtools/capilla
/PrototipoLucene/src/es/sinai/ujaAsistVirtual/modelo/FactorySimpleAnalyzer.java
UTF-8
543
2.296875
2
[]
no_license
/** * SimpleAnalyzer.java * @author Eugenio Martínez Cámara * @date 07/06/2010 * @version */ package es.sinai.ujaAsistVirtual.modelo; import java.io.IOException; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.SimpleAnalyzer; /** * @author Eugenio Martínez Cámara * */ public class FactorySimpleAnalyzer implements FactoryAnalyzer { /* (non-Javadoc) * @see es.sinai.ujaAsistVirtual.modelo.AnalyzerFactory#createAnalyzer() */ @Override public Analyzer createAnalyzer() throws IOException { return (new SimpleAnalyzer()); } }
true
9e9adfd6c732d7cb05901b8255e5081adebca1f0
Java
chris065/188GitHubRepo
/FINAL_PRODUCT/SEPVultureSoftware/src/VultureSoftware/FinalInspectionUI.java
UTF-8
13,647
2.203125
2
[]
no_license
/* * 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 VultureSoftware; import databaseui.DataBaseToolkit; import databaseui.JobObject; import static java.lang.Integer.parseInt; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import javax.swing.JOptionPane; /** * * @author Jordan Thompson 17012215 */ public class FinalInspectionUI extends javax.swing.JFrame { /** * Creates new form FinalInspectionUI */ static DataBaseToolkit dbtk; static ArrayList<JobObject> job; public FinalInspectionUI(ArrayList job) { initComponents(); this.dbtk = new DataBaseToolkit(); this.job = job; setField(); } /** * 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() { finalInspectionPanel = new javax.swing.JPanel(); titleLabel = new javax.swing.JLabel(); JTFcheckedField = new javax.swing.JTextField(); checkedLabel = new javax.swing.JLabel(); endJobButton = new javax.swing.JButton(); dateLabel = new javax.swing.JLabel(); JTFdateField = new javax.swing.JTextField(); infoLabel = new javax.swing.JLabel(); numberLabel = new javax.swing.JLabel(); jobNumberField = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); finalInspectionPanel.setBackground(new java.awt.Color(102, 153, 255)); titleLabel.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N titleLabel.setForeground(new java.awt.Color(255, 255, 255)); titleLabel.setText("Final Inspection"); checkedLabel.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N checkedLabel.setForeground(new java.awt.Color(255, 255, 255)); checkedLabel.setText("Checked By"); endJobButton.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N endJobButton.setText("End Job"); endJobButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { endJobButtonActionPerformed(evt); } }); dateLabel.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N dateLabel.setForeground(new java.awt.Color(255, 255, 255)); dateLabel.setText("Date"); infoLabel.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N infoLabel.setForeground(new java.awt.Color(255, 255, 255)); infoLabel.setText("By clicking 'End Job', you are approving this motor passed the inpection and is ready to be delivered back to the client"); numberLabel.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N numberLabel.setForeground(new java.awt.Color(255, 255, 255)); numberLabel.setText("Job Number"); jobNumberField.setEditable(false); javax.swing.GroupLayout finalInspectionPanelLayout = new javax.swing.GroupLayout(finalInspectionPanel); finalInspectionPanel.setLayout(finalInspectionPanelLayout); finalInspectionPanelLayout.setHorizontalGroup( finalInspectionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(finalInspectionPanelLayout.createSequentialGroup() .addGroup(finalInspectionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(finalInspectionPanelLayout.createSequentialGroup() .addGap(196, 196, 196) .addGroup(finalInspectionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(finalInspectionPanelLayout.createSequentialGroup() .addComponent(numberLabel) .addGap(18, 18, 18) .addComponent(jobNumberField, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(finalInspectionPanelLayout.createSequentialGroup() .addGroup(finalInspectionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(dateLabel) .addComponent(checkedLabel)) .addGap(18, 18, 18) .addGroup(finalInspectionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(JTFdateField, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(JTFcheckedField, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGroup(finalInspectionPanelLayout.createSequentialGroup() .addGap(333, 333, 333) .addComponent(titleLabel)) .addGroup(finalInspectionPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(infoLabel))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, finalInspectionPanelLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(endJobButton, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(280, 280, 280)) ); finalInspectionPanelLayout.setVerticalGroup( finalInspectionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(finalInspectionPanelLayout.createSequentialGroup() .addComponent(titleLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE) .addGroup(finalInspectionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(numberLabel) .addComponent(jobNumberField, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(finalInspectionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(dateLabel) .addComponent(JTFdateField, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(13, 13, 13) .addGroup(finalInspectionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(checkedLabel) .addComponent(JTFcheckedField, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(63, 63, 63) .addComponent(infoLabel) .addGap(21, 21, 21) .addComponent(endJobButton, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 740, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(finalInspectionPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 392, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(finalInspectionPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) ); pack(); }// </editor-fold>//GEN-END:initComponents private void endJobButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_endJobButtonActionPerformed trim(); if(checks()){ if(!checkDate(JTFdateField.getText() ) ){ JOptionPane.showMessageDialog(null, "Format for date field must be DD/MM/YYYY", "", JOptionPane.INFORMATION_MESSAGE); } else{ int jobNo = parseInt(jobNumberField.getText()); String date = JTFdateField.getText(); String checkedBy = JTFcheckedField.getText(); if(dbtk.addNewFinalInspection(jobNo, date, checkedBy)){ JOptionPane.showMessageDialog(null, "Successfully added to database", "Success", JOptionPane.INFORMATION_MESSAGE); this.dispose(); } else { JOptionPane.showMessageDialog(null, "Failed to add to database", "Error", JOptionPane.ERROR_MESSAGE); this.dispose(); } } } }//GEN-LAST:event_endJobButtonActionPerformed /** * @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(FinalInspectionUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FinalInspectionUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FinalInspectionUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FinalInspectionUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FinalInspectionUI(job).setVisible(true); } }); } private void setField(){ jobNumberField.setText(""+job.get(0).getJobNumber() ); } private void trim(){ String textDA = JTFdateField.getText().trim(); JTFdateField.setText(textDA); String textCF = JTFcheckedField.getText().trim(); JTFcheckedField.setText(textCF); } private boolean checkDate(String date){ SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); try{ dateFormat.parse(date.trim()); } catch (ParseException pe){ return false; } return true; } private boolean checks(){ if(JTFcheckedField.getText().equals("")){ JOptionPane.showMessageDialog(null, "Please enter who performed the inspection", "", JOptionPane.INFORMATION_MESSAGE); return false; } else{ return true; } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField JTFcheckedField; private javax.swing.JTextField JTFdateField; private javax.swing.JLabel checkedLabel; private javax.swing.JLabel dateLabel; private javax.swing.JButton endJobButton; private javax.swing.JPanel finalInspectionPanel; private javax.swing.JLabel infoLabel; private javax.swing.JTextField jobNumberField; private javax.swing.JLabel numberLabel; private javax.swing.JLabel titleLabel; // End of variables declaration//GEN-END:variables }
true
f86b2af79771040e06c47b4b183b9b8bc5ef2862
Java
kaka17/SmartLock
/app/src/main/java/com/sht/smartlock/ui/activity/hourroom/BookingHourRoomActivity.java
UTF-8
5,179
2.140625
2
[]
no_license
package com.sht.smartlock.ui.activity.hourroom; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.Intent; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.sht.smartlock.Config; import com.sht.smartlock.R; import com.sht.smartlock.ui.activity.base.BaseActivity; public class BookingHourRoomActivity extends BaseActivity implements View.OnClickListener { private DayRoomFragment frgDayRoom; private HourRoomFragment frgHourRoom; private LinearLayout llHeader, llTabHour, llTabDay; private ImageView mTabLine; private int screenWidth; String room_mode = Config.ROOM_MODE_ALL; ImageView ivGoback; TextView tvTitle; String strHotelId, strHotelCaption; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); InitView(); if (savedInstanceState == null) { frgDayRoom = new DayRoomFragment(BookingHourRoomActivity.this); frgHourRoom = HourRoomFragment.newInstance(strHotelCaption,strHotelId); if (room_mode.equals(Config.ROOM_MODE_HOUR)) { getFragmentManager().beginTransaction().add(R.id.FragmentContainer, frgHourRoom, null).commit(); } else { getFragmentManager().beginTransaction().add(R.id.FragmentContainer, frgDayRoom, null).commit(); } } } private void InitView() { llTabDay = (LinearLayout) findViewById(R.id.id_tab_day); llTabHour = (LinearLayout) findViewById(R.id.id_tab_hour); llHeader = (LinearLayout) findViewById(R.id.lyroomTab); ivGoback = (ImageView) findViewById(R.id.goBack); tvTitle = (TextView) findViewById(R.id.tvTitle); ivGoback.setOnClickListener(this); llTabDay.setOnClickListener(this); llTabHour.setOnClickListener(this); Intent i = getIntent(); strHotelCaption = i.getStringExtra(Config.KEY_HOTEL_CAPTION); strHotelId = i.getStringExtra(Config.KEY_HOTEL_ID); room_mode = i.getStringExtra(Config.KEY_SHOW_ROOM_MODE); tvTitle.setText(strHotelCaption); if (room_mode.equals(Config.ROOM_MODE_ALL)) { llHeader.setVisibility(View.VISIBLE); } else { llHeader.setVisibility(View.GONE); } initTabLine(); } private void initTabLine() { mTabLine = (ImageView) findViewById(R.id.id_tab_line); DisplayMetrics outMetrics = new DisplayMetrics(); getWindow().getWindowManager().getDefaultDisplay().getMetrics(outMetrics); screenWidth = outMetrics.widthPixels; LinearLayout.LayoutParams lp = (android.widget.LinearLayout.LayoutParams) mTabLine.getLayoutParams(); lp.width = screenWidth / 2; mTabLine.setLayoutParams(lp); } @Override public void onAttachFragment(Fragment fragment) { super.onAttachFragment(fragment); //防止内存回收fragment出现重叠现象 if (frgDayRoom == null && fragment instanceof DayRoomFragment) { frgDayRoom = (DayRoomFragment) fragment; } else if (frgHourRoom == null && fragment instanceof HourRoomFragment) { frgHourRoom = (HourRoomFragment) fragment; } } @Override protected int getLayoutId() { return R.layout.activity_booking_hour_room; } protected boolean hasToolBar() { return false; } public String getStrHotelId() { return strHotelId; } public String getStrHotelCaption() { return strHotelCaption; } public String getRoom_mode() { return room_mode; } @Override public void onClick(View v) { LinearLayout.LayoutParams lp; FragmentTransaction transaction = getFragmentManager().beginTransaction(); switch (v.getId()) { case R.id.id_tab_day: if (frgDayRoom.isAdded()) { transaction.hide(frgHourRoom).show(frgDayRoom).commit(); } else { transaction.hide(frgHourRoom).add(R.id.FragmentContainer, frgDayRoom).commit(); } lp = (android.widget.LinearLayout.LayoutParams) mTabLine .getLayoutParams(); lp.leftMargin = 0; mTabLine.setLayoutParams(lp); break; case R.id.id_tab_hour: if (frgHourRoom.isAdded()) { transaction.hide(frgDayRoom).show(frgHourRoom).commit(); } else { transaction.hide(frgDayRoom).add(R.id.FragmentContainer, frgHourRoom).commit(); } lp = (android.widget.LinearLayout.LayoutParams) mTabLine .getLayoutParams(); lp.leftMargin = (int) ((screenWidth * 1.0 / 2)); mTabLine.setLayoutParams(lp); break; case R.id.goBack: finish(); break; } } }
true
cb88be8546246f171dc95d9e57d716596323bd8a
Java
tectronics/apollo
/apollo-ws/service-skeletons/java/tags/2.0/apollo-service-client/src/main/java/edu/pitt/apollo/apolloclient/TutorialChapter2_BasicRunSimulationExample.java
UTF-8
15,381
1.515625
2
[ "Apache-2.0" ]
permissive
/* Copyright 2012 University of Pittsburgh * * 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 edu.pitt.apollo.apolloclient; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URL; import java.util.Calendar; import java.util.GregorianCalendar; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; import edu.pitt.apollo.service.apolloservice.v2_0.ApolloServiceEI; import edu.pitt.apollo.service.apolloservice.v2_0.ApolloServiceV20; import edu.pitt.apollo.types.v2_0.ApolloPathogenCode; import edu.pitt.apollo.types.v2_0.ApolloSoftwareType; import edu.pitt.apollo.types.v2_0.Authentication; import edu.pitt.apollo.types.v2_0.Infection; import edu.pitt.apollo.types.v2_0.InfectionAcquisition; import edu.pitt.apollo.types.v2_0.InfectionState; import edu.pitt.apollo.types.v2_0.InfectiousDisease; import edu.pitt.apollo.types.v2_0.InfectiousDiseaseScenario; import edu.pitt.apollo.types.v2_0.Location; import edu.pitt.apollo.types.v2_0.LocationDefinition; import edu.pitt.apollo.types.v2_0.MethodCallStatus; import edu.pitt.apollo.types.v2_0.MethodCallStatusEnum; import edu.pitt.apollo.types.v2_0.NumericParameterValue; import edu.pitt.apollo.types.v2_0.PopulationInfectionAndImmunityCensus; import edu.pitt.apollo.types.v2_0.PopulationInfectionAndImmunityCensusData; import edu.pitt.apollo.types.v2_0.PopulationInfectionAndImmunityCensusDataCell; import edu.pitt.apollo.types.v2_0.RunAndSoftwareIdentification; import edu.pitt.apollo.types.v2_0.RunSimulationMessage; import edu.pitt.apollo.types.v2_0.RunVisualizationMessage; import edu.pitt.apollo.types.v2_0.SimulatorTimeSpecification; import edu.pitt.apollo.types.v2_0.SoftwareIdentification; import edu.pitt.apollo.types.v2_0.TimeStepUnit; import edu.pitt.apollo.types.v2_0.UnitOfMeasure; import edu.pitt.apollo.types.v2_0.UrlOutputResource; import edu.pitt.apollo.types.v2_0.VisualizationOptions; import edu.pitt.apollo.types.v2_0.VisualizerResult; public class TutorialChapter2_BasicRunSimulationExample { public static final String WSDL_LOC = "http://research.rods.pitt.edu/apolloservice2.0/services/apolloservice?wsdl"; private ApolloServiceEI port; private static final QName SERVICE_NAME = new QName("http://service.apollo.pitt.edu/apolloservice/v2_0/", "ApolloService_v2.0"); protected TutorialChapter2_BasicRunSimulationExample() throws MalformedURLException { ApolloServiceV20 ss = new ApolloServiceV20(new URL(WSDL_LOC), SERVICE_NAME); port = ss.getApolloServiceEndpoint(); } public ApolloServiceEI getPort() { return port; } public SoftwareIdentification getSoftwareIdentificationForSimulator() { SoftwareIdentification softwareId = new SoftwareIdentification(); softwareId.setSoftwareDeveloper("UPitt,PSC,CMU"); softwareId.setSoftwareName("FRED"); softwareId.setSoftwareVersion("2.0.1_i"); softwareId.setSoftwareType(ApolloSoftwareType.SIMULATOR); return softwareId; } protected SoftwareIdentification getSoftwareIdentifiationForTimeSeriesVisualizer() { SoftwareIdentification softwareId = new SoftwareIdentification(); softwareId.setSoftwareName("Time Series Visualizer"); softwareId.setSoftwareType(ApolloSoftwareType.VISUALIZER); softwareId.setSoftwareVersion("1.0"); softwareId.setSoftwareDeveloper("UPitt"); return softwareId; } protected SoftwareIdentification getSoftwareIdentifiationForGaia() { SoftwareIdentification softwareId = new SoftwareIdentification(); softwareId.setSoftwareName("GAIA"); softwareId.setSoftwareType(ApolloSoftwareType.VISUALIZER); softwareId.setSoftwareVersion("1.0"); softwareId.setSoftwareDeveloper("PSC"); return softwareId; } protected Authentication getAuthentication() { Authentication authentication = new Authentication(); authentication.setRequesterId("TutorialUser"); authentication.setRequesterPassword("TutorialPassword"); return authentication; } protected SimulatorTimeSpecification getSimulatorTimeSpecification() { SimulatorTimeSpecification timeSpec = new SimulatorTimeSpecification(); timeSpec.setRunLength(new BigInteger("90")); timeSpec.setTimeStepUnit(TimeStepUnit.DAY); timeSpec.setTimeStepValue(1.0); return timeSpec; } protected PopulationInfectionAndImmunityCensus getPopulationInfectionAndImmunityCensus() { PopulationInfectionAndImmunityCensus census = new PopulationInfectionAndImmunityCensus(); census.setDescription("Population of Allegheny County, Pennsylvania"); GregorianCalendar calendar = new GregorianCalendar(); calendar.set(Calendar.YEAR, 2009); calendar.set(Calendar.MONTH, Calendar.SEPTEMBER); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); XMLGregorianCalendar censusDate = null; try { censusDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar); } catch (DatatypeConfigurationException e) { System.out.println("Error! Unable to set date, error was:" + e.getMessage()); System.exit(-1); } census.setDate(censusDate); Location location = new Location(); location.setLocationCode("42003"); census.setLocation(location); census.setPopulationSpecies("9606"); // homo sapiens ApolloPathogenCode pathId = new ApolloPathogenCode(); pathId.setGisrnCladeName("H1N1"); pathId.setNcbiTaxonId("114727"); // Influenza A subtype H1N1 census.setPathogen(pathId); PopulationInfectionAndImmunityCensusData data = new PopulationInfectionAndImmunityCensusData(); data.setLocation(location); PopulationInfectionAndImmunityCensusDataCell susceptibleCell = new PopulationInfectionAndImmunityCensusDataCell(); susceptibleCell.setInfectionState(InfectionState.SUSCEPTIBLE); susceptibleCell.setFractionInInfectionState(0.94); PopulationInfectionAndImmunityCensusDataCell exposedCell = new PopulationInfectionAndImmunityCensusDataCell(); exposedCell.setInfectionState(InfectionState.EXPOSED); exposedCell.setFractionInInfectionState(0.0); PopulationInfectionAndImmunityCensusDataCell infectiousCell = new PopulationInfectionAndImmunityCensusDataCell(); infectiousCell.setInfectionState(InfectionState.INFECTIOUS); infectiousCell.setFractionInInfectionState(0.01); PopulationInfectionAndImmunityCensusDataCell recoveredCell = new PopulationInfectionAndImmunityCensusDataCell(); recoveredCell.setInfectionState(InfectionState.RECOVERED); recoveredCell.setFractionInInfectionState(0.05); data.getCensusDataCells().add(susceptibleCell); data.getCensusDataCells().add(exposedCell); data.getCensusDataCells().add(infectiousCell); data.getCensusDataCells().add(recoveredCell); census.setCensusData(data); return census; } protected InfectiousDisease getInfectiousDisease() { InfectiousDisease disease = new InfectiousDisease(); disease.setDiseaseID("H1N1"); disease.setSpeciesWithDisease("9606"); // homo sapiens ApolloPathogenCode pathId = new ApolloPathogenCode(); pathId.setGisrnCladeName("H1N1"); pathId.setNcbiTaxonId("114727"); // Influenza A subtype H1N1 disease.setCausalPathogen(pathId); return disease; } protected Infection getInfection() { Infection infection = new Infection(); ApolloPathogenCode pathId = new ApolloPathogenCode(); pathId.setGisrnCladeName("H1N1"); pathId.setNcbiTaxonId("114727"); // Influenza A subtype H1N1 infection.setPathogenTaxonID(pathId); infection.setHostTaxonID("9606"); // homo sapiens NumericParameterValue infectiousPeriod = new NumericParameterValue(); infectiousPeriod.setUnitOfMeasure(UnitOfMeasure.DAYS); infectiousPeriod.setValue(6.0); infection.setInfectiousPeriodDuration(infectiousPeriod); NumericParameterValue latentPeriod = new NumericParameterValue(); latentPeriod.setUnitOfMeasure(UnitOfMeasure.DAYS); latentPeriod.setValue(2.0); infection.setLatentPeriodDuration(latentPeriod); infection.getInfectionAcquisition().add(getInfectionAcquisition()); return infection; } private InfectionAcquisition getInfectionAcquisition() { InfectionAcquisition infectionAcquisition = new InfectionAcquisition(); ApolloPathogenCode pathId = new ApolloPathogenCode(); pathId.setGisrnCladeName("H1N1"); pathId.setNcbiTaxonId("114727"); // Influenza A subtype H1N1 infectionAcquisition.setPathogenTaxonID(pathId); infectionAcquisition.setSusceptibleHostTaxonID("9606"); // homo sapiens infectionAcquisition.setBasicReproductionNumber(1.3); return infectionAcquisition; } protected InfectiousDiseaseScenario getInfectiousDiseaseScenario() { InfectiousDiseaseScenario scenario = new InfectiousDiseaseScenario(); LocationDefinition definition = new LocationDefinition(); definition.setDescription("Allegheny County, Pennsylvania"); // set the scenario location to Allegheny County Location location = new Location(); location.setLocationCode("42003"); scenario.setLocation(location); // set the scenario date to 2009/09/01 GregorianCalendar calendar = new GregorianCalendar(); calendar.set(Calendar.YEAR, 2009); calendar.set(Calendar.MONTH, Calendar.SEPTEMBER); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); // translate from Java style Calendar to an XML compatible calendar XMLGregorianCalendar scenarioDate = null; try { scenarioDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar); } catch (DatatypeConfigurationException e) { System.out.println("Error! Unable to set date, error was:" + e.getMessage()); System.exit(-1); } scenario.setScenarioDate(scenarioDate); scenario.getInfections().add(getInfection()); scenario.getDiseases().add(getInfectiousDisease()); scenario.getPopulationInfectionAndImmunityCensuses().add(getPopulationInfectionAndImmunityCensus()); return scenario; } public RunSimulationMessage getRunSimulationMessage() { RunSimulationMessage message = new RunSimulationMessage(); message.setInfectiousDiseaseScenario(getInfectiousDiseaseScenario()); message.setAuthentication(getAuthentication()); message.setSimulatorIdentification(getSoftwareIdentificationForSimulator()); message.setSimulatorTimeSpecification(getSimulatorTimeSpecification()); return message; } protected MethodCallStatus checkStatusOfWebServiceCall(RunAndSoftwareIdentification runAndSoftwareId) { // give the simulator a chance to launch the simulation try { Thread.sleep(10000); } catch (InterruptedException e1) { // this is acceptable } while (true) { MethodCallStatus status = port.getRunStatus(runAndSoftwareId); switch (status.getStatus()) { case AUTHENTICATION_FAILURE: case UNAUTHORIZED: System.out.println("No authorization for this run! Error message is:" + status.getMessage()); return status; case COMPLETED: System.out.println("Completed!"); return status; case FAILED: System.out.println("Run Failed! Error message is:" + status.getMessage()); return status; case RUNNING: case MOVING: case QUEUED: case HELD: case EXITING: case WAITING: System.out.println("The " + runAndSoftwareId.getSoftwareId().getSoftwareName() + " run is active (" + status.getStatus().toString() + "). The status message is: " + status.getMessage()); try { Thread.sleep(20000); } catch (InterruptedException e) { } } } } protected void getResourcesFromVisualizer(String simulatorRunId, SoftwareIdentification visualizerSoftwareIdentification) { System.out.println("Visualizing runId: " + simulatorRunId + " using the " + visualizerSoftwareIdentification.getSoftwareName() + " visualizer..."); RunVisualizationMessage runVisualizationMessage = new RunVisualizationMessage(); VisualizationOptions options = new VisualizationOptions(); options.setRunId(simulatorRunId); options.setLocation("42003"); options.setOutputFormat("default"); runVisualizationMessage.setVisualizationOptions(options); runVisualizationMessage.setVisualizerIdentification(visualizerSoftwareIdentification); Authentication auth = new Authentication(); auth.setRequesterId("TutorialUser"); auth.setRequesterPassword("TutorialPassword"); runVisualizationMessage.setAuthentication(auth); VisualizerResult visualizerResult = port.runVisualization(runVisualizationMessage); String visualizationRunId = visualizerResult.getRunId(); RunAndSoftwareIdentification visualizationRunAndSoftwareId = new RunAndSoftwareIdentification(); visualizationRunAndSoftwareId.setRunId(visualizationRunId); visualizationRunAndSoftwareId.setSoftwareId(visualizerSoftwareIdentification); if (checkStatusOfWebServiceCall(visualizationRunAndSoftwareId).getStatus() == MethodCallStatusEnum.COMPLETED) { System.out.println("The following resources were returned from the " + visualizerSoftwareIdentification.getSoftwareName() + " visualizer:"); for (UrlOutputResource r : visualizerResult.getVisualizerOutputResource()) { System.out.println("\t" + r.getURL()); } } } protected RunAndSoftwareIdentification runSimulation(RunSimulationMessage runSimulationMessage) { String simulationRunId = port.runSimulation(runSimulationMessage); System.out.println("The simulator returned a runId of " + simulationRunId); RunAndSoftwareIdentification runAndSoftwareId = new RunAndSoftwareIdentification(); runAndSoftwareId.setSoftwareId(getSoftwareIdentificationForSimulator()); runAndSoftwareId.setRunId(simulationRunId); MethodCallStatus status = checkStatusOfWebServiceCall(runAndSoftwareId); if (status.getStatus() == MethodCallStatusEnum.COMPLETED) { return runAndSoftwareId; } else { System.exit(-1); return null; } } protected void displayResults(RunAndSoftwareIdentification simulatorRunAndSoftwareId) { getResourcesFromVisualizer(simulatorRunAndSoftwareId.getRunId(), getSoftwareIdentifiationForTimeSeriesVisualizer()); getResourcesFromVisualizer(simulatorRunAndSoftwareId.getRunId(), getSoftwareIdentifiationForGaia()); } protected RunAndSoftwareIdentification runSimulationAndDisplayResults( RunSimulationMessage runSimulationMessage) { RunAndSoftwareIdentification simulatorRunAndSoftwareId = runSimulation(runSimulationMessage); displayResults(simulatorRunAndSoftwareId); return simulatorRunAndSoftwareId; } public static void main(String args[]) throws java.lang.Exception { TutorialChapter2_BasicRunSimulationExample example = new TutorialChapter2_BasicRunSimulationExample(); RunSimulationMessage runSimulationMessage = example.getRunSimulationMessage(); example.runSimulationAndDisplayResults(runSimulationMessage); } }
true
94baafa336112ad721c3929426fd33a0824595a4
Java
pc5211/match1.0
/nefu/src/main/java/nefu/itgardener/judge/core/model/WorkVo.java
UTF-8
759
1.9375
2
[]
no_license
package nefu.itgardener.judge.core.model; public class WorkVo { private Integer isScore; private String workName; private Integer workId; private Integer page; public Integer getIsScore() { return isScore; } public void setIsScore(Integer isScore) { this.isScore = isScore; } public String getWorkName() { return workName; } public void setWorkName(String workName) { this.workName = workName; } public Integer getWorkId() { return workId; } public void setworkId(Integer workId) { this.workId = workId; } public Integer getPage() { return page; } public void setPage(Integer page) { this.page = page; } }
true
c188ec496e02692106b6cd177b4f63462e797117
Java
hunterhector/lti-event-coref
/event-coref-core/src/main/java/edu/cmu/lti/event_coref/analysis_engine/io/WekaARFFBinaryClassFeatureOutputWriter.java
UTF-8
6,101
1.820313
2
[]
no_license
package edu.cmu.lti.event_coref.analysis_engine.io; import edu.cmu.lti.event_coref.type.EventCoreferenceCluster; import edu.cmu.lti.event_coref.type.EventMention; import edu.cmu.lti.event_coref.type.PairwiseEventCoreferenceEvaluation; import edu.cmu.lti.event_coref.type.PairwiseEventFeature; import edu.cmu.lti.event_coref.utils.eval.CorefChecker; import edu.cmu.lti.event_coref.utils.io.AbstractStepBasedFolderWriter; import edu.cmu.lti.event_coref.utils.ml.FeatureUtils; import edu.cmu.lti.event_coref.utils.ml.WekaFeatureFactory; import edu.cmu.lti.utils.uima.UimaConvenience; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.fit.descriptor.ConfigurationParameter; import org.apache.uima.fit.util.FSCollectionFactory; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.cas.FSList; import org.javatuples.Triplet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import weka.core.converters.ArffSaver; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * This writer will write features using Weka ARFF format * * @author Zhengzhong Liu, Hector */ public class WekaARFFBinaryClassFeatureOutputWriter extends AbstractStepBasedFolderWriter { private static final Logger logger = LoggerFactory.getLogger(WekaARFFBinaryClassFeatureOutputWriter.class); public static final String PARAM_FEATURE_NAME_PATH = "FeatureName"; public static final String PARAM_FEATURE_FILE_OUTPUT_FILE_NAME = "FeatureFileOutputFileName"; // public static final String PARAM_FEATURE_SIEVE_OUTPUT_FILE_NAME = // "FeatureSieveOutputFileName"; public static final String PARAM_COREF_TYPE = "CoreferenceType"; public static final String PARAM_POSITIVE_CLASS_NAME = "PositiveClassName"; public static final String PARAM_TARGET_PECE_COMPONENT_ID = "targetPeceComponentId"; @ConfigurationParameter(name = PARAM_TARGET_PECE_COMPONENT_ID, mandatory = true, description = "Target Pece to output, give null will output everything") private String targetPeceComponentId; @ConfigurationParameter(name = PARAM_POSITIVE_CLASS_NAME, description = "Positive class name", mandatory = true) private String postiveClassName; @ConfigurationParameter(name = PARAM_COREF_TYPE, description = "Coreference types", mandatory = true) private Set<String> coreferenceTypes; @ConfigurationParameter(name = PARAM_FEATURE_NAME_PATH, mandatory = true) private String featureNamePath; @ConfigurationParameter(name = PARAM_FEATURE_FILE_OUTPUT_FILE_NAME, mandatory = true) private String featureOutputFileName; private Map<String, Triplet<Integer, Boolean, String>> featureNameMap; private String featureFileOutputFullPath; private int defaultWeight = 1; private WekaFeatureFactory featureFactory; private HashMap<EventMention, Integer> anaphoricPositions; @Override public void subInitialize() { try { featureFileOutputFullPath = outputDir.getCanonicalPath() + "/" + featureOutputFileName + "." + outputFileSuffix; logger.debug("Writing features to " + featureFileOutputFullPath); } catch (IOException e) { e.printStackTrace(); } featureNameMap = FeatureUtils.getFeatureInfoMap(featureNamePath); featureFactory = new WekaFeatureFactory(featureNameMap, postiveClassName); } @Override public void process(JCas aJCas) throws AnalysisEngineProcessException { UimaConvenience.printProcessLog(aJCas, logger); anaphoricPositions = new HashMap<EventMention, Integer>(); for (EventCoreferenceCluster clusters : JCasUtil.select(aJCas, EventCoreferenceCluster.class)) { Collection<EventMention> mentionInCluster = FSCollectionFactory.create(clusters.getChildEventMentions(), EventMention.class); int anaphoricIndex = -1; for (EventMention evm : mentionInCluster) { int mentionIndex = evm.getEventMentionIndex(); if (evm.getBegin() > 0) { if (anaphoricIndex < 0) { anaphoricIndex = mentionIndex; } else if (mentionIndex < anaphoricIndex) { anaphoricIndex = mentionIndex; } } } if (anaphoricIndex != -1) { for (EventMention evm : mentionInCluster) { if (evm.getBegin() > 0) { anaphoricPositions.put(evm, anaphoricIndex); } } } } for (PairwiseEventCoreferenceEvaluation pece : JCasUtil.select(aJCas, PairwiseEventCoreferenceEvaluation.class)) { if (targetPeceComponentId == null || pece.getComponentId().equals(targetPeceComponentId)) { FSList featuresFS = pece.getPairwiseEventFeatures(); Map<String, Double> featuresMap = new HashMap<String, Double>(); if (featuresFS != null) { for (PairwiseEventFeature feature : FSCollectionFactory.create(featuresFS, PairwiseEventFeature.class)) { featuresMap.put(feature.getName(), feature.getScore()); } } // the feature is automatically added inside the factory featureFactory.addInstance(featuresMap, coreferenceTypes.contains(CorefChecker.getCorefTypeGolden(pece)), defaultWeight); } } } @Override public void collectionProcessComplete() throws AnalysisEngineProcessException { ArffSaver saver = new ArffSaver(); saver.setInstances(featureFactory.getDataset()); try { saver.setFile(new File(featureFileOutputFullPath)); saver.writeBatch(); // featureSieveWriter.close(); } catch (IOException e) { e.printStackTrace(); } } }
true
1d0d6fca662f6d62af4ff570936c78a56ec3d7cd
Java
fatroom/hemingway
/src/main/java/com/upday/hemingway/service/AuthorRepository.java
UTF-8
340
1.59375
2
[]
no_license
package com.upday.hemingway.service; import com.upday.hemingway.domain.Author; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; @RepositoryRestResource public interface AuthorRepository extends PagingAndSortingRepository<Author, Long> { }
true
f1dd4711fdd0f0c70dfc9d481fe75135aed2374a
Java
teodoraj/Book-Shop
/src/BookSpecification.java
UTF-8
1,122
3.1875
3
[]
no_license
import java.util.*; public class BookSpecification { private String title; private int year, pages; private double price; private ArrayList<Person> authors; private ArrayList<Notice> notices; public BookSpecification(String t, int y, int p, double pr, ArrayList<Person> a, ArrayList<Notice> n) { this.title = t; this.year = y; this.pages = p; this.price = pr; this.authors = a; this.notices = n; } public String getTitle() { return title; } public int getYear() { return year; } public int getPages() { return pages; } public ArrayList<Person> getAuthors() { return authors; } public ArrayList<Notice> getNotices() { return notices; } public double getPrice() { return price; } public String toString() { String s; s = "Title: " + title + "\nYear:" + year + "\nPages number:" + pages + "\nAuthors:"; for(int i = 0; i<authors.size(); i++) { s = s + authors.get(i).getLF() + ";"; } s = s + "\nNotices:\n"; for(int i = 0; i<notices.size(); i++) { s = s + notices.get(i).getAuthor().getLF() + ":\n" + notices.get(i).getText() + "\n"; } return s; } }
true
6e90df6caea4faea85bead92512344d725576245
Java
Kev0204/DoldiMeter0.6
/app/src/main/java/com/kevali/doldimeter04/besoffenActivity.java
UTF-8
392
1.773438
2
[]
no_license
package com.kevali.doldimeter04; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; /** * Created by defaultuser0 on 09/08/2016. */ public class besoffenActivity extends AppCompatActivity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_besoffen); } }
true
cc731a114277dd00c843897e074f186ef00d63d9
Java
xundian360/HuaQiaoTong
/HuaQiaoTong/src/com/xundian360/huaqiaotong/activity/b03/B03V01Activity.java
UTF-8
3,547
2.078125
2
[]
no_license
/** * */ package com.xundian360.huaqiaotong.activity.b03; import java.util.List; import org.json.JSONException; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.nostra13.universalimageloader.core.ImageLoader; import com.xundian360.huaqiaotong.R; import com.xundian360.huaqiaotong.activity.com.ComNoTittleActivity; import com.xundian360.huaqiaotong.modle.b03.Posts; import com.xundian360.huaqiaotong.modle.b03.PostsItem; import com.xundian360.huaqiaotong.util.b03.B03v00Util; /** * 帖子明细 * @author Administrator * @date 2013年10月23日 * @version 1.0 */ public class B03V01Activity extends ComNoTittleActivity { ImageView retBtn; LinearLayout detailContainer; // 帖子对象 Posts posts; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.b03v01); // 初始化数据 initData(); // 初始化组件 initModule(); // 设置帖子明细 setDetailContainer(); } /** * 初始化数据 */ private void initData(){ // 设置数据 setData(); } /** * 初始化组件 */ private void initModule(){ retBtn = (ImageView) findViewById(R.id.b03v01RetBtn); retBtn.setOnClickListener(returnBtnClick); detailContainer = (LinearLayout) findViewById(R.id.b03v01DetailContainer); } /** * 返回 */ OnClickListener returnBtnClick = new OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }; /** * 设置数据 */ private void setData() { String postsJson = "{\"status\":0,\"tittle\":\"花桥地铁开通了\",\"commentN\":\"152\",\"author\":\"鬼太郎\",\"time\":\"2013-10-23 24:52:59\",\"uid\":\"befdb29" + "2767279f887154123\",\"dtailL\":[{\"type\":\"txt\",\"msg\":\"花桥地铁开通了花桥地铁开通了花桥地铁开通了花桥地铁开通了花" + "桥地铁开通了\"},{\"type\":\"img\",\"msg\":\"http://img1.gtimg.com/7/791/79120/7912029_1200x1000_0.png\"},{\"type\":\"txt\",\"msg\":\"花桥地铁开通了" + "花桥地铁开通了花桥地铁开通了" + "花桥地铁开通了花桥地铁开通了\"},{\"type\":\"img\",\"msg\":\"http://img1.gtimg.com/7/791/79120/7912031_1200x1000_0.png\"}]}"; try { posts = B03v00Util.getPostsDetailData(postsJson); } catch (JSONException e) { e.printStackTrace(); // TODO } } /** * 设置帖子明细 */ private void setDetailContainer() { List<PostsItem> postsItems = posts.getDtailL(); if (postsItems != null && postsItems.size() > 0) { // 设置明细 for (PostsItem postsItem : postsItems) { // 文本 if (PostsItem.TXT_KEY.equals(postsItem.getType())) { TextView textView = new TextView(this); textView.setText(postsItem.getMsg()); textView.setTextColor(Color.WHITE); // 添加文本到页面显示 detailContainer.addView(textView); } // 图片 else if(PostsItem.IMG_KEY.equals(postsItem.getType())) { ImageView img1 = new ImageView(this); ImageLoader.getInstance().displayImage(postsItem.getMsg(), img1); // 添加图片到页面显示 detailContainer.addView(img1); } } } } }
true
d1a48932ae32a204c47b89be5fc028f3132f6277
Java
fullWaveRectifier/wecare
/coachMS/src/main/java/com/infosys/coachms/service/CoachService.java
UTF-8
521
1.976563
2
[]
no_license
package com.infosys.coachms.service; import com.infosys.coachms.dto.BookingDTO; import com.infosys.coachms.dto.CoachDTO; import com.infosys.coachms.dto.LoginDTO; import com.infosys.coachms.exception.WeCareException; import java.util.List; public interface CoachService { CoachDTO getCoachById(String coachId); List<CoachDTO> getAllCoaches(); List<BookingDTO> getBookingSchedules(String coachId); String createCoach(CoachDTO coachDTO); Boolean coachLogin(LoginDTO login) throws WeCareException; }
true
58dc5b554a6bc5de8538c3ed1e45c65d37fdb13f
Java
moutainhigh/Fexie-Spring-MVC-Backend
/fexie_openservice/fexie-service-provider/src/main/java/com/yuzhidi/service/impl/payment/OrderCancelServiceImpl.java
UTF-8
3,032
2.078125
2
[]
no_license
package com.yuzhidi.service.impl.payment; import com.yuzhidi.dao.account.commission.CommissionDetailDao; import com.yuzhidi.dao.payment.OrderDao; import com.yuzhidi.enums.core.mns.MnsNotifyTypes; import com.yuzhidi.enums.payment.TradeStatusTypes; import com.yuzhidi.global.ActionResultRO; import com.yuzhidi.global.ReturnMap; import com.yuzhidi.ro.account.commission.CommissionDetailRO; import com.yuzhidi.ro.core.mns.NotificationRO; import com.yuzhidi.ro.payment.order.OrderRO; import com.yuzhidi.service.aop.notify.NeedDoNotify; import com.yuzhidi.service.payment.OrderCancelService; import com.yuzhidi.util.StringUtil; import org.apache.commons.collections.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Created by cong.li on 2017/11/9. */ @Service public class OrderCancelServiceImpl implements OrderCancelService { @Autowired private OrderDao orderDao; @Autowired private CommissionDetailDao commissionDetailDao; /** * 减去佣金 * * @param notificationRO * @return */ @Override @NeedDoNotify(type = MnsNotifyTypes.SubtractCommissionWithCancel) public ActionResultRO<ReturnMap> subtractCommissionWithCancel(NotificationRO notificationRO) { String orderNum = notificationRO.getMessage(); OrderRO orderRO = orderDao.findOneByNum(orderNum); if (orderRO == null) { return new ActionResultRO<ReturnMap>(false, "订单不存在"); } if (orderRO.getTrade_status() != TradeStatusTypes.RefundSuccessful.getCode() && orderRO.getTrade_status() != TradeStatusTypes.Canceled.getCode()) { return new ActionResultRO<ReturnMap>(false, "非已退款/已取消订单,不能做减佣金处理"); } if (orderRO.getTrade_status() == TradeStatusTypes.Canceled.getCode() && orderRO.getActual_amount() > 0) { return new ActionResultRO<ReturnMap>(false, "付费订单需退款后才能回收佣金"); } List<CommissionDetailRO> commissionDetailROS = commissionDetailDao.listNoHoldByOrderNum(orderNum); if (CollectionUtils.isEmpty(commissionDetailROS)) { return new ActionResultRO<ReturnMap>(false, "佣金明细不存在或已结算"); } boolean result = true; String message = ""; for (CommissionDetailRO ro : commissionDetailROS) { CommissionDetailRO updateResult = commissionDetailDao.updateExcludeStatus(ro.getUid(), ro.getTrans_id(), TradeStatusTypes.getTradeStatusTypesByCode(""+orderRO.getTrade_status()).getMsg()); if (updateResult == null || updateResult.getExclude_status() != 1) { result = false; message = String.format("trans_id=%s, uid=%s 标记佣金不参与清算失败", ro.getTrans_id(), ro.getUid()); } } return new ActionResultRO<ReturnMap>(result, StringUtil.isEmpty(message) ? "成功" : message); } }
true
ca4237c9729df1e50d016781702e9efa6e1c4bac
Java
jiangjihui/springboot-web-frame
/springboot-web-frame-jpa-business-shiro/src/main/java/com/jjh/business/system/user/controller/SysUserController.java
UTF-8
4,801
2.0625
2
[]
no_license
package com.jjh.business.system.user.controller; import com.jjh.business.common.file.controller.form.UploadFileForm; import com.jjh.business.system.user.controller.form.QueryUserForm; import com.jjh.business.system.user.controller.form.ResetPasswordForm; import com.jjh.business.system.user.controller.form.UserFrozenForm; import com.jjh.business.system.user.model.SysUser; import com.jjh.business.system.user.service.SysUserService; import com.jjh.common.web.controller.BaseController; import com.jjh.common.web.form.PageRequestForm; import com.jjh.common.web.form.PageResponseForm; import com.jjh.common.web.form.SimpleResponseForm; import com.jjh.framework.plugin.excel.ExcelUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import java.util.List; /** * 用户管理 * * @author jjh * @date 2019/11/14 **/ @Api(tags = "用户管理") @RestController @RequestMapping("/system/user/sys_user") public class SysUserController extends BaseController { @Autowired private SysUserService sysUserService; private static final Logger logger = LoggerFactory.getLogger(SysUserController.class); /** * 用户列表 * @param form 分页请求参数 * @return 用户列表 */ @RequiresPermissions("system:sysUser:list") @ApiOperation("用户列表") @PostMapping("/list") public SimpleResponseForm<PageResponseForm<SysUser>> list(@RequestBody PageRequestForm<QueryUserForm> form) { List<SysUser> list = sysUserService.list(form); return page(form, list); } /** * 新增用户 * @param entity 用户信息 * @return 用户信息 */ @ApiOperation(value = "保存") @PostMapping("/add") public SimpleResponseForm<SysUser> add(HttpServletRequest request, @RequestBody SysUser entity) { SysUser result = sysUserService.add(entity); return success(result); } /** * 更新 * @param entity 用户信息 * @return 用户信息 */ @ApiOperation(value = "更新") @PostMapping("/update") public SimpleResponseForm<SysUser> update(HttpServletRequest request, @RequestBody SysUser entity) { SysUser result = sysUserService.update(entity); return success(result); } /** * 删除 * @param ids 待删除的ID数组 */ @ApiOperation(value = "删除") @GetMapping("/delete") public SimpleResponseForm<String> delete(String ids) { sysUserService.delete(ids); return success(); } /** * 用户重置(密码) * @param form * @return */ @ApiOperation(value = "用户重置(密码)") @PostMapping(value = "/reset") public SimpleResponseForm<String> reset(@Valid @RequestBody ResetPasswordForm form) { sysUserService.resetPassword(form); return success(); } /** * 冻结/解冻 * @param list * @return */ @ApiOperation(value = "冻结/解冻") @PostMapping("/frozen") public SimpleResponseForm<String> frozen(@Valid @RequestBody List<UserFrozenForm> list) { sysUserService.frozen(list); return success(); } /** * 用户导出 * @param form 分页请求参数 * @return 导出文件 */ @ApiOperation("用户导出") @PostMapping("/export") public SimpleResponseForm<String> export(@RequestBody PageRequestForm<QueryUserForm> form) { List<SysUser> list = sysUserService.list(form); ExcelUtil<SysUser> excelUtil = new ExcelUtil<>(SysUser.class); return success(excelUtil.exportExcel(list, "用户列表")); } /** * 用户导入模板 * @return */ @ApiOperation(value = "用户导入模板") @GetMapping("/importTemplate") public SimpleResponseForm<String> importTemplate() { ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class); return success(util.importTemplateExcel( "用户导入")); } /** * 用户数据导入 * @return */ @ApiOperation(value = "用户数据导入") @PostMapping("/importData") public SimpleResponseForm<String> importData(UploadFileForm form, boolean updateSupport) { if (form.getFile() != null) { ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class); List<SysUser> list = util.importExcel(form.getFile()); sysUserService.importData(list, updateSupport); } return success(); } }
true
06200238709c1375c8459b02679ce8c07cf5dbf3
Java
KnoWsea/sell
/src/main/java/com/imook/sell/service/impl/SellerServiceImpl.java
UTF-8
667
2
2
[]
no_license
package com.imook.sell.service.impl; import com.imook.sell.dataobject.SellerInfo; import com.imook.sell.repository.SellerInfoRepository; import com.imook.sell.service.SellerService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @author KnoWsea * @create 2019-01-01 19:33 */ @Service public class SellerServiceImpl implements SellerService { @Autowired private SellerInfoRepository repository; @Override public SellerInfo findSellerInfoByUsernameAndPassword(String username, String password) { return repository.findByUsernameAndPassword(username, password); } }
true
025dca07ded3c8752b3fb08a11e8c0ed43047376
Java
Auch-Auch/avito_source
/sources/com/google/android/gms/internal/measurement/zzji.java
UTF-8
560
1.5625
2
[]
no_license
package com.google.android.gms.internal.measurement; public final class zzji { private static final zzjg zza = zzc(); private static final zzjg zzb = new zzjf(); public static zzjg zza() { return zza; } public static zzjg zzb() { return zzb; } private static zzjg zzc() { try { return (zzjg) Class.forName("com.google.protobuf.MapFieldSchemaFull").getDeclaredConstructor(new Class[0]).newInstance(new Object[0]); } catch (Exception unused) { return null; } } }
true
7f344f4aadd3d5280ccbfa2bc46a24228b2aeb5c
Java
yevheniishestakov/DeliveryApp
/app/src/main/java/com/example/yevhenii/deliveryapp/DirectionDataModel/Polyline.java
UTF-8
215
1.882813
2
[]
no_license
package com.example.yevhenii.deliveryapp.DirectionDataModel; /** * Created by Yevhenii on 23-Jul-17. */ public class Polyline { public String getPoints() { return points; } String points; }
true
867fba0b899ccd252dce52ee856b1b7bef88835c
Java
amnaghori/SL-Assignments
/EmailAPI-JDBC/emailWithJDBC-WithRefresh/src/main/java/com/jdbc/test/dao/EmailDAO.java
UTF-8
246
1.84375
2
[]
no_license
package com.jdbc.test.dao; import java.util.List; import com.jdbc.test.entities.Email; public interface EmailDAO { public void update(Email recvr); public int[] batchUpdate(List<Email> emails); public List<Email> getAll(); }
true
f66a29b4a55623f6a2c5044d8c60b295f5cf29de
Java
12gw/Library
/library/src/main/java/com/library/manage/service/CategoryService.java
UTF-8
706
1.9375
2
[]
no_license
package com.library.manage.service; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.library.manage.entity.Category; import com.library.manage.mapper.CategoryMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class CategoryService { @Autowired private CategoryMapper categoryMapper; public List<Category> list() { return categoryMapper.selectList(Wrappers.<Category>lambdaQuery().orderByDesc(Category::getId)); } public Category get(int id) { return categoryMapper.selectOne(Wrappers.<Category>lambdaQuery().eq(Category::getId, id)); } }
true
3300326aa3cb9aee76f7b07ad81f759575c064c5
Java
achowdhury80/leetcode
/src/comp/prep2019/less2000/Prob1154.java
UTF-8
654
3.171875
3
[]
no_license
package comp.prep2019.less2000; public class Prob1154 { public int dayOfYear(String date) { String[] arr = date.split("-"); int[] days = new int[] {31, 28, 31, 30, 31, 30, 31,31, 30, 31, 30, 31}; int result = Integer.valueOf(arr[2]); int cur = 1; int month = Integer.valueOf(arr[1]); while(cur < month) { if (cur != 2) result += days[cur - 1]; else { int year = Integer.valueOf(arr[0]); if (year % 4 != 0 || (year % 100 == 0 && year % 400 != 0)) result += 28; else result += 29; } cur++; } return result; } }
true
fc309a907ffb883983c84364cc35187312abb601
Java
Hadesky/CACW-Android
/app/src/main/java/com/hadesky/cacw/ui/fragment/InvitePersonFragment.java
UTF-8
4,349
1.867188
2
[]
no_license
package com.hadesky.cacw.ui.fragment; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Parcelable; import android.support.v7.app.AlertDialog; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.TextView; import com.hadesky.cacw.R; import com.hadesky.cacw.adapter.InvitePersonAdapter; import com.hadesky.cacw.adapter.viewholder.BaseViewHolder; import com.hadesky.cacw.bean.TeamBean; import com.hadesky.cacw.bean.UserBean; import com.hadesky.cacw.presenter.InvitePersonPresenter; import com.hadesky.cacw.presenter.InvitePersonPresenterImpl; import com.hadesky.cacw.tag.IntentTag; import com.hadesky.cacw.ui.activity.UserInfoActivity; import com.hadesky.cacw.ui.view.InvitePersonView; import java.util.List; public class InvitePersonFragment extends BaseFragment implements InvitePersonView, BaseViewHolder.OnItemClickListener { private EditText mEdtSearch; private RecyclerView mRecyclerView; private TeamBean mTeamBean; private InvitePersonPresenter mPresenter; private InvitePersonAdapter mAdapter; private List<UserBean> mUser; @Override public int getLayoutId() { return R.layout.fragment_invite_person; } @Override protected void initViews(View view) { mRecyclerView = (RecyclerView) view.findViewById(R.id.rv); mEdtSearch = (EditText) view.findViewById(R.id.et); } @Override protected void setupViews(Bundle bundle) { mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); mAdapter = new InvitePersonAdapter(null, R.layout.item_person_in_invite,this,this); mRecyclerView.setAdapter(mAdapter); mTeamBean = (TeamBean) getArguments().getSerializable(IntentTag.TAG_TEAM_BEAN); mPresenter = new InvitePersonPresenterImpl(this,mTeamBean); mEdtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if(actionId== EditorInfo.IME_ACTION_SEARCH) { mPresenter.search(v.getText().toString()); } return true; } }); } private void showInviteDialog(final int position) { View view = getLayoutInflater(null).inflate(R.layout.dialog_with_edit_text_30, null); final EditText editText = (EditText) view.findViewById(R.id.edit_text); AlertDialog.Builder builder = new AlertDialog.Builder(getContext()) .setTitle(getString(R.string.invite_dialog_title)) .setView(view) .setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mPresenter.inviteUser(editText.getText().toString(),position); } }); builder.create().show(); } @Override public void showUser(List<UserBean> list,boolean isfinial) { mUser = list; mAdapter.setData(list,isfinial); } @Override public void onInviteSucceed(int pos) { mAdapter.disableInviteButton(pos); } @Override public void showProgress() { } @Override public void hideProgress() { } @Override public void showMsg(String s) { showToast(s); } @Override public void OnItemClick(View view, int position) { if(position==mAdapter.getNextResultPosition()) { mPresenter.LoadNextPage(); } else if(view.getId()==R.id.layout_invite_item) { UserBean u = mUser.get(position); Intent intent = new Intent(getContext(), UserInfoActivity.class); intent.putExtra(IntentTag.TAG_USER_BEAN,(Parcelable)u); getContext().startActivity(intent); }else if(view.getId()==R.id.bt_invite) { showInviteDialog(position); } } }
true
4434eacacd38e399793a5d8dced2b77291897b13
Java
Danial7777777/addentence
/attendance_common/src/main/java/com/w/attendance/exception/BusinessException.java
UTF-8
1,639
2.859375
3
[]
no_license
package com.w.attendance.exception; /** * 业务异常 * * @author linkai(31876) xmlinkai@gmail.com * @since 2019-05-22 09:10 */ public class BusinessException extends RuntimeException { private final String msg; private final int code; /** * 目前只有中台的错误才有tip */ private final String tip; public BusinessException(BusinessError businessError) { super(businessError.toString()); this.msg = businessError.getMsg(); this.code = businessError.getCode(); this.tip = null; } public BusinessException(BusinessError businessError, String tip) { super(businessError.toString()); this.msg = businessError.getMsg(); this.code = businessError.getCode(); this.tip = tip; } public BusinessException(int code, String msg, String tip) { this.code = code; this.msg = msg; this.tip = tip; } public BusinessException(BusinessError businessError, Throwable cause) { super(businessError.toString(), cause); this.msg = businessError.getMsg(); this.code = businessError.getCode(); this.tip = null; } public String getMsg() { return msg; } public String getTip() { return tip; } public int getCode() { return code; } public boolean hasTip() { return tip != null && tip.length() > 0; } @Override public String toString() { return "BusinessException{" + "msg='" + msg + '\'' + ", code=" + code + ", tip='" + tip + '\'' + '}'; } }
true
3975d7c885c5a5f9be61ac82ad682753d4156465
Java
yyhLogin/hengjia
/hengjia-scheduler/src/main/java/com/baibei/hengjia/scheduler/tasks/DeliveryMatchTimeTask.java
UTF-8
1,617
2.234375
2
[]
no_license
package com.baibei.hengjia.scheduler.tasks; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.baibei.hengjia.common.tool.api.ApiResult; import com.baibei.hengjia.common.tool.constants.Constants; import com.baibei.hengjia.scheduler.feign.ApiFeign; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * @author: Longer * @date: 2019/6/13 * @description: 提货配票定时器 */ @Slf4j @Component @EnableScheduling public class DeliveryMatchTimeTask { @Autowired private ApiFeign apiFeign; @Value("${execute.task.switch}") private String executeTaskSwitch; /** * 执行任务,每分钟跑一次执行 */ @Scheduled(cron = "0 0/1 * * * ?") private void dealTask() { JSONObject jsonObject = JSONObject.parseObject(executeTaskSwitch); String executeFlag = jsonObject.getString("deliverymatch"); if (Constants.ScheduleSwitch.OFF.equals(executeFlag)) { log.info("提货配票定时任务已锁定,不执行相关逻辑"); } if(Constants.ScheduleSwitch.ON.equals(executeFlag)){ log.info("DeliveryMatchTimeTask start..."); ApiResult apiResult = apiFeign.deliveryMatch(); log.info("DeliveryMatchTimeTask end,apiResult={}", JSON.toJSONString(apiResult)); } } }
true
8e0d4597be7cdc168626e1e3638320605ebfb95b
Java
siddharthasingh/accountsummary
/src/main/java/com/cub/ao/vo/LoanAccountVO_.java
UTF-8
2,172
1.875
2
[]
no_license
package com.cub.ao.vo; import java.io.Serializable; import java.math.BigDecimal; /** * * @author Niraja Deshpande * */ public class LoanAccountVO_ implements Serializable{ private static final long serialVersionUID = 545993571579708976L; private String accountTypeCodeDesc; private String loanAccountNumber; private String customerId; private String productCodeDesc; private BigDecimal currentPeriodPrincipalAmt; private int currentPeriodInterestAmt; private String currencyCode; private String facilityStartDate; public String getAccountTypeCodeDesc() { return accountTypeCodeDesc; } public void setAccountTypeCodeDesc(String accountTypeCodeDesc) { this.accountTypeCodeDesc = accountTypeCodeDesc; } public String getLoanAccountNumber() { return loanAccountNumber; } public void setLoanAccountNumber(String loanAccountNumber) { this.loanAccountNumber = loanAccountNumber; } public String getCustomerId() { return customerId; } public void setCustomerId(String customerId) { this.customerId = customerId; } public String getProductCodeDesc() { return productCodeDesc; } public void setProductCodeDesc(String productCodeDesc) { this.productCodeDesc = productCodeDesc; } public BigDecimal getCurrentPeriodPrincipalAmt() { return currentPeriodPrincipalAmt; } public void setCurrentPeriodPrincipalAmt(BigDecimal currentPeriodPrincipalAmt) { this.currentPeriodPrincipalAmt = currentPeriodPrincipalAmt; } public int getCurrentPeriodInterestAmt() { return currentPeriodInterestAmt; } public void setCurrentPeriodInterestAmt(int currentPeriodInterestAmt) { this.currentPeriodInterestAmt = currentPeriodInterestAmt; } public String getCurrencyCode() { return currencyCode; } public void setCurrencyCode(String currencyCode) { this.currencyCode = currencyCode; } public String getFacilityStartDate() { return facilityStartDate; } public void setFacilityStartDate(String facilityStartDate) { this.facilityStartDate = facilityStartDate; } public static long getSerialversionuid() { return serialVersionUID; } }
true
072d9fcca5828245d59ddc957930a51bf95ba969
Java
manikandanprabhu91/RaboAssignment
/src/main/java/com/rabo/assignment/domain/Records.java
UTF-8
534
2.203125
2
[]
no_license
package com.rabo.assignment.domain; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "records") @XmlAccessorType (XmlAccessType.FIELD) public class Records { @XmlElement(name = "record") List<Record> record; public List<Record> getRecord() { return record; } public void setRecord(List<Record> record) { this.record = record; } }
true
47843830b031d3f18723a82b22f4e5a14ece64e9
Java
MikeDLab/Epam_Pre-Training
/Task5/com_Epam_Pre_Training/Task5/Model/entity/cars/Car.java
UTF-8
2,716
3.3125
3
[]
no_license
package com_Epam_Pre_Training.Task5.model.entity.cars; import com_Epam_Pre_Training.Task5.model.entity.fuel.Fuel; public class Car { protected final String DEFAULT_BRAND = "Unknown brand"; protected String type; protected String brand = DEFAULT_BRAND; protected Fuel fuel; protected int cost; protected double tankCapacity; protected double maxSpeed; public Car() { } public Car(int cost, String brand, Fuel fuel, double tankCapacity, double maxSpeed) { this.cost = cost; this.brand = brand; this.maxSpeed = maxSpeed; this.tankCapacity = tankCapacity; setFuel(fuel); } public Car(Car car) { this.type = car.getType(); this.brand = car.getBrand(); this.fuel = car.getFuel(); this.cost = car.getCost(); this.tankCapacity = car.getTankCapacity(); this.maxSpeed = car.getMaxSpeed(); } public String getType() { return type; } public String getBrand() { return brand; } public Fuel getFuel() { return fuel; } public int getCost() { return cost; } public double getTankCapacity() { return tankCapacity; } public double getMaxSpeed() { return maxSpeed; } public void setType(String type) { this.type = type; } public void setBrand(String brand) { this.brand = brand; } public void setFuel(Fuel fuel) { this.fuel = fuel; } public void setCost(int cost) { this.cost = cost; } public void setTankCapacity(double capacity) { this.tankCapacity = capacity; } public void setMaxSpeed(double maxSpeed) { this.maxSpeed = maxSpeed; } @Override public String toString() { // TODO Автоматически созданная заглушка метода return "Car{" + "type=" + type + ",brand=" + brand + ",fuel" + fuel + ",cost=" + cost + ",tankCapacity=" + tankCapacity + ",maxSpeed=" + maxSpeed + '}'; } @Override public int hashCode() { // TODO Автоматически созданная заглушка метода final int prime = 17; int result = 3; result = prime * result + (type == null ? 0 : type.hashCode()) + (brand == null ? 0 : brand.hashCode()) + (fuel == null ? 0 : fuel.hashCode()) + cost + (int) tankCapacity + (int) maxSpeed; return result; } @Override public boolean equals(Object obj) { // TODO Автоматически созданная заглушка метода if (obj == null || obj.getClass() != this.getClass()) { return false; } if (obj == this) { return true; } Car object = (Car) obj; return this.type == object.getType() && this.brand == object.getBrand() && this.fuel.equals(object.getFuel()) && this.cost == object.getCost() && this.tankCapacity == object.getTankCapacity() && this.maxSpeed == object.getMaxSpeed(); } }
true
3efc52c650fbd521a2ff82ed4c753113ae9f93fc
Java
cgroc/flipside-api
/src/main/java/uk/co/grokemon/flipside/domain/Deck.java
UTF-8
170
1.648438
2
[]
no_license
package uk.co.grokemon.flipside.domain; public class Deck { private int deck_id; private int user_id; // is this even necessary? how to structure this stuff? }
true
fd7d08c62a9a9e6e1801d9f7b72ce09ad8f5e11e
Java
solon-aguiar/coding_problems
/UVA/Problems/src/p11878.java
UTF-8
851
3.015625
3
[]
no_license
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class p11878 { public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int correctAnswers = 0; while(true) { String line = bf.readLine(); if (line == null) { break; } String[] tokens = line.split("="); if (tokens[1].contentEquals("?")) { continue; } String[] ab = tokens[0].split("[\\+\\-]"); int c = Integer.parseInt(tokens[1]); int a = Integer.parseInt(ab[0]); int b = Integer.parseInt(ab[1]); int calc = 0; int op = tokens[0].indexOf("+"); if (op == -1) { calc = a - b; } else { calc = a + b; } if (calc == c) { correctAnswers++; } } System.out.println(correctAnswers); } }
true
6b6d2356cf116651d6dd0bc09a165655b27694b2
Java
bakdoolotkeldibekova/homeworksItacademy
/57 - [Задание]- Многопоточность/Thread3.java
UTF-8
165
1.890625
2
[]
no_license
public class Thread3 extends Thread { @Override public void run() { System.out.println("working Thread3 => + "); Result.result += 2; } }
true
b7116cea1607360c7316cbf9da2a09382157de9a
Java
cloudgyb/spring-boot-strategy
/src/main/java/com/gyb/spring/springbootstrategy/service/OrderService.java
UTF-8
672
2.234375
2
[]
no_license
package com.gyb.spring.springbootstrategy.service; import com.gyb.spring.springbootstrategy.dto.OrderDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class OrderService implements IOrderService { private OrderHandlerContext orderHandlerContext; @Autowired public OrderService(OrderHandlerContext orderHandlerContext) { this.orderHandlerContext = orderHandlerContext; } @Override public String handle(OrderDTO dto) { IOrderHandler orderHandler = orderHandlerContext.getOrderHandler(dto.getType()); return orderHandler.handle(dto); } }
true
662ad288eebbfbe3edecc662ae068cdaad4d3212
Java
nati7828/Financly
/app/src/main/java/nati/financly/ResetPasswordDialog.java
UTF-8
2,845
2.203125
2
[]
no_license
package nati.financly; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatDialogFragment; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; public class ResetPasswordDialog extends AppCompatDialogFragment { Context context; @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.dialog); builder.setTitle(R.string.dialog_reset_title) .setMessage(R.string.dialog_reset_message); //creating and handling the cancel button. builder.setNegativeButton(R.string.cancel, null); //creating and handling the Ok button. builder.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { String email = getArguments().getString("user_email"); if (email != null) { FirebaseAuth firebaseAuth = FirebaseAuth.getInstance(); firebaseAuth.sendPasswordResetEmail(email) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Toast.makeText(context, R.string.email_sent, Toast.LENGTH_LONG).show(); } else { if (task.getException() != null) { try { throw task.getException(); } catch (Exception e) { Toast.makeText(context, R.string.email_was_not_sent_successfully, Toast.LENGTH_LONG).show(); //Log.d("$$$", "exception : " + e); } } } } }); } else { Toast.makeText(context, R.string.email_text_is_empty, Toast.LENGTH_LONG).show(); } } }); return builder.create(); } public void passContext(Context context) { this.context = context; } }
true
ef098202b31ff1d9ff4cd9b3be233ade0efd615a
Java
robinsonbrz/estudos
/design-pattern/src/br/com/alura/designpattern/Finalizado.java
ISO-8859-1
644
2.859375
3
[]
no_license
package br.com.alura.designpattern; public class Finalizado implements EstadoDeUmOrcamento { @Override public void aplicaDescontoExtra(Orcamento orcamento) { throw new RuntimeException("No h descontos para oramento finalizado!!!"); } @Override public void aprova(Orcamento orcamento) { throw new RuntimeException("Oramento j foi finalizado!"); } @Override public void reprova(Orcamento orcamento) { throw new RuntimeException("Oramento j foi finalizado!"); } @Override public void finaliza(Orcamento orcamento) { throw new RuntimeException("Oramento j foi finalizado!"); } }
true
664445b31df701fd0ba2af21d4a2ca380b3fa239
Java
easemob/kefu-android-demo
/app/src/main/java/com/easemob/helpdeskdemo/ui/TestDemoActivity.java
UTF-8
482
1.65625
2
[]
no_license
package com.easemob.helpdeskdemo.ui; import android.os.Bundle; import android.support.annotation.Nullable; import com.easemob.helpdeskdemo.R; import com.hyphenate.helpdesk.easeui.ui.BaseActivity; /** * author liyuzhao * email:liyuzhao@easemob.com * date: 04/05/2018 */ public class TestDemoActivity extends BaseActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_call_new); } }
true
9429fc500417087c6d32bab446cbddcc7ef43ada
Java
Jihaishu/ssm-CRUD
/src/main/java/com/atguigu/ssm/controller/EmployeeController.java
UTF-8
4,424
2.625
3
[]
no_license
package com.atguigu.ssm.controller; import com.atguigu.ssm.bean.Employee; import com.atguigu.ssm.bean.Msg; import com.atguigu.ssm.service.EmployeeService; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.HashMap; import java.util.List; import java.util.Map; /** 处理和员工有关的请求 * @author : Administrator * @date : 2020-11-13 11:41 * @description : */ @Controller public class EmployeeController { @Autowired EmployeeService employeeService; /* *@description: 员工更新方法 *@author: Administrator *@date: 2020/11/16 20:58 * @param: employee *@return: com.atguigu.ssm.bean.Msg */ @ResponseBody @RequestMapping(value = "/emp/{empId}",method = RequestMethod.PUT) public Msg saveEmp(Employee employee){ employeeService.updateEmp(employee); return Msg.success(); } /** *@description: 根据id查询员工 *@author: Administrator *@date: 2020/11/16 20:35 * @param: id *@return: com.atguigu.ssm.bean.Msg */ @ResponseBody @RequestMapping(value = "/emp/{id}",method = RequestMethod.GET) public Msg getEmp(@PathVariable("id") Integer id){ Employee employee = employeeService.getEmp(id); return Msg.success().add("emp",employee); } /** *@description: 校验用户名是否可用 *@author: Administrator *@date: 2020/11/16 14:06 * @param: empName *@return: com.atguigu.ssm.bean.Msg */ @ResponseBody @RequestMapping("/checkuser") public Msg checkuser(@RequestParam("empName") String empName){ //先判断用户名是否是合法的表达式 String regx = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\\u2E80-\\u9FFF]{2,5})" ; if (!empName.matches(regx)) { return Msg.fail().add("va_msg","用户名必须是6-16位英文和数字的组合或者是2-5位中文"); } //用户名数据库重复校验 boolean b = employeeService.checkUser(empName); if (b) { return Msg.success(); }else { return Msg.fail().add("va_msg","用户名不可用"); } } //员工保存 :POST请求 @RequestMapping(value = "/emp",method = RequestMethod.POST) @ResponseBody public Msg saveEmp(@Valid Employee employee, BindingResult result){ if (result.hasErrors()) { //校验失败,应该返回失败,在模态框中显示校验失败的提示信息 Map<String, Object> map = new HashMap<>(); List<FieldError> errors = result.getFieldErrors(); for (FieldError fieldError : errors) { System.out.println("错误的字段名:"+fieldError.getField()); System.out.println("错误信息:"+fieldError.getDefaultMessage()); map.put(fieldError.getField(),fieldError.getDefaultMessage()); } return Msg.fail().add("errorFields",map); }else { employeeService.saveEmp(employee); return Msg.success(); } } @ResponseBody @RequestMapping("/emps") public Msg getEmpsWithJson(@RequestParam(value = "pn",defaultValue="1")Integer pn){ //引入pagehelper分页查询插件 //查询之前调用,传入页码,以及每页数量 PageHelper.startPage(pn,5); List<Employee> emps = employeeService.getAll(); //pageInfo包装查询后的结果,只需要将pageInfo交给页面就行 PageInfo page = new PageInfo(emps,5); return Msg.success().add("pageInfo",page); } // @RequestMapping("/emps") public String getEmps(@RequestParam(value = "pn",defaultValue="1")Integer pn,Model model){ //引入pagehelper分页查询插件 //查询之前调用,传入页码,以及每页数量 PageHelper.startPage(pn,5); List<Employee> emps = employeeService.getAll(); //pageInfo包装查询后的结果,只需要将pageInfo交给页面就行 PageInfo page = new PageInfo(emps,5); model.addAttribute("pageInfo",page); return "list"; } }
true
c0645c95c06a3dd5aba61dbd241e2a5545b6d8c2
Java
dileepan/ImageLoader
/demo/src/com/novoda/imageloader/demo/activity/ImageLongList.java
UTF-8
2,734
2.546875
3
[ "Apache-2.0" ]
permissive
package com.novoda.imageloader.demo.activity; import android.database.Cursor; import android.os.Bundle; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.SimpleCursorAdapter.ViewBinder; import com.novoda.imageloader.core.ImageManager; import com.novoda.imageloader.core.model.ImageTagFactory; import com.novoda.imageloader.demo.DemoApplication; import com.novoda.imageloader.demo.R; import com.novoda.imageloader.demo.activity.base.SingleTableBaseListActivity; /** * Example of setting a specific image size. * Not that you can ask the imageLoader to store the small image as files. * In this way you don't need to scale images every time */ public class ImageLongList extends SingleTableBaseListActivity { private static final int SIZE = 400; private Animation fadeInAnimation; private Boolean isAnimated = false; /** * TODO * Generally we can keep an instance of the * image loader and the imageTagFactory. */ private ImageManager imageManager; private ImageTagFactory imageTagFactory; @Override protected String getTableName() { return ImageLongList.class.getSimpleName().toLowerCase(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.single_table_base_list_activity); if (getIntent().hasExtra("animated")) { isAnimated = true; fadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in); } /** * TODO * Need to prepare imageLoader and imageTagFactory */ imageManager = DemoApplication.getImageLoader(); imageTagFactory = ImageTagFactory.newInstance(SIZE, SIZE, R.drawable.bg_img_loading); imageTagFactory.setErrorImageId(R.drawable.bg_img_notfound); imageTagFactory.setSaveThumbnail(true); imageTagFactory.setAnimation(fadeInAnimation); setAdapter(); initButtons(); } /** * TODO * Generally you will have a binder where you have to set the image. * This is an example of using the imageManager to load */ @Override protected ViewBinder getViewBinder() { return new ViewBinder() { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { String url = cursor.getString(columnIndex); ((ImageView) view).setTag(imageTagFactory.build(url)); imageManager.getLoader().load((ImageView) view); return true; } }; } }
true
6c596a5aaeaf362eee3c19fee1217c9f56259a04
Java
wso2/product-ei
/migration/migration-service/src/main/java/org/wso2/carbon/ei/migration/migrate/RegistryTaskDeletionClient.java
UTF-8
3,039
2.046875
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.ei.migration.migrate; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.ei.migration.internal.EIMigrationServiceDataHolder; import org.wso2.carbon.registry.core.CollectionImpl; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.session.UserRegistry; /** * This class delete tasks related to scheduled message processors from the registry */ public class RegistryTaskDeletionClient { private static final Log log = LogFactory.getLog(RegistryTaskDeletionClient.class); private UserRegistry userRegistry; private Resource userRegistryResource; /** * Default constructor */ public RegistryTaskDeletionClient() { String adminUserName = MigrationClientConfig.getInstance() .getMigrationConfiguration() .getProperty(MigrationConstants.ADMIN_USERNAME); if (adminUserName.isEmpty()) { throw new MigrationClientException("Invalid admin username"); } try { this.userRegistry = EIMigrationServiceDataHolder.getRegistryService().getRegistry(adminUserName); this.userRegistryResource = userRegistry.get(MigrationConstants.ESB_TASK_PATH); } catch (RegistryException e) { throw new MigrationClientException("Error occurred while retrieving registry resources", e); } } /** * Delete tasks related to scheduled message processors from the registry */ public void deleteRegistryTasks(){ try { String[] tasks = ((CollectionImpl) userRegistryResource).getChildren(); for (String task : tasks) { if (task.startsWith(MigrationConstants.ESB_TASK_PATH + MigrationConstants.SCHEDULED_MP_TASK_PREFIX)) { log.info("Deleting task : [-1234][ESB_TASK][" + task.substring(MigrationConstants.ESB_TASK_PATH.length()) + "]"); userRegistry.delete(task); } } } catch (RegistryException e) { throw new MigrationClientException("Error occurred while deleting registry tasks", e); } } }
true
39b1a20e7465bd9a7de27cae327b64895c06dbec
Java
DonaldY/coding2017
/group12/247565311/week3_fileDownloader/api/Connection.java
UTF-8
582
2.53125
3
[]
no_license
package week3_fileDownloader.api; import java.io.IOException; import java.net.HttpURLConnection; public interface Connection{ /** * 缁欏畾寮�鍜岀粨鏉熶綅缃紝 璇诲彇鏁版嵁锛�杩斿洖鍊兼槸瀛楄妭鏁扮粍 * @param startPos 寮�浣嶇疆锛�浠�寮� * @param endPos 缁撴潫浣嶇疆 * @return */ public byte[] read(int startPos,int endPos) throws IOException; /** * 寰楀埌鏁版嵁鍐呭鐨勯暱搴� * @return */ public int getContentLength(); /** * 鍏抽棴杩炴帴 */ public void close(); }
true
9dd4a0cc15ef4fb1d6e05d9760ee97c6cb9b0cc6
Java
pjieder/TRiP
/TRiP/src/trip/dal/dbmanagers/dbdao/ProjectDBDAO.java
UTF-8
21,197
2.59375
3
[]
no_license
/* * 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 trip.dal.dbmanagers.dbdao; import trip.dal.dbmanagers.dbdao.Interfaces.IProjectDBDAO; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.chart.XYChart; import trip.be.Project; import trip.dal.dbaccess.DBSettings; import trip.dal.dbmanagers.dbdao.utilities.DatabaseLogger; import trip.utilities.TimeConverter; /** * * @author Jacob */ public class ProjectDBDAO implements IProjectDBDAO { /** * Saves the newly created project in the database. * * @param project The project to be saved. * @throws java.sql.SQLException */ @Override public void createProject(Project project) throws SQLException{ Connection con = null; try { con = DBSettings.getInstance().getConnection(); String sql = "INSERT INTO Project (name, rate, isActive) VALUES (?,?,?);"; PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ps.setString(1, project.getName()); ps.setDouble(2, project.getRate()); ps.setBoolean(3, project.getIsActive()); int affectedRows = ps.executeUpdate(); if (affectedRows < 1) { throw new SQLException(); } ResultSet rs = ps.getGeneratedKeys(); if (rs.next()) { project.setId(rs.getInt(1)); } }finally { DBSettings.getInstance().releaseConnection(con); DatabaseLogger.logAction("Created project with ID: " + project.getId() + " (" + project.getName() + ")"); } } /** * Loads all saved projects in the database. * * @return An observablelist containing all projects stored. * @throws java.sql.SQLException */ @Override public ObservableList<Project> loadAllProjects() throws SQLException{ Connection con = null; ObservableList<Project> allProjects = FXCollections.observableArrayList(); try { con = DBSettings.getInstance().getConnection(); String sql = "SELECT * From Project;"; Statement statement = con.createStatement(); ResultSet rs = statement.executeQuery(sql); while (rs.next()) { String name = rs.getString("name"); double rate = rs.getDouble("rate"); Project project = new Project(name, rate); project.setId(rs.getInt("id")); project.setIsActive(rs.getBoolean("isActive")); allProjects.add(project); } return allProjects; }finally { DBSettings.getInstance().releaseConnection(con); } } /** * Loads all active projects stored in the database. * * @return An observablelist containing all active projects stored. * @throws java.sql.SQLException */ @Override public ObservableList<Project> loadAllActiveProjects() throws SQLException{ Connection con = null; ObservableList<Project> projects = FXCollections.observableArrayList(); try { con = DBSettings.getInstance().getConnection(); String sql = "SELECT * FROM Project WHERE isActive = 1;"; PreparedStatement stmt = con.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); while (rs.next()) { int projectID = rs.getInt("ID"); String projectName = rs.getString("name"); double rate = rs.getDouble("rate"); Project project = new Project(projectName, rate); project.setId(projectID); projects.add(project); } return projects; }finally { DBSettings.getInstance().releaseConnection(con); } } /** * Loads all inactiev projects stored in the database. * * @return An observablelist containing all the inactive projects stored. * @throws java.sql.SQLException */ @Override public ObservableList<Project> loadAllInactiveProjects() throws SQLException{ Connection con = null; ObservableList<Project> projects = FXCollections.observableArrayList(); try { con = DBSettings.getInstance().getConnection(); String sql = "SELECT * FROM Project WHERE isActive = 0;"; PreparedStatement stmt = con.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); while (rs.next()) { int projectID = rs.getInt("ID"); String projectName = rs.getString("name"); double rate = rs.getDouble("rate"); Project project = new Project(projectName, rate); project.setId(projectID); projects.add(project); } return projects; }finally { DBSettings.getInstance().releaseConnection(con); } } /** * Loads all stored projects assigned to the specified employee. * * @param employeeID The ID of the employee. * @return Returns an observablelist containing all projects assigned to the specified employee. * @throws java.sql.SQLException */ @Override public ObservableList<Project> loadEmployeeProjects(int employeeID) throws SQLException{ Connection con = null; ObservableList<Project> projects = FXCollections.observableArrayList(); try { con = DBSettings.getInstance().getConnection(); String sql = "SELECT * FROM Project JOIN Projects on Project.ID = Projects.projID WHERE Projects.employeeID = ? AND Project.isActive = 1;"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setInt(1, employeeID); ResultSet rs = stmt.executeQuery(); while (rs.next()) { int projectID = rs.getInt("ID"); String projectName = rs.getString("name"); double rate = rs.getDouble("rate"); Project project = new Project(projectName, rate); project.setId(projectID); projects.add(project); } return projects; }finally { DBSettings.getInstance().releaseConnection(con); } } /** * Loads the total amount of time worked on the project by the specified employee. * * @param employeeID The ID of the employee working on the project. * @param projectID The ID of the project being worked on. * @return An int value representing the total amount of time worked on the project by the specified user in seconds. * @throws java.sql.SQLException */ @Override public int loadProjectTime(int employeeID, int projectID) throws SQLException{ Connection con = null; int totalTime = 0; try { con = DBSettings.getInstance().getConnection(); String sql = "SELECT SUM(Tasks.time) AS TotalTime FROM Tasks JOIN Task on Tasks.taskID = Task.ID WHERE Task.projID = ? AND Task.employeeID = ?;"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setInt(1, projectID); stmt.setInt(2, employeeID); ResultSet rs = stmt.executeQuery(); while (rs.next()) { totalTime = rs.getInt("TotalTime"); } return totalTime; }finally { DBSettings.getInstance().releaseConnection(con); } } /** * Loads the total amount of time having been used on the project by all users. * * @param projectID The ID of the project. * @return An int value representing the total amount of time worked on the project in seconds. * @throws java.sql.SQLException */ @Override public int loadTotalProjectTime(int projectID) throws SQLException{ Connection con = null; int totalTime = 0; try { con = DBSettings.getInstance().getConnection(); String sql = "SELECT SUM(Tasks.time) AS TotalTime FROM Tasks JOIN Task on Tasks.taskID = Task.ID WHERE Task.projID = ?;"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setInt(1, projectID); ResultSet rs = stmt.executeQuery(); while (rs.next()) { totalTime = rs.getInt("TotalTime"); } return totalTime; }finally { DBSettings.getInstance().releaseConnection(con); } } /** * Loads the total amount of time having been registered on the specified project between a specified timespan. * * @param projectID The ID of the project that the count is based upon. * @param startDate The startdate of the timespan. * @param endDate The enddate of the timespan. * @param isBillable Boolean value representing whether or not the time is billable. * @return An int value representing the total amount of time having been used in seconds. * @throws java.sql.SQLException */ @Override public int loadAllProjectTimeBetweenDates(int projectID, LocalDate startDate, LocalDate endDate, boolean isBillable) throws SQLException{ Connection con = null; int totalTime = 0; try { con = DBSettings.getInstance().getConnection(); String sql = "SELECT SUM(Tasks.time) AS TotalTime FROM Tasks JOIN Task on Tasks.taskID = Task.ID WHERE Task.projID = ? AND Tasks.startTime BETWEEN ? AND ? AND Tasks.isBillable = ?;"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setInt(1, projectID); stmt.setString(2, startDate.toString()); stmt.setString(3, TimeConverter.addDays(endDate, 1).toString()); stmt.setBoolean(4, isBillable); ResultSet rs = stmt.executeQuery(); while (rs.next()) { totalTime = rs.getInt("TotalTime"); } return totalTime; }finally { DBSettings.getInstance().releaseConnection(con); } } /** * Loads the total amount of time having been registered on the specifiec project by the specified employee between the timespan. * * @param employeeID The ID of the specified employee . * @param projectID The ID of the project that the count is based upon. * @param startDate The startdate of the timespan. * @param endDate The enddate of the timespan. * @param isBillable Boolean value representing whether or not the time is billable. * @return An int value representing the total amount of time the specified employe have been working on the project in seconds. * @throws java.sql.SQLException */ @Override public int loadAllEmployeeProjectTimeBetweenDates(int employeeID, int projectID, LocalDate startDate, LocalDate endDate, boolean isBillable) throws SQLException{ Connection con = null; int totalTime = 0; try { con = DBSettings.getInstance().getConnection(); String sql = "SELECT SUM(Tasks.time) AS TotalTime FROM Tasks JOIN Task on Tasks.taskID = Task.ID WHERE Task.projID = ? And Task.employeeID = ? AND Tasks.startTime BETWEEN ? AND ? AND Tasks.isBillable = ?;"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setInt(1, projectID); stmt.setInt(2, employeeID); stmt.setString(3, startDate.toString()); stmt.setString(4, TimeConverter.addDays(endDate, 1).toString()); stmt.setBoolean(5, isBillable); ResultSet rs = stmt.executeQuery(); while (rs.next()) { totalTime = rs.getInt("TotalTime"); } return totalTime; }finally { DBSettings.getInstance().releaseConnection(con); } } /** * Loads the total amount of time having been registered on the specified date. * * @param date The date being searched for. * @return An int value representing the total amount of work done on the specified date in seconds. * @throws java.sql.SQLException */ @Override public int loadAllProjectTimeForDay(LocalDate date) throws SQLException{ Connection con = null; int totalTime = 0; try { con = DBSettings.getInstance().getConnection(); String sql = "SELECT SUM(Tasks.time) AS TotalTime FROM Tasks WHERE Tasks.startTime like ?;"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setString(1, date.toString() + "%"); ResultSet rs = stmt.executeQuery(); while (rs.next()) { totalTime = rs.getInt("TotalTime"); } return totalTime; }finally { DBSettings.getInstance().releaseConnection(con); } } /** * Loads the total amount of time having been registered on the specified project on the date. * * @param projectID The project ID of the project being searched for. * @param date The date being searched for. * @return An int value representing the total amount of work done on the specified project on the specified date in seconds. * @throws java.sql.SQLException */ @Override public int loadProjectTimeForDay(int projectID, LocalDate date) throws SQLException{ Connection con = null; int totalTime = 0; try { con = DBSettings.getInstance().getConnection(); String sql = "SELECT SUM(Tasks.time) AS TotalTime FROM Tasks JOIN Task on Tasks.taskID = Task.ID WHERE Task.projID = ? AND Tasks.startTime like ?;"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setInt(1, projectID); stmt.setString(2, date.toString() + "%"); ResultSet rs = stmt.executeQuery(); while (rs.next()) { totalTime = rs.getInt("TotalTime"); } return totalTime; }finally { DBSettings.getInstance().releaseConnection(con); } } /** * Loads all projects having been worked on between the specified dates by the specified employee. * * @param startDate The startdate of the timespan. * @param endDate The enddate of the timespan. * @param employeeID The ID of the specified employee. * @return A list containing all projects having been worked on by the specified employee between the two dates. * @throws java.sql.SQLException */ @Override public List<Project> loadWorkedOnProjectsBetweenDates(LocalDate startDate, LocalDate endDate, int employeeID) throws SQLException{ Connection con = null; List<Project> allWorkedOnProjects = new ArrayList(); try { con = DBSettings.getInstance().getConnection(); String sql = "WITH x AS (SELECT Tasks.*, Task.employeeID, Task.projID FROM Tasks JOIN Task ON Tasks.taskID = Task.ID WHERE Tasks.startTime BETWEEN ? AND ? AND Task.employeeID = ?)" + "SELECT DISTINCT Project.* FROM x JOIN Project ON x.projID = Project.ID;"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setString(1, startDate.toString()); stmt.setString(2, TimeConverter.addDays(endDate, 1).toString()); stmt.setInt(3, employeeID); ResultSet rs = stmt.executeQuery(); while (rs.next()) { String name = rs.getString("name"); double rate = rs.getDouble("rate"); Project project = new Project(name, rate); project.setId(rs.getInt("id")); project.setIsActive(rs.getBoolean("isActive")); allWorkedOnProjects.add(project); } return allWorkedOnProjects; }finally { DBSettings.getInstance().releaseConnection(con); } } /** * Calculates the chart series for the bargraph representing the total amount of time individual users have been working and on what tasks between the specified days. * * @param startDate The startdate of the timeframe. * @param endDate The enddate of the timeframe. * @param employeeID The Id of the employee that the series is based upon. * @return A series containing all the stored data to be displayed. * @throws java.sql.SQLException */ @Override public XYChart.Series loadTimeForUsersProjects(LocalDate startDate, LocalDate endDate, int employeeID) throws SQLException{ Connection con = null; XYChart.Series series = new XYChart.Series(); try { con = DBSettings.getInstance().getConnection(); String sql = "WITH x AS (SELECT Tasks.*, Task.employeeID, Task.projID FROM Tasks JOIN Task ON Tasks.taskID = Task.ID WHERE Tasks.startTime BETWEEN ? AND ? AND Task.employeeID = ?)" + "SELECT DISTINCT x.employeeID, Project.*, SUM(x.time) over (partition by projID) as totalTime FROM x JOIN Project ON x.projID = Project.ID;"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setString(1, startDate.toString()); stmt.setString(2, TimeConverter.addDays(endDate, 1).toString()); stmt.setInt(3, employeeID); ResultSet rs = stmt.executeQuery(); while (rs.next()) { int totalTime = rs.getInt("totalTime"); String projectName = rs.getString("name"); double value = (double) totalTime / 3600; series.getData().add(new XYChart.Data<>(projectName, value)); } return series; }finally { DBSettings.getInstance().releaseConnection(con); } } /** * Updates the specified project in the database. * * @param project The project that will update the previous project with the same ID. * @throws java.sql.SQLException */ @Override public void updateProject(Project project) throws SQLException{ Connection con = null; try { con = DBSettings.getInstance().getConnection(); String sql = "UPDATE Project SET name=?, rate=?, isActive=? WHERE id=?;"; PreparedStatement ps = con.prepareStatement(sql); ps.setString(1, project.getName()); ps.setDouble(2, project.getRate()); ps.setBoolean(3, project.getIsActive()); ps.setInt(4, project.getId()); int affected = ps.executeUpdate(); if (affected < 1) { throw new SQLException(); } }finally { DBSettings.getInstance().releaseConnection(con); DatabaseLogger.logAction("Updated project with ID: " + project.getId() + " (" + project.getName() + ")"); } } /** * Updates whether or not the specified project is active. * * @param project The project to be updated. * @param active Boolean representing whether or not the project should be active or inactive. * @throws java.sql.SQLException */ @Override public void updateProjectActive(Project project, boolean active) throws SQLException{ Connection con = null; try { con = DBSettings.getInstance().getConnection(); String sql = "UPDATE Project SET isActive = ? WHERE ID = ?;"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setBoolean(1, active); stmt.setInt(2, project.getId()); stmt.executeUpdate(); }finally { DBSettings.getInstance().releaseConnection(con); DatabaseLogger.logAction("Updated project with ID: " + project.getId() + " (" + project.getName() + ") to active: " + active); } } /** * Deletes the specified project from the database. * * @param project The project to be deleted. * @throws java.sql.SQLException */ @Override public void deleteProject(Project project) throws SQLException{ Connection con = null; try { con = DBSettings.getInstance().getConnection(); String sql = "DELETE FROM Project WHERE id=?;"; PreparedStatement ps = con.prepareStatement(sql); ps.setInt(1, project.getId()); ps.execute(); }finally { DBSettings.getInstance().releaseConnection(con); DatabaseLogger.logAction("Deleted project with ID: " + project.getId() + " (" + project.getName() + ")"); } } }
true
4f2c0753193174e02e07b7943c06a268e11a369d
Java
erakai/VinBlood
/src/main/java/com/kai/vinblood/display/Hoverable.java
UTF-8
202
2.21875
2
[]
no_license
package com.kai.vinblood.display; /** * @author Kai on Mar 20, 2019 */ public interface Hoverable { void onHover(); void onNotHovered(); boolean checkCollision(int otherX, int otherY); }
true
26025f7bedbf4f172ee30a330ec0af677208875f
Java
pearez/step4
/src/main/java/es/unileon/repository/OfficeDao.java
UTF-8
203
1.890625
2
[]
no_license
package es.unileon.repository; import es.unileon.domain.Office; import java.util.List; public interface OfficeDao { public List<Office> getOfficeList(); public void saveOffice(Office off); }
true
fb2073a380ae0742fbe2d4e38e53d5041974a8c6
Java
RealMozog/AnalisadorLexico
/src/br/uefs/ecomp/AnalisadorLexico/model/TokenError.java
UTF-8
865
2.71875
3
[]
no_license
package br.uefs.ecomp.AnalisadorLexico.model; /** * * @author Alessandro Costa */ public class TokenError { private String codigo; private String mal_formed_lexema; private int line; public TokenError(int line){ this.line = line; } @Override public String toString() { return "<" + line + ": " + codigo + ", " + mal_formed_lexema + ">"; } public void setCodigo(String codigo) { this.codigo = codigo; } public void setMal_formed_lexema(String mal_formed_lexema) { this.mal_formed_lexema = mal_formed_lexema; } public void setLine(int line) { this.line = line; } public String getCodigo() { return codigo; } public String getMal_formed_lexema() { return mal_formed_lexema; } public int getLine() { return line; } }
true
29d6055fbb13714aa736879bbcbd0dfeb6761857
Java
Aleksey25/HomeWork
/src/lesson17/animal/HorseSer.java
UTF-8
959
3.3125
3
[]
no_license
package lesson17.animal; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * Created by student on 6/18/2017. */ public class HorseSer { public static void main(String[] args) { Horse horse = new Horse("Slevin"); try { FileOutputStream fs = new FileOutputStream("testSer1.ser"); ObjectOutputStream os = new ObjectOutputStream(fs); os.writeObject(horse); os.close(); } catch (Exception e) { e.printStackTrace(); } try { FileInputStream fis = new FileInputStream("testSer1.ser"); ObjectInputStream ois = new ObjectInputStream(fis); horse = (Horse) ois.readObject(); // 4 ois.close(); System.out.println(horse.toString()); } catch (Exception e) { e.printStackTrace(); } } }
true
59c9c35cf3f21252cad750d1d195f53276b08d36
Java
grzegorz-aniol/graphomance
/src/main/java/org/gangel/graphomance/ObjectApi.java
UTF-8
1,135
2.203125
2
[ "MIT" ]
permissive
package org.gangel.graphomance; import java.util.Map; public interface ObjectApi { void startTransaction(); void commit(); void rollback(); Object getNode(final String clsName, final NodeIdentifier nodeId); long shortestPath(final NodeIdentifier start, final NodeIdentifier end); default NodeIdentifier createNode(final String clsName) { return createNode(clsName, null); } NodeIdentifier createNode(final String clsName, Map<String, Object> properties); void updateNode(final String clsName, NodeIdentifier nodeId, Map<String, Object> properties); default RelationIdentifier createRelation(String className, NodeIdentifier fromNode, NodeIdentifier toNode) { return createRelation(className, fromNode, toNode, null); } RelationIdentifier createRelation(String className, NodeIdentifier fromNode, NodeIdentifier toNode, Map<String, Object> properties); void updateRelation(final String clsName, RelationIdentifier edgeId, Map<String, Object> properties); void deleteAllNodes(final String clsName); void deleteAllRelations(final String clsName); }
true
d739504f53e69fcc10df65a2601a32d5ba4c3093
Java
couchbase/couchbase-jvm-clients
/core-io/src/main/java/com/couchbase/client/core/env/LoggingMeterConfig.java
UTF-8
3,251
2.109375
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2020 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.couchbase.client.core.env; import com.couchbase.client.core.annotation.Stability; import com.couchbase.client.core.cnc.metrics.LoggingMeter; import com.couchbase.client.core.error.InvalidArgumentException; import java.time.Duration; import java.util.LinkedHashMap; import java.util.Map; /** * Allows to configure the {@link LoggingMeter}. * <p> * Note: the metrics implementation is considered volatile, and so is this configuration. It is subject to * change at any time. */ public class LoggingMeterConfig { @Stability.Internal public static class Defaults { public static final boolean DEFAULT_ENABLED = true; public static final Duration DEFAULT_EMIT_INTERVAL = Duration.ofSeconds(600); } private final Duration emitInterval; private final boolean enabled; public static Builder builder() { return new Builder(); } public static LoggingMeterConfig create() { return builder().build(); } public static LoggingMeterConfig disabled() { return enabled(false).build(); } LoggingMeterConfig(final Builder builder) { emitInterval = builder.emitInterval; enabled = builder.enabled; } /** * Allows to customize the emit interval * * @param emitInterval the interval to use. * @return this builder for chaining. */ public static Builder emitInterval(final Duration emitInterval) { return builder().emitInterval(emitInterval); } public static Builder enabled(final boolean enabled) { return builder().enabled(enabled); } public Duration emitInterval() { return emitInterval; } public boolean enabled() { return enabled; } Map<String, Object> exportAsMap() { Map<String, Object> export = new LinkedHashMap<>(); export.put("enabled", enabled); export.put("emitIntervalMs", emitInterval.toMillis()); return export; } public static class Builder { private Duration emitInterval = Defaults.DEFAULT_EMIT_INTERVAL; private boolean enabled = Defaults.DEFAULT_ENABLED; /** * Allows to customize the emit interval * * @param emitInterval the interval to use. * @return this builder for chaining. */ public Builder emitInterval(final Duration emitInterval) { if (emitInterval.isZero()) { throw InvalidArgumentException.fromMessage("Emit interval must be greater than 0"); } this.emitInterval = emitInterval; return this; } public Builder enabled(final boolean enabled) { this.enabled = enabled; return this; } public LoggingMeterConfig build() { return new LoggingMeterConfig(this); } } }
true
ead040a6de0c72c6f64926bb52bc05946fbf2ce6
Java
FISTPERFECT/JSONSchmea-UI-Generation
/src/main/java/com/sai/test/JsonSchema/MyClass.java
UTF-8
1,691
2.609375
3
[]
no_license
package com.sai.test.JsonSchema; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; import java.util.HashMap; import java.util.Map; public class MyClass { @JsonProperty("A1") private String A1; @JsonProperty("A2") private String A2 ; @JsonProperty("A3") private String A3 ; @JsonProperty("A4") private MyClass.A4 A4 ; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonProperty("A4") public MyClass.A4 getA4() { return A4; } /** * * @param A4 * The startDayOfWeek */ @JsonProperty("A4") public void setA4(MyClass.A4 A4) { this.A4 = A4; } public static enum A4 { REPLACE("Replace"); private final String value; private static Map<String, MyClass.A4> constants = new HashMap<String, MyClass.A4>(); static { for (MyClass.A4 c: values()) { constants.put(c.value, c); } } private A4(String value) { this.value = value; } @JsonValue @Override public String toString() { return this.value; } @JsonCreator public static MyClass.A4 fromValue(String value) { MyClass.A4 constant = constants.get(value); if (constant == null) { throw new IllegalArgumentException(value); } else { return constant; } } } }
true
7f32ffcab3638241c2f9fecf35cb04cff3728bd7
Java
weylar/Sentinel
/app/src/main/java/com/android/sentinel/HealthCheck/Connectivity/TestHeadphoneJack.java
UTF-8
7,170
1.71875
2
[]
no_license
package com.android.sentinel.HealthCheck.Connectivity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.media.AudioManager; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.android.sentinel.HealthCheck.HealthCheck; import com.android.sentinel.R; import static com.android.sentinel.HealthCheck.TestFragment.FAILED; import static com.android.sentinel.HealthCheck.TestFragment.FROM; import static com.android.sentinel.HealthCheck.TestFragment.HEADPHONE; import static com.android.sentinel.HealthCheck.TestFragment.NETWORK; import static com.android.sentinel.HealthCheck.TestFragment.SUCCESS; import static com.android.sentinel.HealthCheck.TestFragment.UNCHECKED; import static com.android.sentinel.HealthCheck.TestFragment.setDefaults; public class TestHeadphoneJack extends AppCompatActivity { TextView result, skip, reason; Button move; Runnable timerTask; Handler handler; ProgressBar progressBar; HeadsetStateReceiver receiver; IntentFilter receiverFilter; AudioManager audioManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_headphone_jack); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); result = findViewById(R.id.result); reason = findViewById(R.id.reason); skip = findViewById(R.id.skip); move = findViewById(R.id.move); progressBar = findViewById(R.id.progress); skip.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setDefaults(HEADPHONE, UNCHECKED, TestHeadphoneJack.this); if (getIntent().getExtras() != null) { String val = getIntent().getStringExtra(FROM); if (val.equals(NETWORK)) { Intent intent = new Intent(TestHeadphoneJack.this, TestCharging.class); intent.putExtra(FROM, HEADPHONE); startActivity(intent); } } else { finish(); } } }); move.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (getIntent().getExtras() != null) { String val = getIntent().getStringExtra(FROM); if (val.equals(NETWORK)) { Intent intent = new Intent(TestHeadphoneJack.this, TestCharging.class); intent.putExtra(FROM, HEADPHONE); startActivity(intent); } } else { finish(); } } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: setDefaults(HEADPHONE, UNCHECKED, this); Intent intent = new Intent(this, HealthCheck.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(intent); break; } return false; } @Override public void onBackPressed() { super.onBackPressed(); setDefaults(HEADPHONE, UNCHECKED, this); } @Override protected void onResume() { super.onResume(); handler = new Handler(); receiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG); receiver = new HeadsetStateReceiver(); registerReceiver(receiver, receiverFilter); runProgress(); timer(20000); audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); if (audioManager.isWiredHeadsetOn()){ passAction(); }else{ warnNoHeadphone(); } } @Override protected void onPause() { super.onPause(); handler.removeCallbacks(timerTask); unregisterReceiver(receiver); } private void runProgress() { Thread thread = new Thread() { @Override public void run() { super.run(); for (int i = 0; i <= 10; i++) { if (i > 0) { try { sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } progressBar.setMax(10); progressBar.setProgress(i); } } }; thread.start(); } private void timer(long delayMillis) { timerTask = new Runnable() { @Override public void run() { failAction(); } }; handler.postDelayed(timerTask, delayMillis); } private void warnNoHeadphone() { reason.setVisibility(View.VISIBLE); reason.setText(getResources().getString(R.string.insert_headphone)); result.setVisibility(View.GONE); move.setVisibility(View.GONE); skip.setVisibility(View.VISIBLE); progressBar.setVisibility(View.VISIBLE); handler.postDelayed(timerTask, 10000); } private void passAction() { setDefaults(HEADPHONE, SUCCESS, TestHeadphoneJack.this); result.setVisibility(View.VISIBLE); result.setText("PASS"); result.setTextColor(getResources().getColor(R.color.green)); reason.setVisibility(View.GONE); progressBar.setVisibility(View.GONE); skip.setVisibility(View.GONE); move.setVisibility(View.VISIBLE); } private void failAction() { setDefaults(HEADPHONE, FAILED, TestHeadphoneJack.this); reason.setVisibility(View.GONE); result.setVisibility(View.VISIBLE); result.setText("FAIL"); result.setTextColor(getResources().getColor(R.color.colorPrimary)); progressBar.setVisibility(View.GONE); move.setVisibility(View.VISIBLE); skip.setVisibility(View.GONE); } public class HeadsetStateReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, final Intent intent) { String action = intent.getAction(); if ((action.equals(Intent.ACTION_HEADSET_PLUG))) { int headSetState = intent.getIntExtra("state", 0); if (headSetState == 0) { warnNoHeadphone(); }else{ passAction(); } } } } }
true
46f3838aa9d3c2a8a42daf02922793bbfe8c7b3d
Java
maengseungju/sampleProject
/src/javaEx/CConverterApp.java
UTF-8
616
3.125
3
[]
no_license
package javaEx; public class CConverterApp { public static void main(String[] args) { double dollar; double won; dollar = 1000000; won = 100; CConverter.setRate(1099.00); System.out.println("백만원은 " + CConverter.toDollar(dollar) + "달러 입니다."); System.out.println("백달러는 " + CConverter.toKRW(won) + "원 입니다."); //백만원을 달러로 출력 //100달러를 원으로 출력 } }
true
df375af24514702281fce031c99b52966374b7fb
Java
GauravGupta27/Drdo-project1
/InterviewResult.java
UTF-8
3,029
2.65625
3
[]
no_license
import java.io.IOException; import java.io.PrintWriter; import java.sql.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class InterviewResult extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int i=0; String s1=req.getParameter("branch"); PrintWriter pw=resp.getWriter(); pw.println("<html>" + "<body>" + "<form name=\"myForm\" action=\"interviewresultupdate\"> \n"+ "<h1 align=center>"+s1+"</h1>" + "<input type=\"text\" name=\"branch\" value="+s1+" readonly=\"true\" hidden=\"true\" >" + "<table align=center border=\"1\"> \n" + "<tr> \n" + "<td> \n" + "STUDENT NAME \n" + "</td>\n" + "<td>FATHER'S NAME\n" + "</td> \n" + "<td>D.O.B\n" + "</td>\n" + "<td>MARKS\n" + "\n" + "</td>\n" + "\n" + "</tr>"); try{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","1234"); Statement st=con.createStatement(); String q="select * from "+s1; ResultSet rs=st.executeQuery(q); while(rs.next()) { String marks="marks"+String.valueOf(i); String email="email"+String.valueOf(i); String name=rs.getString("name"); String fname=rs.getString("f_name"); String dob=rs.getString("dob"); String emailid=rs.getString("e_mail"); String mark=rs.getString("marks"); pw.println("<tr>" + "<td>"+name+"</td>" + "<td>"+fname+"</td>" + "<td>"+dob+"</td>" + "<td><input type=\"number\" name="+marks+" value='"+mark+"' required/></td>" + "<td><input type=\"text\" name="+email+" value="+emailid+" readonly=\"true\" hidden=\"true\" ></td>" + "</tr>"); i++; } pw.println("</table>" + "<input type=\"text\" name=\"count\" value="+i+" readonly=\"true\" hidden=\"true\" >" + "<br> <br> <br>" + "<input style=margin-left:700px type=\"submit\" value=\"SUBMIT\" >" + "</form>" + "</body>" + "</html>"); rs.close(); st.close(); con.close(); }catch(Exception e) { System.out.println(e); } } }
true
08597775cda735796c7a0132b60107875461090b
Java
mozammel/vBoard
/src/main/java/com/livingoncodes/vboard/repository/BoardRepository.java
UTF-8
267
1.882813
2
[]
no_license
package com.livingoncodes.vboard.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.livingoncodes.vboard.entity.Board; public interface BoardRepository extends JpaRepository<Board, Long> { public Board findByName(String name); }
true
e5a98c5d212db93ae6d55601e176ad84ca9506b1
Java
SeanQinSolver/X
/LintCode/Rotate Array.java
UTF-8
632
3.21875
3
[]
no_license
public class Solution { public void rotate(int[] nums, int k) { if (nums.length == 0 || nums == null) return; k = k % nums.length; System.out.println(k); rotate(nums, nums.length - k, nums.length - 1); rotate(nums, 0, nums.length - k - 1); rotate(nums, 0, nums.length - 1); } private void rotate(int[] A, int start, int end) { for (int i = start, j = end; i <= j; i++, j--) { swap(A, i, j); } } private void swap(int[] A, int start, int end) { int temp = A[start]; A[start] = A[end]; A[end] = temp; } }
true
ae9ac0dfbbd6ebd4ff538897030e31e80eaebb11
Java
ben-barks/java_themepark
/day3/dealership/src/main/java/DealershipComponents/Mechanic.java
UTF-8
430
2.828125
3
[]
no_license
package DealershipComponents; import Vehicles.Vehicle; public class Mechanic { private int hoursWorked; public Mechanic(){ this.hoursWorked = 0; } public void repairDamage(Vehicle vehicle){ this.hoursWorked = vehicle.getDamage() - 1; vehicle.setDamage(1); vehicle.setPrice(vehicle.evaluatePrice()); } public int getHoursWorked() { return hoursWorked; } }
true
fe6429ed2199ca4a15c304557869ce16d1724b48
Java
Ravi1674/Task1-Booking-System-JWT
/src/main/java/com/bookingsystem/api/controller/JwtController.java
UTF-8
758
2.046875
2
[]
no_license
package com.bookingsystem.api.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.bookingsystem.api.entities.JwtRequest; import com.bookingsystem.api.entities.JwtResponse; import com.bookingsystem.api.service.JwtService; @RestController public class JwtController { @Autowired public JwtService jwtService; // Authenticate the User and generate the token... @PostMapping({"/authenticate"}) public JwtResponse createJwtToken(@RequestBody JwtRequest jwtRequest) throws Exception { return jwtService.createJwtToken(jwtRequest); } }
true
b83452820ea555b011b3eb18544fc7d69114c41b
Java
farhanarnob/Android_App_Development_Unit_Testing_Go_Through_From_Lynda
/app/src/test/java/com/mycompany/example/myapplication/SimpleMathTest.java
UTF-8
2,597
2.609375
3
[]
no_license
package com.mycompany.example.myapplication; import com.mycompany.example.myapplication.categories.FastTests; import com.mycompany.example.myapplication.categories.GoogleMapsIntegrationTests; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.ExpectedException; import java.util.Arrays; import java.util.List; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.lessThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @Category(FastTests.class) public class SimpleMathTest { // @Rule public ReportTextExecution rtx = new ReportTextExecution(); @Rule public ExpectedException thrown = ExpectedException.none(); private SimpleMath sm; private List<String> list; @Before public void setUp() throws Exception { sm = new SimpleMath(); list = createList(); } @Category(GoogleMapsIntegrationTests.class) @Test public void testAdd() { int total = sm.add(4, 5); assertEquals("Simple Math is not adding correctly", 9, total); } @Ignore @Test public void testDiff() { int total = sm.diff(9, 2); assertEquals("Simple Math is not subtracting correctly", 7, total); } @Test public void divideByZeroExpectedExceptionTest() { thrown.expect(ArithmeticException.class); sm.div(9, 0); } // With hamcrest @Test public void testListSizeComparingWithHamcrest() { assertThat(list, allOf(hasSize(greaterThanOrEqualTo(3)), hasSize(lessThan(12)))); } public void testTypeSafetyWithHamcrest() { // assertThat("23",equalTo(2)); } @Test public void testCheckContainItemInTheListWithHamcrest() { assertThat("Not contain items", list, hasItems("Arnob", "Work")); } // with jUnit public void testListSizeComparingWithAsserts() { assertTrue(list.size() >= 3); assertTrue(list.size() < 12); } @Test public void testCheckContainItemInTheListWithAsserts() { assertTrue(list.contains("Arnob")); assertTrue(list.contains("Work")); } private List<String> createList() { String list[] = {"Arnob", "Boy", "Work"}; return Arrays.asList(list); } }
true
18df1f903ca1b2292f1b4dc866b76d5e11243192
Java
djulbicb/teamvote
/src/main/java/com/bojan/teamvote/model/exceptions/UserNotFound.java
UTF-8
196
1.648438
2
[]
no_license
package com.bojan.teamvote.model.exceptions; /** * Used in rest services. Double checks if user email exists in database * @author Bojan * */ public class UserNotFound extends Exception { }
true
0b2711cb974e26e6acbfad3120667bf753719f2b
Java
XStrawhatCrew/meliodas
/Order/src/main/java/vn/aliviet/order/common/StatusType.java
UTF-8
927
2.296875
2
[]
no_license
package vn.aliviet.order.common; /** * Created by windluffy on 10/1/2015. */ public class StatusType { public static final int PRODUCT_REJECTED = 12; public static final int PRODUCT_NOT_DONE = 11; public static final int PRODUCT_DONE = 10; public static final int ORDER_REJECTED = 22; public static final int ORDER_NOT_DONE = 21; public static final int ORDER_DONE = 20; public static String getTitle(int statusId) { switch (statusId) { case PRODUCT_REJECTED: return "product rejected"; case PRODUCT_NOT_DONE: return "product not done"; case PRODUCT_DONE: return "product done"; case ORDER_REJECTED: return "order rejected"; case ORDER_NOT_DONE: return "order not done"; default: return "order done"; } } }
true
edb2b16b2a8f221880ed8bdf5730166ac1bdc554
Java
HeyBanditoz/mchelper
/src/main/java/io/banditoz/mchelper/weather/darksky/AlertsItem.java
UTF-8
214
1.53125
2
[ "Apache-2.0" ]
permissive
package io.banditoz.mchelper.weather.darksky; import java.util.List; public record AlertsItem(String severity, int expires, List<String> regions, String description, int time, String title, String uri) { }
true
f70a9c1722cce54268d097f89a21f1c028ea299b
Java
huutrongtdtp/roomie
/src/main/java/com/hcmut/roomie/rest/ReplyAPI.java
UTF-8
1,006
1.953125
2
[]
no_license
package com.hcmut.roomie.rest; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.hcmut.roomie.dto.ReplyDTO; import com.hcmut.roomie.service.ReplyService; @RestController public class ReplyAPI { @Autowired private ReplyService replyService; @PostMapping("api/reply") public ResponseEntity<ReplyDTO> createReply(@RequestBody ReplyDTO replyDTO) { return ResponseEntity.ok(replyService.createReply(replyDTO)); } @GetMapping("api/reply/{cid}") public ResponseEntity<List<ReplyDTO>> getRepliesByComment(@PathVariable Long cid) { return ResponseEntity.ok(replyService.getRepliesByComment(cid)); } }
true
7263251a1ece7f3baa0b2bbd82884932e93c144b
Java
DEBOJYOTI11/Mini-projects-in-Java
/7. Airline Reservation System in servlets and JSP/src/com/nissan/training/corejava/project/controller/AdminRegistrationController.java
UTF-8
2,352
2.640625
3
[]
no_license
package com.nissan.training.corejava.project.controller; import java.io.IOException; import java.sql.SQLException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.nissan.training.corejava.project.enums.Validators; import com.nissan.training.corejava.project.interfaces.IInputInterface; import com.nissan.training.corejava.project.interfaces.IRegistrationInterface; import com.nissan.training.corejava.project.models.AdminModel; import com.nissan.training.corejava.project.services.AdminRegistrationService; import com.nissan.training.corejava.project.utils.MD5; import com.nissan.training.corejava.project.utils.ReadInput; public class AdminRegistrationController implements IRegistrationInterface, IInputInterface { String email; String password; AdminRegistrationService adminRegistrationService = null; AdminModel adminModel = null; ReadInput readInput = null; public AdminRegistrationController() { adminRegistrationService = new AdminRegistrationService(); adminModel = new AdminModel(); readInput = new ReadInput(); } /** * Registers a admin, calls model.save() method internally * @throws SQLException */ @Override public void register() throws SQLException { if(adminModel!=null) adminModel.save(); } /** * takes admin registration details and stores in adminModel object */ @Override public void takeInput(HttpServletRequest request, HttpServletResponse response) { this.email = request.getParameter("name"); adminModel.setAdminEmail(this.email); this.password = request.getParameter("pass"); adminModel.setAdminPassword(MD5.getHash(this.password)); System.err.println("****** NOTE : For purpose of the demo please enter the following admin_registration_token : \"abcd\""); System.err.println("****** NOTE : In real world application this code will be given to the admin\n"); System.out.print("Enter admin_registration_token given : "); String adminRegistrationToken = request.getParameter("token"); if(!AdminRegistrationService.validateToken(adminRegistrationToken)) { try { response.getWriter().println("\nInvalid token. Please enter correct Admin Registration Token"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
true