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
042401a4a8b856eee791071428aae872522d6835
Java
52im/NimbleIO
/nimbleio-core/src/main/java/com/generallycloud/nio/component/concurrent/LinkedListM2O.java
UTF-8
468
2.25
2
[]
no_license
package com.generallycloud.nio.component.concurrent; public class LinkedListM2O<T> extends AbstractLinkedList<T> implements LinkedList<T> { private FixedAtomicInteger _end; protected LinkedListM2O(int capability) { super(capability); _end = new FixedAtomicInteger(capability - 1); } protected LinkedListM2O() { super(); _end = new FixedAtomicInteger(_capability - 1); } public final int getAndIncrementEnd() { return _end.getAndIncrement(); } }
true
b304f0cad227200f463389294a3e25e241cb93c0
Java
Tagpower/sirh-gestion-paie
/src/main/java/dev/paie/web/controller/RemunerationEmployeController.java
UTF-8
2,755
2.15625
2
[]
no_license
package dev.paie.web.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.annotation.Secured; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; 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.servlet.ModelAndView; import dev.paie.entite.Entreprise; import dev.paie.entite.Grade; import dev.paie.entite.ProfilRemuneration; import dev.paie.entite.RemunerationEmploye; import dev.paie.repository.EntrepriseRepository; import dev.paie.repository.GradeRepository; import dev.paie.repository.ProfilRemunerationRepository; import dev.paie.repository.RemunerationEmployeRepository; @Controller @RequestMapping("/employes") public class RemunerationEmployeController { @Autowired private EntrepriseRepository entrepriseRepository; @Autowired private ProfilRemunerationRepository profilRemunerationRepository; @Autowired private GradeRepository gradeRepository; @Autowired private RemunerationEmployeRepository remunerationEmployeRepository; @RequestMapping(method = RequestMethod.GET, path = "/creer") @Secured("ROLE_ADMINISTRATEUR") public ModelAndView creerForm() { ModelAndView mv = new ModelAndView(); mv.setViewName("employes/creerEmploye"); String matricule = null; mv.addObject("matricule", matricule); List<Entreprise> entreprises = entrepriseRepository.findAll(); mv.addObject("entreprises", entreprises); List<ProfilRemuneration> profils = profilRemunerationRepository.findAll(); mv.addObject("profils", profils); List<Grade> grades = gradeRepository.findAll(); mv.addObject("grades", grades); RemunerationEmploye remEmploye = new RemunerationEmploye(); mv.addObject("employe", remEmploye); return mv; } @RequestMapping(method = RequestMethod.POST, path = "/creer") @Secured("ROLE_ADMINISTRATEUR") public ModelAndView submitForm( @ModelAttribute("employe") RemunerationEmploye employe, @RequestParam("matricule") String matricule) { employe.setMatricule(matricule); remunerationEmployeRepository.save(employe); return listerEmployes(); } @RequestMapping(method = RequestMethod.GET, path = "/lister") @Secured({"ROLE_ADMINISTRATEUR", "ROLE_UTILISATEUR"}) public ModelAndView listerEmployes() { ModelAndView mv = new ModelAndView(); mv.setViewName("employes/listerEmployes"); List<RemunerationEmploye> employes = remunerationEmployeRepository.findAll(); mv.addObject("employes", employes); return mv; } }
true
d9ee3aa254f1ba3669dd3b71249739049d59697c
Java
federicotrani/ZMail
/app/src/main/java/com/example/ftrani/zmail/adapters/MensajeAdapter.java
UTF-8
2,118
2.4375
2
[]
no_license
package com.example.ftrani.zmail.adapters; import android.graphics.Color; import android.graphics.PorterDuff; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.example.ftrani.zmail.R; import com.example.ftrani.zmail.models.Mensaje; import java.util.ArrayList; /** * Created by ftrani on 6/9/17. */ public class MensajeAdapter extends BaseAdapter { private ArrayList<Mensaje> mensajes; private final int MAX_LARGO_MENSAJE=40; public MensajeAdapter(ArrayList<Mensaje> mensajes) { this.mensajes = mensajes; } @Override public int getCount() { return mensajes.size(); } @Override public Object getItem(int position) { return mensajes.get(position); } @Override public long getItemId(int i) { return 0; } @Override public View getView(int position, View view, ViewGroup parent) { View convertView; //optimizacion if(view==null){ convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_lista_mensajes,parent,false); }else{ convertView = view; } Mensaje mensaje = (Mensaje) getItem(position); TextView txtIcono = convertView.findViewById(R.id.txtIcono); TextView txtAsunto = convertView.findViewById(R.id.txtAsunto); TextView txtContenido = convertView.findViewById(R.id.txtContenido); txtIcono.setText(mensaje.getRemitente().substring(0,1)); txtIcono.getBackground().setColorFilter(Color.parseColor(mensaje.getColor()), PorterDuff.Mode.SRC); //txtIcono.setBackgroundColor(convertView.getResources().getColor(R.color.colorAccent)); txtAsunto.setText(mensaje.getAsunto()); if(mensaje.getContenido().length()>MAX_LARGO_MENSAJE){ txtContenido.setText(mensaje.getContenido().substring(0,MAX_LARGO_MENSAJE)); }else{ txtContenido.setText(mensaje.getContenido()); } return convertView; } }
true
11d5c22dd2b118193c9a222559b9b42aa31e251c
Java
unive-ingsw2017/bunny-team
/Src/unfinitaly/app/src/main/java/it/unive/dais/bunnyteam/unfinitaly/app/cluster/PercentageClusterRenderer.java
UTF-8
3,409
2.40625
2
[]
no_license
package it.unive.dais.bunnyteam.unfinitaly.app.cluster; import android.content.Context; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.MarkerOptions; import com.google.maps.android.clustering.ClusterManager; import it.unive.dais.bunnyteam.unfinitaly.app.marker.MapMarker; /** * * @author BunnyTeam, Università Ca' Foscari */ public class PercentageClusterRenderer<T extends MapMarker> extends ClusterRenderer { public PercentageClusterRenderer(Context context, GoogleMap map, ClusterManager clusterManager) { super(context, map, clusterManager); } /* test, colorare il cluster in base alle percentuali medie @Override protected void onBeforeClusterRendered(Cluster cluster, MarkerOptions markerOptions) { super.onBeforeClusterRendered(cluster, markerOptions); int size = cluster.getSize(); double sum = 0; double media = 0; int bucket = this.getBucket(cluster); Collection<MapMarker> mM = cluster.getItems(); BitmapDescriptor descriptor = (BitmapDescriptor)this.mIcons.get(bucket); if(descriptor == null) { //descriptor = BitmapDescriptorFactory.fromBitmap(this.mIconGenerator.makeIcon(String.valueOf(cluster.getSize()))); //real numbers descriptor = BitmapDescriptorFactory.fromBitmap(this.mIconGenerator.makeIcon(this.getClusterText(bucket))); //number + this.mIcons.put(bucket, descriptor); } for(MapMarker m : mM) sum += m.getPercentage(); media = sum / size; if(media >= 0 && media < 25){ //Tra 0 e 25 this.mColoredCircleBackground.getPaint().setColor(this.getColor(Color.RED)); }else{ if(media >= 25 && media < 50){ //Tra 25 e 50 this.mColoredCircleBackground.getPaint().setColor(this.getColor(Color.RED)); }else{ if(media >= 50 && media < 75){ //Tra 50 e 75 this.mColoredCircleBackground.getPaint().setColor(this.getColor(Color.YELLOW)); } else{ //Tra 75 e 100 this.mColoredCircleBackground.getPaint().setColor(this.getColor(Color.GREEN)); } } } }*/ @Override protected void onBeforeClusterItemRendered(MapMarker item, MarkerOptions markerOptions) { double percentage = item.getPercentage(); if(percentage >= 0 && percentage < 25){ //Tra 0 e 25 markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)); }else{ if(percentage >= 25 && percentage < 50){ //Tra 25 e 50 markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)); }else{ if(percentage >= 50 && percentage < 75){ //Tra 50 e 75 markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)); } else{ //Tra 75 e 100 markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)); } } } } }
true
0c382d4c9650bbcc6917da04c94b432bdd030019
Java
UrsulaK/iceandfire
/iceandfire_db/src/main/java/iceandfire/de/db/service/repository/HouseRepository.java
UTF-8
683
2.125
2
[]
no_license
package iceandfire.de.db.service.repository; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.query.Param; import iceandfire.de.db.service.model.House; public interface HouseRepository extends PagingAndSortingRepository<House, String>{ Page<House> findByNameLike(@Param("name") String name, Pageable pageable); Page<House> findByRegionLike(@Param("region") String region, Pageable pageable); Page<House> findByNameLikeAndRegionLike(@Param("name") String name, @Param("region") String region, Pageable pageable ); }
true
d7a215dea534553af32efb8cc60a5e1aeda1abcb
Java
nikhil2050/NK_ERP_Inventory_Leave_MgmtSys
/EC_ERP/src/main/java/com/ec/erp/repository/ErpEmployeeRepository.java
UTF-8
407
1.609375
2
[]
no_license
package com.ec.erp.repository; import org.springframework.stereotype.Component; import org.springframework.stereotype.Repository; import com.ec.erp.model.ErpEmployee; import com.ec.erp.softdelete.BaseRepository; import org.springframework.data.repository.CrudRepository; @Repository public interface ErpEmployeeRepository extends CrudRepository<ErpEmployee, Long>, BaseRepository<ErpEmployee, Long>{ }
true
7fcf2e922ea8c337a826b0869010aa3c90c346f0
Java
digi-embedded/android-sample-xbeemanager
/app/src/main/java/com/digi/android/sample/xbeemanager/models/AbstractReceivedPacket.java
UTF-8
4,324
2.515625
3
[ "ISC" ]
permissive
/* * Copyright (c) 2014-2021, Digi International Inc. <support@digi.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package com.digi.android.sample.xbeemanager.models; import java.util.Calendar; import java.util.Date; import com.digi.xbee.api.models.XBee64BitAddress; public abstract class AbstractReceivedPacket { // Variables. protected Date receivedDate; protected XBee64BitAddress sourceAddress; private final PacketType type; /** * Class constructor. Instantiates a new {@code AbstractReceivedXBeePacket} * object with the given parameters. * * @param sourceAddress 64-bit address of the device that sent this packet. * @param type Packet type. */ public AbstractReceivedPacket(XBee64BitAddress sourceAddress, PacketType type) { this.sourceAddress = sourceAddress; this.type = type; receivedDate = new Date(); } /** * Returns the date at which packet was received. * * @return The date at which packet was received. */ public Date getDate() { return receivedDate; } /** * Returns the received time in format HH:mm:ss. * * @return Received time in format HH:mm:ss. */ public String getTimeString() { Calendar cal = Calendar.getInstance(); cal.setTime(receivedDate); return completeNumber(cal.get(Calendar.HOUR_OF_DAY)) + ':' + completeNumber(cal.get(Calendar.MINUTE)) + ':' + completeNumber(cal.get(Calendar.SECOND)) + '.' + completeMilliseconds(cal.get(Calendar.MILLISECOND)); } /** * Returns the received date and time in format yyyy-MM-dd HH:mm:ss. * * @return Received date and time in format yyyy-MM-dd HH:mm:ss. */ public String getDateAndTimeString() { Calendar cal = Calendar.getInstance(); cal.setTime(receivedDate); String dateString = String.valueOf(cal.get(Calendar.YEAR)) + '-' + (cal.get(Calendar.MONTH) + 1) + '-' + cal.get(Calendar.DAY_OF_MONTH) + " "; String timeString = completeNumber(cal.get(Calendar.HOUR_OF_DAY)) + ':' + completeNumber(cal.get(Calendar.MINUTE)) + ':' + completeNumber(cal.get(Calendar.SECOND)) + '.' + completeMilliseconds(cal.get(Calendar.MILLISECOND)); return dateString + timeString; } /** * Returns the received packet source address. * * @return The received packet 64-bit source address. */ public XBee64BitAddress getSourceAddress() { return sourceAddress; } /** * Returns the packet type. * * @return The packet type. */ public PacketType getType() { return type; } /** * Returns the packet data in a readable format. * * @return The packet data in a readable format. */ public abstract String getPacketData(); /** * Returns the packet data (short format) in a readable format. * * @return The packet data (short formal) in a readable format. */ public abstract String getShortPacketData(); /** * Completes the given number by adding a preceding zero if necessary. * * @param number Number to complete. * @return Completed number. */ private String completeNumber(int number) { if (number < 10) return "0" + number; return "" + number; } /** * Completes the given milliseconds value by adding '0' until reaching 3 * floating point decimals. * * @param milliseconds Milliseconds number to complete. * @return Completed milliseconds number. */ private String completeMilliseconds(int milliseconds) { if (("" + milliseconds).length() == 3) return "" + milliseconds; int diff = 3 - ("" + milliseconds).length(); StringBuilder sb = new StringBuilder(); sb.append(milliseconds); for (int i = 0; i < diff; i++){ sb.append("0"); } return sb.toString(); } }
true
c99e45fb0007a96a4dda522c9b0e09dcf4ca107a
Java
SarthakSingh2010/Java_Programming
/exam/test.java
UTF-8
233
2.5
2
[]
no_license
class test { static int x=3; int y=4; public static void main(String args[]) { test obj=new test(); System.out.println("x value "+test.x); System.out.println("y value "+obj.y); } }
true
e00fa6fd754c11f1c31f0e80470d63e6a19b8920
Java
kohsuke/vcc
/vcc-ant-tasks/src/main/java/net/java/dev/vcc/ant/AntLogFactory.java
UTF-8
2,410
2.140625
2
[]
no_license
package net.java.dev.vcc.ant; import net.java.dev.vcc.spi.AbstractLogFactory; import net.java.dev.vcc.spi.AbstractLog; import net.java.dev.vcc.api.Log; import org.apache.tools.ant.Task; import org.apache.tools.ant.Project; import java.text.MessageFormat; /** * Created by IntelliJ IDEA. User: connollys Date: Aug 11, 2009 Time: 3:26:11 PM To change this template use File | * Settings | File Templates. */ public class AntLogFactory extends AbstractLogFactory { private static Task task = null; protected Log newLog(String name, String bundleName) { final Task task; synchronized (AntLogFactory.class) { task = AntLogFactory.task; } return new AbstractLog() { @Override protected void debug(String fqcn, Throwable throwable, String messageKey, Object[] args) { task.log(MessageFormat.format(messageKey, args), Project.MSG_DEBUG); } @Override protected void info(String fqcn, Throwable throwable, String messageKey, Object[] args) { task.log(MessageFormat.format(messageKey, args), Project.MSG_INFO); } @Override protected void warn(String fqcn, Throwable throwable, String messageKey, Object[] args) { task.log(MessageFormat.format(messageKey, args), Project.MSG_WARN); } @Override protected void error(String fqcn, Throwable throwable, String messageKey, Object[] args) { task.log(MessageFormat.format(messageKey, args), Project.MSG_ERR); } @Override protected void fatal(String fqcn, Throwable throwable, String messageKey, Object[] args) { task.log(MessageFormat.format(messageKey, args), Project.MSG_ERR); } public boolean isDebugEnabled() { return true; } public boolean isInfoEnabled() { return true; } public boolean isWarnEnabled() { return true; } public boolean isErrorEnabled() { return true; } public boolean isFatalEnabled() { return true; } }; } public static synchronized void setTask(Task task) { AntLogFactory.task = task; } }
true
c8827d0d73d16b5c8774c03a3deea95a821ed6ec
Java
yangjiugang/teamway
/flf/src/com/fc/flf/eagent/mapper/ICostFeeMapper.java
UTF-8
1,425
1.992188
2
[]
no_license
package com.fc.flf.eagent.mapper; import java.util.List; import java.util.Map; import com.fc.flf.common.domain.UserCostFee; /** * 记录开销Mapper * * @author Administrator * */ public interface ICostFeeMapper { /** * 开销列表查询 * * @param map * @return List<UserCostFee> */ List<UserCostFee> getQueryList(Map<String, Object> map); /** * 开销总数查询 * * @param map * @return List<UserCostFee> */ int getQueryListCount(Map<String, Object> map); /** * 开销条件查询 * * @param map * @return List<UserCostFee> */ List<UserCostFee> getQueryCondition(Map<String, Object> map); /** * 添加开销 * * @param map * @return List<UserCostFee> */ int addCostFee(Map<String, Object> map); /** * 查询历史开销记录总记录数 * * @param map * @return List<UserCostFee> */ int getGroupHistoryCount(Map<String, Object> map); /** * 查询历史开销记录 * * @param map * @return List<UserCostFee> */ List<UserCostFee> getGroupHistory(Map<String, Object> map); /** * 查询历史开销详细记录 * * @param map * @return List<UserCostFee> */ List<UserCostFee> getDetailHistory(Map<String, Object> map); /** * 更新开销记录 * * @param map * @return int */ int updateCost(Map<String, Object> map); }
true
05981e1f790d32e107c17bc94985582823802ccd
Java
SpinyOwl/SpinyGUI
/core/src/main/java/com/spinyowl/spinygui/core/system/event/listener/SystemKeyEventListener.java
UTF-8
1,979
2.4375
2
[ "MIT" ]
permissive
package com.spinyowl.spinygui.core.system.event.listener; import com.spinyowl.spinygui.core.event.KeyboardEvent; import com.spinyowl.spinygui.core.event.processor.EventProcessor; import com.spinyowl.spinygui.core.input.KeyAction; import com.spinyowl.spinygui.core.input.Keyboard; import com.spinyowl.spinygui.core.input.KeyboardKey; import com.spinyowl.spinygui.core.node.Frame; import com.spinyowl.spinygui.core.system.event.SystemKeyEvent; import com.spinyowl.spinygui.core.time.TimeService; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.NonNull; @EqualsAndHashCode public class SystemKeyEventListener extends AbstractSystemEventListener<SystemKeyEvent> { @NonNull private final Keyboard keyboard; @Builder public SystemKeyEventListener( @NonNull EventProcessor eventProcessor, @NonNull TimeService timeService, @NonNull Keyboard keyboard) { super(eventProcessor, timeService); this.keyboard = keyboard; } /** * Used to listen, process and translate system event to gui event. * * @param event system event to process * @param frame target frame for system event. */ @Override public void process(@NonNull SystemKeyEvent event, @NonNull Frame frame) { var element = frame.getFocusedElement(); if (element != null) { int keyCode = event.keyCode(); var key = new KeyboardKey(keyboard.layout().keyCode(keyCode), keyCode, event.scancode()); eventProcessor.push( KeyboardEvent.builder() .source(frame) .target(element) .key(key) .timestamp(timeService.currentTime()) .mods(event.mappedMods()) .action(getAction(event)) .build()); } } private KeyAction getAction(SystemKeyEvent event) { return switch (event.action()) { case PRESS -> KeyAction.PRESS; case RELEASE -> KeyAction.RELEASE; case REPEAT -> KeyAction.REPEAT; }; } }
true
fa53eaa672b457b2c46521d1d8adebc36b9e34bb
Java
EricksonVaz/AndroidTvAppTutorial
/app/src/main/java/com/ericksoncv/androidtvapptutorial/ui/DetailsActivity.java
UTF-8
616
1.742188
2
[ "MIT" ]
permissive
package com.ericksoncv.androidtvapptutorial.ui; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.FragmentActivity; import android.os.Bundle; import com.ericksoncv.androidtvapptutorial.R; public class DetailsActivity extends FragmentActivity { public static final String MOVIE = "Movie"; public static final String SHARED_ELEMENT_NAME = "hero"; public static final String NOTIFICATION_ID = "ID"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_details); } }
true
35ae3c22e48d630479311354e7f002ae0253c718
Java
nhphuong96/my-room
/app/src/main/java/com/myroom/application/RepositoryComponent.java
UTF-8
2,766
1.921875
2
[]
no_license
package com.myroom.application; import com.myroom.activity.CreateBillActivity; import com.myroom.activity.GeneralSettingCurrencyActivity; import com.myroom.activity.GeneralSettingUtilityActivity; import com.myroom.adapter.CreateRoomUtilityAdapter; import com.myroom.adapter.GuestInRoomAdapter; import com.myroom.adapter.PaymentHistoryAdapter; import com.myroom.adapter.RoomAdapter; import com.myroom.adapter.UtilityAdapter; import com.myroom.adapter.UtilityInRoomAdapter; import com.myroom.database.dao.UtilityIndex; import com.myroom.database.repository.CurrencyRepository; import com.myroom.database.repository.GuestRepository; import com.myroom.database.repository.RoomRepository; import com.myroom.database.repository.RoomUtilityRepository; import com.myroom.database.repository.UtilityIndexRepository; import com.myroom.database.repository.UtilityRepository; import com.myroom.fragment.CreateBillFragment; import com.myroom.fragment.PaymentHistoryFragment; import com.myroom.fragment.SendMessageFragment; import com.myroom.service.ICurrencyService; import com.myroom.service.IGuestService; import com.myroom.service.IMessageService; import com.myroom.service.IPaymentService; import com.myroom.service.IRoomService; import com.myroom.service.IUtilityService; import javax.inject.Singleton; import dagger.Component; @Singleton @Component(modules = { RepositoryModule.class, ServiceModule.class }) public interface RepositoryComponent { void inject(RoomAdapter roomAdapter); void inject(CreateRoomUtilityAdapter createRoomUtilityAdapter); void inject(UtilityAdapter utilityAdapter); void inject(UtilityInRoomAdapter utilityInRoomAdapter); void inject(GuestInRoomAdapter guestInRoomAdapter); void inject(PaymentHistoryAdapter paymentHistoryAdapter); void inject(IRoomService roomService); void inject(ICurrencyService currencyService); void inject(IGuestService guestService); void inject(IMessageService messageService); void inject(IUtilityService utilityService); void inject(IPaymentService paymentService); void inject(GeneralSettingUtilityActivity generalSettingUtilityActivity); void inject(CreateBillActivity createBillActivity); void inject(GeneralSettingCurrencyActivity generalSettingCurrencyActivity); void inject(CreateBillFragment createBillFragment); void inject(SendMessageFragment sendMessageFragment); void inject(PaymentHistoryFragment paymentHistoryFragment); RoomRepository getRoomRepository(); GuestRepository getGuestRepository(); UtilityRepository getUtilityRepository(); RoomUtilityRepository getRoomUtilityRepository(); CurrencyRepository getCurrencyRepository(); UtilityIndexRepository getUtilityIndexRepository(); }
true
e90f47b32edb8334cc987110652ca59447d30934
Java
AlperCakiroglu/derivativeCalculator
/calculator/Newton_Raphson.java
UTF-8
1,503
2.875
3
[]
no_license
package itujoker.calculator; public class Newton_Raphson { private double x;//initial guess private double e;//absolute err private int n; private double d; private String function; public Newton_Raphson(double absolute_err, double d, int n, double initial_guess,String function) { this.function=function; this.e = absolute_err; this.d = d; this.n = n; this.x = initial_guess; } private double f(Double a){ String gecici=function; for(int i=0;i<gecici.length();i++){ if(gecici.charAt(i)=='y'&& i<gecici.length()-1){ gecici=gecici.substring(0,i)+a+gecici.substring(i+1); } else if(gecici.charAt(i)=='y' && gecici.length()-1==i){ gecici=gecici.substring(0,i)+a; } } return new Calculator().calculate(gecici,MainActivity.isDeg); } private double fder(Double a){ return new Numerical_Diff(function,a,0.01).find_Derivative(); } public double findRoot(){ for(int i=1;i<=n;i+=2){ double f=f(x); double f1=fder(x); /*if(Math.abs(f1)<d){ return 61.61616161;//to small slope }*/ double x1=x- f/f1; if(Math.abs((x1-x)/x1)<e){ return x1; } x=x1; } return 61.616161;//cant find the root } }
true
a1b56bd13444e25e36b16bc7a827a5f2b68dae32
Java
simonloach/OOP-Chess-Game
/src/MainGUI.java
UTF-8
4,256
2.90625
3
[]
no_license
import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.List; public class MainGUI extends JFrame{ private JPanel PANEL; private List<JPanel> panelList = new ArrayList<>(); private String[] pola = {"a8", "b8", "c8", "d8", "e8", "f8", "g8", "h8", "a7", "b7", "c7", "d7", "e7", "f7", "g7", "h7", "a6", "b6", "c6", "d6", "e6", "f6", "g6", "h6", "a5", "b5", "c5", "d5", "e5", "f5", "g5", "h5", "a4", "b4", "c4", "d4", "e4", "f4", "g4", "h4", "a3", "b3", "c3", "d3", "e3", "f3", "g3", "h3", "a2", "b2", "c2", "d2", "e2", "f2", "g2", "h2", "a1", "b1", "c1", "d1", "e1", "f1", "g1", "h1"}; public void setPanelColor(Container parent) //Działa i to się liczy { for(Component c : parent.getComponents()) { if(c instanceof Container) { if(c.getName().equals("a8")) { c.setBackground(Color.RED); } setPanelColor((Container)c); } } } public void highlightERR(JPanel panel){ // DO NAPISANIA !!! } public MainGUI() { GridLayout grid = new GridLayout(8,8); setLayout(grid); setDefaultCloseOperation(EXIT_ON_CLOSE); int colorcheck = 1; int colorswap = 1; for(int i=0; i<64; i++){ panelList.add(new JPanel()); JLabel lab = new JLabel(pola[i]); PanelListener listener = new PanelListener() { @Override public void mousePressed(MouseEvent mouseEvent) { } @Override public void mouseReleased(MouseEvent mouseEvent) { } @Override public void mouseEntered(MouseEvent mouseEvent) { } @Override public void mouseExited(MouseEvent mouseEvent) { } }; panelList.get(i).setName(pola[i]); if(colorcheck%2 == colorswap%2){ panelList.get(i).setBackground(Color.WHITE); lab.setForeground(Color.BLACK); } else{ panelList.get(i).setBackground(Color.BLACK); lab.setForeground(Color.WHITE); } if(colorcheck == 8){ colorcheck = 1; colorswap += 1; } else { colorcheck += 1; } panelList.get(i).addMouseListener(listener); panelList.get(i).add(lab); add(panelList.get(i)); } //setPanelColor(this); pack(); } private abstract class PanelListener implements MouseListener { @Override public void mouseClicked(MouseEvent event) { Object source = event.getSource(); if (source instanceof JPanel) { JPanel panelPressed = (JPanel) source; //panelPressed.setBackground(Color.blue); for(JPanel p : panelList) { if(panelPressed.equals(p)) { int x = panelList.indexOf(p); //panelList.get(x).setBackground(Color.RED); try{ panelList.get(x+1).setBackground(Color.RED); panelList.get(x-1).setBackground(Color.RED); panelList.get(x+8).setBackground(Color.RED); panelList.get(x-8).setBackground(Color.RED); panelList.get(x+9).setBackground(Color.RED); panelList.get(x-9).setBackground(Color.RED); panelList.get(x+7).setBackground(Color.RED); panelList.get(x-7).setBackground(Color.RED); }catch (Exception ignore){} } } } } } public static void main(String[] args){ new MainGUI().setVisible(true); } }
true
da5b36a5423cdb9df4accf7cec631169151bf1c7
Java
Sania7/job4jtasks
/src/test/sort/ReverseOrderTest.java
UTF-8
287
2.21875
2
[]
no_license
package test.sort; import org.junit.Test; import sort.ReverseOrder; import java.util.Comparator; import static org.junit.Assert.*; public class ReverseOrderTest { @Test public void test() { assertEquals(Comparator.reverseOrder(), ReverseOrder.reverseOrder()); } }
true
769ba8011521c49dbabe7c8d929121576ac02955
Java
shining1510386040/spikesystem
/storeservice/src/main/java/com/demo/springboot/storeservice/config/RedisConfig.java
UTF-8
3,426
2.390625
2
[]
no_license
package com.demo.springboot.storeservice.config; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisStandaloneConfiguration; import org.springframework.data.redis.connection.jedis.JedisClientConfiguration; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import redis.clients.jedis.JedisPoolConfig; import java.time.Duration; /** * @author Wenyi Cao * @version 1.0 * @link * @description redis配置 * @date 2021/1/25 16:19 * @see */ @Configuration public class RedisConfig { @Autowired private RedisStandaloneProperties redisStandaloneProperties; /** * @param * @return * @author Wenyi Cao * @version 1.0 * @description redisTemplate bean * Qualifier注解指明要注入哪个Bean * @date 2021/1/25 19:30 */ @Bean public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate ret = new RedisTemplate(); // 设置k-v 的序列化和反序列化 //使用fastjson序列化 FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class); ret.setKeySerializer(fastJsonRedisSerializer); ret.setValueSerializer(fastJsonRedisSerializer); ret.setHashKeySerializer(fastJsonRedisSerializer); ret.setHashValueSerializer(fastJsonRedisSerializer); ret.setConnectionFactory(redisConnectionFactory); return ret; } /** * @param * @return * @author Wenyi Cao * @version 1.0 * @description redis连接工厂:standalone 单机模式 * Primary注解,当spring中有两个相同类型bean时,选用此bean DI * @date 2021/1/25 16:37 */ @Bean @Primary public RedisConnectionFactory redisConnectionFactoryStandalone() { // jedis pool 池 JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxTotal(redisStandaloneProperties.getPoolMaxActive()); poolConfig.setMaxIdle(redisStandaloneProperties.getPoolMaxIdle()); poolConfig.setMinIdle(redisStandaloneProperties.getPoolMinIdle()); poolConfig.setMaxWaitMillis(redisStandaloneProperties.getPoolMaxWait()); // jedis client 配置 JedisClientConfiguration clientConfig = JedisClientConfiguration.builder() .usePooling() .poolConfig(poolConfig) .and() .readTimeout(Duration.ofMillis(redisStandaloneProperties.getRedisTimeout())) .build(); // 单机模式 RedisStandaloneConfiguration redisConfig = new RedisStandaloneConfiguration(); redisConfig.setHostName(redisStandaloneProperties.getHost()); redisConfig.setPort(redisStandaloneProperties.getPort()); if (StringUtils.isNotBlank(redisStandaloneProperties.getPassword())) { redisConfig.setPassword(redisStandaloneProperties.getPassword()); } return new JedisConnectionFactory(redisConfig, clientConfig); } }
true
aaec2267ae90471681680e49102613dc31200455
Java
hyunmimaust/PopularMovies
/app/src/main/java/com/example/android/popularmovies/data/Movie.java
UTF-8
2,270
2.5
2
[]
no_license
package com.example.android.popularmovies.data; import android.database.Cursor; import java.io.Serializable; /** * Created by hmaust on 6/28/17. */ public class Movie implements Serializable { String imageUrl; String title; String originalLanguage; Boolean adult; String overview; String releaseDate; Double popularity; Double voteAverage; String movieId; public String getMovieId() { return movieId; } public void setMovieId(String id) { this.movieId = id; } public String getOriginalLanguage() { return originalLanguage; } public void setOriginalLanguage(String originalLanguage) { this.originalLanguage = originalLanguage; } public Double getVoteAverage() { return voteAverage; } public void setVoteAverage(Double voteAverage) { this.voteAverage = voteAverage; } public Boolean getAdult() { return adult; } public void setAdult(Boolean adult) { this.adult = adult; } public String getOverview() { return overview; } public void setOverview(String overview) { this.overview = overview; } public String getReleaseDate() { return releaseDate; } public void setReleaseDate(String releaseDate) { this.releaseDate = releaseDate; } public Double getPopularity() { return popularity; } public void setPopularity(Double popularity) { this.popularity = popularity; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getRelease_year() { String release_date = getReleaseDate(); String year = null; if (release_date.length() > 5) { year = release_date.substring(0, 4); } return year; } @Override public String toString() { return "Movie{" + "title='" + title + '\'' + ", movieId='" + movieId + '\'' + '}'; } }
true
dcf22f733f98b680869c39b2e8b41b50af59eec5
Java
lotuswlz/wlz-project
/01.project_as_tool/myTool/src/optdoc/PageInfoUtil.java
EUC-JP
8,191
2.296875
2
[]
no_license
/* * History * Version Update Date Updater Details * 1.0.00 2010-6-9 Cathy Wu Create */ package optdoc; import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; /** * For Offerme. * <pre> * 2010-Jun-9, Ken ask me to list all the action which requires user to access with login status. * So I write this program to read all the action-*.xml and applicationContext-*.xml, get all the return page and link. * * </pre> * @since 2010-6-9 * @author Cathy Wu * @version 1.1.00 */ public class PageInfoUtil { public static Map<String, List<String>> actionList = new HashMap<String, List<String>>(); public static Map<String, String> actionLinkMap = new HashMap<String, String>(); public static Map<String, String> appList = new HashMap<String, String>(); private static FileFilter fileFilter1 = new FileFilter(){ public boolean accept(File pathname) { String tmp=pathname.getName().toLowerCase(); if(pathname.isDirectory() || (tmp.endsWith(".xml") && tmp.startsWith("action"))){ return true; } return false; } }; private static FileFilter fileFilter2 = new FileFilter(){ public boolean accept(File pathname) { String tmp=pathname.getName().toLowerCase(); if(pathname.isDirectory() || (tmp.endsWith(".xml") && tmp.startsWith("application"))){ return true; } return false; } }; public static void getActionPageXml(String path) { List<File> actionFiles = getAllFilesForAction(path, 1); List<File> applicationFiles = getAllFilesForAction(path, 2); appList.clear(); actionLinkMap.clear(); actionList.clear(); for (File f : applicationFiles) { readXml2(f.getPath()); } for (File f : actionFiles) { readXml(f.getPath()); } } public static void readXml(String xmlPath) { try { SAXBuilder sb = new SAXBuilder(); Document doc = sb.build(xmlPath); Element root = doc.getRootElement(); List options = root.getChildren("package"); if (options == null || options.size() == 0) { return; } String name = null; String cls = null; String str = null; List<String> ls = null; for (Object obj : options) { Element e = (Element) obj; List temp = e.getChildren("action"); for (Object o : temp) { Element ce = (Element) o; name = ce.getAttributeValue("name"); cls = ce.getAttributeValue("class"); List tmp = ce.getChildren("result"); ls = new ArrayList<String>(); for (Object co : tmp) { Element cce = (Element) co; List p = cce.getChildren("param"); if (p == null || p.size() == 0) { str = cce.getAttributeValue("name") + ":" + cce.getValue().trim() + ";"; } else { for (Object x : p) { Element xe = (Element) x; if (xe.getAttributeValue("name").equals("location")) { str = cce.getAttributeValue("name") + ":" + xe.getValue().trim() + ";"; } } } ls.add(str); } String appCls = appList.get(cls); actionList.put(appCls, ls); actionLinkMap.put(appCls, name); } } } catch (JDOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void readXml2(String xmlPath) { try { SAXBuilder sb = new SAXBuilder(); Document doc = sb.build(xmlPath); Element root = doc.getRootElement(); List options = root.getChildren("bean"); options = root.getChildren(); if (options == null || options.size() == 0) { return; } String name = null; String cls = null; String str = null; List<String> ls = null; for (Object obj : options) { Element e = (Element) obj; name = e.getAttributeValue("id"); cls = e.getAttributeValue("class"); appList.put(name, cls); } } catch (JDOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static List<File> getAllFilesForAction(String path, int type) { File dir = new File(path); if (!dir.isDirectory()) { return new ArrayList<File>(); } File[] files = null; if (type == 1) { files = dir.listFiles(fileFilter1); } else { files = dir.listFiles(fileFilter2); } List<File> list = new ArrayList<File>(); for (File f : files) { if (f.isFile()) { list.add(f); } if (f.isDirectory()) { list.addAll(getAllFilesForAction(f.getPath(), type)); } } return list; } public static void main(String[] args) { getActionPageXml("D:/projects/offerme/30_Coding/branch/om_web/web/WEB-INF"); //System.out.println(actionList.size()); //System.out.println(actionList.get("au.com.iwanttobuy.offerme.presentation.action.account.SendMobileValidateCodeAction")); readPropertiesFile(); } public static void readPropertiesFile() { try { String filepath = "D:/projects/offerme/30_Coding/branch/om_web/src/resources/accesspower.properties"; File file = new File(filepath); FileReader fr = null; BufferedReader br = null; List<String> list = new ArrayList<String>(); String temp = null; StringBuffer sbf = new StringBuffer(); int count = 0; if(!file.isFile()){ return; } fr = new FileReader(file); br = new BufferedReader(fr); String[] arr = null; do{ temp = br.readLine(); if (temp == null || temp.trim().startsWith("#") || temp.trim().equals("") || !temp.contains("=")) { continue; } arr = temp.split("="); String url = actionLinkMap.get(arr[0].trim()); if (url == null) { continue; } // url url = url.replaceAll("_", "/"); url = "/" + url; sbf.append(url + ","); // action name sbf.append(arr[0] + ","); // page List<String> ls = actionList.get(arr[0].trim()); String t1 = ""; String t2 = ""; if (ls != null && ls.size() > 0) { for (String t : ls) { if (t.contains(".jsp")) { t1 = t; } else { t2 = t; } } sbf.append(t1); sbf.append(","); sbf.append(t2); } sbf.append(","); // accesspower sbf.append(arr[1] + "\n"); } while(temp != null); br.close(); fr.close(); File f = new File("D:/development_documents/temp_data/self_" + System.currentTimeMillis() + ".csv"); OutputStream os = new FileOutputStream(f); os.write(sbf.toString().getBytes()); os.close(); System.out.println(f.getPath()); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void readSettingFile() { } }
true
d0d675eb2cc2c19c79bfb03d12ec3a33baa40a0e
Java
JaganmohanDevendraguru/AMS
/src/main/java/com/sse/dao/SemesterDAO.java
UTF-8
287
2.140625
2
[]
no_license
package com.sse.dao; import java.util.List; import com.sse.model.Semester; public interface SemesterDAO { public List<Semester> findAll(); public Semester findById(String sem); public int create(Semester sem); public int deleteById(String id); public int update(Semester sem); }
true
2c5dc9c9fb4c8dfdfe50fe2d69fa468a6e7eb063
Java
prgmTrouble/prgmML
/prgmML/src/main/java/com/prgmtrouble/ml/prgmML/math/Tensor.java
UTF-8
4,699
3.140625
3
[]
no_license
package com.prgmtrouble.ml.prgmML.math; public final class Tensor { /** * Dilates a flattened rank-3 tensor. * * @param in Input. * @param is Input side length. * @param c Channels. * @param factor Number of empty rows and columns to add between elements. * @return Flattened and dilated matrix. */ public static double[] dilate(double[] in, int is, int c, int factor) { final int ns = is * (++factor) - 1, //Dilated side length. nsq = ns * ns, //Dilated side length squared. isq = is * is; //Input side length squared. final double[] out = new double[c * nsq]; //Output tensor. for(int ch = 0; ch < c; ch++) { //For each channel: final int chisq = ch * isq, //Input channel index. chnsq = ch * nsq; //Dilated channel index. for(int ir = 0; ir < is; ir++) { //For each input row: final int xr = chisq + (ir * is), //Input row index. nr = chnsq + (ir * factor * ns); //Dilated row index. for(int ic = 0; ic < is; ic++) //For each input column: out[nr + (ic * factor)] = in[xr + ic]; //Record input. } } return out; //Return dilated tensor. } public static double[] transpose(double[] in, int is, int c) { final int isq = is * is; for(int ch = 0; ch < c; ch++) { final int chq = ch * isq; for(int ir = 0; ir < is; ir++) for(int ic = 0; ic < is; ic++) { final int aidx = chq + (ir * is) + ic, bidx = chq + (ic * is) + ir; final double t = in[aidx]; in[aidx] = in[bidx]; in[bidx] = t; } } return in; } public static double[] reverseColumns(double[] in, int is, int c) { final int isq = is * is; for(int ch = 0; ch < c; ch++) { final int chq = ch * isq; for(int ir = 0; ir < is; ir++) for(int ic = 0; ic < is; ic++) { final int aidx = chq + (ir * is) + ic, bidx = chq + (ir * is) + (is - ic - 1); final double t = in[aidx]; in[aidx] = in[bidx]; in[bidx] = t; } } return in; } public static double[] rot180(double[] in, int is, int c) { final int il = in.length; final double[] out = new double[il]; System.arraycopy(in, 0, out, 0, il); return reverseColumns(transpose(reverseColumns(transpose(out,is,c),is,c),is,c),is,c); } public static double[] sum(double[] a, double[] b) { int x = 0; for(double i : b) a[x++] += i; return a; } public static double[] scale(double[] a, double b) { for(int i = 0; i < a.length; i++) a[i] *= b; return a; } /** * Performs a convolution operation using flattened arrays. * * @param in Flattened input map. * @param is Input map side length. * @param filter Flattened filter. * @param fs Filter side length. * @param c Channels. * @param step Step size. * @param pad Padding. * @return The flattened output map. */ public static double[] convolve(double[] in, int is, double[] filter, int fs, int c, int step, int pad) { if((is + 2 * pad - fs) % step != 0) //TODO include pad in check? error("Input and filter size difference is not a factor of the step size."); final int os = (is + 2 * pad - fs) / step, osq = os * os, isq = is * is, fsq = fs * fs; final double[] out = new double[osq]; for(int or = 0; or < os; or++) { final int oros = or * os, orst = or * step; for(int oc = 0; oc < os; oc++) { final int ocst = oc * step; double o = 0.0; for(int ch = 0; ch < c; ch++) { final int chisq = ch * isq, chfsq = ch * fsq; for(int fr = 0; fr < fs; fr++) { final int ir = orst + fr - pad, frfs = fr * fs + chfsq; if(ir >= 0 && ir < is) { final int iris = ir * is + chisq; for(int fc = 0; fc < fs; fc++) { final int ic = ocst + fc - pad; if(ic >= 0 && ic < is) o += in[iris + ic] * filter[frfs + fc]; } } } } out[oros + oc] = o; } } return out; } /** * A custom exception which indicates an error in a tensor. * * @author prgmTrouble */ private static class TensorException extends Exception { /***/ private static final long serialVersionUID = 1L; private static final String prefix = "Tensor Exception: "; public TensorException(String s) {super(prefix + s);} } /** * Throws a {@linkplain TensorException} and terminates execution. * * @param s Description of error. */ protected static void error(String s) { try { throw new TensorException(s); } catch(TensorException e) { e.printStackTrace(); System.exit(1); } } }
true
91921e1da00dc7e34ea3411d439b86523d9477f8
Java
NMPavan/MYUdacityBaking
/app/src/main/java/com/example/manikyapavan/myudacitybaking/models/Ingredient.java
UTF-8
2,002
2.65625
3
[]
no_license
package com.example.manikyapavan.myudacitybaking.models; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.SerializedName; public class Ingredient implements Parcelable { @SerializedName(value = "quantity") private double mIngredientQuantity; @SerializedName(value = "measure") private String mIngredientMeasure; @SerializedName(value = "ingredient") private String mIngredient; public Ingredient(double quantity, String measure, String ingredient) { mIngredientQuantity = quantity; mIngredientMeasure = measure; mIngredient = ingredient; } protected Ingredient(Parcel in) { mIngredientQuantity = in.readDouble(); mIngredientMeasure = in.readString(); mIngredient = in.readString(); } public void setIngredientQuantity(double quantity) { mIngredientQuantity = quantity; } public void setIngredientMeasure(String measure) { mIngredientMeasure = measure; } public void setIngredient(String ingredient) { mIngredient = ingredient; } public double getIngredientQuantity() { return mIngredientQuantity; } public String getIngredientMeasure() { return mIngredientMeasure; } public String getIngredient() { return mIngredient; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeDouble(mIngredientQuantity); parcel.writeString(mIngredientMeasure); parcel.writeString(mIngredient); } public static final Parcelable.Creator<Ingredient> CREATOR = new Parcelable.Creator<Ingredient>() { @Override public Ingredient createFromParcel(Parcel in) { return new Ingredient(in); } @Override public Ingredient[] newArray(int size) { return new Ingredient[size]; } }; }
true
ee8957d06dad1112864b12ccc1b06a3220bfcab0
Java
kchandan38/project
/Generic Database Services/src/main/java/com/gendbservices/dbservices/service/DatabaseType.java
UTF-8
714
1.867188
2
[]
no_license
package com.gendbservices.dbservices.service; import com.fasterxml.jackson.core.JsonProcessingException; import com.gendbservices.dbservices.exception.GenDbException; import com.gendbservices.dbservices.request.CreatePoolRequest; import com.gendbservices.dbservices.request.QueryRequest; import com.gendbservices.dbservices.response.QueryResponse; import org.springframework.http.ResponseEntity; import java.util.Map; public interface DatabaseType { ResponseEntity<Map<String, String>> createConnectionPool(CreatePoolRequest createPoolRequest, boolean recreate) throws GenDbException, JsonProcessingException; QueryResponse executeQuery(QueryRequest queryRequest) throws GenDbException; }
true
141dafdcaf05cc1f7c318d7b24b843a02ff204d6
Java
outrunJ/algorithm
/java/src/base/dp2/MinCoinsLimit.java
UTF-8
7,952
3.46875
3
[]
no_license
package base.dp2; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; // (不重复,只1张)/(可重复,限张数),求最小张数 public class MinCoinsLimit { private static int process(int[] arr, int idx, int rest) { if (rest < 0) { return Integer.MAX_VALUE; } if (idx == arr.length) { return rest == 0 ? 0 : Integer.MAX_VALUE; } int p1 = process(arr, idx + 1, rest); int p2 = process(arr, idx + 1, rest - arr[idx]); if (p2 != Integer.MAX_VALUE) { p2++; } return Math.min(p1, p2); } public static int minCoins(int[] arr, int aim) { return process(arr, 0, aim); } // public static int dp1(int[] arr, int aim) { if (aim == 0) { return 0; } int n = arr.length; int[][] dp = new int[n + 1][aim + 1]; dp[n][0] = 0; for (int j = 1; j <= aim; j++) { dp[n][j] = Integer.MAX_VALUE; } for (int idx = n - 1; idx >= 0; idx--) { for (int rest = 0; rest <= aim; rest++) { int p1 = dp[idx + 1][rest]; int p2 = rest - arr[idx] >= 0 ? dp[idx + 1][rest - arr[idx]] : Integer.MAX_VALUE; if (p2 != Integer.MAX_VALUE) { p2++; } dp[idx][rest] = Math.min(p1, p2); } } return dp[0][aim]; } private static class Info { public int[] coins; public int[] nums; public Info(int[] c, int[] z) { coins = c; nums = z; } } private static Info getInfo(int[] arr) { HashMap<Integer, Integer> counts = new HashMap<>(); for (int val : arr) { if (!counts.containsKey(val)) { counts.put(val, 1); } else { counts.put(val, counts.get(val) + 1); } } int n = counts.size(); int[] coins = new int[n]; int[] nums = new int[n]; int idx = 0; for (Map.Entry<Integer, Integer> entry : counts.entrySet()) { coins[idx] = entry.getKey(); nums[idx++] = entry.getValue(); } return new Info(coins, nums); } // O(arr长度) + O(货币种数 * aim * 货币平均张数) public static int dp2(int[] arr, int aim) { if (aim == 0) { return 0; } Info info = getInfo(arr); int[] coins = info.coins; int[] nums = info.nums; int n = coins.length; int[][] dp = new int[n + 1][aim + 1]; dp[n][0] = 0; for (int j = 1; j <= aim; j++) { dp[n][j] = Integer.MAX_VALUE; } for (int i = n - 1; i >= 0; i--) { for (int rest = 0; rest <= aim; rest++) { dp[i][rest] = dp[i + 1][rest]; for (int num = 1; num * coins[i] <= rest && num <= nums[i]; num++) { if (dp[i + 1][rest - num * coins[i]] != Integer.MAX_VALUE) { dp[i][rest] = Math.min(dp[i][rest], num + dp[i + 1][rest - num * coins[i]]); } } } } return dp[0][aim]; } private static int num(int pre, int cur, int coin) { return (cur - pre) / coin; } // O(arr长度) + O(货币种数 * aim) public static int dp3(int[] arr, int aim) { if (aim == 0) { return 0; } Info info = getInfo(arr); int[] c = info.coins; int[] z = info.nums; int n = c.length; int[][] dp = new int[n + 1][aim + 1]; dp[n][0] = 0; for (int j = 1; j <= aim; j++) { dp[n][j] = Integer.MAX_VALUE; } for (int i = n - 1; i >= 0; i--) { for (int mod = 0; mod < Math.min(aim + 1, c[i]); mod++) { LinkedList<Integer> w = new LinkedList<>(); w.add(mod); dp[i][mod] = dp[i + 1][mod]; for (int r = mod + c[i]; r <= aim; r += c[i]) { while (!w.isEmpty() && (dp[i + 1][w.peekLast()] == Integer.MAX_VALUE || dp[i + 1][w.peekLast()] + num(w.peekLast(), r, c[i]) >= dp[i + 1][r])) { w.pollLast(); } w.addLast(r); int overdue = r - c[i] * (z[i] + 1); if (w.peekFirst() == overdue) { w.pollFirst(); } if (dp[i + 1][w.peekFirst()] == Integer.MAX_VALUE) { dp[i][r] = Integer.MAX_VALUE; } else { dp[i][r] = dp[i + 1][w.peekFirst()] + num(w.peekFirst(), r, c[i]); } } } } return dp[0][aim]; } // private static int[] randomArr(int maxLen, int maxVal) { int[] arr = new int[(int) ((maxLen + 1) * Math.random())]; for (int i = 0; i < arr.length; i++) { arr[i] = (int) ((maxVal + 1) * Math.random()) + 1; } return arr; } private static void print(int[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + ","); } System.out.println(); } public static void main(String[] args) { dp2(new int[]{25, 15, 26}, 15); dp3(new int[]{25, 15, 26}, 15); int times = 100000; int maxLen = 20; int maxVal = 30; System.out.println("test begin"); for (int i = 0; i < times; i++) { int[] arr = randomArr(maxLen, maxVal); int aim = (int) ((maxVal + 1) * 2 * Math.random()); int ans1 = minCoins(arr, aim); int ans2 = dp1(arr, aim); int ans3 = dp2(arr, aim); int ans4 = dp3(arr, aim); if (ans1 != ans2 || ans3 != ans4 || ans1 != ans3) { System.out.println("Wrong"); print(arr); System.out.println(aim); System.out.println(ans1 + "|" + ans2 + "|" + ans3 + "|" + ans4); break; } } System.out.println("test end"); System.out.println("=========="); int aim = 0; int[] arr = null; long start; long end; int ans2; int ans3; System.out.println("性能测试开始"); maxLen = 30000; maxVal = 20; aim = 60000; arr = randomArr(maxLen, maxVal); start = System.currentTimeMillis(); ans2 = dp2(arr, aim); end = System.currentTimeMillis(); System.out.println("dp2答案 : " + ans2 + ", dp2运行时间 : " + (end - start) + " ms"); start = System.currentTimeMillis(); ans3 = dp3(arr, aim); end = System.currentTimeMillis(); System.out.println("dp3答案 : " + ans3 + ", dp3运行时间 : " + (end - start) + " ms"); System.out.println("性能测试结束"); System.out.println("==========="); System.out.println("货币大量重复出现情况下,"); System.out.println("大数据量测试dp3开始"); maxLen = 20000000; aim = 10000; maxVal = 10000; arr = randomArr(maxLen, maxVal); start = System.currentTimeMillis(); ans3 = dp3(arr, aim); end = System.currentTimeMillis(); System.out.println("dp3运行时间 : " + (end - start) + " ms"); System.out.println("大数据量测试dp3结束"); System.out.println("==========="); System.out.println("当货币很少出现重复,dp2比dp3有常数时间优势"); System.out.println("当货币大量出现重复,dp3时间复杂度明显优于dp2"); System.out.println("dp3的优化用到了窗口内最小值的更新结构"); } }
true
51b1990529378a368cc2d38a68703166bcdeebad
Java
yeungeek/AndroidRoad
/MVVM-Arsenal/app/src/main/java/com/yeungeek/mvvm/sample/mvvm/GithubViewHolder.java
UTF-8
1,151
2.203125
2
[ "Apache-2.0" ]
permissive
package com.yeungeek.mvvm.sample.mvvm; import android.app.Application; import android.arch.lifecycle.LiveData; import android.arch.lifecycle.MutableLiveData; import android.support.annotation.NonNull; import com.yeungeek.mvvm.core.BaseViewModel; import com.yeungeek.mvvm.sample.http.DataCallback; import com.yeungeek.mvvm.sample.data.Repo; import java.util.List; /** * @date 2018/10/19 */ public class GithubViewHolder extends BaseViewModel<GithubRepository> { private MutableLiveData<List<Repo>> repoData; public GithubViewHolder(@NonNull Application application) { super(application); } public LiveData<List<Repo>> repoData() { if (null == repoData) { repoData = new MutableLiveData<>(); } return repoData; } public void getRepoList(final String name) { mRepository.getRepoList(name, new DataCallback<List<Repo>>() { @Override public void onResponse(List<Repo> response) { repoData.setValue(response); } @Override public void onFailure(Throwable t) { } }); } }
true
9a8ee4c73d5dd74da64ecb4a4e82c94d727896fb
Java
Avicus/AvicusNetwork
/Hook/Bukkit/src/main/java/net/avicus/hook/credits/reward/CompetitveRewardListener.java
UTF-8
2,003
2.25
2
[ "MIT" ]
permissive
package net.avicus.hook.credits.reward; import net.avicus.atlas.sets.competitve.objectives.destroyable.leakable.event.LeakableLeakEvent; import net.avicus.atlas.sets.competitve.objectives.destroyable.monument.event.MonumentDestroyEvent; import net.avicus.atlas.sets.competitve.objectives.flag.events.FlagCaptureEvent; import net.avicus.atlas.sets.competitve.objectives.wool.event.WoolPickupEvent; import net.avicus.atlas.sets.competitve.objectives.wool.event.WoolPlaceEvent; import net.avicus.hook.HookConfig; import net.avicus.hook.credits.Credits; import net.avicus.hook.utils.Messages; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; public class CompetitveRewardListener implements Listener { @EventHandler public void onMonumentDestroy(MonumentDestroyEvent event) { int reward = HookConfig.Credits.Rewards.getMonumentDestroy(); if (reward > 0) { Credits.reward(event.getPlayers().get(0), reward, Messages.UI_REWARD_MONUMENT_DESTROYED); } } @EventHandler public void onFlagCapture(FlagCaptureEvent event) { int reward = HookConfig.Credits.Rewards.getFlagCapture(); if (reward > 0) { Credits.reward(event.getPlayers().get(0), reward, Messages.UI_REWARD_FLAG_CAPTURED); } } @EventHandler public void onWoolPlace(WoolPlaceEvent event) { int reward = HookConfig.Credits.Rewards.getWoolPlace(); if (reward > 0) { Credits.reward(event.getPlayers().get(0), reward, Messages.UI_REWARD_WOOL_PLACE); } } @EventHandler public void onWoolPickup(WoolPickupEvent event) { int reward = HookConfig.Credits.Rewards.getWoolPickup(); if (reward > 0) { Credits.reward(event.getPlayer(), reward, Messages.UI_REWARD_WOOL_PICKUP); } } @EventHandler public void onLeakableLeak(LeakableLeakEvent event) { int reward = HookConfig.Credits.Rewards.getLeakableLeak(); if (reward > 0) { Credits.reward(event.getPlayers().get(0), reward, Messages.UI_REWARD_LEAKABLE_LEAK); } } }
true
eb2c3c9a9d757118f103ccfe97da579fdd57960c
Java
Hasithazz/High-Street-Bank
/BankGUI/src/GUI/EmployeeEditor.java
UTF-8
13,122
2.390625
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 GUI; import java.util.ArrayList; import javax.swing.DefaultListModel; import javax.swing.JOptionPane; /** * * @author hsedi */ public class EmployeeEditor extends javax.swing.JFrame { private CreateEmployee newEmployee; private EmployeeList empList; /** * Creates new form EmployeeEditor */ public EmployeeEditor() { initComponents(); componentInitializing( (ArrayList<String>) sendAllEmployeeNames(), (ArrayList<String>) sendAllEmployeePositions());//calling method by passing return value of the request } /** * 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() { jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jList1 = new javax.swing.JList<>(); jbtnCreateNew = new javax.swing.JButton(); jbtnSelect = new javax.swing.JButton(); jbtnDelete = new javax.swing.JButton(); jbtnRefresh = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Employee List"); jPanel1.setBackground(new java.awt.Color(204, 204, 255)); jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane1.setViewportView(jList1); jbtnCreateNew.setBackground(new java.awt.Color(102, 102, 255)); jbtnCreateNew.setText("Create New"); jbtnCreateNew.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnCreateNewActionPerformed(evt); } }); jbtnSelect.setBackground(new java.awt.Color(102, 102, 255)); jbtnSelect.setText("Select"); jbtnSelect.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnSelectActionPerformed(evt); } }); jbtnDelete.setBackground(new java.awt.Color(102, 102, 255)); jbtnDelete.setText("Delete"); jbtnDelete.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnDeleteActionPerformed(evt); } }); jbtnRefresh.setBackground(new java.awt.Color(102, 102, 255)); jbtnRefresh.setText("Refresh"); jbtnRefresh.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnRefreshActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 208, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jbtnCreateNew, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jbtnSelect, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jbtnDelete, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jbtnRefresh, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jbtnCreateNew) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jbtnSelect) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jbtnDelete) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jbtnRefresh)) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE))) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jbtnSelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnSelectActionPerformed // TODO add your handling code here: if (jList1.getSelectedIndex() != -1) { String data = jList1.getSelectedValue(); String[] empDetails = data.split("-"); String empName = empDetails[0]; String empPosition = empDetails[1]; setEmpNameAndPosition(empName, empPosition);//set current employee name and postion in the service empList = new EmployeeList(); empList.setVisible(true); } else { JOptionPane.showMessageDialog(null, "Please select a customer first", "ERROR", JOptionPane.INFORMATION_MESSAGE); } }//GEN-LAST:event_jbtnSelectActionPerformed private void jbtnCreateNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnCreateNewActionPerformed // TODO add your handling code here: newEmployee = new CreateEmployee(); newEmployee.setVisible(true); }//GEN-LAST:event_jbtnCreateNewActionPerformed private void jbtnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnDeleteActionPerformed // TODO add your handling code here: if (jList1.getSelectedIndex() != -1) { String data = jList1.getSelectedValue(); String[] empDetails = data.split("-"); String empName = empDetails[0]; String empPosition = empDetails[1]; //delete selected employee by using name and postion if (deleteEmployee(empName, empPosition)) { JOptionPane.showMessageDialog(null, "Employee Deleted", "SUCSESSFUL", JOptionPane.INFORMATION_MESSAGE); } } else { JOptionPane.showMessageDialog(null, "Please select a employee first", "ERROR", JOptionPane.INFORMATION_MESSAGE); } }//GEN-LAST:event_jbtnDeleteActionPerformed private void jbtnRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnRefreshActionPerformed // TODO add your handling code here: componentInitializing( (ArrayList<String>) sendAllEmployeeNames(), (ArrayList<String>) sendAllEmployeePositions());//calling method by passing return value of the request }//GEN-LAST:event_jbtnRefreshActionPerformed /** * @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(EmployeeEditor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(EmployeeEditor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(EmployeeEditor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(EmployeeEditor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new EmployeeEditor().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JList<String> jList1; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton jbtnCreateNew; private javax.swing.JButton jbtnDelete; private javax.swing.JButton jbtnRefresh; private javax.swing.JButton jbtnSelect; // End of variables declaration//GEN-END:variables public void componentInitializing(ArrayList<String> allNames, ArrayList<String> allPositions) { DefaultListModel employeeListModel = new DefaultListModel(); for (int i = 0; i < allNames.size(); i++) { String name = allNames.get(i); String position = allPositions.get(i); employeeListModel.addElement(name + "-" + position); } jList1.setModel(employeeListModel); } private static java.util.List<java.lang.String> sendAllEmployeeNames() { com.bankservice.BankWebService_Service service = new com.bankservice.BankWebService_Service(); com.bankservice.BankWebService port = service.getBankWebServicePort(); return port.sendAllEmployeeNames(); } private static java.util.List<java.lang.String> sendAllEmployeePositions() { com.bankservice.BankWebService_Service service = new com.bankservice.BankWebService_Service(); com.bankservice.BankWebService port = service.getBankWebServicePort(); return port.sendAllEmployeePositions(); } private static void setEmpNameAndPosition(java.lang.String arg0, java.lang.String arg1) { com.bankservice.BankWebService_Service service = new com.bankservice.BankWebService_Service(); com.bankservice.BankWebService port = service.getBankWebServicePort(); port.setEmpNameAndPosition(arg0, arg1); } private static boolean deleteEmployee(java.lang.String name, java.lang.String position) { com.bankservice.BankWebService_Service service = new com.bankservice.BankWebService_Service(); com.bankservice.BankWebService port = service.getBankWebServicePort(); return port.deleteEmployee(name, position); } }
true
72df285de60217d0cddb97d55bfb78cdeed79c5a
Java
LanceXuan/Lsproject
/Lsteamtalk/src/com/lesso/action/CcNoticeAction.java
UTF-8
9,949
1.929688
2
[]
no_license
package com.lesso.action; import java.io.IOException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts2.dispatcher.Dispatcher; import net.sf.json.JSON; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import com.lesso.beans.CcNotice; import com.lesso.beans.ErrorMsg; import com.lesso.beans.IMAdmin; import com.lesso.beans.IMUser; import com.lesso.beans.tbl_NoticesReceived; import com.lesso.model.RemarkBack; import com.lesso.service.CcNoticeService; import com.lesso.service.tbl_NoticesReceivedService; import com.lesso.serviceImpl.CcNoticeServiceImpl; import com.lesso.serviceImpl.tbl_NoticesReceivedServiceImpl; import com.lesso.util.DateWorkUtil; import com.lesso.util.ResponseUtil; import com.lesso.util.StringUtil; import com.lib.Security; public class CcNoticeAction extends HttpServlet { private CcNoticeService service = new CcNoticeServiceImpl(); private tbl_NoticesReceivedService ntservice = new tbl_NoticesReceivedServiceImpl(); public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String method = request.getParameter("method") == null ? "" : request .getParameter("method"); if ("saveCcNotice".equals(method)) { saveCcNotice(request, response); } else if ("getCcNotice".equals(method)) { getCcNotice(request, response); } else if ("".equals(method)) { getNoticeList(request, response); } else if ("getReadstatus".equals(method)){ getReadstatus(request, response); } else if("updateCcNotice".equals(method)){ updateCcNotice(request, response); } else if("deleteCcNotice".equals(method)){ deleteCcNotice(request, response); } } private void getNoticeList(HttpServletRequest request, HttpServletResponse response) { Log logs = LogFactory.getLog(CcNoticeAction.class); try { logs.info("获取公告列表"); String page = request.getParameter("page") == null ? "0" : request .getParameter("page"); String rows = request.getParameter("rows") == null ? "0" : request .getParameter("rows"); String begindate = request.getParameter("begindate") == null ? "" : request.getParameter("begindate"); String enddate = request.getParameter("enddate") == null ? "" : request.getParameter("enddate"); String title = request.getParameter("title") == null ? "" : request.getParameter("title"); Map<String,Object> map = new HashMap<String,Object>(); if(!"".equals(begindate)){ map.put("createdA", begindate); } if(!"".equals(enddate)){ map.put("createdB", begindate); } if(!"".equals(title)){ map.put("title", title); } map.put("sort", "created"); List<CcNotice> list = service.findByPagination(Integer.parseInt(page), Integer.parseInt(rows), map); int total = service.getTotal(map); ResponseUtil.toPaginationJson(response, list, total); } catch (Exception e) { e.printStackTrace(); logs.info("获取公告列表出错:"+e.getMessage()); } } private void saveCcNotice(HttpServletRequest request, HttpServletResponse response) { try { String title = request.getParameter("title") == null ? "" : request .getParameter("title"); String content = request.getParameter("content") == null ? "" : request.getParameter("content"); String reviceor = request.getParameter("reviceor") == null ? "" : request.getParameter("reviceor"); String firstImg = request.getParameter("firstImg") == null ? "" : request.getParameter("firstImg"); CcNotice ccNotice = new CcNotice(); HttpSession session = request.getSession(); IMAdmin inadmin = (IMAdmin) session.getAttribute("userinfo"); if(inadmin == null){ throw(new Exception("会话过期,请刷新重新登录!")); } ccNotice.setTitle(title); ccNotice.setContent(content); ccNotice.setFirstImg(firstImg); ccNotice.setReviceor(reviceor); ccNotice.setSendor(String.valueOf(inadmin.getIMUserId())); ccNotice.setReadStatus(0); ccNotice.setCreated(DateWorkUtil.stringToDatenow()); int isok = service.saveCcNotice(ccNotice); List<RemarkBack> listrb = new ArrayList<RemarkBack>(); ErrorMsg msg = new ErrorMsg(); if (isok>0) { // HttpSession session = request.getSession(); //insert tbl_NoticesReceived String[] arr = reviceor.split(","); for(int i=0;i<arr.length;i++){ tbl_NoticesReceived mp = new tbl_NoticesReceived(); mp.setCreated(DateWorkUtil.stringToDatenow()); mp.setNoticeId(isok); mp.setUserId(Integer.parseInt(arr[i])); mp.setReceivetime(null); mp.setStatus(0); ntservice.save(mp); RemarkBack rb = new RemarkBack(); String s =""; if(content.length()>18){ s = StringUtil.removeHtmlTag(content).substring(0,10); }else{ s = StringUtil.removeHtmlTag(content); } String dcontent = "msgtype:7[{:&$#@~^@:}]http://im2.lesso.com:8181/Lsteamtalk/privilegemgmt/ccNotice.action?method=getCcNotice&&iceId="+isok+"&&suid" + "="+arr[i]+"[{:&$#@~^@:}]"+title+"[{:&$#@~^@:}]"+DateWorkUtil.stringToDatenow()+"[{:&$#@~^@:}]"+s; String encmsg =Security.getInstance().EncryptMsg(dcontent); rb.setExceptionMag(String.valueOf(isok)); rb.setHasError(false); rb.setLogMsg(String.valueOf(isok)); rb.setRemarka(encmsg); rb.setRemarkb(arr[i]); rb.setRemarkc(""); listrb.add(rb); } //insert end msg.setHasError(false); msg.setLogMsg(String.valueOf(isok)); } else { msg.setHasError(true); msg.setLogMsg("fail"); RemarkBack rb = new RemarkBack(); rb.setExceptionMag(String.valueOf(isok)); rb.setHasError(true); rb.setLogMsg("fail"); rb.setRemarka(""); rb.setRemarkb(""); rb.setRemarkc(""); listrb.add(rb); } response.setContentType("text/html;charset=utf-8"); response.getWriter().write(JSONArray.fromObject(listrb).toString()); } catch (Exception e) { e.printStackTrace(); ResponseUtil.ReMsg(response, true, e.getMessage(), "fail"); } } private void getCcNotice(HttpServletRequest request, HttpServletResponse response) { Log logs = LogFactory.getLog(CcNoticeAction.class); try { String noticeId = request.getParameter("iceId") == null ? "" : request.getParameter("iceId"); String uid = request.getParameter("suid") == null ? "" : request.getParameter("suid"); logs.info("CcNoticeAction-getCcNotice is begin and iceid is "+noticeId+" and uid is "+uid); CcNotice notice = service.getCcNotice(Integer.valueOf(noticeId)); if(StringUtil.isNotEmpty(uid)){ boolean isok = service.updateMarkRead(uid, Integer.valueOf(noticeId)); ntservice.updateReceivedNotices(request, response); } notice.setCreated(notice.getCreated()); request.setAttribute("notice", notice); request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); RequestDispatcher dispatcher = request .getRequestDispatcher("../jsp/checkNotice.jsp"); dispatcher.forward(request, response); } catch (Exception e) { e.printStackTrace(); logs.info(e.getMessage()); } } public void getReadstatus(HttpServletRequest request, HttpServletResponse response){ Log logs = LogFactory.getLog(CcNoticeAction.class); try { String id = request.getParameter("id") == null ? "": request.getParameter("id"); System.out.println(id); service.getNoticeReadList(request, response); } catch (Exception e) { e.printStackTrace(); logs.info(e.getMessage()); } } public void updateCcNotice(HttpServletRequest request, HttpServletResponse response){ Log logs = LogFactory.getLog(CcNoticeAction.class); try { String noticeId = request.getParameter("noticeId") == null ? "" : request.getParameter("noticeId"); CcNotice notice = service.getCcNotice(Integer.valueOf(noticeId)); List<IMUser> userList = service.getIMUserListByIdString(notice.getReviceor()); request.setAttribute("userList", userList); request.setAttribute("notice", notice); request.setAttribute("operate", "update"); response.setContentType("text/html;charset=UTF-8"); RequestDispatcher dispatcher = request .getRequestDispatcher("ccNotice.jsp"); dispatcher.forward(request, response); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); logs.info(e.getMessage()); } } public void deleteCcNotice(HttpServletRequest request, HttpServletResponse response){ try { String noticeIds = request.getParameter("noticeIds") == null ? "" : request.getParameter("noticeIds"); service.deleteCcNoticeByIds(noticeIds); RemarkBack rb = new RemarkBack(); //rb.setExceptionMag("成功删除"); rb.setHasError(true); rb.setLogMsg("success"); rb.setRemarka("成功删除"); rb.setRemarkb(""); rb.setRemarkc(""); response.setContentType("text/html;charset=utf-8"); response.getWriter().write(JSONObject.fromObject(rb).toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
true
045b0bed4e4153969d954d267e7c253b4c964517
Java
gitlinxd/pawo
/pawo-common/pawo-common-basic/src/main/java/com/gm/user/ShoppingOrders.java
UTF-8
2,128
1.851563
2
[]
no_license
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * Copyright (c) 2012-2019. haiyi Inc. * pawo-common All rights reserved. */ package com.gm.user; import com.baomidou.mybatisplus.activerecord.Model; import com.baomidou.mybatisplus.annotations.TableId; import com.baomidou.mybatisplus.annotations.TableLogic; import com.baomidou.mybatisplus.annotations.TableName; import java.io.Serializable; import lombok.Data; /** * <p> </p> * * <pre> Created: 2019-01-16 22:47 </pre> * <pre> Project: pawo-common </pre> * * @author gmzhao * @version 1.0 * @since JDK 1.7 */ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * Copyright (c) 2012-2019. 赵贵明 * pawo-server All rights reserved. */ @TableName("SHOPPING_ORDERS") @Data public class ShoppingOrders extends Model<ShoppingOrders> { private static final long serialVersionUID = 6463201706516176118L; /** * 物理主键 */ @TableId private Long iid; /** * 订单编号 */ private String sn; /** * 关联父订单SN */ private String parentSn; /** * 订单商品类型代码 */ private String orderTypeCode; /** * 下单类型(秒杀/下单) */ private Integer transactionType; /** * 商品编号 */ private String goodsCode; /** * 价格 */ private Double price; /** * 下单数量 */ private Integer volume; /** * 剩余数量 */ private Integer volumeTotal; /** * 已交易数量 */ private Integer volumeTraded; /** * 订单状态 */ private String orderStatus; /** * 订单状态信息 */ private String statusMsg; /** * 下单时间 */ private String insertTime; /** * 用户编号 */ private Integer userId; /** * 用户姓名 */ private String userName; /** * 0-正常;1-删除 */ @TableLogic private Integer deleteFlag; @Override protected Serializable pkVal() { return this.iid; } }
true
44b7e81b74f438b3d0d92a1ecf88d7240f0e415a
Java
laivieeeee/ruiqing
/code/ruiqing/rq-common/src/main/java/com/ruiqing/common/utils/Resources.java
UTF-8
1,981
2.25
2
[]
no_license
package com.ruiqing.common.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; /** * 国际化支持 Created by zlb on 2017年12月19日 */ public final class Resources { /** 国际化信息 */ private static final Map<String, ResourceBundle> MESSAGES = new HashMap<String, ResourceBundle>(); /** * 定义记录日志信息 */ protected static Logger logger = LoggerFactory.getLogger(Resources.class); /** 国际化信息 */ public static String getMessage(String key, Object... params) { Locale locale = LoginUserSessionHelper.getLoginUserLocale(getRequest()); if (logger.isDebugEnabled()) { logger.debug(" locale :{}", JSONUtils.toJSONString(locale)); } if (locale == null) { locale = new Locale("zh","CN"); if (logger.isDebugEnabled()) { logger.debug(" locale is null:{}", JSONUtils.toJSONString(locale)); } } ResourceBundle resourceBundle = MESSAGES.get(locale.getLanguage()); if (resourceBundle == null) { synchronized (MESSAGES) { resourceBundle = MESSAGES.get(locale.getLanguage()); if (resourceBundle == null) { resourceBundle = ResourceBundle.getBundle("messages", locale); MESSAGES.put(locale.getLanguage(), resourceBundle); } } } if (params != null && params.length > 0) { return String.format(resourceBundle.getString(key), params); } return resourceBundle.getString(key); } /** 清除国际化信息 */ public static void flushMessage() { MESSAGES.clear(); } public static HttpServletRequest getRequest() { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); return request; } }
true
248823f2051a105ec3b9a655c94b151c06770db0
Java
lndlazy/supermarket
/app/src/main/java/com/supermarket/haidilao/home/HomeActivity.java
UTF-8
9,850
1.625
2
[]
no_license
package com.supermarket.haidilao.home; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import com.google.android.material.tabs.TabLayout; import com.jaeger.library.StatusBarUtil; import com.supermarket.haidilao.R; import com.supermarket.haidilao.base.BaseActivity; import com.supermarket.haidilao.bean.ShopListEntity; import com.supermarket.haidilao.my.MyActivity; import com.supermarket.haidilao.net.BaseNoTObserver; import com.supermarket.haidilao.net.RetrofitHttpUtil; import com.supermarket.haidilao.utils.Constant; import com.supermarket.haidilao.utils.LogUtil; import java.util.List; public class HomeActivity extends BaseActivity implements View.OnClickListener { private static final String TAG = "HomeActivity"; private static final int REQUEST_PERMISSION_LOCATION_CODE = 0x111; MapFragment mapFragment = new MapFragment(); ListFragment listFragment = new ListFragment(); private ImageView my; private String key = ""; private String latitude = "0.0"; private String longitude = "0.0"; private int pageIndex = Constant.PAGE_INDEX_BEGIN; private EditText etKey; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mapplication.addA(this); } @Override protected void doWork() { getPermission(); // getShopList(pageIndex); } public void setLocation(String latitude, String longitude, String city) { this.latitude = latitude; this.longitude = longitude; mapplication.latitude = latitude; mapplication.longitude = longitude; mapplication.city = city; } public void getShopList(int pageIndex) { key = etKey.getText().toString(); RetrofitHttpUtil.getInstance().shopList(new BaseNoTObserver<ShopListEntity>() { @Override public void onHandleSuccess(ShopListEntity shopListEntity) { if (listFragment != null) listFragment.stopRefush(); setShopInfo(shopListEntity, pageIndex); } @Override public void onHandleError(String message) { if (listFragment != null) listFragment.stopRefush(); } }, key, latitude, longitude, pageIndex + "", Constant.PAGE_SIZE + ""); } private void setShopInfo(ShopListEntity shopListEntity, int pageIndex) { if (shopListEntity == null) return; List<ShopListEntity.DataBean> data = shopListEntity.getData(); if (data == null) return; if (listFragment != null) listFragment.setLocationList(data, pageIndex == Constant.PAGE_INDEX_BEGIN); if (mapFragment != null) mapFragment.setShopMap(data, pageIndex == Constant.PAGE_INDEX_BEGIN); } @Override protected void setTitleBarColor() { StatusBarUtil.setColor(this, getResources().getColor(R.color.white)); } /** * 获取定位权限 */ private void getPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { checkLocationPer(); } } /** * 检查定位权限, 获取定位信息 */ private void checkLocationPer() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { //具有定位, 开始定位 LogUtil.d("有定位权限,不需要再获取定位权限"); startLocation(); } else { //不具有定位权限,需要进行权限申请 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE} , REQUEST_PERMISSION_LOCATION_CODE); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case REQUEST_PERMISSION_LOCATION_CODE://定位权限 if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.d(TAG, "允许了定位权限,可以定位了"); startLocation(); } else { showErr("没有定位权限"); finish(); System.exit(0); } break; } } @Override protected int getLayoutView() { return R.layout.activity_home; } @Override protected void initView() { ImageView my = findViewById(R.id.my); etKey = findViewById(R.id.etKey); TabLayout tab_layout = findViewById(R.id.tab_layout); // ViewPager viewPager = findViewById(R.id.viewPager); my.setOnClickListener(this); tab_layout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { //选中某个tab chooseFragment(tab); } @Override public void onTabUnselected(TabLayout.Tab tab) { //当tab从选择到未选择 } @Override public void onTabReselected(TabLayout.Tab tab) { //已经选中tab后的重复点击tab } }); etKey.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { //隐藏软键盘 InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); /*判断是否是“搜索”键*/ if (actionId == EditorInfo.IME_ACTION_SEARCH) { pageIndex = 1; getShopList(pageIndex); return true; } return false; } }); } private void startLocation() { //定位权限获取成功 LogUtil.d(TAG, "定位权限获取成功"); showMap(); } private void chooseFragment(TabLayout.Tab tab) { Log.d(TAG, "position::" + tab.getPosition()); switch (tab.getPosition()) { case 0: showMap(); break; case 1: if (listFragment == null) listFragment = new ListFragment(); FragmentTransaction transaction1 = switchFragment(listFragment); transaction1.commit(); break; } } private void showMap() { if (mapFragment == null) mapFragment = new MapFragment(); FragmentTransaction transaction = switchFragment(mapFragment); transaction.commit(); } private Fragment currentFragment; private FragmentTransaction switchFragment(Fragment targetFragment) { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); if (!targetFragment.isAdded()) { //第一次使用switchFragment()时currentFragment为null,所以要判断一下 if (currentFragment != null) transaction.hide(currentFragment); transaction.add(R.id.fragment, targetFragment, targetFragment.getClass().getName()); } else { transaction.hide(currentFragment).show(targetFragment); } currentFragment = targetFragment; return transaction; } @Override public void onBackPressed() { exitApp(); } private long mPressedTime = 0; public void exitApp() { long mNowTime = System.currentTimeMillis();//获取第一次按键时间 if ((mNowTime - mPressedTime) > 2000) {//比较两次按键时间差 showErr("再按一次退出程序"); mPressedTime = mNowTime; } else {//退出程序 finishActivity(); } } public void finishActivity() { try { mapplication.exit(); } catch (Exception e) { e.printStackTrace(); } finish(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.my: nextActivity(MyActivity.class); break; } } }
true
c7183514aad82c66d29dc7180219484cce24c2df
Java
ChrisL89/OMT
/src/main/java/com/offer/messages/v2/MessageConverter.java
UTF-8
3,001
2.703125
3
[]
no_license
package com.offer.messages.v2; import com.fasterxml.jackson.databind.ObjectMapper; import com.offer.exceptions.InvalidMessageTypeException; import com.offer.exceptions.MissingHeaderException; import com.offer.messages.v2.responses.AbstractResponse; import com.rabbitmq.client.LongString; import com.rabbitmq.client.QueueingConsumer; import com.offer.helper.Logger; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.nio.charset.Charset; import java.util.Map; /** * Created by erwan on 1/10/15. * * Converts the rabbitMq messages to POJOs */ public class MessageConverter { private ObjectMapper mapper; public MessageConverter(ObjectMapper mapper) { this.mapper = mapper; } /** * Convert a RabbitMQ Message to a Response object. * * @param delivery The RabbitMQ delivery message * @return A Response object. * @throws MissingHeaderException * @throws InvalidMessageTypeException * @throws IOException When the JSON is invalid */ public AbstractResponse convertResponse(QueueingConsumer.Delivery delivery) throws MissingHeaderException, InvalidMessageTypeException, IOException { Map<String, Object> headers = delivery.getProperties().getHeaders(); if (headers == null) { throw new MissingHeaderException("No headers"); } Object messageTypeObj = headers.get(Message.MESSAGE_TYPE_HEADER); if (messageTypeObj == null) { throw new MissingHeaderException("Missing message_type header."); } String messageTypeString = new String(((LongString)messageTypeObj).getBytes(), Charset.forName("UTF-8")); if (messageTypeString.length() == 0) { throw new MissingHeaderException("Missing message_type header."); } try { // Get the class name for the response from the message_type header. MessageType messageTypeEnum = MessageType.valueOf(messageTypeString.toUpperCase()); Class<?> responseClass = messageTypeEnum.getClassName(); // Instantiate the class Constructor<?> constructor = responseClass.getConstructor(MessageType.class); AbstractResponse response = (AbstractResponse) constructor.newInstance(messageTypeEnum); // And load it with the JSON. String body = new String(delivery.getBody(), Charset.forName("UTF-8")); mapper.readerForUpdating(response).readValue(body); return response; } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException | InstantiationException e) { Logger.log("Error creating response object from message_type {" + e + "}", Logger.LogType.ERROR); // Rethrow. throw new InvalidMessageTypeException("Could not create responce from " + messageTypeString, e); } } public ObjectMapper getMapper() { return mapper; } }
true
7f8d73d151b67c2ef1e6743401a1b2eb72067e0e
Java
Peterragheb/CSE430-Android-Development
/Lab6_Money_Collector_Game/app/src/main/java/com/games/peter/lab6_money_collector_game/CustomAdapter.java
UTF-8
3,166
2.796875
3
[]
no_license
package com.games.peter.lab6_money_collector_game; /** * Created by Peter on 30/3/2018. */ import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.ArrayList; /** * Created by peter on 3/6/18. */ public class CustomAdapter extends ArrayAdapter<Record> { //===================================== //create class for all the fields in a single row of the listview private static class ViewHolder { TextView date; TextView score; TextView coins; } //===================================== //to specify the view type , inflater,and list of users private final int VIEW_TYPE_TODAY = 0; private final int VIEW_TYPE_FUTURE_DAY = 1; private LayoutInflater inflater; private ArrayList<Record> records; //===================================== //constructor public CustomAdapter(Context context, int resource, ArrayList<Record> items) { //Todo change layout here super(context,resource, items); inflater = LayoutInflater.from(context); this.records = items; } //===================================== //get count of users public int getCount() { return records.size(); } //===================================== //get the user view type public int getItemViewType(int position){ return (position==0)? VIEW_TYPE_TODAY : VIEW_TYPE_FUTURE_DAY; } //===================================== public int getViewTypeCount(){ return 2; } //===================================== //get the user at a certain position public Record getItem(int position) { return records.get(position); } //===================================== //get user position public long getItemId(int position) { return position; } //===================================== //create view @Override public View getView(int position, View view, ViewGroup parent) { Record record = getItem(position); ViewHolder vh; //===================================== if (view == null) { vh = new ViewHolder(); inflater = LayoutInflater.from(getContext()); //===================================== view = inflater.inflate(R.layout.list_item, parent, false); //===================================== vh.date = view.findViewById(R.id.tv_record_date); vh.score = view.findViewById(R.id.tv_record_score); vh.coins = view.findViewById(R.id.tv_record_coins); view.setTag(vh); } //===================================== else { vh = (ViewHolder) view.getTag(); } //===================================== vh.date.setText(record.parseDate(null)); vh.score.setText(record.getScore()+""); vh.coins.setText(record.getCoins()+""); return view; } //===================================== }
true
7d1c9ee0d8f5b2e75a7ba72015c98da6a1125507
Java
S04Nik/JavaHW
/src/com/company/HW01/array/Array.java
UTF-8
1,695
3.390625
3
[]
no_license
package com.company.HW01.array; public class Array implements Imath, Isort { public int[] nums; public Array(){ nums=new int[]{1,2,3,4,5,9,12,55,36,78,0}; } @Override public int Max() { int tmp=nums[0]; for(int i:nums){ if(tmp<i) tmp=i; } System.out.println("MAX: "+tmp); return tmp; } @Override public float Avg() { int tmp=0; for(int i:nums){ tmp+=i; } tmp/=nums.length; System.out.println("AVG: "+tmp); return tmp; } @Override public int Min() { int tmp=nums[0]; for(int i=0;i<nums.length;i++){ if(tmp>nums[i]) tmp=nums[i]; } System.out.println("MIN: "+tmp); return tmp; } @Override public void SortAsc() { // tmp=Arrays.copyOf(nums,nums.length); for (int i=nums.length;i>0;i--) { for (int j=0;j<i-1;j++) { if(nums[j]>nums[j+1]){ int tmp=nums[j]; nums[j]=nums[j+1]; nums[j+1]=tmp; } } } for (int i:nums) { System.out.println(i); } } @Override public void SortDesc() { for (int i=nums.length;i>0;i--) { for (int j=0;j<i-1;j++) { if(nums[j]<nums[j+1]){ int tmp=nums[j]; nums[j]=nums[j+1]; nums[j+1]=tmp; } } } for (int i:nums) { System.out.println(i); } } }
true
9b60591b385a7c13c2224b0145d6599f33193226
Java
cybernetics/learning-rsocket-using-rsc
/src/test/java/com/example/UpperCaseControllerTest.java
UTF-8
860
2.09375
2
[]
no_license
package com.example; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.rsocket.context.LocalRSocketServerPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.messaging.rsocket.RSocketRequester; @SpringBootTest("spring.rsocket.server.port=0") class UpperCaseControllerTest { @LocalRSocketServerPort int port; @Autowired RSocketRequester.Builder builder; @Test void requestResponse() { final RSocketRequester requester = builder.tcp("localhost", port); final Mono<String> response = requester.route("uc") .data("Hello") .retrieveMono(String.class); StepVerifier.create(response) .expectNext("HELLO") .expectComplete() .verify(); } }
true
759276569c4bbb1656121f0b0d00a3a6b35d5ce2
Java
KangZhiDong/DataLink
/dl-domain/src/main/java/com/ucar/datalink/domain/event/HBaseConfigClearEvent.java
UTF-8
748
2
2
[ "CDDL-1.1", "Apache-2.0", "CDDL-1.0" ]
permissive
package com.ucar.datalink.domain.event; import com.ucar.datalink.common.event.CallbackEvent; import com.ucar.datalink.common.utils.FutureCallback; import com.ucar.datalink.domain.media.MediaSourceInfo; /** * Created by qianqian.shi on 2018/11/21. */ public class HBaseConfigClearEvent extends CallbackEvent { private MediaSourceInfo mediaSourceInfo; public HBaseConfigClearEvent(FutureCallback callback, MediaSourceInfo mediaSourceInfo) { super(callback); this.mediaSourceInfo = mediaSourceInfo; } public MediaSourceInfo getMediaSourceInfo() { return mediaSourceInfo; } public void setMediaSourceInfo(MediaSourceInfo mediaSourceInfo) { this.mediaSourceInfo = mediaSourceInfo; } }
true
dcb8863dc8201a5fadcfa35420d7f863a45245cc
Java
josepgitz/FuturisticApp
/src/main/java/com/csa/cashsasa/utility/StepOnePersist.java
UTF-8
1,911
2.40625
2
[]
no_license
package com.csa.cashsasa.utility; import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import java.util.HashMap; public class StepOnePersist { SharedPreferences pref; Editor editor; Context _context; int PRIVATE_MODE = 0; private static final String PREFER_NAME = "stepOnePersist"; private static final String IS_VALUES_SET_1 = "stepOneExists"; public static final String KEY_FIRST_NAME = "fname"; public static final String KEY_LAST_NAME = "lname"; public static final String KEY_COUNTRY = "country"; @SuppressLint("CommitPrefEdits") public StepOnePersist(Context context) { this._context = context; pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE); editor = pref.edit(); } public void createInputSession(String fname, String lname, String country) { editor.putBoolean(IS_VALUES_SET_1, true); editor.putString(KEY_FIRST_NAME, fname); editor.putString(KEY_LAST_NAME, lname); editor.putString(KEY_COUNTRY, country); editor.apply(); } public boolean valuesExist() { if(!this.ifValuesExist()){ return true; } return false; } public HashMap<String, String> getInputValues() { HashMap<String, String> user = new HashMap<String, String>(); user.put(KEY_FIRST_NAME, pref.getString(KEY_FIRST_NAME, null)); user.put(KEY_LAST_NAME, pref.getString(KEY_LAST_NAME, null)); user.put(KEY_COUNTRY, pref.getString(KEY_COUNTRY, null)); return user; } public void clearInputValues() { editor.clear(); editor.apply(); } boolean ifValuesExist() { return pref.getBoolean(IS_VALUES_SET_1, false); } }
true
9445643bf1cfcf16a19e50556e8d493274e6495f
Java
fbwkzl333/homework5
/homework5/src/homework5/IsoscelesTriangleStars.java
UTF-8
1,300
3.75
4
[]
no_license
// 3번메뉴 클래스 :IsoscelesTriangleStars package homework5; import java.util.Scanner; public class IsoscelesTriangleStars { public void Iso(){ Scanner s = new Scanner(System.in); System.out.print("이등변삼각형 높이입력 : "); int input = s.nextInt(); // 높이 int star =0; // * 그리기 할 녀석 int gap = input; // 공백을 그릴 녀석, 입력받은 크기값을 넣어줌 (입력값을 기준으로 공백의 갯수를 정하는데 쓰임) for(int i=0; i<input; i++){ // input만큼 줄 입력(높이) [ 높이 for문 시작] for(int j=0; j<=gap; j++){System.out.print(" ");} // gap 만큼 공백을 만듬("공백길이") for(int k=0; k <=star; k++){System.out.print("*");} // star만큼 *을 출력함 (*갯수) System.out.println(); // 한줄 개행(한줄이 끝남, 이제 공백, *갯수 변동주고 다시 똑같이 실행) [ 이곳은 높이 for문] gap--; // h를 1줄임 : " "를 전보다 1개씩 덜 출력하겠다. (이등변삼각형 모양을 위해 한칸 왼쪽까지만 공백 출력) star+=2; // star를 2개 늘림 : *를 전보다 2개씩 더 출력하겠다. ( nul 자리가 왼쪽으로 옮겨지니 *을 2개씩 더 출력시 이등변삼각형 완성) } } }
true
e8081f1f09c7f898555d1851d64418d5a6175f15
Java
xinhaoqi1667/Grasshopper
/Grasshopper_server/src/com/hp/dao/ConditionReleaseDao.java
GB18030
623
2.21875
2
[]
no_license
package com.hp.dao; import java.util.List; import com.hp.entity.Release; public class ConditionReleaseDao extends BaseDao{ public static void main(String[] args) { ConditionReleaseDao d = new ConditionReleaseDao(); List<Release> list = d.getlist(1); System.out.println(list); for (Release release : list) { System.out.println(release); } } //index.htmlaǩԭ public List<Release> getlist(int sort_id){ Object[] params = {sort_id}; return super.QueryList("SELECT id,title,sort_id,content,imgs from `release` WHERE sort_id=? ORDER BY id DESC", Release.class, params); } }
true
f04ed923a58ccc1f48a4bd57306a3f96e0f9e274
Java
Vignesh78199/Springmvc
/SpringMvcJava/src/main/java/com/spring/Controller/RemoveFriend.java
UTF-8
1,850
2.265625
2
[]
no_license
package com.spring.Controller; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; @Controller public class RemoveFriend { @RequestMapping(value="/RemoveFriend") @ResponseBody public void removeFriend(String user,String friend, Model model,HttpServletRequest request,HttpServletResponse response) throws ClassNotFoundException { Cookie[] cookies=request.getCookies(); for(Cookie temp:cookies) { if("userid".equals(temp.getName())) { user=temp.getValue(); } } int userid=Integer.parseInt(user); friend=request.getParameter("userid"); int friendid=Integer.parseInt(friend); System.out.println(userid+" "+friendid); try { Class.forName("com.mysql.jdbc.Driver"); Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/register","root","root"); String queryString = "UPDATE friends SET status='3' WHERE (userid=? AND friendid=?) OR (friendid=? AND userid=?)"; PreparedStatement ps=conn.prepareStatement(queryString); ps.setInt(1,userid); ps.setInt(2,friendid); ps.setInt(3,userid); ps.setInt(4,friendid); int result = ps.executeUpdate(); ps.close(); conn.close(); } catch (SQLException sql) { } } }
true
5ece94323a88340617e34377d9dd47dd8fd103c4
Java
jeshua2018/UIP-PROG2
/Tarea/Futbool/Jugador15.java
UTF-8
203
2.0625
2
[ "MIT" ]
permissive
package ArabeUnido; public class Jugador15 extends Equipo { public void mostrar() { System.out.println("posicion es: delantero Izquierdo"); System.out.println("Su dorsal es: "); } }
true
8e28e67bb66dc01ccf0807bb892949a39c16d589
Java
yue31313/cnblog
/src/com/cnblogs/android/MyRssActivity.java
GB18030
8,165
1.90625
2
[]
no_license
package com.cnblogs.android; import java.util.ArrayList; import java.util.List; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Resources; import android.os.AsyncTask; import android.os.Bundle; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnCreateContextMenuListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageButton; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.cnblogs.android.adapter.RssListAdapter; import com.cnblogs.android.dal.RssListDalHelper; import com.cnblogs.android.entity.RssList; /** * ҵĶ * @author walkingp * @date:2012-3-22 * */ public class MyRssActivity extends BaseMainActivity { List<RssList> listRss = new ArrayList<RssList>(); int pageIndex = 1;// ҳ ListView listView; private RssListAdapter adapter;// Դ ProgressBar bodyProgressBar;// ListViewؿ ImageButton btnRefresh;// ˢ°ť ProgressBar topProgressBar;// ذť TextView txtNoData;// û private ProgressDialog progressDialog; int lastItemPosition; Resources res;// Դ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.my_rss_layout); res = this.getResources(); InitialControls(); BindControls(); new PageTask().execute(); //ע㲥 UpdateListViewReceiver receiver=new UpdateListViewReceiver(); IntentFilter filter=new IntentFilter(); filter.addAction("android.cnblogs.com.update_rsslist"); registerReceiver(receiver, filter); } /** * ʼб */ private void InitialControls() { listView = (ListView) findViewById(R.id.rss_list); bodyProgressBar = (ProgressBar) findViewById(R.id.rssList_progressBar); btnRefresh = (ImageButton) findViewById(R.id.btn_refresh); topProgressBar = (ProgressBar) findViewById(R.id.rss_progressBar); txtNoData = (TextView) findViewById(R.id.txtNoData); } /** * ¼ */ private void BindControls() { // ת btnRefresh.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(); intent.setClass(MyRssActivity.this, RssCateActivity.class); startActivityForResult(intent, 0); } }); // ת listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { TextView tvTitle = (TextView) v .findViewById(R.id.rss_item_title); TextView tvUrl = (TextView) v.findViewById(R.id.rss_item_url); TextView tvIsCnblogs = (TextView) v .findViewById(R.id.rss_item_is_cnblogs); TextView tvAuthor = (TextView) v .findViewById(R.id.rss_item_author); String title = tvTitle.getText().toString(); String url = tvUrl.getText().toString(); boolean isCnblogs = tvIsCnblogs.getText().toString() .equals("1"); String author = tvAuthor.getText().toString(); Intent intent = new Intent(); Bundle bundle = new Bundle(); if (isCnblogs) {// ԰ intent.setClass(MyRssActivity.this, AuthorBlogActivity.class); bundle.putString("blogName", title); bundle.putString("author", author); } else { intent.setClass(MyRssActivity.this, RssItemsActivity.class); bundle.putString("title", title); bundle.putString("url", url); } lastItemPosition=listView.getSelectedItemPosition(); intent.putExtras(bundle); startActivity(intent); } }); // ¼ listView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() { @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.my_rss_contextmenu, menu); menu.setHeaderTitle(R.string.menu_bar_title); } }); } // ˵Ӧ @Override public boolean onContextItemSelected(MenuItem item) { int itemIndex = item.getItemId(); AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); View v = menuInfo.targetView; switch (itemIndex) { case R.id.menu_unrss://ȡ default: //ʾProgressDialog progressDialog = ProgressDialog.show(MyRssActivity.this, "˶Ŀ", "ڴ˶УԺ", true, false); TextView tvLink=(TextView)v.findViewById(R.id.rss_item_url); String link=tvLink.getText().toString(); RssListDalHelper helper=new RssListDalHelper(getApplicationContext()); try{ helper.Delete(link); Toast.makeText(getApplicationContext(), R.string.unrss_succ, Toast.LENGTH_SHORT).show(); }catch(Exception ex){ Toast.makeText(getApplicationContext(), R.string.unrss_fail, Toast.LENGTH_SHORT).show(); } progressDialog.dismiss(); // 㲥 TextView tvTitle = (TextView) v.findViewById(R.id.rss_item_title); TextView tvSummary = (TextView) v.findViewById(R.id.rss_item_summary); TextView tvId = (TextView) v.findViewById(R.id.rss_item_id); TextView tvIsCnblogs = (TextView) v.findViewById(R.id.rss_item_is_cnblogs); TextView tvAuthor = (TextView) v.findViewById(R.id.rss_item_author); Intent intent = new Intent(); Bundle bundle = new Bundle(); bundle.putStringArray("rsslist", new String[]{tvAuthor.getText().toString() ,tvSummary.getText().toString(), tvId.getText().toString(),tvTitle.getText().toString(), "",link, tvIsCnblogs.getText().toString() }); bundle.putBoolean("isrss", false); intent.putExtras(bundle); intent.setAction("android.cnblogs.com.update_rsslist"); sendBroadcast(intent); } return super.onContextItemSelected(item); } /** * * * @author walkingp * @date 2012-3-13 */ public class PageTask extends AsyncTask<String, Integer, List<RssList>> { @Override protected List<RssList> doInBackground(String... params) { RssListDalHelper helper = new RssListDalHelper( getApplicationContext()); return helper.GetRssList(); } @Override protected void onPostExecute(List<RssList> result) { if (listView.getCount() == 0) { bodyProgressBar.setVisibility(View.GONE); topProgressBar.setVisibility(View.GONE); btnRefresh.setVisibility(View.VISIBLE); } if (result == null || result.size() == 0) { txtNoData.setVisibility(View.VISIBLE); } else { adapter = new RssListAdapter(getApplicationContext(), result, listView, RssListAdapter.EnumSource.MyRss, adapter); listView.setAdapter(adapter); listView.setSelection(lastItemPosition); } } @Override protected void onPreExecute() { if (listView.getCount() == 0) { bodyProgressBar.setVisibility(View.VISIBLE); topProgressBar.setVisibility(View.VISIBLE); btnRefresh.setVisibility(View.GONE); } } } /** * ɾݣ㲥 * @author Administrator * */ public class UpdateListViewReceiver extends BroadcastReceiver{ @Override public void onReceive(Context content, Intent intent) { Bundle bundle=intent.getExtras(); String[] arr=bundle.getStringArray("rsslist"); if(arr!=null){ boolean isRss=bundle.getBoolean("isrss"); RssList entity=new RssList(); entity.SetAuthor(arr[0]); entity.SetDescription(arr[1]); entity.SetGuid(arr[2]); entity.SetTitle(arr[3]); entity.SetImage(arr[4]); entity.SetLink(arr[5]); entity.SetIsCnblogs(arr[6].equals("1")); if(isRss){ List<RssList> list=new ArrayList<RssList>(); list.add(entity); adapter.AddMoreData(list); }else{ adapter.RemoveData(entity); } } } } }
true
6b3057e2ac690f43fa3a870adea33a0436a8ec15
Java
gAmUssA/hazelcast-simulator
/simulator/src/main/java/com/hazelcast/simulator/protocol/connector/ClientConnector.java
UTF-8
4,200
2.15625
2
[ "Apache-2.0" ]
permissive
package com.hazelcast.simulator.protocol.connector; import com.hazelcast.simulator.protocol.core.MessageFuture; import com.hazelcast.simulator.protocol.core.Response; import com.hazelcast.simulator.protocol.core.SimulatorMessage; import com.hazelcast.simulator.protocol.handler.MessageEncoder; import com.hazelcast.simulator.protocol.handler.MessageResponseHandler; import com.hazelcast.simulator.protocol.handler.ResponseDecoder; import com.hazelcast.simulator.protocol.handler.SimulatorFrameDecoder; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import org.apache.log4j.Logger; import java.net.InetSocketAddress; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import static com.hazelcast.simulator.protocol.configuration.BootstrapConfiguration.DEFAULT_SHUTDOWN_QUIET_PERIOD; import static com.hazelcast.simulator.protocol.configuration.BootstrapConfiguration.DEFAULT_SHUTDOWN_TIMEOUT; import static com.hazelcast.simulator.protocol.core.SimulatorMessageCodec.getMessageId; import static java.lang.String.format; /** * Client connector for a Simulator Coordinator or Agent. */ public class ClientConnector { private static final Logger LOGGER = Logger.getLogger(ClientConnector.class); private final EventLoopGroup group = new NioEventLoopGroup(); private final ConcurrentMap<String, MessageFuture<Response>> futureMap = new ConcurrentHashMap<String, MessageFuture<Response>>(); private final int addressIndex; private final String host; private final int port; private Channel channel; public ClientConnector(int addressIndex, String host, int port) { this.addressIndex = addressIndex; this.host = host; this.port = port; } public void start() { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .remoteAddress(new InetSocketAddress(host, port)) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel channel) { ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast("frameDecoder", new SimulatorFrameDecoder()); pipeline.addLast("decoder", new ResponseDecoder()); pipeline.addLast("encoder", new MessageEncoder()); pipeline.addLast("handler", new MessageResponseHandler(addressIndex, futureMap)); } }); ChannelFuture future = bootstrap.connect().syncUninterruptibly(); channel = future.channel(); LOGGER.info(format("%s started and sends to %s", ClientConnector.class.getName(), channel.remoteAddress())); } public void shutdown() { group.shutdownGracefully(DEFAULT_SHUTDOWN_QUIET_PERIOD, DEFAULT_SHUTDOWN_TIMEOUT, TimeUnit.SECONDS).syncUninterruptibly(); } public Response write(SimulatorMessage message) throws Exception { return writeAsync(message).get(); } public Response write(ByteBuf buffer) throws Exception { return writeAsync(buffer).get(); } private MessageFuture<Response> writeAsync(SimulatorMessage message) { return writeAsync(message.getMessageId(), message); } private MessageFuture<Response> writeAsync(ByteBuf buffer) { return writeAsync(getMessageId(buffer), buffer); } private MessageFuture<Response> writeAsync(long messageId, Object msg) { String futureKey = messageId + "_" + addressIndex; MessageFuture<Response> future = MessageFuture.createInstance(futureMap, futureKey); channel.writeAndFlush(msg); return future; } }
true
78ba461a2d392bb4f49657e32b7c2db6808e7514
Java
MarcosGaitan/Proyecto
/Sistema_Restaurante/src/controladores/ControladorUnirMesas.java
UTF-8
2,480
2.515625
3
[]
no_license
package controladores; import java.io.IOException; import java.util.GregorianCalendar; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import datos.Mesa; import datos.MesaFinal; import negocio.MesaABM; import negocio.MesaFinalABM; @WebServlet("/ControladorUnirMesas") public class ControladorUnirMesas extends HttpServlet { protected void doGet(HttpServletRequest request , HttpServletResponse response ) throws ServletException, IOException { procesarPeticion( request , response ); } protected void doPost(HttpServletRequest request , HttpServletResponse response ) throws ServletException, IOException { procesarPeticion( request , response ); } private void procesarPeticion(HttpServletRequest request , HttpServletResponse response ) throws ServletException, IOException { response .setContentType( "text/html;charset=UTF-8" ); try { long idMesa1 = Long.parseLong(request.getParameter ( "mesa1" )); long idMesa2 = Long.parseLong(request.getParameter ( "mesa2" )); MesaFinalABM mesaFinalABM = new MesaFinalABM(); MesaABM mesaABM = new MesaABM(); MesaFinal mesaFinal = null; MesaFinal mesaFinal1 = mesaFinalABM.traerMesaFinalDesdeIdMesa(idMesa1); MesaFinal mesaFinal2 = mesaFinalABM.traerMesaFinalDesdeIdMesa(idMesa2); if (mesaFinal1 == null || mesaFinal2 == null){ if (mesaFinal1 != null){ mesaFinal = mesaFinal1; } else{ mesaFinal = mesaFinal2; } Mesa mesa1 = mesaABM.traerMesa(idMesa1); Mesa mesa2 = mesaABM.traerMesa(idMesa2); mesa1.ocupar(); mesa2.ocupar(); mesaABM.actualizarMesa(mesa1); mesaABM.actualizarMesa(mesa2); if(mesaFinal != null){ mesaFinal.agregarMesa(mesa1); mesaFinal.agregarMesa(mesa2); mesaFinalABM.actualizarMesaFinal(mesaFinal); }else{ mesaFinal = new MesaFinal(true); mesaFinal.agregarMesa(mesa1); mesaFinal.agregarMesa(mesa2); mesaFinalABM.agregarMesaFinal(mesaFinal); } } request .getRequestDispatcher( "/layoutMesas.jsp" ).forward( request ,response ); } catch (Exception e) { response.sendError(500, "ERROR: problemas al intentar unir las mesas. ." ); } } }
true
3bcec63ed14173647502730b1904e94c9d8fbc3f
Java
lixiaodong/sharemind
/sharemind/src/com/google/sharemind/dao/ArticleDaoImpl.java
UTF-8
849
2.203125
2
[]
no_license
package com.google.sharemind.dao; import javax.annotation.Resource; import javax.jdo.JDOHelper; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import com.google.appengine.api.datastore.Key; import com.google.sharemind.entity.Article; public class ArticleDaoImpl implements IArticleDao { private PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("transactions-optional"); @Override public void save(Article article) { PersistenceManager manager = pmf.getPersistenceManager(); try { manager.makePersistent(article); } finally { manager.close(); } } public Article getArticle(Key key) { PersistenceManager manager = pmf.getPersistenceManager(); Article article = manager.getObjectById(Article.class,key); return article; } }
true
bfb3c46bb8b463f4b308c1372cc393f5a714ff29
Java
LingWu0/JingDongJD
/app/src/main/java/com/example/xxsj/jingdongjd/view/activity/GuidePageActivity.java
UTF-8
2,324
2.375
2
[]
no_license
package com.example.xxsj.jingdongjd.view.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.view.View; import android.widget.TextView; import com.example.xxsj.jingdongjd.R; import java.util.Timer; import java.util.TimerTask; /** * Created by Administrator on 2017/9/6. */ public class GuidePageActivity extends Activity { private Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what==0){ int time = (int) msg.obj; tvTime.setText(time+"秒"); if (time==0){ Intent intent = new Intent(GuidePageActivity.this, MainActivity.class); startActivity(intent); finish(); } } } }; private TextView tvTime; private Timer timer; private TextView tvBreak; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_guide_page); tvTime = (TextView) findViewById(R.id.tv_time); tvBreak = (TextView) findViewById(R.id.tv_break); timer = new Timer(); timer.schedule(new TimerTask() { int time=5; @Override public void run() { if (time!=0){ time--; } Message message = handler.obtainMessage(); message.what=0; message.obj=time; handler.sendMessage(message); } },1000,1000); //设置跳过的监听事件 tvBreak.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(GuidePageActivity.this, MainActivity.class); startActivity(intent); finish(); } }); } @Override protected void onDestroy() { super.onDestroy(); if (timer!=null){ //关闭timer timer.cancel(); } } }
true
a1260d6ee7259f951948601c7ad335da34ddf851
Java
togaurav/encuestame
/encuestame-core/src/main/java/org/encuestame/core/exception/EnMeMappingExceptionResolver.java
UTF-8
2,630
1.890625
2
[ "Apache-2.0" ]
permissive
/* ************************************************************************************ * Copyright (C) 2001-2011 encuestame: system online surveys Copyright (C) 2011 * encuestame Development Team. * Licensed under the Apache Software License version 2.0 * 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.encuestame.core.exception; import java.io.PrintWriter; import java.io.StringWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.encuestame.core.filter.RequestSessionMap; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver; /** * Description. * @author Picado, Juan juanATencuestame.org * @since May 6, 2011 */ public class EnMeMappingExceptionResolver extends SimpleMappingExceptionResolver{ private Logger logger = Logger.getLogger(this.getClass()); /* * (non-Javadoc) * @see org.springframework.web.servlet.handler.SimpleMappingExceptionResolver#doResolveException(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception) */ @Override protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { String errorView = "redirect:/error"; if (ex.equals(DataAccessResourceFailureException.class)) { errorView = "redirect:/error"; } ModelAndView modelAndView = new ModelAndView(errorView); if (logger.isDebugEnabled()) { ex.printStackTrace(); } //set get parameters; //modelAndView.getModel().put(EXCEPTION_TYPE, ex.getClass()); //modelAndView.getModel().put("error", "fail"); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); ex.printStackTrace(pw); //System.out.println(sw.toString()); RequestSessionMap.setErrorMessage(ex.getMessage(), sw.toString()); return modelAndView; } }
true
ef838ce2c7e683b5bcff2108a9aaaef3036e8a88
Java
fucct/jwp-was
/src/main/java/exception/InvalidRequestBodyException.java
UTF-8
211
2.03125
2
[]
no_license
package exception; public class InvalidRequestBodyException extends HttpRequestException { public InvalidRequestBodyException() { super("지원하지 않는 request body 형식입니다."); } }
true
5e23f150ede6e72c755c4e96715dec1142e1b700
Java
moonlightBeautiful/springMVCStudy
/c00workingGet/src/main/java/com/ims/c01timedTask/c01xml/MyTimeTask.java
UTF-8
495
2.078125
2
[]
no_license
package com.ims.c01timedTask.c01xml; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; @Component public class MyTimeTask { /** * 定时器的任务方法不能有返回值,请求项目一次任意接口后回启动 */ public void cycleTask() { System.out.println("定时任务:" + new SimpleDateFormat("HH:mm:ss").format(new Date())); } }
true
dd70dd14ed188d722f05385320439e293e37ea40
Java
mormolis/zbtsm-location-notes
/app/src/main/java/com/example/georgioslamprakis/zboutsam/activities/AddCategories.java
UTF-8
4,982
2.28125
2
[]
no_license
package com.example.georgioslamprakis.zboutsam.activities; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AlertDialog; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import com.example.georgioslamprakis.zboutsam.R; import com.example.georgioslamprakis.zboutsam.ZbtsmApp; import com.example.georgioslamprakis.zboutsam.database.daos.CategoryDao; import com.example.georgioslamprakis.zboutsam.database.entities.Category; import com.example.georgioslamprakis.zboutsam.helpers.AccessDB; import java.util.ArrayList; import java.util.List; public class AddCategories extends ZbtsmActivity { EditText editText; Button button; ListView listView; CategoryDao categoryDao; final List<String> titles = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, titles);; categoryDao = ZbtsmApp.get().getDB().categoryDao(); setContentView(R.layout.activity_add_category); editText = findViewById(R.id.editTextAddCategory); button = findViewById(R.id.buttonAddCategory); listView = findViewById(R.id.listViewCategory); arrayAdapter.addAll(AccessDB.getAllCategories()); listView.setAdapter(arrayAdapter); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) { DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which){ case DialogInterface.BUTTON_POSITIVE: AccessDB.deleteCategoryByTitle(arrayAdapter.getItem(position)); arrayAdapter.clear(); arrayAdapter.addAll(AccessDB.getAllCategories()); break; case DialogInterface.BUTTON_NEGATIVE: break; } } }; AlertDialog.Builder builder = new AlertDialog.Builder(AddCategories.this); builder.setMessage("Delete this category? All Notes assosiated with this category will be removed as well.").setPositiveButton("Yes", dialogClickListener) .setNegativeButton("No", dialogClickListener).show(); return true; } }); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String categoryTitleSelectedFromList = listView.getItemAtPosition(position).toString(); Intent intent = new Intent(AddCategories.this, NotesList.class); Bundle b = new Bundle(); b.putInt("id", AccessDB.findCategoryIdByCategoryTitle(categoryTitleSelectedFromList)); intent.putExtras(b); startActivity(intent); } }); button.setOnClickListener( new View.OnClickListener() { String newCategory; @Override public void onClick(View v) { newCategory = editText.getText().toString(); if (!newCategory.equals("") && !titles.contains(newCategory)){ insertItem(newCategory); } else { displayToastMessage(newCategory); } editText.setText(""); } }); } private void insertItem(final String categoryTitle){ final Category category = new Category(); category.setTitle(categoryTitle); titles.add(categoryTitle); new Thread(new Runnable() { @Override public void run() { Log.i("insertItem Thread", "I am in!!!!!!!!"); categoryDao.insert(category); } }).start(); } private void displayToastMessage(String categoryTitle){ Context context = getApplicationContext(); CharSequence text; text = categoryTitle.equals("") ? "you cannot give empty category" : categoryTitle+ " already exists!"; Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT); toast.show(); } }
true
edc0f7ae0b076c7efa58f36f725c99722792e9ad
Java
srolemberg/rss-reader
/Simple RSS Reader/src/br/com/samirrolemberg/simplerssreader/adapter/ListarPostsFragmentAdapter.java
UTF-8
1,900
2.359375
2
[]
no_license
package br.com.samirrolemberg.simplerssreader.adapter; import java.util.List; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import br.com.samirrolemberg.simplerssreader.R; import br.com.samirrolemberg.simplerssreader.model.Post; import br.com.samirrolemberg.simplerssreader.u.U; public class ListarPostsFragmentAdapter extends BaseAdapter{ final ListView listView; final List<Post> posts; public ListarPostsFragmentAdapter(List<Post> posts, ListView listView) { this.posts = posts; this.listView = listView; } @Override public int getCount() { return posts.size(); } @Override public Object getItem(int position) { return posts.get(position); } @Override public long getItemId(int position) { return posts.get(position).getIdPost(); } @Override public View getView(int position, View convertView, ViewGroup parent) { //View view = activity.getLayoutInflater().inflate(R.layout.activity_lista_feeds_principal, null); View v = View.inflate(listView.getContext(), R.layout.fragment_list_item_listar_posts, null); // TextView titulo = (TextView) v.findViewById(R.id.titulo__exibir_post_fragment_list_item); TextView data = (TextView) v.findViewById(R.id.data__exibir_post_fragment_list_item); TextView autor = (TextView) v.findViewById(R.id.autor__exibir_post_fragment_list_item); titulo.setText(posts.get(position).getTitulo()); //CharSequence dateFormat = DateFormat.format("HH:mm:ss dd/MM/yyyy", posts.get(position).getData_publicacao()); //data.setText(posts.get(position).getData_publicacao().toString()); data.setText(U.time_24_date_mask(posts.get(position).getData_publicacao(), v.getContext())); autor.setText(posts.get(position).getAutor()); return v; } }
true
121d3f16c3babbd6900d8898f616bd88627de5db
Java
mpradeep1994/Personal-medical-Application
/code/src/parser/dom_sax/expensesSAX.java
UTF-8
4,761
2.5
2
[]
no_license
package dom_sax; import java.io.File; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class expensesSAX { public static void main(String[] args){ try { File inputFile = new File("expenses.xml"); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); UserHandlerexpenses userhandler = new UserHandlerexpenses(); saxParser.parse(inputFile, userhandler); } catch (Exception e) { e.printStackTrace(); } } } class UserHandlerexpenses extends DefaultHandler{ boolean ExpenseID = false; boolean EmployeeID = false; boolean ExpenseType = false; boolean PurposeofExpense = false; boolean AmountSpent = false; boolean Description = false; boolean DatePurchased = false; boolean DateSubmitted = false; boolean AdvanceAmount = false; boolean PaymentMethod = false; public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("expense")) { } else if (qName.equalsIgnoreCase("expense1")) { } else if(qName.equalsIgnoreCase("ExpenseID")){ ExpenseID = true; } else if (qName.equalsIgnoreCase("EmployeeID")) { EmployeeID = true; } else if (qName.equalsIgnoreCase("ExpenseType")) { ExpenseType = true; } else if (qName.equalsIgnoreCase("PurposeofExpense")) { PurposeofExpense = true; } else if (qName.equalsIgnoreCase("AmountSpent")) { AmountSpent = true; } else if (qName.equalsIgnoreCase("Description")) { Description = true; } else if (qName.equalsIgnoreCase("DatePurchased")) { DatePurchased = true; } else if (qName.equalsIgnoreCase("DateSubmitted")) { DateSubmitted = true; } else if (qName.equalsIgnoreCase("AdvanceAmount")) { AdvanceAmount = true; } else if (qName.equalsIgnoreCase("PaymentMethod")) { PaymentMethod = true; } else if (qName.equalsIgnoreCase("expense1")) { } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equalsIgnoreCase("expense")) { System.out.println("End Element :" + qName); System.out.println("\n\n"); } } @Override public void characters(char ch[], int start, int length) throws SAXException { if (ExpenseID) { System.out.println("ExpenseID: " + new String(ch, start, length)); ExpenseID = false; } else if (EmployeeID) { System.out.println("EmployeeID: " + new String(ch, start, length)); EmployeeID = false; } else if (ExpenseType) { System.out.println("ExpenseType: " + new String(ch, start, length)); ExpenseType = false; } else if (PurposeofExpense) { System.out.println("PurposeofExpense: " + new String(ch, start, length)); PurposeofExpense = false; } else if (PurposeofExpense) { System.out.println("PurposeofExpense: " + new String(ch, start, length)); PurposeofExpense = false; } else if (Description) { System.out.println("Description: " + new String(ch, start, length)); Description = false; } else if (DatePurchased) { System.out.println("DatePurchased: " + new String(ch, start, length)); DatePurchased = false; } else if (DateSubmitted) { System.out.println("DateSubmitted: " + new String(ch, start, length)); DateSubmitted = false; } else if (AdvanceAmount) { System.out.println("AdvanceAmount: " + new String(ch, start, length)); AdvanceAmount = false; } else if (PaymentMethod) { System.out.println("PaymentMethod: " + new String(ch, start, length)); PaymentMethod = false; } } }
true
83f9f0714968df23e0ee698614b222cda041bbb9
Java
notMoveICome/backApp
/src/main/java/com/hxlc/backstageapp/service/impl/AppNewsServiceImpl.java
UTF-8
3,678
2.171875
2
[]
no_license
package com.hxlc.backstageapp.service.impl; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.hxlc.backstageapp.mapper.AppNewsMapper; import com.hxlc.backstageapp.pojo.AppNews; import com.hxlc.backstageapp.service.AppNewsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.sql.Date; import java.util.List; @Service public class AppNewsServiceImpl implements AppNewsService{ @Autowired private AppNewsMapper appNewsMapper; @Value("${fileDir.appNews}") private String appNews; @Override public List<AppNews> findNewsList() { return appNewsMapper.selectList(new EntityWrapper<AppNews>().orderBy("news_time",true)); } @Override public List<AppNews> queryNewsByTitle(String title) { return appNewsMapper.selectList(new EntityWrapper<AppNews>().like("title",title)); } @Transactional @Override public Integer addNews(AppNews news,MultipartFile pictureFile) { try { String picName = pictureFile.getOriginalFilename(); InputStream is = pictureFile.getInputStream(); String fileName = System.currentTimeMillis() + picName.substring(picName.lastIndexOf(".")); FileOutputStream fos = new FileOutputStream(appNews + "/" + fileName); int length; byte[] b = new byte[1024]; while ((length = is.read(b)) > -1){ fos.write(b,0,length); } fos.close(); is.close(); news.setPicture(appNews.substring(appNews.lastIndexOf("/"),appNews.length()) + "/" + fileName); news.setNewsTime(new Date(System.currentTimeMillis())); Integer row = appNewsMapper.insert(news); return row; } catch (IOException e) { e.printStackTrace(); } return null; } @Transactional @Override public Integer deleteNewsById(Integer newsId) { return appNewsMapper.deleteById(newsId); } @Transactional @Override public Integer editNews(AppNews news, MultipartFile pictureFile) { try { String picName = pictureFile.getOriginalFilename(); if ("".equals(picName)){ return appNewsMapper.updateById(news); } InputStream is = pictureFile.getInputStream(); String fileName = System.currentTimeMillis() + picName.substring(picName.lastIndexOf(".")); FileOutputStream fos = new FileOutputStream(appNews + "/" + fileName); int length; byte[] b = new byte[1024]; while ((length = is.read(b)) > -1){ fos.write(b,0,length); } fos.close(); is.close(); news.setPicture(appNews.substring(appNews.lastIndexOf("/"),appNews.length()) + "/" + fileName); // news.setNewsTime(new Date(System.currentTimeMillis())); Integer row = appNewsMapper.updateById(news); return row; } catch (IOException e) { e.printStackTrace(); } return null; } @Override public List<AppNews> getRecentNews() { Date date = new Date(System.currentTimeMillis()); return appNewsMapper.selectList(new EntityWrapper<AppNews>().eq("news_time",date)); } }
true
4a72c66dcfeb072a240bc97d0023c271057df5b8
Java
pablobecerra94/Algoritmo-de-calidad
/src/com/unlam/analisis/algoritmo/vistas/SeguridadDeAccesoView.java
UTF-8
3,902
2.296875
2
[]
no_license
package com.unlam.analisis.algoritmo.vistas; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextArea; import javax.swing.border.EmptyBorder; public class SeguridadDeAccesoView extends JFrame { /** * */ private static final long serialVersionUID = 1L; private JPanel contentPane; private final ButtonGroup buttonGroup = new ButtonGroup(); private String opcionElegida; ExactitudView exactitud; private boolean ponderada=true; /** * Create the frame. */ public SeguridadDeAccesoView() { setTitle("Algoritmo de calidad"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JRadioButton rdbtnBueno = new JRadioButton("Bueno"); rdbtnBueno.setActionCommand("Bueno"); rdbtnBueno.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { seleccionar(); } }); buttonGroup.add(rdbtnBueno); rdbtnBueno.setBounds(44, 93, 109, 23); contentPane.add(rdbtnBueno); JRadioButton rdbtnMalo = new JRadioButton("Malo"); rdbtnMalo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { seleccionar(); } }); rdbtnMalo.setActionCommand("Malo"); buttonGroup.add(rdbtnMalo); rdbtnMalo.setBounds(44, 145, 109, 23); contentPane.add(rdbtnMalo); JRadioButton rdbtnRegular = new JRadioButton("Regular"); rdbtnRegular.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { seleccionar(); } }); rdbtnRegular.setActionCommand("Regular"); buttonGroup.add(rdbtnRegular); rdbtnRegular.setBounds(44, 119, 109, 23); contentPane.add(rdbtnRegular); JLabel lblFuncionalidad = new JLabel("Seguridad"); lblFuncionalidad.setFont(new Font("Tahoma", Font.PLAIN, 18)); lblFuncionalidad.setBounds(153, 11, 173, 48); contentPane.add(lblFuncionalidad); JTextArea txtrExplicacion = new JTextArea(); txtrExplicacion.setBackground(Color.LIGHT_GRAY); txtrExplicacion.setText("Integridad y confidencialidad \nde los datos"); txtrExplicacion.setEditable(false); txtrExplicacion.setBounds(216, 76, 191, 109); contentPane.add(txtrExplicacion); JButton btnSiguiente = new JButton("Siguiente"); btnSiguiente.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { mostrarSiguiente(); } }); btnSiguiente.setBounds(269, 212, 89, 23); contentPane.add(btnSiguiente); JButton btnSalir = new JButton("Salir"); btnSalir.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { cerrar(); } }); btnSalir.setBounds(56, 212, 89, 23); contentPane.add(btnSalir); } protected void mostrarSiguiente() { if(buttonGroup.getSelection()!=null){ this.setVisible(false); exactitud.setVisible(true); } else{ JOptionPane.showMessageDialog(null, "Error! Debe seleccionar una opción","Error",JOptionPane.ERROR_MESSAGE); } } protected void seleccionar() { setOpcionElegida(buttonGroup.getSelection().getActionCommand()); } protected void cerrar() { this.dispose(); } public String getOpcionElegida() { return opcionElegida; } public void setOpcionElegida(String opcionElegida) { this.opcionElegida = opcionElegida; } public void setViews(ExactitudView eficiencia2) { this.exactitud=eficiencia2; } public boolean isPonderada() { return ponderada; } public void setPonderada(boolean ponderada) { this.ponderada = ponderada; } }
true
51ee4ff4130c243e5b62fe326b3869db900610a1
Java
didrocks/timetosmile
/app/src/main/java/fr/teamrocks/timetosmile/entities/SmileData.java
UTF-8
2,002
3.28125
3
[]
no_license
package fr.teamrocks.timetosmile.entities; import android.os.SystemClock; import java.util.Date; import fr.teamrocks.timetosmile.utils.TimeFormat; /** * Smile Data storing current smile stats for a given day */ public class SmileData extends TimeFormat { private static final String TAG = "SmileData"; public static final long TARGETSMILINGTIME = 60*1000; private final Date mDay; // Length of smiling time in milliseconds private long mSmilingDuration; // Last start smiling time in ms private long mCurrentSmileStartTime; private boolean isSmiling = false; /** * Create a brand new SmileData for today */ public SmileData() { this(new Date(), 0); } /** * Restore a SmileData with a specific day and stored smilingTime * * @param day the day this Smile Data is attached to * @param smilingDuration the length of the smiling in ms for that day. */ public SmileData(Date day, long smilingDuration) { mDay = day; mSmilingDuration = smilingDuration; } /** * Start the timer clock if it's a new smile */ public void Smile() { if (isSmiling) return; isSmiling = true; mCurrentSmileStartTime = SystemClock.elapsedRealtime(); } /** * Stop the timer if the person isn't smiling anymore */ public void NoSmile() { if (!isSmiling) return; isSmiling = false; mSmilingDuration += SystemClock.elapsedRealtime() - mCurrentSmileStartTime; } /** * @return current smiling duration for that day */ public long getmSmilingDuration() { if (isSmiling) return mSmilingDuration + SystemClock.elapsedRealtime() - mCurrentSmileStartTime; else return mSmilingDuration; } /** * @return chain to the current smiling duration */ protected long getTime() { return getmSmilingDuration(); } }
true
4f632b3e8f3112fffe6ef394f8ed4fcbf9ea6615
Java
Nomad95/to-do-list
/src/main/java/pl/pollub/api/commons/factory/GeneralFactory.java
UTF-8
538
2.390625
2
[]
no_license
package pl.pollub.api.commons.factory; import pl.pollub.api.collaborators.model.Collaboration; import pl.pollub.api.collaborators.model.User; import pl.pollub.api.todo.model.Todo; public class GeneralFactory { public static Todo createTodo(Integer id, String content){ return new Todo(id,content); } public static User createNewUser(Integer id, String name){ return new User(id,name); } public static Collaboration createNewCollaboration(Integer id){ return new Collaboration(id); } }
true
76c5ac3077d2874e4a48b9b8b363ed3a440e1044
Java
jerome-tan-git/kibana
/src/com/inv/parser/TestRedis.java
UTF-8
4,119
2.453125
2
[]
no_license
package com.inv.parser; import java.util.List; import redis.clients.jedis.Jedis; public class TestRedis { public static void main(String[] args) throws InterruptedException { // SimpleDateFormat sdf = new // SimpleDateFormat("yyyy-MM-dd HH:mm:ss [Z]"); // String json = "{message:'Monitor phone works well at:\n "+ // sdf.format(new // Date())+"',phoneNumber:'18501755307',property:'property',type:'sms-info'}"; // // String a = new String(base64.encode(json.getBytes())); // // System.out.println(a); // // // Jedis jedis = new Jedis("192.168.103.18"); // jedis.auth("123456redis"); // jedis.rpush("sendQueue", json); // jedis.sadd("validPhone", "13671605961"); // System.out.println(jedis.smembers("validPhone")); // jedis.lpush("validPhone", "13671605961"); // jedis.lpush("validPhone", "13671605961"); // // jedis.lpush("access:123456789", System.currentTimeMillis()+""); // // jedis.lpush("access:123456789", System.currentTimeMillis()+""); // jedis.ltrim("access:123456789", 0, 2); // System.out.println(jedis.lrange("access:1", 0, 2)); // jedis.sadd("validPhone", "1"); // jedis.sadd("validPhone", "2"); // jedis.sadd("validPhone", "3"); // System.out.println(jedis.sismember("validPhone", "5")); // jedis.incr("temp:123"); // System.out.println(jedis.get("temp:1231")); // jedis.decr("temp:123"); // System.out.println(jedis.get("temp:123")); // String a = jedis.lpop("receiveQueue"); // System.out.println(a); // while (true) { // try { // // Jedis jedis = new Jedis("192.168.103.18"); // // jedis.auth("123456redis"); // System.out.println("Read data!"); // String value = jedis.lpop("toSend"); // if (value == null) { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // } // } else { // // MessageObject o = JSON.parseObject(value, MessageObject.class); // System.out.println(value); // } // } catch (Exception e) { // if (e instanceof redis.clients.jedis.exceptions.JedisDataException) // { // jedis.del("toSend"); // System.out.println("delete wrong data"); // continue; // } // try { // Thread.sleep(5000); // } catch (InterruptedException e1) { // e1.printStackTrace(); // } // } // } // MessageObject o = JSON.parseObject(json, MessageObject.class); // System.out.println(o); // jedis.set("testJson", json); // String value = jedis.get("testJson"); // // JSO // // //System.out.println(o.getPhoneNumber()); // System.out.println(value); Jedis jedis1 = new Jedis("192.168.145.238"); for (;;) { for (String a : jedis1.keys("*")) { try { System.out.println(a + " ==> " + jedis1.llen(a)); if(a.equals("mysql_slowlog")) { System.out.println(jedis1.lpop(a)); } } catch(Exception e) { e.getMessage(); } if(a.indexOf("inv_binlog")!=-1) { try { System.out.println(jedis1.del("inv_binlog")); } catch(Exception e) { e.getMessage(); } } } } // System.out.println(jedis1.llen("inv_binlog")); // jedis1.del(new String[]{"inv_binlog"}); // jedis1.ltrim("inv_binlog", 0, 1); // jedis1.rpoplpush("inv_binlog", ""); // jedis1.ltrim("inv_binlog", 0, 1000000); // // jedis1.del(new String[] { "inv_mysql_master" }); // while (true) { // // try // // { // // System.out.println(new Date().toLocaleString()+ ":"+ // // jedis1.llen("cmus_apache")); // List<String> values = jedis1.blpop(1, // new String[] { "inv_mysql_master" }); // if (values != null) { // String _log = (values.get(1)); // System.out.println(_log); // // String host = _log.substring(0, _log.indexOf(' ')); // // System.out.println(host + " | " + values.get(1)); // } // if(a.indexOf('[')==-1) // { // System.out.println(values); // } // else // { // System.out.println("aaa" + a); // } // } // catch(Exception e) // { // // } // Thread.sleep(1000); // } } }
true
ea6b82a91e2a09faf437cc2626cbffc456f496c8
Java
DreamFlyC/yimi
/src/com/lw/traceabilitytype/entity/TraceabilityType.java
UTF-8
820
2.15625
2
[]
no_license
package com.lw.traceabilitytype.entity; import java.io.Serializable; public class TraceabilityType implements Serializable{ private int id; private String name; private int parent_id; private Integer point_id; private Integer type_id; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getParent_id() { return parent_id; } public void setParent_id(int parent_id) { this.parent_id = parent_id; } public Integer getPoint_id() { return point_id; } public void setPoint_id(Integer point_id) { this.point_id = point_id; } public Integer getType_id() { return type_id; } public void setType_id(Integer type_id) { this.type_id = type_id; } }
true
c05e3b87ec09b6ba462f71ec42adbde41be9e2fd
Java
mraz811/PaRaPaRa
/src/main/java/com/happy/para/model/Notice_IDao.java
UTF-8
955
1.898438
2
[]
no_license
package com.happy.para.model; import java.util.List; import com.happy.para.dto.NoticeDto; import com.happy.para.dto.PagingDto; import com.happy.para.dto.ReplyDto; public interface Notice_IDao { // Notice // 공지사항 등록 public boolean noticeWrite(NoticeDto dto); // 공지사항 수정 public boolean noticeModify(NoticeDto dto); // 공지사항 삭제 public boolean noticeDelete(String notice_seq); // 공지사항 조회(Paging) public List<NoticeDto> noticeList(PagingDto dto); // 공지사항 조회(Paging 글 목록 Total) public int noticeListRow(); // 공지사항 상세 조회 public NoticeDto noticeDetail(String notice_seq); // Notice_reply // 공지사항 댓글 조회 public List<ReplyDto> replyList(String notice_seq); // 공지사항 댓글 등록 public boolean replyWrite(ReplyDto dto); // 공지사항 댓글 삭제 public boolean replyDelete(String reply_seq); }
true
7fb51bcb5edf9fe12630941170da5c8467e343c8
Java
anjali628/Pass-data-from-one-activity-to-another
/app/src/main/java/com/example/passdatafromoneactivitytoanotheractivity/MainActivity.java
UTF-8
1,181
2.21875
2
[]
no_license
package com.example.passdatafromoneactivitytoanotheractivity; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView title; private EditText provideinput; private Button transferdata; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); title=(TextView) findViewById(R.id.textview); provideinput=(EditText) findViewById(R.id.provideinput); transferdata=(Button)findViewById(R.id.button); transferdata.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String data=provideinput.getText().toString(); Intent intent=new Intent(MainActivity.this,MainActivity2.class); intent.putExtra("data",data); startActivity(intent); } }); } }
true
9895db195ed2dc006a21891ed787106f6fd62469
Java
sluizin/Gradle-luckdraw
/src/main/java/com/maqiao/was/luckActivity/web/ProjectActivityClass.java
UTF-8
9,035
2.34375
2
[]
no_license
/** * */ package com.maqiao.was.luckActivity.web; import java.io.Serializable; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; /** * 抽奖专题项目类<br> * 包括基础总数、显示总数、Targetid、开始与结束日期、奖项等<br> * 抽中奖后发送到邮箱<br> * @author Sunjian * @version 1.0 * @since jdk1.7 */ public final class ProjectActivityClass implements Serializable { private static final long serialVersionUID = 1L; /** 项目名称 */ String projectName = ""; /** 抽奖名称 */ String title = "抽奖活动"; /** 设置基础总数 */ int sortBase = 1700; /** 设置显示总数 */ int showListMax = 40; /** 设置项目编号 targetid 用于入库 */ int targetid = 0; /** 设置活动开始日期 */ String dateStart = "2016-06-26"; /** 设置活动结束日期 */ String dateEnd = "2016-06-26"; /** 允许随机中奖人数 */ boolean rndAllow = true; /** 设置随机中奖人员的日期,当前日期的前几天 */ int rndListBeforeDay = 3; /** 设置中奖项目 */ List<ProjectActivityItem> itemList = new ArrayList<ProjectActivityItem>(8); /** 设置库币消息代码 */ String msgCoinCode = ""; /** 设置实物消息代码 */ String msgGoodsCode = ""; /** 设置溢出次数 */ int overflowTimes = 0; /** 设置是否开通下线状态1 */ boolean openSubCount1 = false; /** 设置是否开通下线状态2 */ boolean openSubCount2 = false; /** 设置是否开通项目总数的记录 */ boolean openProjectAmount = false; /** 会员资格对象 */ ProjectActivityQualifications qualifications = new ProjectActivityQualifications(); /** 抽中奖后向管理员发送邮件 */ ProjectActivityEmailService emailService = new ProjectActivityEmailService(); /** 抽中奖后向中奖会员发送邮件 */ ProjectActivityEmailMember emailMember = new ProjectActivityEmailMember(); /** * 判断会员注意日期是否在活动期间 * @param addTime String "2016-06-26" * @return boolean */ final boolean isNewMember(final String addTime) { return UtilsDate.dateBetweenIn(addTime, dateStart, dateEnd, true); } /** * 得到中文日期<br> * datetype:0 dateStart<br> * datetype:1 dateEnd<br> * @param datetype int * @return String */ final String getDateChn(final int datetype) { Date date2 = getDate(datetype); if (date2 == null) return ""; Calendar c1 = Calendar.getInstance(); c1.setTime(date2); SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日"); return format.format(c1.getTime()); } /** * 得到日期型日期 2010-01-01<br> * datetype:0 dateStart<br> * datetype:1 dateEnd<br> * @param datetype int * @return Date */ final Date getDate(final int datetype) { String date = (datetype == 0 ? this.dateStart : this.dateEnd); try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date datenew = sdf.parse(date); return datenew; } catch (ParseException e) { LuckActivityLogger.logger.error(e); } return null; } /** * 判断是否发布站内信--库币 * @return boolean */ public final boolean ismsgCoin() { if (msgCoinCode == null || msgCoinCode.length() == 0) return false; return true; } /** * 判断是否发布站内信--实物 * @return boolean */ public final boolean ismsgGoods() { if (msgGoodsCode == null || msgGoodsCode.length() == 0) return false; return true; } /** * 判断项目活动日期之间多少天 * @return int */ public final int daysBetween() { return UtilsDate.daysBetween(this.dateStart, this.dateEnd); } /** * 得到项目的Li 的template<br> * templatetime:几分钟之前<br> * templatetitle:获得中奖的名称<br> * @param targetid int * @return String */ public final String getUITemplateList(int targetid) { if (targetid == 5) { return "<li class='clearfix'><span class='date'>templatetime前</span><span class='huojiang'>templatetitle</span></li>"; } return ""; } public final String getProjectName() { return projectName; } public final void setProjectName(String projectName) { this.projectName = projectName; } public final String getTitle() { return title; } public final void setTitle(String title) { this.title = title; } public final int getSortBase() { return sortBase; } public final void setSortBase(int sortBase) { this.sortBase = sortBase; } public final int getShowListMax() { return showListMax; } public final void setShowListMax(int showListMax) { this.showListMax = showListMax; } public final int getTargetid() { return targetid; } public final void setTargetid(int targetid) { this.targetid = targetid; } public final String getDateStart() { return dateStart; } public final void setDateStart(String dateStart) { this.dateStart = dateStart; } public final String getDateEnd() { return dateEnd; } public final void setDateEnd(String dateEnd) { this.dateEnd = dateEnd; } public final boolean isRndAllow() { return rndAllow; } public final void setRndAllow(boolean rndAllow) { this.rndAllow = rndAllow; } public final int getRndListBeforeDay() { return rndListBeforeDay; } public final void setRndListBeforeDay(int rndListBeforeDay) { this.rndListBeforeDay = rndListBeforeDay; } public final List<ProjectActivityItem> getItemList() { return itemList; } public final void setItemList(List<ProjectActivityItem> itemList) { this.itemList = itemList; } public final String getMsgCoinCode() { return msgCoinCode; } public final void setMsgCoinCode(String msgCoinCode) { this.msgCoinCode = msgCoinCode; } public final String getMsgGoodsCode() { return msgGoodsCode; } public final void setMsgGoodsCode(String msgGoodsCode) { this.msgGoodsCode = msgGoodsCode; } public final int getOverflowTimes() { return overflowTimes; } public final void setOverflowTimes(int overflowTimes) { this.overflowTimes = overflowTimes; } public final ProjectActivityQualifications getQualifications() { return qualifications; } public final void setQualifications(ProjectActivityQualifications qualifications) { this.qualifications = qualifications; } public final ProjectActivityEmailService getEmailService() { return emailService; } public final void setEmailService(ProjectActivityEmailService emailService) { this.emailService = emailService; } public final ProjectActivityEmailMember getEmailMember() { return emailMember; } public final void setEmailMember(ProjectActivityEmailMember emailMember) { this.emailMember = emailMember; } public final boolean isOpenSubCount1() { return openSubCount1; } public final void setOpenSubCount1(boolean openSubCount1) { this.openSubCount1 = openSubCount1; } public final boolean isOpenSubCount2() { return openSubCount2; } public final void setOpenSubCount2(boolean openSubCount2) { this.openSubCount2 = openSubCount2; } public final boolean isOpenProjectAmount() { return openProjectAmount; } public final void setOpenProjectAmount(boolean openProjectAmount) { this.openProjectAmount = openProjectAmount; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("ProjectActivityClass [projectName="); builder.append(projectName); builder.append(", title="); builder.append(title); builder.append(", sortBase="); builder.append(sortBase); builder.append(", showListMax="); builder.append(showListMax); builder.append(", targetid="); builder.append(targetid); builder.append(", dateStart="); builder.append(dateStart); builder.append(", dateEnd="); builder.append(dateEnd); builder.append(", rndAllow="); builder.append(rndAllow); builder.append(", rndListBeforeDay="); builder.append(rndListBeforeDay); builder.append(", itemList="); builder.append(itemList); builder.append(", msgCoinCode="); builder.append(msgCoinCode); builder.append(", msgGoodsCode="); builder.append(msgGoodsCode); builder.append(", overflowTimes="); builder.append(overflowTimes); builder.append(", openSubCount1="); builder.append(openSubCount1); builder.append(", openSubCount2="); builder.append(openSubCount2); builder.append(", openProjectAmount="); builder.append(openProjectAmount); builder.append(", qualifications="); builder.append(qualifications); builder.append(", emailService="); builder.append(emailService); builder.append(", emailMember="); builder.append(emailMember); builder.append("]"); return builder.toString(); } }
true
43d18a1712dc1dea3f5288b6e02e76ce87cf55ba
Java
raniless/AlgorithmStudy
/src/question/leetcode/easy/range101to200/LP160.java
UTF-8
1,168
3.203125
3
[]
no_license
package question.leetcode.easy.range101to200; import question.leetcode.util.ListNode; import java.util.HashSet; import java.util.Set; // Intersection of Two Linked Lists // - https://leetcode.com/problems/intersection-of-two-linked-lists/ public class LP160 { public static void main(String[] args) { } //Two Pointer public ListNode getIntersectionNode(ListNode headA, ListNode headB) { ListNode pA = headA; ListNode pB = headB; while (pA != pB) { pA = (pA != null) ? pA.next : headB; pB = (pB != null) ? pB.next : headA; } return pA; } /* //Hash Set public ListNode getIntersectionNode(ListNode headA, ListNode headB) { Set<ListNode> checkSet = new HashSet<>(); ListNode currNode = headA; while(currNode != null) { checkSet.add(currNode); currNode = currNode.next; } currNode = headB; while(currNode != null) { if(checkSet.contains(currNode)) { return currNode; } currNode = currNode.next; } return null; } */ }
true
4e13fe1fb5c163e3b81fa15802982118ef7cf9c8
Java
kezabrenda/newsPortal
/src/test/java/models/DepartmentNewsTest.java
UTF-8
841
2.421875
2
[ "MIT" ]
permissive
package models; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class DepartmentNewsTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void getDepartment_id() { DepartmentNews testDepartmentNews = setupDepartmentNews(); assertEquals(1, testDepartmentNews.getDepartment_id()); } private DepartmentNews setupDepartmentNews() { return new DepartmentNews("Work Life", "Brenda","Enjoyyyyy",1,1); } @Test public void setDepartment_id() { DepartmentNews testDepartmentNews = setupDepartmentNews(); testDepartmentNews.setDepartment_id(10); assertNotEquals(1, testDepartmentNews.getDepartment_id()); } }
true
b07063976387ef8b2a066b7a4cac1ceb957ead57
Java
zhanght86/HSBC20171018
/LIS/sinosoft-parents/lis-business/src/main/java/com/sinosoft/lis/taskservice/taskinstance/RnewPolAutoTMThread.java
UTF-8
10,698
1.632813
2
[]
no_license
package com.sinosoft.lis.taskservice.taskinstance; import org.apache.log4j.Logger; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Vector; import com.sinosoft.lis.db.LCContDB; import com.sinosoft.lis.db.LDSysVarDB; import com.sinosoft.lis.db.LMEdorCalDB; import com.sinosoft.lis.operfee.IndiDueFeePartQuery; import com.sinosoft.lis.operfee.RnDealBL; import com.sinosoft.lis.pubfun.Calculator; import com.sinosoft.lis.pubfun.GlobalInput; import com.sinosoft.lis.pubfun.MMap; import com.sinosoft.lis.pubfun.PubConcurrencyLock; import com.sinosoft.lis.pubfun.PubFun; import com.sinosoft.lis.pubfun.PubSubmit; import com.sinosoft.lis.schema.LCContSchema; import com.sinosoft.lis.schema.LPEdorAppSchema; import com.sinosoft.lis.schema.LWMissionSchema; import com.sinosoft.lis.taskservice.TaskThread; import com.sinosoft.lis.vschema.LCContSet; import com.sinosoft.lis.vschema.LMEdorCalSet; import com.sinosoft.lis.vschema.LWMissionSet; import com.sinosoft.service.ServiceA; import com.sinosoft.utility.CError; import com.sinosoft.utility.CErrors; import com.sinosoft.utility.ExeSQL; import com.sinosoft.utility.RSWrapper; import com.sinosoft.utility.SQLwithBindVariables; import com.sinosoft.utility.SSRS; import com.sinosoft.utility.TransferData; import com.sinosoft.utility.VData; import com.sinosoft.workflow.bq.EdorWorkFlowUI; /** * * 续期续保抽档批处理 -入口 * **/ public class RnewPolAutoTMThread extends TaskThread { /** 公共锁定号码类 */ private PubConcurrencyLock mPubLock = new PubConcurrencyLock(); private static Logger logger = Logger.getLogger(RnewPolAutoTMThread.class); public CErrors mErrors = new CErrors(); private GlobalInput tG = new GlobalInput(); private String mCurrentDate = PubFun.getCurrentDate(); public RnewPolAutoTMThread() { } public boolean dealMain() { /* 业务处理逻辑 */ logger.debug("进入业务逻辑处理!--续期续保抽档批处理" + PubFun.getCurrentDate() + "**" + PubFun.getCurrentTime()); tG.ComCode = "86"; tG.Operator = "AUTO"; tG.ManageCom = "86"; //日志监控,初始化 tG.LogID[0]="TASK"+(String)mParameters.get("TaskCode"); tG.LogID[1]=(String)mParameters.get("SerialNo"); PubFun.logPerformance (tG,tG.LogID[1],"续期续保抽档批处理开始","1"); // 日志监控,性能监控 PubFun.logTrack(tG,tG.LogID[1],"续期续保抽档批处理启动"); //启动时间 Date dNow = new Date(); long initTime =dNow.getTime(); // 每次最大取数量,默认是100条 int tConutMax = 100; String tResult = ""; String tSQL_Count = "select sysvarvalue from ldsysvar where sysvar='RnewPolAutoCount' "; SQLwithBindVariables sqlbv1=new SQLwithBindVariables(); sqlbv1.sql(tSQL_Count); ExeSQL tExeSQL = new ExeSQL(); tResult = tExeSQL.getOneValue(sqlbv1); // 如果有描述的话,取描述的数据 if (tResult != null && !tResult.equals("")) { tConutMax = Integer.parseInt(tResult); } Vector mTaskWaitList = new Vector(); logger.debug("续期续保自动催收开始:RnewPolAuto..."); String AheadDays = ""; // 催收提前天数--默认60天 LDSysVarDB tLDSysVarDB = new LDSysVarDB(); tLDSysVarDB.setSysVar("aheaddays"); if (tLDSysVarDB.getInfo() == false) { AheadDays = "60"; } else { AheadDays = tLDSysVarDB.getSysVarValue(); } LDSysVarDB xLDSysVarDB = new LDSysVarDB(); xLDSysVarDB.setSysVar("ExtendLapseDates"); String ExtendDays =""; if (xLDSysVarDB.getInfo() == false) { ExtendDays = "0";//默认为0天 } else { ExtendDays = xLDSysVarDB.getSysVarValue(); } VData tVData = new VData(); TransferData tTransferData = new TransferData(); tTransferData.setNameAndValue("StartDate", PubFun.calDate(PubFun .getCurrentDate(), -(Integer.parseInt(AheadDays) + Integer.parseInt(ExtendDays)), "D", null)); tTransferData.setNameAndValue("EndDate", PubFun.calDate(PubFun .getCurrentDate(), Integer.parseInt(AheadDays), "D", null)); logger.debug("StartDate" + tTransferData.getValueByName("StartDate")); logger.debug("EndDate" + tTransferData.getValueByName("EndDate")); // GlobalInput tGlobalInput = new GlobalInput(); // tGlobalInput.Operator = "001"; // tGlobalInput.ComCode = "86"; // tGlobalInput.ManageCom = "86"; tVData.add(tG); // VData tVData = new VData(); tVData.add(tTransferData); // 查询所有符合抽档条件的所有保单 IndiDueFeePartQuery tIndiDueFeePartQuery = new IndiDueFeePartQuery(); //LCContSet tLCContSet = new LCContSet(); String[][] xResult ; if (!tIndiDueFeePartQuery.submitData(tVData, "ZC")) { this.mErrors.copyAllErrors(tIndiDueFeePartQuery.mErrors); return false; } else { VData hVData = tIndiDueFeePartQuery.getResult(); xResult = (String[][]) hVData.get(0); } int ErrCount = 0; int xLength = xResult.length; if (xLength<=0) { return false; } // 加锁contno,LR0001:续期催收 String LockNo = ""; try { // 循环对每个保单情况进行区分,并进行抽档操作,每个保单分别提交 VData mVData = new VData(); for (int i = 1; i <= xLength; i++) { // 先加锁 logger.debug(i); logger.debug("当前处理contno:"+xResult[i-1][0]); LockNo = ""; LockNo= xResult[i-1][0]; // if (!mPubLock.lock(LockNo, "LR0001", tGI.Operator)) // { // CError tError = new CError(mPubLock.mErrors.getLastError()); // this.mErrors.addOneError(tError); // continue; // } MMap tMap = new MMap(); RnDealBL tRnDealBL = new RnDealBL(); LCContSchema tLCContSchema = new LCContSchema(); LCContDB xLCContDB = new LCContDB(); xLCContDB.setContNo(xResult[i-1][0]); if(!xLCContDB.getInfo()) { this.mErrors.addOneError("未找到保单"+xResult[i-1][0]+"的信息"); // 日志监控,状态监控 PubFun.logState(tG,xResult[i-1][0],"未找到保单"+xResult[i-1][0]+"的信息","0"); ErrCount++; continue; } tLCContSchema=xLCContDB.getSchema(); Map map = new HashMap(); map.put("LCContSchema", tLCContSchema); map.put("StartDate",(String)tTransferData.getValueByName("StartDate")); map.put("EndDate",(String)tTransferData.getValueByName("EndDate")); map.put("TransferData", tTransferData); map.put("GlobalInput", tG); mVData.add(map); if(i%tConutMax==0) { mTaskWaitList.add(mVData); mVData = new VData(); } if(i%tConutMax!=0&&i==xLength) { mTaskWaitList.add(mVData); mVData = new VData(); } } } catch (Exception e) { e.printStackTrace(); CError.buildErr(this, e.toString()); return false; } finally { mPubLock.unLock();// 解锁 } String TaskCode = (String) this.mParameters.get("TaskGroupCode") + ":" + (String) this.mParameters.get("TaskCode") + ":" + (String) this.mParameters.get("TaskPlanCode"); // tongmeng 2009-05-21 add // 自适应线程数 int tThreadCount = 5; tExeSQL = new ExeSQL(); String tSQL_ThreadCount = "select (case when sysvarvalue is not null then sysvarvalue else '0' end) from ldsysvar where sysvar ='RnewPolAutoThread'"; SQLwithBindVariables sqlbv2=new SQLwithBindVariables(); sqlbv2.sql(tSQL_ThreadCount); String tSignMThreadCount = tExeSQL.getOneValue(sqlbv2); if (tSignMThreadCount != null && !"".equals(tSignMThreadCount) && Integer.parseInt(tSignMThreadCount) > 0) { tThreadCount = Integer.parseInt(tSignMThreadCount); } if (xLength < tThreadCount) { tThreadCount =xLength; } this.mServiceA = new ServiceA( "com.sinosoft.lis.operfee.RnDealBLMthread", mTaskWaitList, tThreadCount, 10, TaskCode); this.mServiceA.start(); //完成时间 Date dend = new Date(); long endTime = dend.getTime(); long tt=(endTime-initTime)/1000; //日志监控,结果监控 PubFun.logResult(tG,tG.LogID[1], "续期续保抽档批处理"+String.valueOf(xLength)+"笔,共花费"+tt+"秒"); return true; } /** * 获取各种保全逾期终止批处理的逾期天数 */ private String getEdorTypeTimeoutDays(String sEdorType) { String sResultTimeoutDays = new String(""); //查询逾期天数计算代码 String QuerySQL = "select * from LMEdorCal where CalType = '" + "?sEdorType?" + "'"; SQLwithBindVariables sqlbv3=new SQLwithBindVariables(); sqlbv3.sql(QuerySQL); sqlbv3.put("sEdorType", sEdorType); LMEdorCalDB tLMEdorCalDB = new LMEdorCalDB(); LMEdorCalSet tLMEdorCalSet = new LMEdorCalSet(); try { tLMEdorCalSet = tLMEdorCalDB.executeQuery(sqlbv3); } catch (Exception ex) { logger.debug("\t@> PEdorValidTask.getEdorTypeTimeoutDays() : 执行 SQL 查询出错"); logger.debug("\t 错误原因 : " + tLMEdorCalDB.mErrors.getFirstError()); return null; } if (tLMEdorCalSet == null || tLMEdorCalSet.size() <= 0) { logger.debug("\t@> PEdorValidTask.getEdorTypeTimeoutDays() : 未知的保全类型! 查询逾期天数失败!"); return null; } else { String sTempCalCode = tLMEdorCalSet.get(1).getCalCode(); if (sTempCalCode == null || sTempCalCode.trim().equals("")) { logger.debug("\t@> PEdorValidTask.getEdorTypeTimeoutDays() : 查询逾期天数计算代码失败!"); return null; } else { //根据计算代码计算逾期天数 Calculator tCalculator = new Calculator(); tCalculator.setCalCode(sTempCalCode); sResultTimeoutDays = tCalculator.calculate(); if (sResultTimeoutDays == null || sResultTimeoutDays.trim().equals("")) { logger.debug("\t@> PEdorValidTask.getEdorTypeTimeoutDays() : 根据计算代码计算逾期天数失败!"); return null; } tCalculator = null; } } tLMEdorCalDB = null; tLMEdorCalSet = null; return sResultTimeoutDays; } //function getEdorTypeTimeoutDays end //========================================================================== public static void main(String[] args) { RnewPolAutoTMThread tRnewPolAutoTMThread = new RnewPolAutoTMThread(); tRnewPolAutoTMThread.dealMain(); } }
true
ed14e1b3fe8a3804ab2dee082ff705f6e0fa480a
Java
791837060/qipai_huainanmajiang
/qipai_admin_facade/src/main/java/com/anbang/qipai/admin/plan/bean/permission/Role.java
UTF-8
623
1.953125
2
[]
no_license
package com.anbang.qipai.admin.plan.bean.permission; import java.util.List; public class Role { private String id;// 角色id private String role;// 角色名称 private List<RoleRefPrivilege> privilegeList;// 权限列表 public String getId() { return id; } public void setId(String id) { this.id = id; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public List<RoleRefPrivilege> getPrivilegeList() { return privilegeList; } public void setPrivilegeList(List<RoleRefPrivilege> privilegeList) { this.privilegeList = privilegeList; } }
true
1b751f00d857b9959a19a5dddfa4ccaf181e2adc
Java
rawrrencee/PointOfSaleSystemV54
/PointOfSaleSystemV54/PointOfSaleSystemV54Library/build/generated-sources/ap-source-output/entity/CategoryEntity_.java
UTF-8
940
1.757813
2
[]
no_license
package entity; import entity.CategoryEntity; import entity.ProductEntity; import javax.annotation.Generated; import javax.persistence.metamodel.ListAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2019-03-25T15:14:11") @StaticMetamodel(CategoryEntity.class) public class CategoryEntity_ { public static volatile ListAttribute<CategoryEntity, CategoryEntity> subCategoryEntities; public static volatile SingularAttribute<CategoryEntity, CategoryEntity> parentCategoryEntity; public static volatile ListAttribute<CategoryEntity, ProductEntity> productEntities; public static volatile SingularAttribute<CategoryEntity, String> name; public static volatile SingularAttribute<CategoryEntity, String> description; public static volatile SingularAttribute<CategoryEntity, Long> categoryId; }
true
7d94a2c5c1b4a7d4e7f2f2a01d4b35d4bac59a35
Java
liorgabay/DontMissItProj
/app/src/main/java/com/example/liorozit/dontmissitproj/SignInActivity.java
UTF-8
15,031
2
2
[]
no_license
package com.example.liorozit.dontmissitproj; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; public class SignInActivity extends AppCompatActivity { EditText usernametext; EditText passwordtext; SharedPreferences sharedpref; EditText firstnametext; EditText lastnametext; EditText emailtext; MyDBHandler handlerdb; String regiondrive; boolean stayflag; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_in); usernametext=(EditText)findViewById(R.id.username); passwordtext=(EditText)findViewById(R.id.password); firstnametext=(EditText)findViewById(R.id.firstname); lastnametext=(EditText)findViewById(R.id.lastname); emailtext=(EditText)findViewById(R.id.email); stayflag=false; } public void CreateProfileOnClick(View V) { if (firstnametext.getText().toString().matches("") || lastnametext.getText().toString().matches("") || emailtext.getText().toString().matches("") || ((RadioGroup) findViewById(R.id.regiondrivebuttons)).getCheckedRadioButtonId() == -1 || usernametext.getText().toString().matches("") || passwordtext.getText().toString().matches("")) { Toast.makeText(getApplicationContext(), "At least one detail is empty", Toast.LENGTH_SHORT).show(); } else { final Dialog dialog = new Dialog(SignInActivity.this); dialog.setTitle("Attention!"); dialog.setContentView(R.layout.popup_sign_in); dialog.show(); Button yesbutton = (Button) dialog.findViewById(R.id.YesButton); final Button nobutton = (Button) dialog.findViewById(R.id.NoButtom); yesbutton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { sharedpref = getSharedPreferences("1", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedpref.edit(); editor.putString("username", usernametext.getText().toString()); editor.putString("password", passwordtext.getText().toString()); editor.commit(); sharedpref = getSharedPreferences("2", Context.MODE_PRIVATE); SharedPreferences.Editor editor2 = sharedpref.edit(); editor2.putString("sign", "true"); editor2.commit(); sharedpref = getSharedPreferences("3", Context.MODE_PRIVATE); SharedPreferences.Editor editor3 = sharedpref.edit(); editor3.putBoolean("WakeMeAndCancelSwitch",true); editor3.commit(); //save all the sql data... //first, clear all 3 tables try { DeleteAndCreateTables(); // PreferenceManager.setDefaultValues(getApplicationContext(), R.xml.pref, false); //String initregion; // if(regiondrive.equals("hasharon")){ // initregion="Hasharon"; // } // else{ // initregion="Hadarom"; // } SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); SharedPreferences.Editor editor4 = settings.edit(); // editor3.putString("listOptions",initregion); editor4.putString("listValues",regiondrive); editor4.putString("four",emailtext.getText().toString()); editor4.commit(); } catch (Exception e) { stayflag = true; Log.d(this.getClass().getName(), e.getMessage()); } if (!stayflag) { Intent i = new Intent(SignInActivity.this, MainActivity.class); startActivity(i); } dialog.cancel(); } }); nobutton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { dialog.cancel(); } }); } } public void onRadioButtonClicked(View v){ // Is the button now checked? boolean checked = ((RadioButton) v).isChecked(); // Check which radio button was clicked switch(v.getId()) { case R.id.hasharonButton: if (checked) regiondrive=((RadioButton) v).getText().toString(); break; case R.id.hadaromButton: if (checked) regiondrive=((RadioButton) v).getText().toString(); break; } } public void DeleteAndCreateTables(){ handlerdb = new MyDBHandler(getApplicationContext(), null, null, 1); handlerdb.DeleteAllTablesContent(); UserTable ut = new UserTable(firstnametext.getText().toString(), lastnametext.getText().toString(), emailtext.getText().toString(), regiondrive, 1); BusLinesTable bl1=new BusLinesTable(29,"hasharon","תחנה מרכזית,כפר סבא","ויצמן / רוטשילד,כפר סבא","ויצמן / ירושלים,כפר סבא","קניון ערים- וייצמן / אנה פרנק,כפר סבא","ויצמן/ברנר,כפר סבא","קרית חינוך,כפר סבא","טשרניחובסקי / ויצמן,כפר סבא","מסוף רעננה,רעננה","אחוזה / כביש 4,כפר סבא","אחוזה / רבוצקי,רעננה"); BusLinesTable bl2=new BusLinesTable(65,"hasharon","תחנת רכבת,כפר סבא","אסירי ציון / ויצמן,הוד השרון","החומש / חנקין,הוד השרון","חנקין,הוד השרון","חנקין / נצח ישראל,הוד השרון","מגדל המים- חנקין 68,הוד השרון","ששת הימים,הוד השרון","ששת הימים / הר מירון,הוד השרון","החרמון / אילת,הוד השרון","החרמון / הגולן,הוד השרון"); BusLinesTable bl3=new BusLinesTable(360,"hadarom","תחנה מרכזית,אשדוד","שדרות מנחם בגין / שדרות משה סנה,אשדוד","צומת עד הלום/ כביש 4,באר טוביה","צומת ברכיה,אשקלון","מרכז אורן,באר שבע","בית חולים סורוקה,באר שבע","שדרות יצחק רגר / ביאליק,באר שבע","יד לבנים- שדרות יצחק רגר,באר שבע","שדרות יצחק רגר,באר שבע","תחנה מרכזית,באר שבע"); BusLinesTable bl4=new BusLinesTable(353,"hadarom","תחנה מרכזית חדשה,תל אביב","מקווה ישראל / צומת חולון,מקוה ישראל","דרך השבעה/המכתש למזרח,חולון","דרך השבעה / קפלן,חולון","תחנה מרכזית,ראשון לציון","צומת עין הקורא,ראשון לציון","כביש 42/בית חנן,בית חנן","עיינות/ כביש 42,גן רווה","כפר הנגיד- כביש 42,גן רווה","שדרות העצמאות / אהרון חג'ג',יבנה"); BusLinesTable bl5=new BusLinesTable(1,"hasharon","קניון שרונים,הוד השרון","מסעף נווה נאמן,הוד השרון","צומת רמת הדר,הוד השרון","צומת ירקונה,הוד השרון","צומת גני עם,הוד השרון","הוד השרון מרכז/דרך רמתיים,הוד השרון","מגדיאל / יהושע בן גמלא,הוד השרון","מגדיאל / פדויים,הוד השרון","כיכר מגדיאל- זקיף,הוד השרון","הצריף הראשון- סוקולוב / הידידות,הוד השרון"); StationLocationTable sl1=new StationLocationTable("תחנה מרכזית,כפר סבא",32.173863, 34.914819);StationLocationTable sl2=new StationLocationTable("ויצמן / רוטשילד,כפר סבא",32.175088, 34.909375); StationLocationTable sl3=new StationLocationTable("ויצמן / ירושלים,כפר סבא",32.175620, 34.906589);StationLocationTable sl4=new StationLocationTable("קניון ערים- וייצמן / אנה פרנק,כפר סבא",32.176347, 34.903877); StationLocationTable sl5=new StationLocationTable("ויצמן/ברנר,כפר סבא",32.177206, 34.900293);StationLocationTable sl6=new StationLocationTable("קרית חינוך,כפר סבא",32.177959, 34.897174); StationLocationTable sl7=new StationLocationTable("טשרניחובסקי / ויצמן,כפר סבא",32.177882, 34.894075);StationLocationTable sl8=new StationLocationTable("מסוף רעננה,רעננה",32.175540, 34.890263); StationLocationTable sl9=new StationLocationTable("אחוזה / כביש 4,כפר סבא",32.177867, 34.886757);StationLocationTable sl10=new StationLocationTable("אחוזה / רבוצקי,רעננה",32.178524, 34.883894); StationLocationTable sl12=new StationLocationTable("תחנת רכבת,כפר סבא",32.167641, 34.917442);StationLocationTable sl22=new StationLocationTable("אסירי ציון / ויצמן,הוד השרון",32.165924, 34.909627); StationLocationTable sl32=new StationLocationTable("החומש / חנקין,הוד השרון",32.159377, 34.906473);StationLocationTable sl42=new StationLocationTable("חנקין,הוד השרון",32.158120, 34.910238); StationLocationTable sl52=new StationLocationTable("חנקין / נצח ישראל,הוד השרון",32.158516, 34.909123);StationLocationTable sl62=new StationLocationTable("מגדל המים- חנקין 68,הוד השרון",32.157196, 34.912933); StationLocationTable sl72=new StationLocationTable("ששת הימים,הוד השרון",32.157410, 34.912263);StationLocationTable sl82=new StationLocationTable("ששת הימים / הר מירון,הוד השרון",32.157676, 34.917777); StationLocationTable sl92=new StationLocationTable("החרמון / אילת,הוד השרוןן",32.157678, 34.921868);StationLocationTable sl102=new StationLocationTable("החרמון / הגולן,הוד השרון",32.159111, 34.922504); /////////////////////// // StationLocationTable hasharon1=new StationLocationTable();StationLocationTable hasharon2=new StationLocationTable(); // StationLocationTable hasharon3=new StationLocationTable();StationLocationTable hasharon4=new StationLocationTable(); // StationLocationTable hasharon5=new StationLocationTable();StationLocationTable hasharon6=new StationLocationTable(); // StationLocationTable hasharon7=new StationLocationTable();StationLocationTable hasharon8=new StationLocationTable(); // StationLocationTable hasharon9=new StationLocationTable();StationLocationTable hasharon10=new StationLocationTable(); ////////////////////////// StationLocationTable hadarom11=new StationLocationTable("תחנה מרכזית חדשה,תל אביב",32.055975, 34.780282);StationLocationTable hadarom12=new StationLocationTable("מקווה ישראל / צומת חולון,מקוה ישראל",32.037199, 34.777021); StationLocationTable hadarom13=new StationLocationTable("דרך השבעה/המכתש למזרח,חולון",32.027458, 34.798369);StationLocationTable hadarom14=new StationLocationTable("דרך השבעה / קפלן,חולון",32.017674, 34.808901); StationLocationTable hadarom15=new StationLocationTable("תחנה מרכזית,ראשון לציון",32.056228, 34.780864);StationLocationTable hadarom16=new StationLocationTable("צומת עין הקורא,ראשון לציון",31.956502, 34.786228); StationLocationTable hadarom17=new StationLocationTable("כביש 42/בית חנן,בית חנן",31.935698, 34.778282);StationLocationTable hadarom18=new StationLocationTable("עיינות/ כביש 42,גן רווה",31.914785, 34.771023 ); StationLocationTable hadarom19=new StationLocationTable("כפר הנגיד- כביש 42,גן רווה",31.889694, 34.756266 );StationLocationTable hadarom110=new StationLocationTable("שדרות העצמאות / אהרון חג'ג',יבנה",31.875753, 34.749396 ); //////////////// StationLocationTable hadarom1=new StationLocationTable("תחנה מרכזית,אשדוד",31.790081, 34.639407);StationLocationTable hadarom2=new StationLocationTable("שדרות מנחם בגין / שדרות משה סנה,אשדוד",31.784786, 34.650033); StationLocationTable hadarom3=new StationLocationTable("צומת עד הלום/ כביש 4,באר טוביה",31.765900, 34.667360);StationLocationTable hadarom4=new StationLocationTable("צומת ברכיה,אשקלון",31.665286, 34.606619); StationLocationTable hadarom5=new StationLocationTable("מרכז אורן,באר שבע",31.270670, 34.797955);StationLocationTable hadarom6=new StationLocationTable("בית חולים סורוקה,באר שבע",31.260937, 34.801054); StationLocationTable hadarom7=new StationLocationTable("שדרות יצחק רגר / ביאליק,באר שבע",31.260046, 34.801402);StationLocationTable hadarom8=new StationLocationTable("יד לבנים- שדרות יצחק רגר,באר שבע",31.250171, 34.798114); StationLocationTable hadarom9=new StationLocationTable("שדרות יצחק רגר,באר שבע",31.258872, 34.798013);StationLocationTable hadarom10=new StationLocationTable("תחנה מרכזית,באר שבע",31.242864, 34.797961); handlerdb.AddUserDetailsRow(ut); handlerdb.AddBusLinesRow(bl1);handlerdb.AddBusLinesRow(bl2);handlerdb.AddBusLinesRow(bl3); handlerdb.AddBusLinesRow(bl4);//;handlerdb.AddBusLinesRow(bl5); handlerdb.AddStationLocationDetailsRow(sl1, sl2, sl3, sl4, sl5, sl6, sl7, sl8, sl9, sl10); handlerdb.AddStationLocationDetailsRow(sl12,sl22,sl32,sl42,sl52,sl62,sl72,sl82,sl92,sl102); handlerdb.AddStationLocationDetailsRow(hadarom1,hadarom2,hadarom3,hadarom4,hadarom5,hadarom6,hadarom7,hadarom8,hadarom9,hadarom10); handlerdb.AddStationLocationDetailsRow(hadarom11,hadarom12,hadarom13,hadarom14,hadarom15,hadarom16,hadarom17,hadarom18,hadarom19,hadarom110); // handlerdb.AddStationLocationDetailsRow(sl12,sl22,sl32,sl42,sl52,sl62,sl72,sl82,sl92,sl102); } }
true
27031e3a01bfb6ab98208481a46e200d915a30f2
Java
msranand95/new-life
/src/com/lifebuds/data/ImageDAOImpl.java
UTF-8
1,837
2.640625
3
[]
no_license
package com.lifebuds.data; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.lifebuds.domain.UploadImage; public class ImageDAOImpl extends MYSQLDatabaseInfo implements ImageDAO{ @Override public void insertImage(UploadImage image) { // TODO Auto-generated method stub PreparedStatement statement=null; Connection connection=null; try { connection=getConnection(); statement=connection.prepareStatement("insert into tb_image values(?,?,?)"); statement.setInt(1, image.getImageId()); statement.setString(2, image.getDesc()); statement.setString(3, image.getImagepath()); statement.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public List<UploadImage> imageList() { // TODO Auto-generated method stub PreparedStatement statement=null; Connection connection=null; ResultSet resultset=null; List<UploadImage> imageList=new ArrayList<UploadImage>(); try { connection=getConnection(); statement=connection.prepareStatement("select * from tb_image"); resultset=statement.executeQuery(); if(resultset!=null){ while(resultset.next()) { UploadImage img=new UploadImage(); img.setImageId(resultset.getInt(1)); img.setDesc(resultset.getString(2)); img.setImagepath(resultset.getString(3)); System.out.println(img.toString()); imageList.add(img); } } else{ System.out.println("no image"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ closeDBResource(); } return imageList; } }
true
a0364b6afb7e84f2727d0d6f3c6800f52ed3498b
Java
wsx180808/-
/web/Project1/JDBC/jdbc3/commons/commons-dbcp-1.2.2-src/src/test/org/apache/commons/dbcp/TestConnectionPool.java
UTF-8
17,302
2.296875
2
[ "Apache-2.0" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.dbcp; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Hashtable; import java.util.Stack; import junit.framework.TestCase; // XXX FIX ME XXX // this class still needs some cleanup, but at least // this consolidates most of the relevant test code // in a fairly re-usable fashion // XXX FIX ME XXX /** * Base test suite for DBCP pools. * * @author Rodney Waldhoff * @author Sean C. Sullivan * @author John McNally * @author Dirk Verbeeck * @version $Revision: 479137 $ $Date: 2006-11-25 08:51:48 -0700 (Sat, 25 Nov 2006) $ */ public abstract class TestConnectionPool extends TestCase { public TestConnectionPool(String testName) { super(testName); } public void setUp() throws Exception { super.setUp(); } public void tearDown() throws Exception { super.tearDown(); // Close any connections opened by the test while (!connections.isEmpty()) { Connection conn = (Connection) connections.pop(); try { conn.close(); } catch (Exception ex) { // ignore } finally { conn = null; } } } protected abstract Connection getConnection() throws Exception; protected int getMaxActive() { return 10; } protected long getMaxWait() { return 100L; } /** Connections opened during the course of a test */ protected Stack connections = new Stack(); /** Acquire a connection and push it onto the connections stack */ protected Connection newConnection() throws Exception { Connection connection = getConnection(); connections.push(connection); return connection; } // ----------- Utility Methods --------------------------------- protected String getUsername(Connection conn) throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select username"); if (rs.next()) { return rs.getString(1); } return null; } // ----------- tests --------------------------------- public void testClearWarnings() throws Exception { Connection[] c = new Connection[getMaxActive()]; for (int i = 0; i < c.length; i++) { c[i] = newConnection(); assertTrue(c[i] != null); // generate SQLWarning on connection c[i].prepareCall("warning"); } for (int i = 0; i < c.length; i++) { assertNotNull(c[i].getWarnings()); } for (int i = 0; i < c.length; i++) { c[i].close(); } for (int i = 0; i < c.length; i++) { c[i] = newConnection(); } for (int i = 0; i < c.length; i++) { // warnings should have been cleared by putting the connection back in the pool assertNull(c[i].getWarnings()); } for (int i = 0; i < c.length; i++) { c[i].close(); } } public void testIsClosed() throws Exception { for(int i=0;i<getMaxActive();i++) { Connection conn = newConnection(); assertTrue(null != conn); assertTrue(!conn.isClosed()); PreparedStatement stmt = conn.prepareStatement("select * from dual"); assertTrue(null != stmt); ResultSet rset = stmt.executeQuery(); assertTrue(null != rset); assertTrue(rset.next()); rset.close(); stmt.close(); conn.close(); assertTrue(conn.isClosed()); } } public void testCantCloseConnectionTwice() throws Exception { for(int i=0;i<getMaxActive();i++) { // loop to show we *can* close again once we've borrowed it from the pool again Connection conn = newConnection(); assertTrue(null != conn); assertTrue(!conn.isClosed()); conn.close(); assertTrue(conn.isClosed()); try { conn.close(); fail("Expected SQLException on second attempt to close (" + conn.getClass().getName() + ")"); } catch(SQLException e) { // expected } assertTrue(conn.isClosed()); } } public void testCantCloseStatementTwice() throws Exception { Connection conn = newConnection(); assertTrue(null != conn); assertTrue(!conn.isClosed()); for(int i=0;i<2;i++) { // loop to show we *can* close again once we've borrowed it from the pool again PreparedStatement stmt = conn.prepareStatement("select * from dual"); assertTrue(null != stmt); stmt.close(); try { stmt.close(); fail("Expected SQLException on second attempt to close (" + stmt.getClass().getName() + ")"); } catch(SQLException e) { // expected } } conn.close(); } public void testSimple() throws Exception { Connection conn = newConnection(); assertTrue(null != conn); PreparedStatement stmt = conn.prepareStatement("select * from dual"); assertTrue(null != stmt); ResultSet rset = stmt.executeQuery(); assertTrue(null != rset); assertTrue(rset.next()); rset.close(); stmt.close(); conn.close(); } public void testRepeatedBorrowAndReturn() throws Exception { for(int i=0;i<100;i++) { Connection conn = newConnection(); assertTrue(null != conn); PreparedStatement stmt = conn.prepareStatement("select * from dual"); assertTrue(null != stmt); ResultSet rset = stmt.executeQuery(); assertTrue(null != rset); assertTrue(rset.next()); rset.close(); stmt.close(); conn.close(); } } public void testSimple2() throws Exception { Connection conn = newConnection(); assertTrue(null != conn); { PreparedStatement stmt = conn.prepareStatement("select * from dual"); assertTrue(null != stmt); ResultSet rset = stmt.executeQuery(); assertTrue(null != rset); assertTrue(rset.next()); rset.close(); stmt.close(); } { PreparedStatement stmt = conn.prepareStatement("select * from dual"); assertTrue(null != stmt); ResultSet rset = stmt.executeQuery(); assertTrue(null != rset); assertTrue(rset.next()); rset.close(); stmt.close(); } conn.close(); try { conn.createStatement(); fail("Can't use closed connections"); } catch(SQLException e) { ; // expected } conn = newConnection(); assertTrue(null != conn); { PreparedStatement stmt = conn.prepareStatement("select * from dual"); assertTrue(null != stmt); ResultSet rset = stmt.executeQuery(); assertTrue(null != rset); assertTrue(rset.next()); rset.close(); stmt.close(); } { PreparedStatement stmt = conn.prepareStatement("select * from dual"); assertTrue(null != stmt); ResultSet rset = stmt.executeQuery(); assertTrue(null != rset); assertTrue(rset.next()); rset.close(); stmt.close(); } conn.close(); conn = null; } public void testPooling() throws Exception { // Grab a maximal set of open connections from the pool Connection[] c = new Connection[getMaxActive()]; Connection[] u = new Connection[getMaxActive()]; for (int i = 0; i < c.length; i++) { c[i] = newConnection(); if (c[i] instanceof DelegatingConnection) { u[i] = ((DelegatingConnection) c[i]).getInnermostDelegate(); } else { for (int j = 0; j <= i; j++) { c[j].close(); } return; // skip this test } } // Close connections one at a time and get new ones, making sure // the new ones come from the pool for (int i = 0; i < c.length; i++) { c[i].close(); Connection con = newConnection(); Connection underCon = ((DelegatingConnection) con).getInnermostDelegate(); assertTrue("Failed to get connection", underCon != null); boolean found = false; for (int j = 0; j < c.length; j++) { if (underCon == u[j]) { found = true; break; } } assertTrue("New connection not from pool", found); con.close(); } } public void testAutoCommitBehavior() throws Exception { Connection conn = newConnection(); assertTrue(conn != null); assertTrue(conn.getAutoCommit()); conn.setAutoCommit(false); conn.close(); Connection conn2 = newConnection(); assertTrue( conn2.getAutoCommit() ); Connection conn3 = newConnection(); assertTrue( conn3.getAutoCommit() ); conn2.close(); conn3.close(); } /** @see http://issues.apache.org/bugzilla/show_bug.cgi?id=12400 */ public void testConnectionsAreDistinct() throws Exception { Connection[] conn = new Connection[getMaxActive()]; for(int i=0;i<conn.length;i++) { conn[i] = newConnection(); for(int j=0;j<i;j++) { assertTrue(conn[j] != conn[i]); assertTrue(!conn[j].equals(conn[i])); } } for(int i=0;i<conn.length;i++) { conn[i].close(); } } public void testOpening() throws Exception { Connection[] c = new Connection[getMaxActive()]; // test that opening new connections is not closing previous for (int i = 0; i < c.length; i++) { c[i] = newConnection(); assertTrue(c[i] != null); for (int j = 0; j <= i; j++) { assertTrue(!c[j].isClosed()); } } for (int i = 0; i < c.length; i++) { c[i].close(); } } public void testClosing() throws Exception { Connection[] c = new Connection[getMaxActive()]; // open the maximum connections for (int i = 0; i < c.length; i++) { c[i] = newConnection(); } // close one of the connections c[0].close(); assertTrue(c[0].isClosed()); // get a new connection c[0] = newConnection(); for (int i = 0; i < c.length; i++) { c[i].close(); } } public void testMaxActive() throws Exception { Connection[] c = new Connection[getMaxActive()]; for (int i = 0; i < c.length; i++) { c[i] = newConnection(); assertTrue(c[i] != null); } try { newConnection(); fail("Allowed to open more than DefaultMaxActive connections."); } catch (java.sql.SQLException e) { // should only be able to open 10 connections, so this test should // throw an exception } for (int i = 0; i < c.length; i++) { c[i].close(); } } /** * DBCP-128: BasicDataSource.getConnection() * Connections don't work as hashtable keys */ public void testHashing() throws Exception { Connection con = getConnection(); Hashtable hash = new Hashtable(); hash.put(con, "test"); assertEquals("test", hash.get(con)); assertTrue(hash.containsKey(con)); assertTrue(hash.contains("test")); hash.clear(); con.close(); } public void testThreaded() { TestThread[] threads = new TestThread[getMaxActive()]; for(int i=0;i<threads.length;i++) { threads[i] = new TestThread(50,50); Thread t = new Thread(threads[i]); t.start(); } for(int i=0;i<threads.length;i++) { while(!(threads[i]).complete()) { try { Thread.sleep(100L); } catch(Exception e) { // ignored } } if(threads[i].failed()) { fail(); } } } class TestThread implements Runnable { java.util.Random _random = new java.util.Random(); boolean _complete = false; boolean _failed = false; int _iter = 100; int _delay = 50; public TestThread() { } public TestThread(int iter) { _iter = iter; } public TestThread(int iter, int delay) { _iter = iter; _delay = delay; } public boolean complete() { return _complete; } public boolean failed() { return _failed; } public void run() { for(int i=0;i<_iter;i++) { try { Thread.sleep((long)_random.nextInt(_delay)); } catch(Exception e) { // ignored } Connection conn = null; PreparedStatement stmt = null; ResultSet rset = null; try { conn = newConnection(); stmt = conn.prepareStatement("select 'literal', SYSDATE from dual"); rset = stmt.executeQuery(); try { Thread.sleep((long)_random.nextInt(_delay)); } catch(Exception e) { // ignored } } catch(Exception e) { e.printStackTrace(); _failed = true; _complete = true; break; } finally { try { rset.close(); } catch(Exception e) { } try { stmt.close(); } catch(Exception e) { } try { conn.close(); } catch(Exception e) { } } } _complete = true; } } // Bugzilla Bug 24328: PooledConnectionImpl ignores resultsetType // and Concurrency if statement pooling is not enabled // http://issues.apache.org/bugzilla/show_bug.cgi?id=24328 public void testPrepareStatementOptions() throws Exception { Connection conn = newConnection(); assertTrue(null != conn); PreparedStatement stmt = conn.prepareStatement("select * from dual", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); assertTrue(null != stmt); ResultSet rset = stmt.executeQuery(); assertTrue(null != rset); assertTrue(rset.next()); assertEquals(ResultSet.TYPE_SCROLL_SENSITIVE, rset.getType()); assertEquals(ResultSet.CONCUR_UPDATABLE, rset.getConcurrency()); rset.close(); stmt.close(); conn.close(); } // Bugzilla Bug 24966: NullPointer with Oracle 9 driver // wrong order of passivate/close when a rset isn't closed public void testNoRsetClose() throws Exception { Connection conn = newConnection(); assertNotNull(conn); PreparedStatement stmt = conn.prepareStatement("test"); assertNotNull(stmt); ResultSet rset = stmt.getResultSet(); assertNotNull(rset); // forget to close the resultset: rset.close(); stmt.close(); conn.close(); } // Bugzilla Bug 26966: Connectionpool's connections always returns same public void testHashCode() throws Exception { Connection conn1 = newConnection(); assertNotNull(conn1); Connection conn2 = newConnection(); assertNotNull(conn2); assertTrue(conn1.hashCode() != conn2.hashCode()); } }
true
bc38fe0d9339fb1ffa9bd739c9e4b0c592cf013f
Java
Sawrr/gravity-game
/core/src/com/sawyerharris/gravitygame/ui/TextItem.java
UTF-8
1,955
3.15625
3
[]
no_license
package com.sawyerharris.gravitygame.ui; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.GlyphLayout; import com.badlogic.gdx.scenes.scene2d.Touchable; import com.badlogic.gdx.utils.Align; import com.sawyerharris.gravitygame.game.GravityGame; /** * Implementation of BorderedItem with text. * * @author Sawyer Harris * */ public class TextItem extends BorderedItem { /** Color of text */ private static final Color TEXT_COLOR = Color.WHITE; /** Margin of text from sides */ private static final int TEXT_MARGIN = 10; /** Width of text */ private float textWidth; /** Glyph layout of text */ private GlyphLayout textGL; /** Font of text */ private BitmapFont font; /** * Constructs a TextItem with the given parameters. * * @param x * x of bottom left corner * @param y * y of bottom left corner * @param width * width of TextItem * @param height * height of TextItem * @param color * color of TextItem * @param touchable * if item can be touched * @param text * text of item * @param fontSize * font size */ public TextItem(float x, float y, float width, float height, Color color, Touchable touchable, String text, int fontSize) { super(x, y, width, height, color, touchable); textWidth = width; font = GravityGame.getInstance().getAssets().getFont(fontSize); setText(text); } /** * Sets the text of the item. * * @param text */ public void setText(String text) { textGL = new GlyphLayout(font, text, TEXT_COLOR, textWidth - 2 * BORDER_WIDTH - 2 * TEXT_MARGIN, Align.center, true); } @Override public void draw(Batch batch, float alpha) { font.draw(batch, textGL, getX() + BORDER_WIDTH + TEXT_MARGIN, getY() + (getHeight() + textGL.height) / 2); } }
true
bbb43081a35a08ee896af6d9121a3183fd0ad188
Java
Heverton/ermasterr
/src/org/insightech/er/editor/model/diagram_contents/element/node/table/column/NormalColumn.java
UTF-8
20,436
2.046875
2
[ "Apache-2.0" ]
permissive
package org.insightech.er.editor.model.diagram_contents.element.node.table.column; import java.util.ArrayList; import java.util.List; import org.insightech.er.db.sqltype.SqlType; import org.insightech.er.editor.model.diagram_contents.element.connection.Relation; import org.insightech.er.editor.model.diagram_contents.element.node.table.ERTable; import org.insightech.er.editor.model.diagram_contents.not_element.dictionary.TypeData; import org.insightech.er.editor.model.diagram_contents.not_element.dictionary.Word; import org.insightech.er.editor.model.diagram_contents.not_element.sequence.Sequence; import org.insightech.er.util.Check; public class NormalColumn extends Column { private static final long serialVersionUID = -3177788331933357906L; private Word word; private String foreignKeyPhysicalName; private String foreignKeyLogicalName; private String foreignKeyDescription; private boolean notNull; private boolean primaryKey; private boolean uniqueKey; private boolean autoIncrement; private String defaultValue; private String constraint; private String uniqueKeyName; private Sequence autoIncrementSetting; private String characterSet; private String collation; /** 親が2つある外部キーは、通常ないが、親の大元が同じ参照キーの場合はありえる. */ private List<NormalColumn> referencedColumnList = new ArrayList<NormalColumn>(); private List<Relation> relationList = new ArrayList<Relation>(); public NormalColumn(final Word word, final boolean notNull, final boolean primaryKey, final boolean uniqueKey, final boolean autoIncrement, final String defaultValue, final String constraint, final String uniqueKeyName, final String characterSet, final String collation) { this.word = word; init(notNull, primaryKey, uniqueKey, autoIncrement, defaultValue, constraint, uniqueKeyName, characterSet, collation); autoIncrementSetting = new Sequence(); } protected NormalColumn(final NormalColumn from) { referencedColumnList.addAll(from.referencedColumnList); relationList.addAll(from.relationList); foreignKeyPhysicalName = from.foreignKeyPhysicalName; foreignKeyLogicalName = from.foreignKeyLogicalName; foreignKeyDescription = from.foreignKeyDescription; init(from.notNull, from.primaryKey, from.uniqueKey, from.autoIncrement, from.defaultValue, from.constraint, from.uniqueKeyName, from.characterSet, from.collation); word = from.word; autoIncrementSetting = (Sequence) from.autoIncrementSetting.clone(); } private NormalColumn() {} /** * 外部キーを作成します * * @param from * @param referencedColumn * @param relation * @param primaryKey * 主キーかどうか */ public NormalColumn createForeignKey(final Relation relation, final boolean primaryKey) { final NormalColumn newColumn = new NormalColumn(); newColumn.word = null; newColumn.referencedColumnList.add(this); newColumn.relationList.add(relation); copyData(this, newColumn); newColumn.primaryKey = primaryKey; newColumn.autoIncrement = false; newColumn.autoIncrementSetting = new Sequence(); return newColumn; } protected void init(final boolean notNull, final boolean primaryKey, final boolean uniqueKey, final boolean autoIncrement, final String defaultValue, final String constraint, final String uniqueKeyName, final String characterSet, final String collation) { this.notNull = notNull; this.primaryKey = primaryKey; this.uniqueKey = uniqueKey; this.autoIncrement = autoIncrement; this.defaultValue = defaultValue; this.constraint = constraint; this.uniqueKeyName = uniqueKeyName; this.characterSet = characterSet; this.collation = collation; } public NormalColumn getFirstReferencedColumn() { if (referencedColumnList.isEmpty()) { return null; } return referencedColumnList.get(0); } public NormalColumn getReferencedColumn(final Relation relation) { for (final NormalColumn referencedColumn : referencedColumnList) { if (referencedColumn.getColumnHolder() == relation.getSourceTableView()) { return referencedColumn; } } return null; } public String getLogicalName() { if (getFirstReferencedColumn() != null) { if (!Check.isEmpty(foreignKeyLogicalName)) { return foreignKeyLogicalName; } else { return getFirstReferencedColumn().getLogicalName(); } } return word.getLogicalName(); } public String getPhysicalName() { if (getFirstReferencedColumn() != null) { if (!Check.isEmpty(foreignKeyPhysicalName)) { return foreignKeyPhysicalName; } else { return getFirstReferencedColumn().getPhysicalName(); } } return word.getPhysicalName(); } public String getDescription() { if (getFirstReferencedColumn() != null) { if (!Check.isEmpty(foreignKeyDescription)) { return foreignKeyDescription; } else { return getFirstReferencedColumn().getDescription(); } } return word.getDescription(); } public String getForeignKeyLogicalName() { return foreignKeyLogicalName; } public String getForeignKeyPhysicalName() { return foreignKeyPhysicalName; } public String getForeignKeyDescription() { return foreignKeyDescription; } public SqlType getType() { if (getFirstReferencedColumn() != null) { final SqlType type = getFirstReferencedColumn().getType(); if (SqlType.valueOfId(SqlType.SQL_TYPE_ID_SERIAL).equals(type)) { return SqlType.valueOfId(SqlType.SQL_TYPE_ID_INTEGER); } else if (SqlType.valueOfId(SqlType.SQL_TYPE_ID_BIG_SERIAL).equals(type)) { return SqlType.valueOfId(SqlType.SQL_TYPE_ID_BIG_INT); } return type; } return word.getType(); } public TypeData getTypeData() { if (getFirstReferencedColumn() != null) { return getFirstReferencedColumn().getTypeData(); } return word.getTypeData(); } public boolean isNotNull() { return notNull; } public boolean isPrimaryKey() { return primaryKey; } public boolean isSinglePrimaryKey() { if (isPrimaryKey()) { if (getColumnHolder() instanceof ERTable) { if (((ERTable) getColumnHolder()).getPrimaryKeySize() == 1) { return true; } } } return false; } public boolean isUniqueKey() { return uniqueKey; } public boolean isAutoIncrement() { return autoIncrement; } public String getDefaultValue() { return defaultValue; } public String getConstraint() { return constraint; } public String getUniqueKeyName() { return uniqueKeyName; } public String getCharacterSet() { return characterSet; } public void setCharacterSet(final String characterSet) { this.characterSet = characterSet; } public String getCollation() { return collation; } public void setCollation(final String collation) { this.collation = collation; } /** * {@inheritDoc} */ @Override public String getName() { String name = getLogicalName(); if (Check.isEmpty(name)) { name = getPhysicalName(); } return name; } public NormalColumn getRootReferencedColumn() { NormalColumn root = getFirstReferencedColumn(); if (root != null) { while (root.getFirstReferencedColumn() != null) { root = root.getFirstReferencedColumn(); } } return root; } public List<Relation> getOutgoingRelationList() { final List<Relation> outgoingRelationList = new ArrayList<Relation>(); final ColumnHolder columnHolder = getColumnHolder(); if (columnHolder instanceof ERTable) { final ERTable table = (ERTable) columnHolder; for (final Relation relation : table.getOutgoingRelations()) { if (relation.isReferenceForPK()) { if (isPrimaryKey()) { outgoingRelationList.add(relation); } } else { if (this == relation.getReferencedColumn()) { outgoingRelationList.add(relation); } } } } return outgoingRelationList; } public List<NormalColumn> getForeignKeyList() { final List<NormalColumn> foreignKeyList = new ArrayList<NormalColumn>(); final ColumnHolder columnHolder = getColumnHolder(); if (columnHolder instanceof ERTable) { final ERTable table = (ERTable) columnHolder; for (final Relation relation : table.getOutgoingRelations()) { boolean found = false; for (final NormalColumn column : relation.getTargetTableView().getNormalColumns()) { if (column.isForeignKey()) { for (final NormalColumn referencedColumn : column.referencedColumnList) { if (referencedColumn == this) { foreignKeyList.add(column); found = true; break; } } if (found) { break; } } } } } return foreignKeyList; } public List<Relation> getRelationList() { return relationList; } public void addReference(final NormalColumn referencedColumn, final Relation relation) { foreignKeyDescription = getDescription(); foreignKeyLogicalName = getLogicalName(); foreignKeyPhysicalName = getPhysicalName(); referencedColumnList.add(referencedColumn); relationList.add(relation); copyData(this, this); word = null; } public void renewRelationList() { final List<Relation> newRelationList = new ArrayList<Relation>(); newRelationList.addAll(relationList); relationList = newRelationList; } public void removeReference(final Relation relation) { relationList.remove(relation); if (relationList.isEmpty()) { NormalColumn temp = getFirstReferencedColumn(); while (temp.isForeignKey()) { temp = temp.getFirstReferencedColumn(); } word = temp.getWord(); if (getPhysicalName() != word.getPhysicalName() || getLogicalName() != word.getLogicalName() || getDescription() != word.getDescription()) { word = new Word(word); word.setPhysicalName(getPhysicalName()); word.setLogicalName(getLogicalName()); word.setDescription(getDescription()); } foreignKeyDescription = null; foreignKeyLogicalName = null; foreignKeyPhysicalName = null; referencedColumnList.clear(); copyData(this, this); } else { for (final NormalColumn referencedColumn : referencedColumnList) { if (referencedColumn.getColumnHolder() == relation.getSourceTableView()) { referencedColumnList.remove(referencedColumn); break; } } } } public boolean isForeignKey() { if (!relationList.isEmpty()) { return true; } return false; } public boolean isRefered() { if (!(getColumnHolder() instanceof ERTable)) { return false; } boolean isRefered = false; final ERTable table = (ERTable) getColumnHolder(); for (final Relation relation : table.getOutgoingRelations()) { if (!relation.isReferenceForPK()) { for (final NormalColumn foreignKeyColumn : relation.getForeignKeyColumns()) { for (final NormalColumn referencedColumn : foreignKeyColumn.referencedColumnList) { if (referencedColumn == this) { isRefered = true; break; } } if (isRefered) { break; } } if (isRefered) { break; } } } return isRefered; } public boolean isReferedStrictly() { if (!(getColumnHolder() instanceof ERTable)) { return false; } boolean isRefered = false; final ERTable table = (ERTable) getColumnHolder(); for (final Relation relation : table.getOutgoingRelations()) { if (!relation.isReferenceForPK()) { for (final NormalColumn foreignKeyColumn : relation.getForeignKeyColumns()) { for (final NormalColumn referencedColumn : foreignKeyColumn.referencedColumnList) { if (referencedColumn == this) { isRefered = true; break; } } if (isRefered) { break; } } if (isRefered) { break; } } else { if (isPrimaryKey()) { isRefered = true; break; } } } return isRefered; } public Word getWord() { return word; } public boolean isFullTextIndexable() { return getType().isFullTextIndexable(); } public static void copyData(final NormalColumn from, final NormalColumn to) { to.init(from.isNotNull(), from.isPrimaryKey(), from.isUniqueKey(), from.isAutoIncrement(), from.getDefaultValue(), from.getConstraint(), from.uniqueKeyName, from.characterSet, from.collation); to.autoIncrementSetting = (Sequence) from.autoIncrementSetting.clone(); if (to.isForeignKey()) { final NormalColumn firstReferencedColumn = to.getFirstReferencedColumn(); if (firstReferencedColumn.getPhysicalName() == null) { to.foreignKeyPhysicalName = from.getPhysicalName(); } else { if (from.foreignKeyPhysicalName != null && !firstReferencedColumn.getPhysicalName().equals(from.foreignKeyPhysicalName)) { to.foreignKeyPhysicalName = from.foreignKeyPhysicalName; } else if (!firstReferencedColumn.getPhysicalName().equals(from.getPhysicalName())) { to.foreignKeyPhysicalName = from.getPhysicalName(); } else { to.foreignKeyPhysicalName = null; } } if (firstReferencedColumn.getLogicalName() == null) { to.foreignKeyLogicalName = from.getLogicalName(); } else { if (from.foreignKeyLogicalName != null && !firstReferencedColumn.getLogicalName().equals(from.foreignKeyLogicalName)) { to.foreignKeyLogicalName = from.foreignKeyLogicalName; } else if (!firstReferencedColumn.getLogicalName().equals(from.getLogicalName())) { to.foreignKeyLogicalName = from.getLogicalName(); } else { to.foreignKeyLogicalName = null; } } if (firstReferencedColumn.getDescription() == null) { to.foreignKeyDescription = from.getDescription(); } else { if (from.foreignKeyDescription != null && !firstReferencedColumn.getDescription().equals(from.foreignKeyDescription)) { to.foreignKeyDescription = from.foreignKeyDescription; } else if (!firstReferencedColumn.getDescription().equals(from.getDescription())) { to.foreignKeyDescription = from.getDescription(); } else { to.foreignKeyDescription = null; } } } else { from.word.copyTo(to.word); } to.setColumnHolder(from.getColumnHolder()); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(super.toString()); sb.append(", physicalName:" + getPhysicalName()); sb.append(", logicalName:" + getLogicalName()); return sb.toString(); } public void setForeignKeyPhysicalName(final String physicalName) { foreignKeyPhysicalName = physicalName; } public void setForeignKeyLogicalName(final String logicalName) { foreignKeyLogicalName = logicalName; } public void setForeignKeyDescription(final String description) { foreignKeyDescription = description; } public void setDefaultValue(final String defaultValue) { this.defaultValue = defaultValue; } public void setConstraint(final String constraint) { this.constraint = constraint; } public void setUniqueKeyName(final String uniqueKeyName) { this.uniqueKeyName = uniqueKeyName; } public void setNotNull(final boolean notNull) { this.notNull = notNull; } public void setUniqueKey(final boolean uniqueKey) { this.uniqueKey = uniqueKey; } public void setPrimaryKey(final boolean primaryKey) { this.primaryKey = primaryKey; } public void setAutoIncrement(final boolean autoIncrement) { this.autoIncrement = autoIncrement; } public void setWord(final Word word) { this.word = word; } public Sequence getAutoIncrementSetting() { return autoIncrementSetting; } public void setAutoIncrementSetting(final Sequence autoIncrementSetting) { this.autoIncrementSetting = autoIncrementSetting; } public void copyForeikeyData(final NormalColumn to) { to.setConstraint(getConstraint()); to.setForeignKeyDescription(getForeignKeyDescription()); to.setForeignKeyLogicalName(getForeignKeyLogicalName()); to.setForeignKeyPhysicalName(getForeignKeyPhysicalName()); to.setNotNull(true); to.setUniqueKey(isUniqueKey()); to.setPrimaryKey(isPrimaryKey()); to.setAutoIncrement(isAutoIncrement()); to.setCharacterSet(getCharacterSet()); to.setCollation(getCollation()); } public List<NormalColumn> getReferencedColumnList() { return referencedColumnList; } @Override public NormalColumn clone() { final NormalColumn clone = (NormalColumn) super.clone(); clone.relationList = new ArrayList<Relation>(relationList); clone.referencedColumnList = new ArrayList<NormalColumn>(referencedColumnList); return clone; } }
true
78705ce222ceb8a3dfeede8eeee1e1acb7943d1e
Java
TapasDash/Java-Programmes
/Genrics2.java
UTF-8
530
3.453125
3
[]
no_license
class Genrics2 { public static void main(String args[]) { Integer a[]={1,2,3,4,5}; Gen<Integer> ob1=new Gen<Integer>(a); ob1.display(); Float f[]={1.2f,2.3f,4.5f,6.7f}; Gen<Float> ob2=new Gen<Float>(f); ob2.display(); ArrayList arl=new ArrayList(1,2,3,4,5); Gen<ArrayList> obj3=new Gen<ArrayList>(arl); obj3.display(); } } class Gen<T> { T arr[]; Gen(T arr[]) { this.arr=arr; } void display() { for(int i=0;i<arr.length;i++) { System.out.println(arr[i]); } } }
true
4c2a755ae1c39a0c97f7121e1413b0a7deed390a
Java
diana-dr/Systems-for-Design-and-Implementation
/lab10/core/src/main/java/application/Core/Service/ClientServiceImpl.java
UTF-8
1,319
2.578125
3
[]
no_license
package application.Core.Service; import application.Core.Domain.Client; import application.Core.Domain.Validators.ClientValidator; import application.Core.Repository.ClientRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class ClientServiceImpl extends EntityServiceImpl<Client> implements IClientService { public static final Logger log = LoggerFactory.getLogger(ClientServiceImpl.class); ClientValidator validator = new ClientValidator(); @Autowired public ClientServiceImpl(ClientRepository repo) { super(repo); } @Override @Transactional public Client updateClient(Long id, Client client) { log.trace("updateClient() --- method entered: client={}", client); validator.validate(client); Client update = repository.findById(id).orElse(client); update.setFirstName(client.getFirstName()); update.setLastName(client.getLastName()); update.setEmail(client.getEmail()); update.setDateOfBirth(client.getDateOfBirth()); log.trace("updateBook() --- method finished"); return update; } }
true
9decb8d3145008df2427671732f29f4f8d1ad7db
Java
GoodListener/Bit_Java
/coding_game/src/algorithm/ex1/PowerSigma.java
UTF-8
649
3.40625
3
[]
no_license
package algorithm.ex1; public class PowerSigma { public static void main(String[] args) { nonReculsive(5,10); System.out.println(reculsive(5,5)); } public static void nonReculsive(int n, int m) { int result = 0, a=1; for (int i = 1; i <= n; i++) { for (int k = 0; k < m; k++) { a=a*i; } result = result + a; a = 1; } System.out.println(result); } public static int reculsive(int n, int m) { int result = 0; if(m==1) { return result; } result = result + reculsive((int)Math.pow(n, m), m-1); return result; } }
true
1604ecfeda3df1483394f69600feade56917cb8d
Java
zxlsyhl/storm-topology-demo
/src/main/java/zxl/com/stormtopologydemo/ConsumeBolt.java
UTF-8
1,496
2.234375
2
[]
no_license
package zxl.com.stormtopologydemo; import org.apache.storm.task.OutputCollector; import org.apache.storm.task.TopologyContext; import org.apache.storm.topology.OutputFieldsDeclarer; import org.apache.storm.topology.base.BaseRichBolt; import org.apache.storm.tuple.Tuple; import java.io.FileWriter; import java.io.IOException; import java.util.Map; import java.util.UUID; public class ConsumeBolt extends BaseRichBolt { private static final long serialVersionUID = -7114915627898482737L; private FileWriter fileWriter = null; private OutputCollector collector; public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) { this.collector = collector; try { // TODO: 2019/9/9 要随着本地和集群上变动 // fileWriter = new FileWriter("/usr/local/tmpdata/" + UUID.randomUUID()); fileWriter = new FileWriter("E:\\workspace\\storm-topology-demo\\test\\" + UUID.randomUUID()); } catch (IOException e) { throw new RuntimeException(e); } } public void execute(Tuple tuple) { try { String word = tuple.getStringByField("word") + "......." + "\n"; fileWriter.write(word); fileWriter.flush(); System.out.println(word); } catch (IOException e) { throw new RuntimeException(e); } } public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) { } }
true
cede70cdff791d2f6de67876455e87ffa032d0d8
Java
karpuwapower1/XMLParser_Greenhouse-
/src/main/java/by/training/task04/karpilovich/command/CommandType.java
UTF-8
112
1.648438
2
[]
no_license
package by.training.task04.karpilovich.command; public enum CommandType { LOGIN, SIGNIN, SIGNOUT, PARSE; }
true
38f915405c1731c345118d0e28ed7e23b3c496e9
Java
BeiLiLin/Algorithms
/src/main/java/Unit1/test1/Test_13/Parentheses.java
UTF-8
3,066
3.53125
4
[]
no_license
package Unit1.test1.Test_13; import edu.princeton.cs.algs4.StdOut;; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Iterator; import java.util.Scanner; public class Parentheses<T> implements Iterable<T> { private T[] a; private int N; public Parentheses(int cap){ a = (T[])new Object[cap]; } public int size(){return N;} public Boolean isEmpty(){return N==0;} public T pop(){ T t = a[--N]; a[N] = null;//防止对象游离 if (N == a.length/4) resize(a.length/2); return t; } public void push(T t){ if (N == a.length) resize(a.length*2); a[N++] = t; } public void resize(int max){ T [] temp = (T[])new Object[max]; for (int i =0 ; i<a.length ; i++) temp[i] = a[i]; a=temp; } @Override public Iterator<T> iterator() { return new ParenthesesIterator(); } private class ParenthesesIterator implements Iterator<T>{ private int i = N; @Override public boolean hasNext() { return i>0; } @Override public T next() { return a[--i]; } } public static void main(String[] args){ //定义栈存放左括号 Parentheses<String> left = new Parentheses<String>(40); StdOut.print("请输入文件路径:"); String file = ""; Scanner sc = new Scanner(System.in); if (sc.hasNext()) file = sc.nextLine(); //读取文本数据存放在sc try { FileInputStream is = new FileInputStream(file); sc = new Scanner(new BufferedInputStream(is),"utf-8"); } catch (FileNotFoundException e) { e.printStackTrace(); } //将sc的内容存放在两个栈,左括号存放在left栈中,有括号存放在right栈中 while(sc.hasNext()){ String str=sc.next(); StdOut.print(str+" "); switch (str){ case "(":left.push(str);break; case "[":left.push(str);break; case "{":left.push(str);break; case ")": if (left.pop().equals("(")) break; else { StdOut.println("false"); return; } case "}": if (left.pop().equals("{")) break; else{ StdOut.println("false"); return; } case "]": if (left.pop().equals("[")) break; else{ StdOut.println("false"); return; } } } if (left.size() == 0) StdOut.println("true"); else StdOut.println("false"); } }
true
79737f5ed5e9e074c20f8f0dc04d081b52584728
Java
foilen/foilen-infra-plugins-core
/src/test/java/com/foilen/infra/resource/website/WebsiteTest.java
UTF-8
11,351
1.953125
2
[ "MIT" ]
permissive
/* Foilen Infra Plugins Core https://github.com/foilen/foilen-infra-plugins-core Copyright (c) 2018-2021 Foilen (https://foilen.com) The MIT License http://opensource.org/licenses/MIT */ package com.foilen.infra.resource.website; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeSet; import org.junit.Test; import com.foilen.infra.plugin.core.system.junits.JunitsHelper; import com.foilen.infra.plugin.v1.core.context.ChangesContext; import com.foilen.infra.plugin.v1.model.docker.DockerContainerEndpoints; import com.foilen.infra.plugin.v1.model.resource.IPResource; import com.foilen.infra.plugin.v1.model.resource.LinkTypeConstants; import com.foilen.infra.resource.application.Application; import com.foilen.infra.resource.machine.Machine; import com.foilen.infra.resource.test.AbstractCorePluginTest; import com.foilen.infra.resource.unixuser.UnixUser; import com.foilen.infra.resource.urlredirection.UrlRedirection; import com.foilen.infra.resource.webcertificate.WebsiteCertificate; import com.foilen.smalltools.tools.DateTools; import com.foilen.smalltools.tuple.Tuple2; import com.google.common.base.Joiner; public class WebsiteTest extends AbstractCorePluginTest { private WebsiteCertificate createWebsiteCertificate(String certificate, String... domainNames) { WebsiteCertificate websiteCertificate = new WebsiteCertificate(); websiteCertificate.setThumbprint(Joiner.on(",").join(domainNames)); websiteCertificate.setDomainNames(new TreeSet<>(Arrays.asList(domainNames))); websiteCertificate.setStart(DateTools.parseDateOnly("2000-01-01")); websiteCertificate.setEnd(DateTools.parseDateOnly("2050-01-01")); websiteCertificate.setCertificate(certificate); return websiteCertificate; } @Test public void testEditingWebsiteForUrlRedirection() { // Create resources Machine machine = new Machine("h1.example.com", "192.168.0.200"); UnixUser infraUrlUnixUser = new UnixUser(70000L, "infra_url_redirection", "/home/infra_url_redirection", null, null); UnixUser unixUser = new UnixUser(72000L, "myapp", "/home/myapp", null, null); UrlRedirection urlRedirection = new UrlRedirection(); urlRedirection.setDomainName("myapp.example.com"); urlRedirection.setHttpRedirectToUrl("https://google.com"); ChangesContext changes = new ChangesContext(getCommonServicesContext().getResourceService()); changes.resourceAdd(machine); changes.resourceAdd(infraUrlUnixUser); changes.resourceAdd(unixUser); changes.resourceAdd(urlRedirection); // Create links changes.linkAdd(urlRedirection, LinkTypeConstants.INSTALLED_ON, machine); // Execute getInternalServicesContext().getInternalChangeService().changesExecute(changes); // Assert JunitsHelper.assertState(getCommonServicesContext(), getInternalServicesContext(), "WebsiteTest-testEditingWebsiteForUrlRedirection-state.json", getClass(), true); // Edit the website Website website = getCommonServicesContext().getResourceService().resourceFindByPk(new Website("HTTP Redirection of myapp.example.com")).get(); List<Tuple2<String, ? extends IPResource>> links = getCommonServicesContext().getResourceService().linkFindAllByFromResource(website); Map<String, String> formValues = new HashMap<>(); formValues.put(Website.PROPERTY_NAME, website.getName()); formValues.put(Website.PROPERTY_DOMAIN_NAMES + "[0]", website.getDomainNames().first()); formValues.put(Website.PROPERTY_IS_HTTPS, website.isHttps() ? "TRUE" : "FALSE"); formValues.put(Website.PROPERTY_IS_HTTPS_ORIGIN_TO_HTTP, website.isHttpsOriginToHttp() ? "TRUE" : "FALSE"); formValues.put(Website.PROPERTY_APPLICATION_ENDPOINT, website.getApplicationEndpoint()); formValues.put("applications", links.stream().filter(l -> LinkTypeConstants.POINTS_TO.equals(l.getA())).findAny().get().getB().getInternalId()); formValues.put("machines", links.stream().filter(l -> LinkTypeConstants.INSTALLED_ON.equals(l.getA())).findAny().get().getB().getInternalId()); assertEditorNoErrors(website.getInternalId(), new WebsiteEditor(), formValues); // Assert JunitsHelper.assertState(getCommonServicesContext(), getInternalServicesContext(), "WebsiteTest-testEditingWebsiteForUrlRedirection-state.json", getClass(), true); } @Test public void testWithAppHttp() { // Create resources Machine machine = new Machine("h1.example.com", "192.168.0.200"); UnixUser infraUrlUnixUser = new UnixUser(70000L, "infra_url_redirection", "/home/infra_url_redirection", null, null); UnixUser unixUser = new UnixUser(72000L, "myapp", "/home/myapp", null, null); Website website = new Website("myapp"); website.getDomainNames().add("myapp.example.com"); website.setApplicationEndpoint(DockerContainerEndpoints.HTTP_TCP); Application application = new Application(); application.setName("myphp"); ChangesContext changes = new ChangesContext(getCommonServicesContext().getResourceService()); changes.resourceAdd(machine); changes.resourceAdd(infraUrlUnixUser); changes.resourceAdd(unixUser); changes.resourceAdd(application); changes.resourceAdd(website); // Create links changes.linkAdd(application, LinkTypeConstants.RUN_AS, unixUser); changes.linkAdd(application, LinkTypeConstants.INSTALLED_ON, machine); changes.linkAdd(website, LinkTypeConstants.INSTALLED_ON, machine); changes.linkAdd(website, LinkTypeConstants.POINTS_TO, application); // Execute getInternalServicesContext().getInternalChangeService().changesExecute(changes); // Assert JunitsHelper.assertState(getCommonServicesContext(), getInternalServicesContext(), "WebsiteTest-testWithAppHttp-state.json", getClass(), true); } @Test public void testWithAppHttpHttpsAndOriginRewrite() { // Create resources Machine machine = new Machine("h1.example.com", "192.168.0.200"); UnixUser infraUrlUnixUser = new UnixUser(70000L, "infra_url_redirection", "/home/infra_url_redirection", null, null); UnixUser unixUser = new UnixUser(72000L, "myapp", "/home/myapp", null, null); Website websiteHttp = new Website("myapp-http"); websiteHttp.getDomainNames().add("myapp.example.com"); websiteHttp.setApplicationEndpoint(DockerContainerEndpoints.HTTP_TCP); WebsiteCertificate websiteHttpsCertificate = createWebsiteCertificate("CERTaaaCERT", "myapp.example.com"); Website websiteHttps = new Website("myapp-https"); websiteHttps.getDomainNames().add("myapp.example.com"); websiteHttps.setApplicationEndpoint(DockerContainerEndpoints.HTTP_TCP); websiteHttps.setHttps(true); Website websiteHttps2 = new Website("myapp2-https"); websiteHttps2.getDomainNames().add("myapp2.example.com"); websiteHttps2.setApplicationEndpoint(DockerContainerEndpoints.HTTP_TCP); WebsiteCertificate websiteHttps2Certificate = createWebsiteCertificate("CERTbbbCERT", "myapp2.example.com"); websiteHttps2.setHttps(true); websiteHttps2.setHttpsOriginToHttp(true); Application application = new Application(); application.setName("myphp"); ChangesContext changes = new ChangesContext(getCommonServicesContext().getResourceService()); changes.resourceAdd(machine); changes.resourceAdd(infraUrlUnixUser); changes.resourceAdd(unixUser); changes.resourceAdd(application); changes.resourceAdd(websiteHttp); changes.resourceAdd(websiteHttps); changes.resourceAdd(websiteHttpsCertificate); changes.resourceAdd(websiteHttps2); changes.resourceAdd(websiteHttps2Certificate); // Create links changes.linkAdd(application, LinkTypeConstants.RUN_AS, unixUser); changes.linkAdd(application, LinkTypeConstants.INSTALLED_ON, machine); changes.linkAdd(websiteHttp, LinkTypeConstants.INSTALLED_ON, machine); changes.linkAdd(websiteHttp, LinkTypeConstants.POINTS_TO, application); changes.linkAdd(websiteHttps, LinkTypeConstants.INSTALLED_ON, machine); changes.linkAdd(websiteHttps, LinkTypeConstants.POINTS_TO, application); changes.linkAdd(websiteHttps, LinkTypeConstants.USES, websiteHttpsCertificate); changes.linkAdd(websiteHttps2, LinkTypeConstants.INSTALLED_ON, machine); changes.linkAdd(websiteHttps2, LinkTypeConstants.POINTS_TO, application); changes.linkAdd(websiteHttps2, LinkTypeConstants.USES, websiteHttps2Certificate); // Execute getInternalServicesContext().getInternalChangeService().changesExecute(changes); // Assert JunitsHelper.assertState(getCommonServicesContext(), getInternalServicesContext(), "WebsiteTest-testWithAppHttpHttpsAndOriginRewrite-state-1.json", getClass(), true); // Update one cert changes.clear(); websiteHttpsCertificate = getCommonServicesContext().getResourceService().resourceFindByPk(new WebsiteCertificate("myapp.example.com")).get(); changes.resourceUpdate(websiteHttpsCertificate, createWebsiteCertificate("CERTcccCERT", "myapp.example.com")); getInternalServicesContext().getInternalChangeService().changesExecute(changes); JunitsHelper.assertState(getCommonServicesContext(), getInternalServicesContext(), "WebsiteTest-testWithAppHttpHttpsAndOriginRewrite-state-2.json", getClass(), true); } @Test public void testWithAppHttps() { // Create resources Machine machine = new Machine("h1.example.com", "192.168.0.200"); UnixUser infraUrlUnixUser = new UnixUser(70000L, "infra_url_redirection", "/home/infra_url_redirection", null, null); UnixUser unixUser = new UnixUser(72000L, "myapp", "/home/myapp", null, null); Website website = new Website("myapp"); website.getDomainNames().add("myapp.example.com"); website.setApplicationEndpoint(DockerContainerEndpoints.HTTPS_TCP); Application application = new Application(); application.setName("myphp"); ChangesContext changes = new ChangesContext(getCommonServicesContext().getResourceService()); changes.resourceAdd(machine); changes.resourceAdd(infraUrlUnixUser); changes.resourceAdd(unixUser); changes.resourceAdd(application); changes.resourceAdd(website); // Create links changes.linkAdd(application, LinkTypeConstants.RUN_AS, unixUser); changes.linkAdd(application, LinkTypeConstants.INSTALLED_ON, machine); changes.linkAdd(website, LinkTypeConstants.INSTALLED_ON, machine); changes.linkAdd(website, LinkTypeConstants.POINTS_TO, application); // Execute getInternalServicesContext().getInternalChangeService().changesExecute(changes); // Assert JunitsHelper.assertState(getCommonServicesContext(), getInternalServicesContext(), "WebsiteTest-testWithAppHttps-state.json", getClass(), true); } }
true
9263e4ae7bfb908f8b092cf04e1d0519e13421aa
Java
stroandr/labs
/trainer/JAVA_LABS/src/main/java/de/gedoplan/seminar/java/exercise/oo/HolzArtikel.java
UTF-8
763
2.671875
3
[]
no_license
/* * Copyright (c) 2016 * GEDOPLAN Unternehmensberatung und EDV-Organisation GmbH * Stieghorster Str. 60, D-33605 Bielefeld, Germany * http://www.gedoplan.de * All rights reserved. */ package de.gedoplan.seminar.java.exercise.oo; public class HolzArtikel extends Artikel3 { private boolean zuschnitt; public HolzArtikel(int artikelnummer, String bezeichnung, double preis, boolean zuschnitt) { super(artikelnummer, bezeichnung, preis); this.zuschnitt = zuschnitt; } public boolean getZuschnitt() { return this.zuschnitt; } public void setZuschnitt(boolean zuschnitt) { this.zuschnitt = zuschnitt; } @Override public String toString() { return super.toString() + ", Zuschnitt möglich = " + this.zuschnitt; } }
true
0849664c1c20af9a1f315ae82e8e31e35e2a2a57
Java
snamper/sofn-server
/sofn-sso-web/src/main/java/com/sofn/service/sso/SSOAppService.java
UTF-8
990
1.96875
2
[]
no_license
package com.sofn.service.sso; import com.sofn.core.base.BaseService; import com.sofn.core.constant.CurrentUser; import com.sofn.core.support.dubbo.spring.annotation.DubboReference; import com.sofn.provider.sso.SSOLoginProvider; import org.springframework.stereotype.Service; import java.util.Map; @Service public class SSOAppService extends BaseService<SSOLoginProvider,CurrentUser> { @DubboReference public void setSSOLoginProvider(SSOLoginProvider provider){ this.provider = provider; } /** * Login map. * * @param account the account * @param password the password * @return the map */ public Map<String, Object> loginApp(String account, String password) { return provider.loginApp(account, password); } /** * Logout. * * @param token the token * @param type the type */ public void logout(String token, String type) { provider.logout(token, type); } }
true
e731cf62f1e8c64fb979be898cff0be50f7f7ee3
Java
nidhalmesselmani/FrontEnd
/app/src/main/java/com/example/nidhal/frontend/mainclasses/FillInsurance.java
UTF-8
9,082
2.0625
2
[]
no_license
package com.example.nidhal.frontend.mainclasses; import android.content.Intent; import android.os.Bundle; import android.os.PersistableBundle; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Toast; import com.example.nidhal.frontend.R; import com.example.nidhal.frontend.TokenManager; import com.example.nidhal.frontend.entities.Agency; import com.example.nidhal.frontend.entities.AgencyResponse; import com.example.nidhal.frontend.entities.Insurance; import com.example.nidhal.frontend.entities.InsuranceResponse; import com.example.nidhal.frontend.entities.PoliceResponse; import com.example.nidhal.frontend.entities.UserResponse; import com.example.nidhal.frontend.network.ApiService; import com.example.nidhal.frontend.network.RetrofitBuilder; import com.weiwangcn.betterspinner.library.material.MaterialBetterSpinner; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by Nidhal on 27/07/2017. */ public class FillInsurance extends AppCompatActivity { //crée le tag Actitivity private static final String TAG = "FillInsurance"; String[] AssuranceList = {"One", "Two"}; String[] AgenceList = {"One"}; List<Insurance> insurances; List<Agency> agencies; ApiService service; TokenManager tokenManager; @BindView(R.id.Assurance_spinner) MaterialBetterSpinner Assurance_spinner; @BindView(R.id.Agence_spinner) MaterialBetterSpinner Agence_spinner; @BindView(R.id.num_police_value) EditText num_police_value; Call<InsuranceResponse> insuranceCall; Call<AgencyResponse> agencyeCall; Call<UserResponse> callGetUser; MaterialBetterSpinner insuranceSpinner; MaterialBetterSpinner agenceSpinner; int idList[]; String userId; Agency selectedAgency; Insurance selectedInsurance; //make a police call Call<Void> callPolice; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.creating_account_insurance); Toast.makeText(this, "I'm here", Toast.LENGTH_SHORT).show(); insurances = new ArrayList<Insurance>(); agencies = new ArrayList<Agency>(); ; //get an instance of the token manager tokenManager = TokenManager.getInstance(getSharedPreferences("prefs", MODE_PRIVATE)); //service pour accéder a des ressources privés service = RetrofitBuilder.createServiceWithAuth(ApiService.class, tokenManager); ButterKnife.bind(this); //call the insurance service callGetUser = service.getUser(); callGetUser.enqueue(new Callback<UserResponse>() { @Override public void onResponse(Call<UserResponse> call, Response<UserResponse> response) { userId = response.body().getId(); } @Override public void onFailure(Call<UserResponse> call, Throwable t) { } }); insuranceCall = service.getInsurances(); insuranceCall.enqueue(new Callback<InsuranceResponse>() { @Override public void onResponse(Call<InsuranceResponse> call, Response<InsuranceResponse> response) { int i; for (i = 0; i < response.body().getData().toArray().length; i++) { AssuranceList[i] = response.body().getData().get(i).getName(); Insurance is = new Insurance(); is.setName(response.body().getData().get(i).getName()); is.setId(response.body().getData().get(i).getId()); insurances.add(is); } ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(FillInsurance.this, android.R.layout.simple_dropdown_item_1line, AssuranceList); insuranceSpinner.setAdapter(arrayAdapter); } @Override public void onFailure(Call<InsuranceResponse> call, Throwable t) { } }); //make adapter assurance list spinner ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, AssuranceList); insuranceSpinner = (MaterialBetterSpinner) findViewById(R.id.Assurance_spinner); insuranceSpinner.setAdapter(arrayAdapter); ArrayAdapter<String> arrayAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, AgenceList); agenceSpinner = (MaterialBetterSpinner) findViewById(R.id.Agence_spinner); agenceSpinner.setAdapter(arrayAdapter1); insuranceSpinner.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { Toast.makeText(getApplicationContext(), "selected" + insuranceSpinner.getText().toString(), Toast.LENGTH_SHORT).show(); selectedInsurance = new Insurance(); selectedInsurance.setName(insuranceSpinner.getText().toString()); int i = 0; for (Insurance ainsurance : insurances) { if (ainsurance.getName().equals(insuranceSpinner.getText().toString())) { selectedInsurance.setId(ainsurance.getId()); agencyeCall = service.get_agences(ainsurance.getId()); agencyeCall.enqueue(new Callback<AgencyResponse>() { @Override public void onResponse(Call<AgencyResponse> call, Response<AgencyResponse> response) { int i; agenceSpinner.setText(""); List<String> agenciesList = new ArrayList<String>(); for (i = 0; i < response.body().getData().toArray().length; i++) { agenciesList.add(response.body().getData().get(i).getName()); Agency ag = new Agency(); ag.setId(response.body().getData().get(i).getId()); ag.setName(response.body().getData().get(i).getName()); agencies.add(ag); } ArrayAdapter<String> arrayAdapter1 = new ArrayAdapter<String>(FillInsurance.this, android.R.layout.simple_dropdown_item_1line, agenciesList); agenceSpinner.setAdapter(arrayAdapter1); } @Override public void onFailure(Call<AgencyResponse> call, Throwable t) { } }); } } } }); agenceSpinner.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { selectedAgency = new Agency(); selectedAgency.setName(agenceSpinner.getText().toString()); for (Agency aAgency : agencies) { if (aAgency.getName().equals(agenceSpinner.getText().toString())) { selectedAgency.setId(aAgency.getId()); } } } }); } @OnClick(R.id.apply_fill) void apply_fill() { callPolice = service.create_police(num_police_value.getText().toString(),userId,String.valueOf(selectedInsurance.getId()),String.valueOf(selectedAgency.getId())); callPolice.enqueue(new Callback<Void>() { @Override public void onResponse(Call<Void> call, Response<Void> response) { Intent intent = new Intent(getBaseContext(), FillVehicle.class); intent.putExtra("num_police", num_police_value.getText().toString()); startActivity(intent); } @Override public void onFailure(Call<Void> call, Throwable t) { Log.d(TAG,t.toString()); } }); } }
true
5bad4e8ad94cc6cb0b51d44ff4767915dc7ccd83
Java
GaryDev/java-android
/WCFApp/src/org/snow/wcfapp/soap/object/KvmListBase.java
UTF-8
1,141
2.21875
2
[]
no_license
package org.snow.wcfapp.soap.object; import java.util.Hashtable; import java.util.List; import org.ksoap2.serialization.KvmSerializable; import org.ksoap2.serialization.PropertyInfo; public abstract class KvmListBase<T> implements KvmSerializable { public static final String NAMESPACE = "http://snow.org/retailservice/2014/02/27/"; protected List<T> list; protected List<String> nameList; protected String nameSpace; public KvmListBase(List<T> list, List<String> nameList) { this(NAMESPACE, list, nameList); } public KvmListBase(String nameSpace, List<T> list, List<String> nameList) { this.nameSpace = nameSpace; this.list = list; this.nameList = nameList; } @Override public Object getProperty(int index) { return list.get(index); } @Override public int getPropertyCount() { return list.size(); } @Override public void getPropertyInfo(int index, Hashtable ht, PropertyInfo info) { info.namespace = nameSpace; info.name = nameList.get(index); } @Override public void setProperty(int index, Object value) { list.add(index, (T)value); } }
true
81ba55ed83f8afda086d68bfa478b2ba9d414144
Java
alexisvincent/ArtExplorer
/src/artexplorer/expressions/X.java
UTF-8
365
2.4375
2
[]
no_license
package artexplorer.expressions; import java.util.Random; /** * * @author alexisvincent */ public class X extends Expression { @Override public double evaluate(double x, double y) { return x; } @Override public Expression variation(int maxDepth, Random random) { return leafVariation(this, maxDepth, random); } }
true
fa88e80e4b903f6beaebb41070081403879893d4
Java
RayWuBlue/Anywhere
/app/src/main/java/com/ray/anywhere/activity/WebContent.java
UTF-8
5,279
1.84375
2
[]
no_license
package com.ray.anywhere.activity; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.webkit.DownloadListener; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.RelativeLayout; import com.ray.anywhere.R; import com.ray.anywhere.base.BaseActivity; import com.ray.anywhere.helper.NetHelper; import com.ray.anywhere.utils.AndroidShare; import com.ray.anywhere.utils.DownloadManageUtil; import com.ray.anywhere.utils.T; import com.ray.anywhere.widgets.MyProgressBar; public class WebContent extends BaseActivity { private WebSettings webSettings = null; private WebView web = null; private MyProgressBar mpb; private RelativeLayout clickReLoad; public Context mcontext; @SuppressLint("SetJavaScriptEnabled") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.act_web_content); setTitle(getIntent().getStringExtra("title")); mcontext = this; web = (WebView) super.findViewById(R.id.news_content_webview); // ���ͼƬ���¼��� clickReLoad.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { if (!NetHelper.isNetConnected(mcontext)) { T.showShort(mcontext, R.string.net_error_tip); } else { onCreate(null); } } }); // ������ϲ����� if (!NetHelper.isNetConnected(this)) { web.setVisibility(View.GONE); clickReLoad.setVisibility(View.VISIBLE); return; } else { web.setVisibility(View.VISIBLE); clickReLoad.setVisibility(View.GONE); } webSettings = web.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setBlockNetworkImage(false); webSettings.setBuiltInZoomControls(true); webSettings.setUseWideViewPort(false); webSettings.setLoadWithOverviewMode(true); web.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY); web.loadUrl(getIntent().getStringExtra("url")); //web.addJavascriptInterface(new JavascriptInterface(this),"imagelistner"); web.setDownloadListener(new MyWebViewDownLoadListener()); web.setWebViewClient(new MyWebViewClient()); web.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return false; } }); } // ע��js�������� private void addImageClickListner() { // ���js�����Ĺ��ܾ��ǣ��������е�img���㣬�����onclick�����������Ĺ�������ͼƬ�����ʱ����ñ���java�ӿڲ�����url��ȥ web.loadUrl("javascript:(function(){" + "var objs = document.getElementsByTagName(\"img\"); " + "for(var i=0;i<objs.length;i++) " + "{" + " objs[i].onclick=function() " + " { " + " window.imagelistner.openImage(this.src); " + " } " + "}" + "})()"); } // jsͨ�Žӿ� public class JavascriptInterface { private Context context; public JavascriptInterface(Context context) { this.context = context; } public void openImage(String img) { Intent intent = new Intent(); intent.putExtra("imgsrc", img); intent.setClass(context, ImgPreview.class); context.startActivity(intent); } } // ���� @SuppressLint("SetJavaScriptEnabled") private class MyWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return super.shouldOverrideUrlLoading(view, url); } @Override public void onPageFinished(WebView view, String url) { web.setVisibility(View.VISIBLE); mpb.dismiss(); view.getSettings().setJavaScriptEnabled(true); super.onPageFinished(view, url); // html�������֮����Ӽ���ͼƬ�ĵ��js���� addImageClickListner(); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { web.setVisibility(View.GONE); mpb = new MyProgressBar(WebContent.this); mpb.setMessage("���ڼ�����..."); view.getSettings().setJavaScriptEnabled(true); super.onPageStarted(view, url, favicon); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); } } /** * ����ϵͳ������������� * */ private class MyWebViewDownLoadListener implements DownloadListener { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { DownloadManageUtil.DownloadFile(mcontext, url,"/yuol/DownLoad"); } } public void onClick(View v){ switch (v.getId()) { case R.id.intro: AndroidShare as = new AndroidShare(WebContent.this,"#"+getIntent().getStringExtra("title")+"#"+getIntent().getStringExtra("url"),""); as.show(); break; default: break; } } }
true
4845654df51004869947f620676479f5113097f9
Java
hawkular/hawkular-commons
/hawkular-rest-status/src/test/java/org/hawkular/commons/rest/status/ManifestUtilTest.java
UTF-8
2,306
1.710938
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2014-2015 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.hawkular.commons.rest.status; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map; import org.junit.Assert; import org.junit.Test; /** * @author <a href="https://github.com/ppalaga">Peter Palaga</a> * */ public class ManifestUtilTest { @Test public void testEmpty() throws IOException { Map<String, String> expected = new LinkedHashMap<>(); expected.put(ManifestUtil.IMPLEMENTATION_VERSION, ManifestUtil.UNKNOWN_VALUE); expected.put(ManifestUtil.BUILT_FROM_GIT, ManifestUtil.UNKNOWN_VALUE); Assert.assertEquals(expected, ManifestUtil.getVersionAttributes(getClass().getResource("/manifests/MANIFEST-empty.txt"))); } @Test public void testFull() throws IOException { Map<String, String> expected = new LinkedHashMap<>(); expected.put(ManifestUtil.IMPLEMENTATION_VERSION, "1.2.3.Final"); expected.put(ManifestUtil.BUILT_FROM_GIT, "eb699f45f5461bb4cf52aca651679edb01802c04"); Assert.assertEquals(expected, ManifestUtil.getVersionAttributes(getClass().getResource("/manifests/MANIFEST-full.txt"))); } @Test public void testPartial() throws IOException { Map<String, String> expected = new LinkedHashMap<>(); expected.put(ManifestUtil.IMPLEMENTATION_VERSION, ManifestUtil.UNKNOWN_VALUE); expected.put(ManifestUtil.BUILT_FROM_GIT, "eb699f45f5461bb4cf52aca651679edb01802c04"); Assert.assertEquals(expected, ManifestUtil.getVersionAttributes(getClass().getResource("/manifests/MANIFEST-partial.txt"))); } }
true
1c30eab0fe3c51da51609af7a4df48a67d946027
Java
sfohart/mestrado-ufba-pesquisa-orientada
/pesquisa-orientada/mestrado-core/src/main/java/br/ufba/dcc/mestrado/computacao/repository/impl/TagRepositoryImpl.java
UTF-8
2,483
2.28125
2
[]
no_license
package br.ufba.dcc.mestrado.computacao.repository.impl; import java.util.List; import javax.persistence.NoResultException; import javax.persistence.NonUniqueResultException; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.springframework.stereotype.Repository; import br.ufba.dcc.mestrado.computacao.entities.openhub.core.project.OpenHubTagEntity; import br.ufba.dcc.mestrado.computacao.repository.base.TagRepository; @Repository(TagRepositoryImpl.BEAN_NAME) public class TagRepositoryImpl extends BaseRepositoryImpl<Long, OpenHubTagEntity> implements TagRepository { public static final String BEAN_NAME = "tagRepository"; /** * */ private static final long serialVersionUID = 7801826722021443632L; public TagRepositoryImpl() { super(OpenHubTagEntity.class); } @Override public List<OpenHubTagEntity> findTagListByName(String name) { CriteriaBuilder criteriaBuilder = getEntityManager() .getCriteriaBuilder(); CriteriaQuery<OpenHubTagEntity> criteriaQuery = criteriaBuilder .createQuery(getEntityClass()); Root<OpenHubTagEntity> root = criteriaQuery.from(getEntityClass()); CriteriaQuery<OpenHubTagEntity> select = criteriaQuery.select(root); Path<String> namePath = root.<String>get("name"); Predicate namePredicate = criteriaBuilder.like(namePath, name + "%"); select.where(namePredicate); TypedQuery<OpenHubTagEntity> query = getEntityManager().createQuery( criteriaQuery); return query.getResultList(); } @Override public OpenHubTagEntity findByName(String name) { CriteriaBuilder criteriaBuilder = getEntityManager() .getCriteriaBuilder(); CriteriaQuery<OpenHubTagEntity> criteriaQuery = criteriaBuilder .createQuery(getEntityClass()); Root<OpenHubTagEntity> root = criteriaQuery.from(getEntityClass()); CriteriaQuery<OpenHubTagEntity> select = criteriaQuery.select(root); Predicate namePredicate = criteriaBuilder.equal(root.get("name"), name); select.where(namePredicate); TypedQuery<OpenHubTagEntity> query = getEntityManager().createQuery( criteriaQuery); OpenHubTagEntity result = null; try { result = query.getSingleResult(); } catch (NoResultException ex) { } catch (NonUniqueResultException ex) { } return result; } }
true
0e472f0102c33aac90189a05330060709cb1663d
Java
Aflynch/DriveSpectrum
/src/com/lynchsoftwareengineering/drivespectrum/MakeTestData.java
UTF-8
3,258
2.5
2
[]
no_license
package com.lynchsoftwareengineering.drivespectrum; import java.util.ArrayList; public class MakeTestData { public MakeTestData(){ } public static ArrayList<PointTime> getTestPointTimeArrayList(int numberOfPointTimesInt, int numberOfRountesInt, int numberOfOverLappingRountesInt){ // stringArraylist.add("33.97941432#-84.01260397#30.1#1396312154436#178.0"); // stringArraylist.add("33.97941432#-80.01260397#30.1#1396312154436#178.0"); // stringArraylist.add("35.97941432#-82.01260397#30.1#1396312154436#178.0"); ArrayList<PointTime> testPointTimeArraylist = new ArrayList<PointTime>(); String routeNameString; PointTime zeroPointTime = new PointTime(33.97941432, -84.01260397, 4.f, 90.f, (long) 10000000, "mac1", ""); routeNameString = zeroPointTime.getTimeInMillsLong()+zeroPointTime.getMacAddressString(); for(int i = 0; i < 4; i++){ testPointTimeArraylist.add(new PointTime(zeroPointTime.getLatDouble(), zeroPointTime.getLonDouble()+(.0001*(double)i), zeroPointTime.getSpeedMPS(), zeroPointTime.getBearingFloat(), zeroPointTime.getTimeInMillsLong()+i, zeroPointTime.getMacAddressString(), routeNameString)); } PointTime onePointTime = new PointTime(33.97941432, -84.01265397, 8.f, 90.f, (long) 20000000, "mac2", ""); routeNameString = onePointTime.getTimeInMillsLong()+onePointTime.getMacAddressString(); for(int i = 0; i < 4; i++){ testPointTimeArraylist.add(new PointTime(onePointTime.getLatDouble(), onePointTime.getLonDouble()+(.0001*(double)i), onePointTime.getSpeedMPS(), onePointTime.getBearingFloat(), onePointTime.getTimeInMillsLong()+i, onePointTime.getMacAddressString(), routeNameString)); } PointTime twoPointTime = new PointTime(33.97941432, -84.01260397, 6.f, 180.f, (long) 30000000, "mac3", ""); routeNameString = twoPointTime.getTimeInMillsLong()+twoPointTime.getMacAddressString(); for(int i = 0; i < 4; i++){ testPointTimeArraylist.add(new PointTime(twoPointTime.getLatDouble()+(.0001*(double)i), twoPointTime.getLonDouble(), twoPointTime.getSpeedMPS(), twoPointTime.getBearingFloat(), twoPointTime.getTimeInMillsLong()+i, twoPointTime.getMacAddressString(), routeNameString)); } PointTime threePointTime = new PointTime(33.97946432, -84.01260397, 10.f, 180.f, (long) 40000000, "mac4", ""); routeNameString = threePointTime.getTimeInMillsLong()+threePointTime.getMacAddressString(); for(int i = 0; i < 4; i++){ testPointTimeArraylist.add(new PointTime(threePointTime.getLatDouble()+(.0001*(double)i), threePointTime.getLonDouble(), threePointTime.getSpeedMPS(), threePointTime.getBearingFloat(), threePointTime.getTimeInMillsLong()+i, threePointTime.getMacAddressString(), routeNameString)); } PointTime fourPointTime = new PointTime(33.97945432, -84.01261397, 2.f, 180.f, (long) 50000000, "mac5", ""); routeNameString = fourPointTime.getTimeInMillsLong()+fourPointTime.getMacAddressString(); for(int i = 0; i < 4; i++){ testPointTimeArraylist.add(new PointTime(fourPointTime.getLatDouble()+(.0001*(double)i), fourPointTime.getLonDouble(), fourPointTime.getSpeedMPS(), fourPointTime.getBearingFloat(), fourPointTime.getTimeInMillsLong()+i, fourPointTime.getMacAddressString(), routeNameString)); } return testPointTimeArraylist; } }
true
b9b5d9846237260c7d8588064da4d30f0896701d
Java
yelcartoubi/ebics-java-service
/src/main/java/io/element36/cash36/ebics/generated/camt_053_001_04/CardAggregated1.java
UTF-8
4,994
1.664063
2
[ "Apache-2.0" ]
permissive
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.1 // See <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2021.05.13 at 08:22:07 AM CEST // package io.element36.cash36.ebics.generated.camt_053_001_04; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for CardAggregated1 complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="CardAggregated1"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="AddtlSvc" type="{urn:iso:std:iso:20022:tech:xsd:camt.053.001.04}CardPaymentServiceType2Code" minOccurs="0"/&gt; * &lt;element name="TxCtgy" type="{urn:iso:std:iso:20022:tech:xsd:camt.053.001.04}ExternalCardTransactionCategory1Code" minOccurs="0"/&gt; * &lt;element name="SaleRcncltnId" type="{urn:iso:std:iso:20022:tech:xsd:camt.053.001.04}Max35Text" minOccurs="0"/&gt; * &lt;element name="SeqNbRg" type="{urn:iso:std:iso:20022:tech:xsd:camt.053.001.04}CardSequenceNumberRange1" minOccurs="0"/&gt; * &lt;element name="TxDtRg" type="{urn:iso:std:iso:20022:tech:xsd:camt.053.001.04}DateOrDateTimePeriodChoice" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "CardAggregated1", propOrder = { "addtlSvc", "txCtgy", "saleRcncltnId", "seqNbRg", "txDtRg" }) public class CardAggregated1 { @XmlElement(name = "AddtlSvc") @XmlSchemaType(name = "string") protected CardPaymentServiceType2Code addtlSvc; @XmlElement(name = "TxCtgy") protected String txCtgy; @XmlElement(name = "SaleRcncltnId") protected String saleRcncltnId; @XmlElement(name = "SeqNbRg") protected CardSequenceNumberRange1 seqNbRg; @XmlElement(name = "TxDtRg") protected DateOrDateTimePeriodChoice txDtRg; /** * Gets the value of the addtlSvc property. * * @return * possible object is * {@link CardPaymentServiceType2Code } * */ public CardPaymentServiceType2Code getAddtlSvc() { return addtlSvc; } /** * Sets the value of the addtlSvc property. * * @param value * allowed object is * {@link CardPaymentServiceType2Code } * */ public void setAddtlSvc(CardPaymentServiceType2Code value) { this.addtlSvc = value; } /** * Gets the value of the txCtgy property. * * @return * possible object is * {@link String } * */ public String getTxCtgy() { return txCtgy; } /** * Sets the value of the txCtgy property. * * @param value * allowed object is * {@link String } * */ public void setTxCtgy(String value) { this.txCtgy = value; } /** * Gets the value of the saleRcncltnId property. * * @return * possible object is * {@link String } * */ public String getSaleRcncltnId() { return saleRcncltnId; } /** * Sets the value of the saleRcncltnId property. * * @param value * allowed object is * {@link String } * */ public void setSaleRcncltnId(String value) { this.saleRcncltnId = value; } /** * Gets the value of the seqNbRg property. * * @return * possible object is * {@link CardSequenceNumberRange1 } * */ public CardSequenceNumberRange1 getSeqNbRg() { return seqNbRg; } /** * Sets the value of the seqNbRg property. * * @param value * allowed object is * {@link CardSequenceNumberRange1 } * */ public void setSeqNbRg(CardSequenceNumberRange1 value) { this.seqNbRg = value; } /** * Gets the value of the txDtRg property. * * @return * possible object is * {@link DateOrDateTimePeriodChoice } * */ public DateOrDateTimePeriodChoice getTxDtRg() { return txDtRg; } /** * Sets the value of the txDtRg property. * * @param value * allowed object is * {@link DateOrDateTimePeriodChoice } * */ public void setTxDtRg(DateOrDateTimePeriodChoice value) { this.txDtRg = value; } }
true
442eecc186061a9b5997419867cd6811c6967043
Java
iamslash/learntocode
/leetcode/ParallelCourses/Solution.java
UTF-8
1,390
3.203125
3
[]
no_license
import java.util.*; // 9ms 81.46% 46MB 100.00% // DFS // O(V+E) O(V) class Solution { private boolean dfs(List<List<Integer>> G, List<Integer> D, List<Integer> S, int u) { // base if (S.get(u) == 1) return true; if (S.get(u) == 0) return false; // recursion S.set(u, 0); for (Integer v : G.get(u)) { if (!dfs(G, D, S, v)) return false; D.set(u, Math.max(D.get(u), 1 + D.get(v))); } S.set(u, 1); return true; } public int minimumSemesters(int N, int[][] R) { List<List<Integer>> G = new ArrayList<>(); for (int i = 0; i < N; ++i) G.add(new ArrayList<Integer>()); List<Integer> D = new ArrayList<Integer>(Collections.nCopies(N, 1)); List<Integer> S = new ArrayList<Integer>(Collections.nCopies(N, -1)); for (int[] e : R) { int u = e[0]-1; int v = e[1]-1; G.get(u).add(v); } // for (List<Integer> g : G) // System.out.println(Arrays.toString(g.toArray())); for (int u = 0; u < N; ++u) { if (!dfs(G, D, S, u)) return -1; } return Collections.max(D); } public static void main(String[] args) { int N = 3; int[][] R = {{1, 3},{2, 3}}; Solution sln = new Solution(); System.out.println(String.format("%d", sln.minimumSemesters(N, R))); } }
true
7a4ce854cc3e1286702f87ca514a4173d1d6e596
Java
1284517067/SmartParkAttractInvestmentManagementSystem_ServerSystem
/src/main/java/com/rzh/iot/service/impl/ApprovalProcessNodeServiceImpl.java
UTF-8
9,459
2.234375
2
[]
no_license
package com.rzh.iot.service.impl; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.rzh.iot.dao.ApprovalProcessDao; import com.rzh.iot.dao.ApprovalProcessNodeDao; import com.rzh.iot.model.ApprovalProcess; import com.rzh.iot.model.ApprovalProcessNode; import com.rzh.iot.service.ApprovalProcessNodeService; import com.rzh.iot.service.ApprovalProcessService; import com.rzh.iot.service.DepartmentService; import com.rzh.iot.service.PositionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; @Service public class ApprovalProcessNodeServiceImpl implements ApprovalProcessNodeService { @Autowired ApprovalProcessDao approvalProcessDao; @Autowired ApprovalProcessNodeDao approvalProcessNodeDao; @Autowired DepartmentService departmentService; @Autowired PositionService positionService; @Override public List<ApprovalProcessNode> getApprovalProcessNodeData(Long approvalProcessId) { List<ApprovalProcessNode> list = approvalProcessNodeDao .getApprovalProcessNodeListByApprovalProcessId(approvalProcessId); LinkedList<ApprovalProcessNode> data = new LinkedList<>(); for (ApprovalProcessNode item : list){ item.setDepartmentName(departmentService.getDepartmentNameByPositionId(item.getPositionId())); item.setPositionName(positionService.getPositionNameById(item.getPositionId())); if (item.getPrevNodeId() == null){ data.add(item); } } int size = data.size(); for (int i = 0 ; i < size ; i++){ for (ApprovalProcessNode next : list){ if (next.getPrevNodeId() != null && next.getPrevNodeId() == data.getLast().getApprovalProcessNodeId()){ data.add(next); size++; } } } return data; } @Override public HashMap<String, String> updateApprovalProcessNode(String approvalProcessId, String nodes , String submitType) { HashMap<String,String> map = new HashMap<>(); List<ApprovalProcessNode> list = mountApprovalProcessNode(approvalProcessId,nodes); switch (submitType){ case "新增": if (approvalProcessNodeDao.isApprovalProcessExist(Long.parseLong(approvalProcessId)) != 0){ map.put("responseCode","400"); map.put("msg","该审批流已存在审批节点"); return map; } createApprovalProcessNode(list); map.put("responseCode","200"); map.put("msg","保存成功"); break; case "更新": if (approvalProcessNodeDao.isApprovalProcessExist(Long.parseLong(approvalProcessId)) == 0) { map.put("responseCode","400"); map.put("msg","该审批流的节点已不存在"); return map; } approvalProcessNodeDao.deleteApprovalProcessNodeByApprovalProcessId(Long.parseLong(approvalProcessId)); createApprovalProcessNode(list); map.put("responseCode","200"); map.put("msg","更新成功"); break; } return map; } @Override public List<ApprovalProcess> getApprovalProcessNodeListData(Integer currentPage,Integer limit) { List<ApprovalProcess> list = approvalProcessNodeDao.getApprovalProcessList((currentPage - 1)*limit,limit); List<ApprovalProcessNode> nodes = approvalProcessNodeDao.getApprovalProcessNodeList(); for(ApprovalProcessNode node : nodes){ node.setPositionName(positionService.getPositionNameById(node.getPositionId())); node.setDepartmentName(departmentService.getDepartmentNameByPositionId(node.getPositionId())); } for (ApprovalProcess item : list){ List<ApprovalProcessNode> nodeList = new ArrayList<>(); for (ApprovalProcessNode node : nodes){ if (item.getApprovalProcessId().equals(node.getApprovalProcessId())){ nodeList.add(node); } } item.setNodes(sortApprovalProcessNodeList(nodeList)); } return list; } @Override public int getApprovalProcessCount() { return approvalProcessNodeDao.getApprovalProcessCount(); } @Override public HashMap<String, String> deleteApprovalProcessNodeByApprovalProcessId(Long approvalProcessId) { HashMap<String,String> map = new HashMap<>(); int result = approvalProcessNodeDao.deleteApprovalProcessNodeByApprovalProcessId(approvalProcessId); if (result == 0){ map.put("responseCode","400"); map.put("msg","删除失败"); return map; } map.put("responseCode","200"); map.put("msg","删除成功"); return map; } @Override public HashMap<String, Object> getApprovalProcessNodeListByKey(String key) { HashMap<String,Object> map = new HashMap<>(); List<ApprovalProcess> list = approvalProcessNodeDao.getApprovalProcessListByKey(key); if (list.size() == 0 ){ map.put("responseCode",400); map.put("msg","暂无数据"); return map; } List<ApprovalProcessNode> nodes = approvalProcessNodeDao.getApprovalProcessNodeList(); for (ApprovalProcessNode node:nodes){ node.setDepartmentName(departmentService.getDepartmentNameByPositionId(node.getPositionId())); node.setPositionName(positionService.getPositionNameById(node.getPositionId())); } list = mountApprovalProcessData(list,nodes); map.put("responseCode",200); map.put("dataList",list); map.put("msg","查询成功"); return map; } @Override public int getCountOfApprovalProcessNodeByKey(String key) { return approvalProcessNodeDao.getCountOfApprovalProcessByKey(key); } @Override public JSONObject getApprovalProcessNodesByContractType(String contractType,String businessType) { JSONObject object = new JSONObject(); Long approvalProcessId = approvalProcessDao.getActiveApprovalProcessIdByContractType(contractType,businessType); if (approvalProcessId == null){ return null; } object.put("responseCode",200); object.put("approvalProcess",getApprovalProcessNodeData(approvalProcessId)); return object; } public List<ApprovalProcessNode> mountApprovalProcessNode(String approvalProcessId,String nodes){ JSONArray nodeData = JSONArray.parseArray(nodes); List<ApprovalProcessNode> list = new ArrayList<>(); for (int i = 0 ; i < nodeData.size() ; i++){ JSONObject object = nodeData.getJSONObject(i); Object positionIds = JSONObject.parse(object.getString("positionId")); Long positionId = null; if (positionIds instanceof Integer){ positionId = ((Integer) positionIds).longValue(); }else { positionId = ((JSONArray) positionIds).getLong(((JSONArray) positionIds).size() - 1); } ApprovalProcessNode node = new ApprovalProcessNode(); node.setApprovalProcessId(Long.parseLong(approvalProcessId)); node.setApprovalProcessNodeName(object.getString("approvalProcessNodeName")); node.setPositionId(positionId); list.add(node); } return list; } public void createApprovalProcessNode(List<ApprovalProcessNode> list){ for (int i = 0 ; i < list.size() ; i++){ if (i != 0){ list.get(i).setPrevNodeId(list.get(i-1).getApprovalProcessNodeId()); } approvalProcessNodeDao.createApprovalProcessNode(list.get(i)); } } public List<ApprovalProcessNode> sortApprovalProcessNodeList(List<ApprovalProcessNode> list){ List<ApprovalProcessNode> nodes = new ArrayList<>(); for (ApprovalProcessNode item : list){ if (item.getPrevNodeId() == null){ nodes.add(item); } } int size = nodes.size(); for (int i = 0 ; i < size; i++){ for (ApprovalProcessNode item : list){ if (item.getPrevNodeId() != null){ if (item.getPrevNodeId().equals(nodes.get(i).getApprovalProcessNodeId())){ nodes.add(item); size++; } } } } return nodes; } private List<ApprovalProcess> mountApprovalProcessData(List<ApprovalProcess> list , List<ApprovalProcessNode> nodes){ for (ApprovalProcess item : list){ List<ApprovalProcessNode> nodeList = new ArrayList<>(); for (ApprovalProcessNode node :nodes){ if (node.getApprovalProcessId().equals(item.getApprovalProcessId())){ nodeList.add(node); } } item.setNodes(sortApprovalProcessNodeList(nodeList)); } return list; } }
true
584b69fe2e701dd5c9c6f8ea2f35167d7cd23066
Java
ajedaev/TestMap
/app/src/main/java/com/map/test/MainActivity.java
UTF-8
4,588
1.976563
2
[]
no_license
package com.map.test; import android.arch.lifecycle.LiveData; import android.arch.lifecycle.Observer; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.map.test.utils.SharedPreferencesFile; import java.io.IOException; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class MainActivity extends AppCompatActivity implements OnMapReadyCallback { private SupportMapFragment mapFragment; private GoogleMap map; private final String TAG = "myLogs"; private CameraPosition mCameraPosition; private MarkerOptions mMarkerOptions; private LiveData<String> liveData; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SharedPreferencesFile.initSharedReferences(this); mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); MapApplication.getApi().getData("bash", 50).enqueue(new Callback<List<PostModel>>() { @Override public void onResponse(Call<List<PostModel>> call, Response<List<PostModel>> response) { //Данные успешно пришли, но надо проверить response.body() на null String str = ""; } @Override public void onFailure(Call<List<PostModel>> call, Throwable t) { //Произошла ошибка } }); liveData = DataController.getInstance().getData(); liveData.observe(this, new Observer<String>() { @Override public void onChanged(@Nullable String value) { ((TextView) findViewById(R.id.location_tv)).setText(value); } }); } private void init() { map.setMyLocationEnabled(true); map.getUiSettings().setCompassEnabled(true); map.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() { @Override public void onCameraMove() { mCameraPosition = map.getCameraPosition(); // ((TextView) findViewById(R.id.location_tv)).setText(mCameraPosition.toString()); } }); map.setOnMapClickListener(new GoogleMap.OnMapClickListener() { @Override public void onMapClick(LatLng latLng) { map.clear(); map.addMarker(new MarkerOptions() .position(latLng) .title("Hello world")); } }); } public void onClickTest(View view) { // if (map.getMapType() == GoogleMap.MAP_TYPE_NORMAL) // map.setMapType(GoogleMap.MAP_TYPE_HYBRID); // else // map.setMapType(GoogleMap.MAP_TYPE_NORMAL); // mapFragment.getMapAsync(this); DataController.getInstance().setValue("QQQ"); } public void onClickLocation(View view) { CameraPosition cameraPosition = new CameraPosition.Builder() .target(new LatLng(SharedPreferencesFile.getLocationPosX(), SharedPreferencesFile.getLocationPosY())) .zoom(SharedPreferencesFile.getLocationPosZoom()) .build(); CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition); map.animateCamera(cameraUpdate); } @Override public void onMapReady(GoogleMap googleMap) { map = googleMap; init(); } @Override protected void onStop() { super.onStop(); if (mCameraPosition != null) { SharedPreferencesFile.setLocationPosX((float) mCameraPosition.target.latitude); SharedPreferencesFile.setLocationPosY((float) mCameraPosition.target.longitude); SharedPreferencesFile.setLocationPosZoom(mCameraPosition.zoom); } DataController.getInstance().setValue("PAUSE"); } }
true
7fd728bc2b462a2014ec8871ea1c44c1baabdefc
Java
SibRaza15/BitCoin-Pricer
/src/test/java/com/bitcoin/BitcoinPricerTest.java
UTF-8
4,315
2.25
2
[]
no_license
package com.bitcoin; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; import org.testng.annotations.DataProvider; import org.junit.After; import org.junit.Before; import org.junit.Test; import junitparams.JUnitParamsRunner; import org.mockito.Mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.times; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import com.tngtech.java.junit.dataprovider.UseDataProvider; @RunWith(JUnitParamsRunner.class) public class BitcoinPricerTest { @Test public void testMock1 (){ //Arrange double price = 6000.00; BitCoinValueService bsp = Mockito.mock(BitCoinValueService.class); Mockito.when(bsp.findPrice()).thenReturn(price); BitCoinPricer bp = new BitCoinPricer(bsp); double expected = price * 1.227481; //Act double actual = bp.convertEuro(); //Assert assertEquals(expected, actual, 1.0); Mockito.verify(bsp).findPrice(); } @Test public void testMock2 (){ //Arrange double price = 5000.00; BitCoinValueService bsp = Mockito.mock(BitCoinValueService.class); Mockito.when(bsp.findPrice()).thenReturn(price); BitCoinPricer bp = new BitCoinPricer(bsp); // bad logic double expected = price * 1.227481; //Act double actual = bp.convertEuro(); //Assert assertEquals(expected, actual, 1.0); Mockito.verify(bsp).findPrice(); } @Test(expected=NullPointerException.class) public void testMock3 (){ //Arrange double price = (Double) null; BitCoinValueService bsp = Mockito.mock(BitCoinValueService.class); Mockito.when(bsp.findPrice()).thenReturn(price); //Assert assertNull(bsp.findPrice()); Mockito.verify(bsp).findPrice(); } @Test public void testMock4 (){ //Arrange double price = 0.00; BitCoinValueService bsp = Mockito.mock(BitCoinValueService.class); Mockito.when(bsp.findPrice()).thenReturn(price); BitCoinPricer bp = new BitCoinPricer(bsp); double expected = price * 1.227481; //Act double actual = bp.convertEuro(); //Assert assertEquals(expected, actual, 1.0); Mockito.verify(bsp).findPrice(); } @Test public void testMock5 (){ //Arrange double price = -1000.00; BitCoinValueService bsp = Mockito.mock(BitCoinValueService.class); Mockito.when(bsp.findPrice()).thenReturn(price); BitCoinPricer bp = new BitCoinPricer(bsp); //fail this test on purpose double expected = 5000.00 * 1.227481; //Act double actual = bp.convertEuro(); //Assert assertEquals(expected, actual, 1.0); Mockito.verify(bsp).findPrice(); } @Test public void testAssertEqualsSameObjects() { BitCoinValueService bsp = Mockito.mock(BitCoinValueService.class); BitCoinPricer bp = new BitCoinPricer(bsp); bp.convertEuro(); assertEquals("These are two different object", bsp.findPrice(),bp.convertEuro(), 5.00); } // integration testing @Test public void testIntegration_TDD() { double price = 9000.00; BitCoinValueService bsp = Mockito.mock(BitCoinValueService.class); Mockito.when(bsp.findPrice()).thenReturn(price); BitCoinPricer bp = new BitCoinPricer(bsp); assertEquals(11047.32,bp.convertEuro_TDD(bsp.findPrice()),1.00); Mockito.verify(bsp, times(2)).findPrice(); } @Test public void testIntegration() { double price = 9000.00; BitCoinValueService bsp = Mockito.mock(BitCoinValueService.class); Mockito.when(bsp.findPrice()).thenReturn(price); BitCoinPricer bp = new BitCoinPricer(bsp); assertEquals(11047.32,bp.convertEuro(),1.00); Mockito.verify(bsp, times(1)).findPrice(); } }
true
47e2debb4f8f9746b77ed51a0127db49979baec1
Java
Sashanity/Sudoku-game
/src/edu/sjsu/cs/cs151/model/EasyGame.java
UTF-8
796
3.21875
3
[]
no_license
package edu.sjsu.cs.cs151.model; /** * This is a Model class * One of the implementations of the Game class * Number of set up to the board is 27 */ import java.util.Random; /** * Second implementation of the Gaame class * * @author Aleksandra, Ben, Jefferson * */ public class EasyGame extends Game { /** * Constructor */ public EasyGame() { super(); setDifficulty(0); } @Override /** * @see Game.java */ public void addClues(int[][] aSolution) { int randRow, randCol, value; for (int i = 0; i < MIN_NUM_CLUES + 10; i++) { randRow = new Random().nextInt(SIZE); randCol = new Random().nextInt(SIZE); value = aSolution[randRow][randCol]; if (getGameArray()[randRow][randCol] == 0) setValue(value, randRow, randCol); else { i--; } } } }
true
ea407ec4c0b4b71a9bb31e7549076483c68cac3a
Java
my-jabin/springbootTutorial
/src/main/java/com/jiujiu/springboot/controller/LinkController.java
UTF-8
1,560
2.453125
2
[]
no_license
package com.jiujiu.springboot.controller; import com.jiujiu.springboot.annotation.Timed; import com.jiujiu.springboot.exception.LinkNotFoundException; import com.jiujiu.springboot.model.Link; import com.jiujiu.springboot.service.LinkService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Optional; /** * @ClassName LinkController * @AuThor yanbin.hu * @Date 1/18/2019 * @Description **/ @RestController @RequestMapping("/link") public class LinkController { private final Logger logger = LoggerFactory.getLogger(LinkController.class); private final LinkService linkService; public LinkController(LinkService linkService) { this.linkService = linkService; } /** * @Timed annotation is used for experimentation of spring aop. */ @GetMapping @Timed public List<Link> read(){ return this.linkService.findAll(); } @GetMapping("/{id}") @Timed public Link getLinkById(@PathVariable long id){ logger.info("find link by id = " +id); Optional<Link> link = this.linkService.findById(id); if(link.isPresent()){ return link.get(); }else{ throw new LinkNotFoundException("Cannot find the link with id " + id); } } }
true
5969b9270cd29c835ad76f83139770b9d58bb39b
Java
benjaminrclark/cate
/src/main/java/org/cateproject/repository/jpa/auth/UserAccountRepository.java
UTF-8
577
2.125
2
[ "MIT" ]
permissive
package org.cateproject.repository.jpa.auth; import org.cateproject.domain.auth.UserAccount; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface UserAccountRepository extends JpaRepository<UserAccount, Long>, JpaSpecificationExecutor<UserAccount>{ UserAccount findByUsername(String username); Page<UserAccount> findByUsernameStartingWith(String username, Pageable pageable); }
true
cc4ee8bb11d6441eff810aada24e630e47480eaa
Java
HessTina-YuI/leetcode-java
/src/main/java/org/yui/medium/p0394/Solution.java
UTF-8
1,491
3.3125
3
[ "MIT" ]
permissive
package org.yui.medium.p0394; import java.util.Stack; /** * @program: leetcode * @package: org.yui.hard.p0345 * @description: 394. 字符串解码 * @author: YuI * @create: 2020/5/28 11:00 **/ public class Solution { private static class Encode { /** 重复次数 */ public int time = 0; /** 拼接字符串 */ public StringBuilder str = new StringBuilder(); } public String decodeString(String s) { Stack<Encode> stack = new Stack<>(); Encode encode = new Encode(); encode.time = -1; stack.push(encode); encode = new Encode(); for (char c : s.toCharArray()) { if (c >= '0' && c <= '9') { encode.time = encode.time * 10 + (c - '0'); } if (c == '[') { stack.push(encode); encode = new Encode(); } if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') { stack.peek().str.append(c); } if (c == ']') { Encode temp = stack.pop(); for (int i = 0; i < temp.time; i++) { stack.peek().str.append(temp.str); } } } return stack.peek().str.toString(); } public static void main(String[] args) { Solution solution = new Solution(); String result = solution.decodeString("3[a]2[b4[F]c]"); System.out.println(result); } }
true
1562566605e7a975a99458309c76e848d576d516
Java
rubertmi00/LeftoversCookbook
/src/util/Sanitizer.java
UTF-8
164
2.390625
2
[]
no_license
package util; public class Sanitizer { public static String sanitizeInput(String input) { return input.replace(";", "").replace("(", "").replace(")", ""); } }
true
ec33fb75d47b0f9fd6891bae873f923acdc0b098
Java
louismarie/budgetview
/budgetview/bv_server/src/test/java/com/budgetview/server/cloud/functests/CloudAutoImportTest.java
UTF-8
10,793
1.84375
2
[]
no_license
package com.budgetview.server.cloud.functests; import com.budgetview.model.TransactionType; import com.budgetview.server.cloud.functests.testcases.CloudDesktopTestCase; import com.budgetview.server.cloud.stub.BudgeaStatement; import com.budgetview.shared.cloud.budgea.BudgeaCategory; import org.globsframework.utils.Dates; public class CloudAutoImportTest extends CloudDesktopTestCase { public void setUp() throws Exception { resetWindow(); setInMemory(false); setDeleteLocalPrevayler(true); super.setUp(); setDeleteLocalPrevayler(false); } protected void tearDown() throws Exception { resetWindow(); super.tearDown(); } public void testAutoImportOnStartup() throws Exception { cloud.createSubscription("toto@example.com", Dates.tomorrow()); budgea.pushNewConnectionResponse(1, 123, 40); budgea.pushStatement(BudgeaStatement.init() .addConnection(1, 123, 40, "Connecteur de test", "2016-08-10 17:44:26") .addAccount(1, "Main account 1", "100200300", "checking", 1000.00, "2016-08-10 13:00:00") .addTransaction(1, "2016-08-10 13:00:00", -100.00, "AUCHAN") .addTransaction(2, "2016-08-12 17:00:00", -50.00, "EDF") .endAccount() .addAccount(2, "Main account 2", "200300400", "checking", 2000.00, "2016-08-10 11:00:00") .addTransaction(3, "2016-08-11 11:00:00", -200.00, "FNAC") .endAccount() .endConnection() .get()); operations.openImportDialog() .selectCloudForNewUser() .register("toto@example.com") .processEmailAndNextToBankSelection(mailbox.getDeviceVerificationCode("toto@example.com")) .selectBank("Connecteur de test") .next() .setChoice("Type de compte", "Particuliers") .setText("Identifiant", "1234") .setPassword("Code (1234)", "1234") .next() .waitForNotificationAndDownload(mailbox.checkStatementReady("toto@example.com")) .checkTransactions(new Object[][]{ {"2016/08/12", "EDF", "-50.00"}, {"2016/08/10", "AUCHAN", "-100.00"}, }) .importAccountAndOpenNext() .checkTransactions(new Object[][]{ {"2016/08/11", "FNAC", "-200.00"}, }) .importAccountAndComplete(); categorization.setNewVariable("AUCHAN", "Groceries", 100.00); budgea.sendStatement(BudgeaStatement.init() .addConnection(1, 123, 40, "Connecteur de test", "2016-08-15 17:44:26") .addAccount(1, "Main account 1", "100200300", "checking", 1000.00, "2016-08-15 13:00:00") .addTransaction(4, "2016-08-13 13:00:00", -25.00, "TOTAL", BudgeaCategory.ESSENCE) .addTransaction(5, "2016-08-14 15:00:00", -20.00, "AUCHAN", BudgeaCategory.ALIMENTATION) .addTransaction(6, "2016-08-15 15:00:00", -50.00, "FOUQUETS", BudgeaCategory.RESTAURANT) .endAccount() .addAccount(2, "Main account 2", "200300400", "checking", 1500.00, "2016-08-15 13:00:00") .addTransaction(7, "2016-08-13 14:00:00", -500.00, "APPLE") .endAccount() .endConnection() .get()); restartApplication(); autoImport.checkDisplayed() .waitForEndOfProgress() .performAction("Categorize operations"); views.checkCategorizationSelected(); categorization.checkShowsAllTransactions(); categorization.initContent() .add("14/08/2016", "Groceries", "AUCHAN", -20.00) .add("15/08/2016", "", "FOUQUETS", -50.00) .add("13/08/2016", "", "TOTAL", -25.00) .check(); transactions.initContent() .add("15/08/2016", TransactionType.PRELEVEMENT, "FOUQUETS", "", -50.00) .add("14/08/2016", TransactionType.PRELEVEMENT, "AUCHAN", "", -20.00, "Groceries") .add("13/08/2016", TransactionType.PRELEVEMENT, "TOTAL", "", -25.00) .add("12/08/2016", TransactionType.PRELEVEMENT, "EDF", "", -50.00) .add("11/08/2016", TransactionType.PRELEVEMENT, "FNAC", "", -200.00) .add("10/08/2016", TransactionType.PRELEVEMENT, "AUCHAN", "", -100.00, "Groceries") .check(); } public void testCancelAfterImport() throws Exception { cloud.createSubscription("toto@example.com", Dates.tomorrow()); budgea.pushNewConnectionResponse(1, 123, 40); budgea.pushStatement(BudgeaStatement.init() .addConnection(1, 123, 40, "Connecteur de test", "2016-08-10 17:44:26") .addAccount(1, "Main account 1", "100200300", "checking", 1000.00, "2016-08-10 13:00:00") .addTransaction(1, "2016-08-10 13:00:00", -100.00, "AUCHAN") .addTransaction(2, "2016-08-12 17:00:00", -50.00, "EDF") .endAccount() .addAccount(2, "Main account 2", "200300400", "checking", 2000.00, "2016-08-10 11:00:00") .addTransaction(3, "2016-08-11 11:00:00", -200.00, "FNAC") .endAccount() .endConnection() .get()); operations.openImportDialog() .selectCloudForNewUser() .register("toto@example.com") .processEmailAndNextToBankSelection(mailbox.getDeviceVerificationCode("toto@example.com")) .selectBank("Connecteur de test") .next() .setChoice("Type de compte", "Particuliers") .setText("Identifiant", "1234") .setPassword("Code (1234)", "1234") .next() .waitForNotificationAndDownload(mailbox.checkStatementReady("toto@example.com")) .checkTransactions(new Object[][]{ {"2016/08/12", "EDF", "-50.00"}, {"2016/08/10", "AUCHAN", "-100.00"}, }) .importAccountAndOpenNext() .checkTransactions(new Object[][]{ {"2016/08/11", "FNAC", "-200.00"}, }) .importAccountAndComplete(); budgea.sendStatement(BudgeaStatement.init() .addConnection(1, 123, 40, "Connecteur de test", "2016-08-15 17:44:26") .addAccount(1, "Main account 1", "100200300", "checking", 750.00, "2016-08-15 13:00:00") .addTransaction(4, "2016-08-13 13:00:00", -50.00, "TOTAL", BudgeaCategory.ESSENCE) .addTransaction(5, "2016-08-15 15:00:00", -200.00, "FOUQUETS", BudgeaCategory.RESTAURANT) .endAccount() .addAccount(2, "Main account 2", "200300400", "checking", 1500.00, "2016-08-15 13:00:00") .addTransaction(6, "2016-08-13 14:00:00", -500.00, "APPLE") .endAccount() .endConnection() .get()); restartApplication(); autoImport.checkDisplayed() .waitForEndOfProgress() .cancel(); views.checkHomeSelected(); transactions.initContent() .add("12/08/2016", TransactionType.PRELEVEMENT, "EDF", "", -50.00) .add("11/08/2016", TransactionType.PRELEVEMENT, "FNAC", "", -200.00) .add("10/08/2016", TransactionType.PRELEVEMENT, "AUCHAN", "", -100.00) .check(); operations.openImportDialog() .selectCloudRefresh() .checkTransactions(new Object[][]{ {"2016/08/15", "FOUQUETS", "-200.00"}, {"2016/08/13", "TOTAL", "-50.00"}, }) .importAccountAndOpenNext() .checkTransactions(new Object[][]{ {"2016/08/13", "APPLE", "-500.00"}, }) .importAccountAndComplete(); transactions.initContent() .add("15/08/2016", TransactionType.PRELEVEMENT, "FOUQUETS", "", -200.00, "Restaurant") .add("13/08/2016", TransactionType.PRELEVEMENT, "APPLE", "", -500.00) .add("13/08/2016", TransactionType.PRELEVEMENT, "TOTAL", "", -50.00, "Fuel") .add("12/08/2016", TransactionType.PRELEVEMENT, "EDF", "", -50.00) .add("11/08/2016", TransactionType.PRELEVEMENT, "FNAC", "", -200.00) .add("10/08/2016", TransactionType.PRELEVEMENT, "AUCHAN", "", -100.00) .check(); } public void testNoNewOperations() throws Exception { cloud.createSubscription("toto@example.com", Dates.tomorrow()); budgea.pushNewConnectionResponse(1, 123, 40); budgea.pushStatement(BudgeaStatement.init() .addConnection(1, 123, 40, "Connecteur de test", "2016-08-10 17:44:26") .addAccount(1, "Main account 1", "100200300", "checking", 1000.00, "2016-08-10 13:00:00") .addTransaction(1, "2016-08-10 13:00:00", -100.00, "AUCHAN") .addTransaction(2, "2016-08-12 17:00:00", -50.00, "EDF") .endAccount() .addAccount(2, "Main account 2", "200300400", "checking", 2000.00, "2016-08-10 11:00:00") .addTransaction(3, "2016-08-11 11:00:00", -200.00, "FNAC") .endAccount() .endConnection() .get()); operations.openImportDialog() .selectCloudForNewUser() .register("toto@example.com") .processEmailAndNextToBankSelection(mailbox.getDeviceVerificationCode("toto@example.com")) .selectBank("Connecteur de test") .next() .setChoice("Type de compte", "Particuliers") .setText("Identifiant", "1234") .setPassword("Code (1234)", "1234") .next() .waitForNotificationAndDownload(mailbox.checkStatementReady("toto@example.com")) .checkTransactions(new Object[][]{ {"2016/08/12", "EDF", "-50.00"}, {"2016/08/10", "AUCHAN", "-100.00"}, }) .importAccountAndOpenNext() .checkTransactions(new Object[][]{ {"2016/08/11", "FNAC", "-200.00"}, }) .importAccountAndComplete(); restartApplication(); autoImport.checkDisplayed() .waitForEndOfProgress() .checkMessage("There are no new transactions") .performAction("OK"); views.checkHomeSelected(); transactions.initContent() .add("12/08/2016", TransactionType.PRELEVEMENT, "EDF", "", -50.00) .add("11/08/2016", TransactionType.PRELEVEMENT, "FNAC", "", -200.00) .add("10/08/2016", TransactionType.PRELEVEMENT, "AUCHAN", "", -100.00) .check(); } public void testNewAccountNeedsManualImport() throws Exception { } public void testSubscriptionExpired() throws Exception { fail("on envoie vers le site"); } public void testServerError() throws Exception { fail("on ouvre une fenetre pour nous envoyer l'exception"); } }
true
4d24182c3b23c83d6eb803112f5ee5d62a9db04b
Java
kumaneko-japan/SystemErrorLog
/system-errorLog/src/main/java/syserrLog/message/ResultMessageType.java
UTF-8
94
1.9375
2
[]
no_license
package syserrLog.message; public interface ResultMessageType { String getType(); }
true
2713e7bf202c474081845f5b729375739fc396c4
Java
shaikm/SampleApp
/app/src/main/java/com/nytimes/application/api/ApiManager.java
UTF-8
2,808
2.328125
2
[]
no_license
package com.nytimes.application.api; import android.content.Context; import com.nytimes.application.data.DataManager; import com.nytimes.application.data.entity.NewsEntity; import com.nytimes.application.util.Utils; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import static com.nytimes.application.api.NyClient.getClient; public class ApiManager { private final Retrofit client; private final String apiKey = "Ag3kGAyLkdSHT1hyi5dsR7DmmXiUrL6W"; private final DataManager dataManager; private final Context context; public ApiManager(Context context) { client = getClient(); this.context = context; dataManager = new DataManager(context); } public void getArticles(final String period, final ApiCallback<List<Result>> callback) { if (Utils.isNetworkConnected(context)) { NyInterface services = client.create(NyInterface.class); services.getAllArticles(period, apiKey).enqueue(new Callback<Article>() { @Override public void onResponse(Call<Article> call, Response<Article> response) { if (response.isSuccessful() && response.body() != null) { callback.success(response.body().getResults()); insertNewsData(response.body()); } else { callback.failure(response.code()); } } @Override public void onFailure(Call<Article> call, Throwable t) { callback.failure(500); } }); } else { Executors.newSingleThreadExecutor().execute(new Runnable() { @Override public void run() { List<Result> articles = new ArrayList<>(); for (NewsEntity newsEntity : dataManager.getNewsData()) { articles.add(Json.gson().fromJson(newsEntity.getNewsData(), Result.class)); } callback.success(articles); } }); } } private void insertNewsData(final Article body) { Executors.newSingleThreadExecutor().execute(new Runnable() { @Override public void run() { dataManager.deleteAll(); for (Result result : body.getResults()) { dataManager.insert(new NewsEntity(Json.gson().toJson(result, Result.class))); } } }); } public interface ApiCallback<T> { void success(T response); void failure(int responseCode); } }
true