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
caab75fd1253af77dbaaf945b7cb207ed135e175
Java
huyquyen0501/springboot-hibernate-test
/src/main/java/com/example/demo/entity/HelloWorld.java
UTF-8
793
2.40625
2
[]
no_license
package com.example.demo.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "customer") public class HelloWorld { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name = "namepeople") private String namePeople; private int money; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNamePeople() { return namePeople; } public void setNamePeople(String namePeople) { this.namePeople = namePeople; } public int getMoney() { return money; } public void setMoney(int money) { this.money = money; } }
true
63836fd06469b4a7fd64d6290a5b2c02bd100932
Java
tianhaolin1991/ssm_super
/ssm_service/src/main/java/cn/itcast/service/ProductService.java
UTF-8
320
1.875
2
[]
no_license
package cn.itcast.service; import cn.itcast.domain.Product; import java.util.List; public interface ProductService { /** * 查询所有 * @return * @param currentPage * @param pageSize */ List<Product> findAll(Integer currentPage, Integer pageSize); void add(Product product); }
true
253de6f14c0d69725b5960c8d8a69563de4dd18f
Java
Hanan2412/ClientSide-ServerSide
/ServerSide/src/server/Server.java
UTF-8
1,797
2.796875
3
[]
no_license
package server; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.Vector; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Server implements Runnable{//this class implements runnable because the main GUI thread freezes once this class is invoked private ServerSocket serverSocket; private Socket socket; private boolean runnable = false; private PropertyChangeSupport pcs; private int numberOfConnections; public static Vector<ServerHandler>ar = new Vector<>(); private ExecutorService threadPool; private final int numberOfAllowedThreads = 5; public Server(int port) { numberOfConnections = 0; try { serverSocket = new ServerSocket(port); pcs = new PropertyChangeSupport(this); threadPool = Executors.newFixedThreadPool(numberOfAllowedThreads); }catch(IOException e) { e.printStackTrace(); } } public void TurnServerOnOrOff(boolean on) { if(on) { runnable = true; Thread runServer = new Thread(this); runServer.setName("runServer"); runServer.start(); } else runnable = false; } public void addPropertyChangeListener(PropertyChangeListener listener) { pcs.addPropertyChangeListener(listener); } public int getNumberOfConnections() { return numberOfConnections; } @Override public void run() { while(runnable = true) { try { socket = serverSocket.accept(); numberOfConnections++; ServerHandler handler = new ServerHandler(socket,numberOfConnections); threadPool.execute(handler); } catch (IOException e) { e.printStackTrace(); } } } }
true
03f0619a8a5a1e78b89eb8c7d254873d6a55f8e5
Java
jaspreetjhass/MongoDbRepo
/MongoSpringIntegration/src/main/java/org/jp/MongoSpringIntegrationApproach1/InsertMany.java
UTF-8
1,436
2.765625
3
[]
no_license
package org.jp.MongoSpringIntegrationApproach1; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.bson.Document; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.data.mongodb.core.MongoTemplate; import com.mongodb.client.MongoCollection; public class InsertMany { public static void main(String[] args) { // create instance of application context ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); // get instance of template MongoTemplate template = context.getBean(MongoTemplate.class); // get collection name from database MongoCollection<Document> collection = template.getCollection("person"); // perpare key value map to pass it to the document Map<String, Object> map = new HashMap<>(); map.put("name", "harpreet"); List<String> skills = new ArrayList<>(); skills.add("cricket"); skills.add("volleyball"); map.put("skillset", skills); // create document instance and store the map Document document = new Document(map); // perpare list of documents List<Document> documents = new ArrayList<Document>(); documents.add(document); // call insertMany method to store only one document in the collection collection.insertMany(documents); context.close(); } }
true
e52ccbdfd105e6c9aeedd39b098a36034602c00a
Java
aurelien-baudet/yoga-classes-booking-back
/src/main/java/fr/yoga/booking/service/business/ContactService.java
UTF-8
3,842
2.3125
2
[]
no_license
package fr.yoga.booking.service.business; import static java.util.concurrent.CompletableFuture.completedFuture; import java.util.concurrent.CompletableFuture; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import fr.sii.ogham.core.exception.MessagingException; import fr.sii.ogham.core.message.Message; import fr.sii.ogham.core.service.MessagingService; import fr.sii.ogham.email.message.Email; import fr.sii.ogham.sms.message.Sms; import fr.yoga.booking.domain.account.Student; import fr.yoga.booking.domain.account.User; import fr.yoga.booking.domain.notification.ClassCanceledNotification; import fr.yoga.booking.domain.notification.Notification; import fr.yoga.booking.domain.notification.PlaceChangedNotification; import fr.yoga.booking.service.business.exception.UnreachableUserException; import fr.yoga.booking.service.business.exception.user.UserException; import lombok.Data; import lombok.RequiredArgsConstructor; @Service @RequiredArgsConstructor public class ContactService { private final MessagingService messagingService; @Async public CompletableFuture<Message> sendMessage(Student student, Notification notification) throws MessagingException, UnreachableUserException, UserException { Message message = prepareMessage(student, notification); if(message == null) { throw new UnreachableUserException(student, notification); } messagingService.send(message); return completedFuture(message); } @Async public void sendResetPasswordMessage(User user, String emailOrPhoneNumber, String token) throws MessagingException { Message message = prepareResetPasswordMessage(user, emailOrPhoneNumber, token); messagingService.send(message); } private Message prepareResetPasswordMessage(User user, String emailOrPhoneNumber, String token) { if (isEmail(emailOrPhoneNumber)) { return new Email() .to(user.getContact().getEmail()) .body().template("reset-password", new PasswordReset(user, token)); } return new Sms() .to(user.getContact().getPhoneNumber()) .message().template("reset-password", new PasswordReset(user, token)); } private Message prepareMessage(Student student, Notification notification) throws UserException { if (canReceiveSmsOnly(student) || (canReceiveSms(student) && preferSms(student, notification))) { return new Sms() .to(getPhoneNumber(student)) .message().template(toTemplateName(notification), notification); } if (canReceiveEmail(student)) { return new Email() .to(getEmail(student)) .body().template(toTemplateName(notification), notification); } return null; } private boolean canReceiveSmsOnly(Student student) throws UserException { return canReceiveSms(student) && !canReceiveEmail(student); } private boolean canReceiveEmail(Student student) throws UserException { return getEmail(student) != null && !getEmail(student).isBlank(); } private boolean preferSms(Student student, Notification notification) { return notification instanceof PlaceChangedNotification || notification instanceof ClassCanceledNotification; } private boolean canReceiveSms(Student student) throws UserException { return getPhoneNumber(student) != null && !getPhoneNumber(student).isBlank(); } private String toTemplateName(Notification notification) { return notification.getType().name().toLowerCase().replaceAll("_", "-"); } private String getEmail(Student student) throws UserException { return student.getContact().getEmail(); } private String getPhoneNumber(Student student) throws UserException { return student.getContact().getPhoneNumber(); } private boolean isEmail(String str) { return str.contains("@"); } @Data public static class PasswordReset { private final User user; private final String token; } }
true
e6d4f50a79b05f13699c46f0d5b9099d202b8092
Java
stephenchu530/parley-app
/src/main/java/com/parley/parley/models/UserAccount.java
UTF-8
5,223
2.46875
2
[ "MIT" ]
permissive
package com.parley.parley.models; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import javax.persistence.*; import java.util.*; @Entity public class UserAccount implements UserDetails { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String firstName; private String lastName; private String email; @Column(unique = true) private String username; private String password; @ManyToMany private List<Schedules> interviewSchedule; @Column @ElementCollection(targetClass=String.class) private List<String> listOfAssessments; @Column @ElementCollection(targetClass=String.class) private List<String> classes; @ManyToMany(fetch = FetchType.EAGER) @JoinTable( name = "AdminRoles", joinColumns = @JoinColumn( name = "instructor_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn( name = "role_id", referencedColumnName = "id")) private Set<RoleType> roleTypes = new HashSet<RoleType>(); public boolean isAdmin() { List<String> roleNames = new ArrayList<String>(); roleTypes.forEach(roleType -> roleNames.add(roleType.getRole())); if(roleNames.contains("admin")) { return true; } else { return false; } } //instance variable for student users private String classDesignator; //constructors for admin/instructor users public UserAccount(){} public UserAccount( String firstName, String lastName, String username, String password, String email){ this.setFirstName(firstName); this.setLastName(lastName); this.setUsername(username); this.setPassword(password); this.setEmail(email); this.setInterviewSchedule(new ArrayList<Schedules>()); this.setListOfAssessments(new ArrayList<String>()); } //constructors for student users public UserAccount(String firstName, String lastName, String username, String password, String classDesignator, String email){ this.setFirstName(firstName); this.setLastName(lastName); this.setUsername(username); this.setPassword(password); this.setClassDesignator(classDesignator); this.setEmail(email); } //getters public Long getId() { return id; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getEmail() { return email; } public String getUsername() { return username; } public String getClassDesignator() { return classDesignator; } public List<Schedules> getInterviewSchedule() { return interviewSchedule; } public List<String> getListOfAssessments() { return listOfAssessments; } //users details service methods @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } public String getPassword() { return password; } public List<String> getClasses() { return classes; } public Set<RoleType> getRoleTypes() { return roleTypes; } //setters public void setId(Long id) { this.id = id; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public void setEmail(String email) { this.email = email; } public void setUsername(String username) { this.username = username; } public void setPassword(String password) { this.password = password; } public void setClasses(List<String> classes) { this.classes = classes; } public void setRoleTypes(Set<RoleType> roleTypes) { this.roleTypes = roleTypes; } public void setClassDesignator(String classDesignator) { this.classDesignator = classDesignator; } public void setInterviewSchedule(List<Schedules> interviewerSchedule) { this.interviewSchedule = interviewerSchedule; } public void setListOfAssessments(List<String> listOfAssessments) { this.listOfAssessments = listOfAssessments; } public Collection<? extends GrantedAuthority> getAuthorities() { List<GrantedAuthority> roles = new ArrayList<GrantedAuthority>(); roleTypes.forEach(roleType -> roles.add(new SimpleGrantedAuthority("role_" + roleType.getRole()))); return roles; } }
true
67885fbcf03a4452a93f36a63f972804aa172d7b
Java
Lodoran/AulasPOO
/1003.java
UTF-8
408
3.40625
3
[]
no_license
import java.util.Scanner; public class primeiro{ public static void main(String[] args){ Scanner numero = new Scanner (System.in); double numero1, numero2; double media; System.out.println ("Digite o valor de A: "); numero1 = scan.nextDouble(); System.out.println ("Digite o valor de B: "); numero2 = scan.nextDouble(); media= (numero1 + numero2)/2; System.out.println("MEDIA= ",+ media); } }
true
007b269907d86e84f2f039a1867f367309cbb848
Java
japes930/SpringBoot_103
/ChallengeOne/src/challengeOne.java
UTF-8
1,950
3.4375
3
[]
no_license
import java.util.Scanner; import java.util.Random; public class challengeOne { public static void main( String[] args){ Scanner keyboard = new Scanner(System.in); //************************************************** // OPTION 1 * //************************************************** boolean cont = true; do { boolean prime = true; System.out.println("Enter a number: "); int num = keyboard.nextInt(); //If number is divisible by 2, 3, or 5 it is not prime if((num%2==0) || (num%3==0) || (num%5==0)){ //Test 1 prime = false; } //If number selected is 2, 3, or 5 it will know its prime int[] primeArr = {2, 3, 5}; for (int i = 0; i < primeArr.length; i++) { if(num == primeArr[i]){ prime = true; } } //Prints out whether the number selected is prime or not if (prime) { System.out.println(num + " IS a prime number!"); } else { System.out.println(num + " is not a prime number."); } //Asks user if they'd like to pick another number System.out.println("Would you like to select another number? [Y/N]"); char reply = keyboard.next().charAt(0); char r = Character.toUpperCase(reply); if (r == 'N'){ cont = false; } } while (cont); //**************************************************** // OPTION 2 * //**************************************************** // Random rnd = new Random(); // int rdnNum= rnd.nextInt(250) + 1; } }
true
a992d0657c76829482b063d33df30c7e5777488d
Java
vxvy/JDBC
/T2SAX/src/t2sax/T2SAXMain.java
UTF-8
1,271
2.328125
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 t2sax; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * * @author VCV */ public class T2SAXMain { /** * @param args the command line arguments */ public static void main(String[] args) { try { // SAXHandler saxH=new SAXHandler(); T2SAX1 saxH=new T2SAX1(); // T2SAX2 saxH=new T2SAX2(); // T2SAX3 saxH=new T2SAX3(); // T2SAX4 saxH=new T2SAX4(1); // T2SAX5 saxH=new T2SAX5(); SAXParseatorino saxPino=new SAXParseatorino(System.getProperty("user.home")+"/peliculas.xml", (DefaultHandler)saxH); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (SAXException saxe) { saxe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } }
true
dee26c8792f5192e8547a5e6bad5063a53ca45ba
Java
mohana-vamsee/ssplat
/Javaresources/src/title.java
UTF-8
298
2.296875
2
[]
no_license
@Entity public class State { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; private String title; @OneToMany(cascade = {CascadeType.ALL}) public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
true
8400c9ba9bf6a4fe1578292855d39b3832f6f0a8
Java
isfce/pid-hifi
/Tp01_Hifi/src/main/java/hifi/ChargeurCdFactory.java
UTF-8
1,051
2.78125
3
[]
no_license
package hifi; import java.io.IOException; import java.util.Properties; import java.util.stream.Collectors; public class ChargeurCdFactory { /** * Fabrique qui construit un chargeur avec une liste de CD à partir d'un fichier * l'organisation du fichier étant * nomDisque= liste des morceaux séparés avec une virgule * Exemple d'appel: * ChargeurCdFactory.createChargeur("/hifi/CDBeatles.properties"); * * @param file * @return * @throws IOException */ public static IChargeur createChargeur(String file) throws IOException { IChargeur chargeur=null; Properties disques = new Properties(); //Charge dans un dictionnaire (titre==>liste des morceaux séparés par une virgule) disques.load(ChargeurCdFactory.class.getResourceAsStream(file)); try { chargeur=new ChargeurCds(disques.keySet().stream() .map(d -> new DisqueCD((String) d, disques.getProperty((String) d))).collect(Collectors.toList())); } catch (Exception e) { e.printStackTrace(); } return chargeur; } }
true
3073db3cffd7a0774ae786fbf2cf2c802351d3a2
Java
apache/incubator-pekko
/docs/src/test/java/jdocs/ddata/protobuf/TwoPhaseSetSerializer2.java
UTF-8
2,850
1.828125
2
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "LicenseRef-scancode-protobuf", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "Unlicense", "CC0-1.0" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more * license agreements; and to You under the Apache License, version 2.0: * * https://www.apache.org/licenses/LICENSE-2.0 * * This file is part of the Apache Pekko project, which was derived from Akka. */ /* * Copyright (C) 2015-2022 Lightbend Inc. <https://www.lightbend.com> */ package jdocs.ddata.protobuf; // #serializer import jdocs.ddata.TwoPhaseSet; import docs.ddata.protobuf.msg.TwoPhaseSetMessages; import docs.ddata.protobuf.msg.TwoPhaseSetMessages.TwoPhaseSet2.Builder; import org.apache.pekko.actor.ExtendedActorSystem; import org.apache.pekko.cluster.ddata.GSet; import org.apache.pekko.cluster.ddata.protobuf.AbstractSerializationSupport; import org.apache.pekko.cluster.ddata.protobuf.ReplicatedDataSerializer; public class TwoPhaseSetSerializer2 extends AbstractSerializationSupport { private final ExtendedActorSystem system; private final ReplicatedDataSerializer replicatedDataSerializer; public TwoPhaseSetSerializer2(ExtendedActorSystem system) { this.system = system; this.replicatedDataSerializer = new ReplicatedDataSerializer(system); } @Override public ExtendedActorSystem system() { return this.system; } @Override public boolean includeManifest() { return false; } @Override public int identifier() { return 99998; } @Override public byte[] toBinary(Object obj) { if (obj instanceof TwoPhaseSet) { return twoPhaseSetToProto((TwoPhaseSet) obj).toByteArray(); } else { throw new IllegalArgumentException("Can't serialize object of type " + obj.getClass()); } } @Override public Object fromBinaryJava(byte[] bytes, Class<?> manifest) { return twoPhaseSetFromBinary(bytes); } protected TwoPhaseSetMessages.TwoPhaseSet2 twoPhaseSetToProto(TwoPhaseSet twoPhaseSet) { Builder b = TwoPhaseSetMessages.TwoPhaseSet2.newBuilder(); if (!twoPhaseSet.adds.isEmpty()) b.setAdds(otherMessageToProto(twoPhaseSet.adds).toByteString()); if (!twoPhaseSet.removals.isEmpty()) b.setRemovals(otherMessageToProto(twoPhaseSet.removals).toByteString()); return b.build(); } @SuppressWarnings("unchecked") protected TwoPhaseSet twoPhaseSetFromBinary(byte[] bytes) { try { TwoPhaseSetMessages.TwoPhaseSet2 msg = TwoPhaseSetMessages.TwoPhaseSet2.parseFrom(bytes); GSet<String> adds = GSet.create(); if (msg.hasAdds()) adds = (GSet<String>) otherMessageFromBinary(msg.getAdds().toByteArray()); GSet<String> removals = GSet.create(); if (msg.hasRemovals()) adds = (GSet<String>) otherMessageFromBinary(msg.getRemovals().toByteArray()); return new TwoPhaseSet(adds, removals); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } } // #serializer
true
12048276576775c69418d61e5050709efeb47d89
Java
lucianluci96/shop
/shop/src/main/java/org/myproject/shop/service/api/impl/OutputService.java
UTF-8
1,833
2.25
2
[]
no_license
package org.myproject.shop.service.api.impl; import org.myproject.shop.core.model.OutputEntity; import org.myproject.shop.core.model.ProductEntity; import org.myproject.shop.core.model.ShopEntity; import org.myproject.shop.core.repository.OutputRepository; import org.myproject.shop.core.repository.ProductRepository; import org.myproject.shop.core.repository.ShopRepository; import org.myproject.shop.rest.dto.OutputDto; import org.myproject.shop.service.api.IOutputService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class OutputService implements IOutputService { @Autowired OutputRepository outputRepository; @Autowired ShopRepository shopRepository; @Autowired ProductRepository productRepository; @Override public List<OutputDto> getOutputs() { List<OutputDto> outputs = new ArrayList<>(); for (OutputEntity output : outputRepository.findAll()) outputs.add(output.toDto()); return outputs; } @Override public OutputDto getOutput(long id) { if (!outputRepository.exists(id)) { return null; } return (outputRepository.findOne(id).toDto()); } @Override public boolean addOutput(OutputDto output) { OutputEntity outputEntity= new OutputEntity(); ShopEntity shop = shopRepository.findByName(output.getShop().getName()).get(0); ProductEntity productEntity = productRepository.findByName(output.getProduct().getName()).get(0); outputEntity.setShop(shop); outputEntity.setProduct(productEntity); outputEntity.setLong(output.getQuantity()); outputRepository.save(outputEntity); return true; } }
true
d0bdd7b45958e895a7cc7188f2f78b4bcab4f94b
Java
LRuffati/ing-sw-2019-9
/src/main/java/controller/externalinterfaces/ActorIface.java
UTF-8
635
2.28125
2
[]
no_license
package controller.externalinterfaces; import actions.ActionTemplate; import java.util.List; public interface ActorIface { /** * * @return the actions available to the user. Each list of templates will generate an * actionBundle */ List<List<ActionTemplate>> getActions(); /** * Signals to the actor that the final frenzy has begun. If the player has not been damaged * it will change the actions available right away, otherwise on the first death * @param beforeFirst if the actor comes after the first player in the game order */ void frenzyStarted(boolean beforeFirst); }
true
6d238fffecdcc7b0d7284d0a4eafef9d0d2e871c
Java
Asfarus1/cloud-increment
/src/test/java/asfarus/example/cloudincrement/repository/internal/JdbcIncrementRepositoryTest.java
UTF-8
2,643
2.296875
2
[]
no_license
package asfarus.example.cloudincrement.repository.internal; import asfarus.example.cloudincrement.repository.IncrementRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.jdbc.Sql; import java.util.Optional; import java.util.concurrent.TimeUnit; import static asfarus.example.cloudincrement.repository.internal.JdbcIncrementRepository.CACHE_INC_KEY; import static asfarus.example.cloudincrement.repository.internal.JdbcIncrementRepository.CACHE_INC_NAME; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest @ActiveProfiles("test") @Sql(statements = "UPDATE inc SET val = 0") class JdbcIncrementRepositoryTest { @Autowired private IncrementRepository repository; @Autowired private CacheManager cacheManager; @BeforeEach void setUp() { Optional.ofNullable(cacheManager.getCache(CACHE_INC_NAME)) .ifPresent(Cache::clear); } @Test void get() { assertThat(repository.get()).isEqualTo(0L); assertCacheHasValue(0L); } @Test @Disabled("H2 not supported UPDATE with RETURNING") void incrementAndGet() { assertThat(repository.incrementAndGet()).isEqualTo(1L); assertCacheHasValue(1L); } @Test void reset() { putValueIntoCache(); repository.reset(); assertCacheHasNoValue(); } @Test void cacheExpireAfter1s() throws InterruptedException { putValueIntoCache(); TimeUnit.SECONDS.sleep(1); assertCacheHasNoValue(); } private void assertCacheHasValue(Long val) { Cache cache = cacheManager.getCache(CACHE_INC_NAME); assertThat(cache).isNotNull(); Cache.ValueWrapper actual = cache.get(CACHE_INC_KEY); assertThat(actual).isNotNull(); assertThat(actual.get()).isEqualTo(val); } private void putValueIntoCache() { Cache cache = cacheManager.getCache(CACHE_INC_NAME); assertThat(cache).isNotNull(); cache.put(CACHE_INC_KEY, 1L); } private void assertCacheHasNoValue() { Cache cache = cacheManager.getCache(CACHE_INC_NAME); assertThat(cache).isNotNull(); Cache.ValueWrapper actual = cache.get(CACHE_INC_KEY); assertThat(actual).isNull(); } }
true
3b26b538c4be9b71ae5acd5a0ea8212927567fe0
Java
MichaelD58/StarCraft-Optimiser
/src/Optimiser.java
UTF-8
7,746
2.578125
3
[]
no_license
import java.util.ArrayList; import java.util.Random; public class Optimiser { ArrayList<Construction> buildOrder = new ArrayList<>(); Random rand = new Random(); private StarCraft g; private int marines = 0; private int hellions = 0; private int medivacs = 0; private int vikings = 0; private int seigeTanks = 0; private int banshees = 0; private int thors = 0; private int marauders = 0; public Optimiser(int marines, int hellions, int medivacs, int vikings, int seigeTanks, int banshees, int thors, int marauders, StarCraft starCraft) { this.marines = marines; this.hellions = hellions; this.medivacs = medivacs; this.vikings = vikings; this.seigeTanks = seigeTanks; this.banshees = banshees; this.thors = thors; this.marauders = marauders; this.g = starCraft; } public void randomTurn(State s, StarCraft g, int t) { int n = rand.nextInt(18); int m = rand.nextInt(3); while (m > 0) { m--; randomMove(n, s, g, t); n = rand.nextInt(18); } } public void randomMove(int i, State s, StarCraft g, int t) { switch (i) { case 0: { if (g.constructionCount(new SCV(), g.units) < (s.NUMBEROFPOORPATCHSLOTSM + s.NUMBEROFGOODPATCHSLOTSM + (g.constructionCount(new Refinery(), g.buildings) * 3)) && s.getSpareSupply() > (marines + hellions * 2 + medivacs * 2 + vikings * 2 + seigeTanks * 3 + thors * 6 + banshees * 3 + marauders * 2) / 5 && g.constructionCount(new SCV(), g.units) + g.constructionCount(new SCV(), g.inBuilding) < (marines + hellions + medivacs + vikings + seigeTanks + thors + banshees + marauders) / 2) { g.build(new SCV(t, s), s); } break; } case 1: { if (((g.constructionCount(new Supply_Depot(), g.buildings) + g.constructionCount(new Supply_Depot(), g.inBuilding)) * 8 + 10) < (marines + (hellions * 2 ) + (medivacs * 2 ) + (vikings * 2) + (seigeTanks * 3) + (thors * 6) + (banshees * 3) + (marauders * 2)) || g.constructionCount(new Supply_Depot(), g.buildings) + g.constructionCount(new Supply_Depot(), g.inBuilding) == 0 || thors > 0 && s.getSpareSupply() < 6 || thors == 0 && seigeTanks + banshees > 0 && s.getSpareSupply() < 3 || thors + seigeTanks + banshees == 0 && s.getSpareSupply() < 2 ) { g.build(new Supply_Depot(t, s), s); } break; } case 2: { if (g.constructionCount(new Marine(), g.units) < marines) { g.build(new Marine(t), s); } break; } case 3: { if (g.constructionCount(new Barracks(), g.buildings) + g.constructionCount(new Barracks(), g.inBuilding) == 0 || (g.constructionCount(new Barracks(), g.buildings) + g.constructionCount(new Barracks(), g.inBuilding)) < (marines + marauders) / 2) { if (marines + marauders != 0 && (g.constructionCount(new Marine(), g.inBuilding) + g.constructionCount(new Marauder(), g.inBuilding)) < g.constructionCount(new Barracks(), g.buildings)) { if (marines > g.constructionCount(new Marine(), g.inBuilding) + g.constructionCount(new Marine(), g.units) && g.constructionCount(new Barracks(), g.buildings) != 0){ g.build(new Marine(t), s); } else if (marauders > g.constructionCount(new Marauder(), g.inBuilding) + g.constructionCount(new Marauder(), g.units) && g.constructionCount(new Barracks(), g.buildings) != 0) { g.build(new Marauder(t), s); } } else { g.build(new Barracks(t), s); } } break; } case 5: { if (vikings + medivacs + seigeTanks + thors + banshees + marauders + hellions != 0) { g.build(new Refinery(t), s); } break; } case 6: { // if (hellions !=0 && (g.constructionCount(new Factory(), g.buildings) + g.constructionCount(new Factory(), g.inBuilding)) == 0) { //|| (hellions == 0 && vikings + medivacs + seigeTanks + thors + banshees != 0 && g.constructionCount(new Factory(), g.buildings) + g.constructionCount(new Factory(), g.inBuilding) == 0) || g.constructionCount(new Factory(), g.buildings) + g.constructionCount(new Factory(), g.inBuilding) < (hellions + seigeTanks + thors) / 2 g.build(new Factory(t), s); // } break; } case 7: { if (g.constructionCount(new Hellion(), g.units) < hellions) { g.build(new Hellion(t), s); } break; } case 8: { s.moveToVespene(g); break; } case 9: { s.moveToMinerals(g); break; } case 10: { if (vikings + medivacs + banshees != 0 && g.constructionCount(new Starport(), g.buildings) + g.constructionCount(new Starport(), g.inBuilding) < ((medivacs + vikings + banshees) / 2)) { g.build(new Starport(t), s); } break; } case 11: { if (g.constructionCount(new Medivac(), g.units) < medivacs) { g.build(new Medivac(t), s); } break; } case 12: { if (g.constructionCount(new Viking(), g.units) < vikings) { g.build(new Viking(t), s); } break; } case 13: { if (g.constructionCount(new Armoury(), g.buildings) == 0 && thors > 0) { g.build(new Armoury(t), s); } } case 14: { if (g.constructionCount(new Siege_Tank(), g.units) < seigeTanks) { g.build(new Siege_Tank(t), s); } } case 15: { if (g.constructionCount(new Thor(), g.units) < thors) { g.build(new Thor(t), s); } } case 16: { if (g.constructionCount(new Marauder(), g.units) < marauders) { g.build(new Marauder(t), s); } } case 17: { if (g.constructionCount(new Banshee(), g.units) < banshees) { g.build(new Banshee(t), s); } } case 18: { //if ((marauders + seigeTanks + thors + banshees) != 0){ int w = rand.nextInt(3); g.build(new TechLab(t, w, g), s); //} break; } } } public boolean checkGoals() { if (marines <= g.constructionCount(new Marine(), g.units) && hellions <= g.constructionCount(new Hellion(), g.units) && medivacs <= g.constructionCount(new Medivac(), g.units) && vikings <= g.constructionCount(new Viking(), g.units) && seigeTanks <= g.constructionCount(new Siege_Tank(), g.units) && thors <= g.constructionCount(new Thor(), g.units) && banshees <= g.constructionCount(new Banshee(), g.units) && marauders <= g.constructionCount(new Marauder(), g.units)) { //System.out.println("Finished producing required units"); return true; } return false; } }
true
302d89c933cab3c65c16f5e320b419e16bf1ad02
Java
shubhamkank/interview-prep
/src/main/java/com/interview/KMP.java
UTF-8
1,491
3.625
4
[]
no_license
package com.interview; public class KMP { /** * Compute temporary array to maintain size of suffix which is same as prefix * Time/space complexity is O(size of pattern) */ private static int[] computePiTable(char[] pattern) { //lps stands for longest proper prefix which is also suffix int[] lps = new int[pattern.length]; int j = 0; for (int i = 1; i < pattern.length;) { if(pattern[j] == pattern[i]) { lps[i] = j + 1; j++; i++; } else { if(j != 0) { j = lps[j - 1]; } else { lps[i] = 0; i++; } } } return lps; } public static boolean KMP(char[] text, char[] pattern) { int[] lps = computePiTable(pattern); int i = 0; int j = 0; while (i < text.length && j < pattern.length) { if(text[i] == pattern[j]) { i++; j++; } else { if(j != 0) { j = lps[j - 1]; } else { i++; } } } if(j == pattern.length) { return true; } return false; } public static void main(String[] args) { System.out.println(KMP("abcxabcdabcdabcy".toCharArray(), "abcdabcy".toCharArray())); } }
true
7a14613bdcede2517d62f1a967056956dbcd1169
Java
softgo/ApplicationO
/src/main/java/com/javabase/demo/constant/ResultConstant.java
UTF-8
453
2.140625
2
[]
no_license
package com.javabase.demo.constant; /** * 异常信息输出 * @author rocky */ public class ResultConstant { /** * 通用设置. */ public interface CommonResult{ String GET_RESULT_IS_NULL = "GET_RESULT_IS_NULL"; String OPERATE_ACTION_IS_FAILD = "OPERATE_ACTION_IS_FAILD"; } /** * 老师 */ public interface TestTeacherResult{ String TESTTEACHER_IS_NULL = "TESTTEACHER_IS_NULL"; } }
true
e2ed48b82d45769823c1cb6ac62d33210b00e391
Java
MarineCastello/Airport
/Airport/src/dbAccess/FlightPlanDAO.java
ISO-8859-1
19,035
2.6875
3
[]
no_license
package dbAccess; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import entity.Airline; import entity.Airport; import entity.Factory; import entity.FlightDuration; import entity.FlightPlan; import entity.Plane; public class FlightPlanDAO { private DBAccess dbaccess = null; private static FlightPlanDAO instance = null; /** * Retourne une instance de FlightPlanDAO * * @return instance de la classe * @throws MyDBException */ public static FlightPlanDAO getInstance() throws MyDBException { if (instance == null) { instance = new FlightPlanDAO(); } return instance; } /** * Constructeur par dfaut Initialisation de la connexion la base de * donnes * * @throws MyDBException */ private FlightPlanDAO() throws MyDBException { super(); dbaccess = DBAccess.getInstance(); } /** * Connexion la base de donnes * * @throws MyDBException */ public void getConnection() throws MyDBException { try { dbaccess.connect(); } catch (SQLException e) { throw new MyDBException("Connexion la base de donnees impossible"); } } /** * Fermeture de la connexion * * @throws MyDBException */ public void close() throws MyDBException { dbaccess.close(); } /** * Permet d'insrer un nouvel enregistrement dans la table FlightPlan * * @param m * FlightPlan insrer * @throws MyDBException */ public void insertFlightPlan(FlightPlan fp) throws MyDBException { // ajout de l'avion avec le bon id_FlightPlan et le bon id_FlightPlan PreparedStatement preparedStmt = null; getConnection(); // rcupration de l'id du plane Integer idPlane = PlaneDAO.getInstance().selectIdPlane(fp.getPlane().getPlaneName()); // rcupration de l'id de la flight duration Integer idFlightDuration = FlightDurationDAO.getInstance().selectIdFlightDuration(fp.getDuration().getAirportDeparture(), fp.getDuration().getAirportArrival()); // insert du flight plan dans la BDD String requete = "INSERT INTO flight_plan (fk_id_plane, fk_id_flight_duration, departure_time) VALUES (?,?,?);"; try { preparedStmt = dbaccess.getConnection().prepareStatement(requete); preparedStmt.setInt(1, idPlane); preparedStmt.setInt(2, idFlightDuration); preparedStmt.setDate(3, fp.getDepartureTime()); preparedStmt.executeUpdate(); } catch (SQLException e) { throw new MyDBException("Probleme lors de la creation ou de l'excution de la requete d'insertion"); } try { preparedStmt.close(); } catch (SQLException e) { throw new MyDBException("Erreur lors du close du statement de l'insertion"); } close(); } /** * Permet d'afficher toute la table FlightPlan * * @throws MyDBException */ public List<FlightPlan> selectAll() throws MyDBException { ResultSet resultats = null; List<FlightPlan> lstFlightPlans = new ArrayList<FlightPlan>(); String requete = "SELECT P.plane_name, A.airline_name, Ai1.airport_name AS airport_departure, Ai2.airport_name AS airport_arrival, FD.duration, FP.departure_time" + "FROM rechercheultime.flight_plan FP" + "INNER JOIN rechercheultime.plane P ON FP.fk_id_plane = P.id_plane" + "INNER JOIN rechercheultime.flight_duration FD ON FP.fk_id_flight_duration = FD.id_flight_duration" + "INNER JOIN rechercheultime.airline A ON P.fk_id_airline = A.id_airline" + "INNER JOIN rechercheultime.airport Ai1 ON FD.fk_id_airport_departure = Ai1.id_airport" + "INNER JOIN rechercheultime.airport Ai2 ON FD.fk_id_airport_arrival = Ai2.id_airport;"; PreparedStatement preparedStmt = null; // connexion la base de donnes getConnection(); // envoi de la requete try { preparedStmt = dbaccess.getConnection().prepareStatement(requete); resultats = preparedStmt.executeQuery(); } catch (SQLException e1) { throw new MyDBException("Erreur lors de la cration ou de l'excution da la requete de selection"); } // traitement des rsultats try { while (resultats.next()) { Airline airline = Factory.createAirline(resultats.getString("airline_name")); Plane p = Factory.createPlane(resultats.getString("plane_name")); p.setAirline(airline); Airport airportDeparture = Factory.createAirport(resultats.getString("airport_departure")); Airport airportArrival = Factory.createAirport(resultats.getString("airport_arrival")); FlightDuration fd = Factory.createFlightDuration(airportDeparture, airportArrival, resultats.getInt("duration")); FlightPlan a = Factory.createFlightPlan(p, fd, resultats.getDate("departure_time")); lstFlightPlans.add(a); } } catch (SQLException e) { throw new MyDBException("Erreur lors de la rcupration des donnes du select"); } // fermeture du ResultSet ainsi que de la connexion try { preparedStmt.close(); } catch (SQLException e1) { throw new MyDBException("Erreur lors de la fermeture du statement de selection"); } try { resultats.close(); } catch (SQLException e) { throw new MyDBException("Erreur lors de la fermeture du ResultSet"); } close(); return lstFlightPlans; } public FlightPlan selectFlightPlanOfPlane(String planeName, String airportDeparture, String airportArrival, Date date) throws MyDBException { FlightPlan fp = null; // rcupration de l'id de l'aroport de dpart Integer idAirportDeparture = PlaneDAO.getInstance().selectIdPlane(airportDeparture); // rcupration de l'id de l'aroport d'arrive Integer idAirportArrival = PlaneDAO.getInstance().selectIdPlane(airportArrival); ResultSet resultats = null; String requete = "SELECT P.plane_name, A.airline_name, Ai1.airport_name AS airport_departure, Ai2.airport_name AS airport_arrival, FD.duration, FP.departure_time" + "FROM rechercheultime.flight_plan FP" + "INNER JOIN rechercheultime.plane P ON FP.fk_id_plane = P.id_plane" + "INNER JOIN rechercheultime.flight_duration FD ON FP.fk_id_flight_duration = FD.id_flight_duration" + "INNER JOIN rechercheultime.airline A ON P.fk_id_airline = A.id_airline" + "INNER JOIN rechercheultime.airport Ai1 ON FD.fk_id_airport_departure = Ai1.id_airport" + "INNER JOIN rechercheultime.airport Ai2 ON FD.fk_id_airport_arrival = Ai2.id_airport" + "WHERE Ai1.id_airport = ? AND Ai2.id_airport = ? AND P.plane_name = ?;"; PreparedStatement preparedStmt = null; // connexion la base de donnes getConnection(); // envoi de la requete try { preparedStmt = dbaccess.getConnection().prepareStatement(requete); preparedStmt.setInt(1, idAirportDeparture); preparedStmt.setInt(2, idAirportArrival); preparedStmt.setString(3, planeName); resultats = preparedStmt.executeQuery(); } catch (SQLException e1) { throw new MyDBException("Erreur lors de la cration ou de l'excution da la requete de selection"); } // traitement des rsultats try { if (resultats.next()) { Airline airline = Factory.createAirline(resultats.getString("airline_name")); Plane p = Factory.createPlane(resultats.getString("plane_name")); p.setAirline(airline); Airport airportD = Factory.createAirport(resultats.getString("airport_departure")); Airport airportA = Factory.createAirport(resultats.getString("airport_arrival")); FlightDuration fd = Factory.createFlightDuration(airportD, airportA, resultats.getInt("duration")); fp = Factory.createFlightPlan(p, fd, resultats.getDate("departure_time")); } } catch (SQLException e) { throw new MyDBException("Erreur lors de la rcupration des donnes du select"); } // fermeture du ResultSet ainsi que de la connexion try { preparedStmt.close(); } catch (SQLException e1) { throw new MyDBException("Erreur lors de la fermeture du statement de selection"); } try { resultats.close(); } catch (SQLException e) { throw new MyDBException("Erreur lors de la fermeture du ResultSet"); } close(); return fp; } public List<FlightPlan> selectFlightFromAirport(String airport) throws MyDBException { List<FlightPlan> lstFlightPlan = new ArrayList<FlightPlan>(); ResultSet resultats = null; List<FlightPlan> lstFlightPlans = new ArrayList<FlightPlan>(); String requete = "SELECT P.plane_name, A.airline_name, Ai1.airport_name AS airport_departure, Ai2.airport_name AS airport_arrival, FD.duration, FP.departure_time" + "FROM rechercheultime.flight_plan FP" + "INNER JOIN rechercheultime.plane P ON FP.fk_id_plane = P.id_plane" + "INNER JOIN rechercheultime.flight_duration FD ON FP.fk_id_flight_duration = FD.id_flight_duration" + "INNER JOIN rechercheultime.airline A ON P.fk_id_airline = A.id_airline" + "INNER JOIN rechercheultime.airport Ai1 ON FD.fk_id_airport_departure = Ai1.id_airport" + "INNER JOIN rechercheultime.airport Ai2 ON FD.fk_id_airport_arrival = Ai2.id_airport" + "WHERE Ai1.airport_name = ?;"; PreparedStatement preparedStmt = null; // connexion la base de donnes getConnection(); // envoi de la requete try { preparedStmt = dbaccess.getConnection().prepareStatement(requete); preparedStmt.setString(1, airport); resultats = preparedStmt.executeQuery(); } catch (SQLException e1) { throw new MyDBException("Erreur lors de la cration ou de l'excution da la requete de selection"); } // traitement des rsultats try { while (resultats.next()) { Airline airline = Factory.createAirline(resultats.getString("airline_name")); Plane p = Factory.createPlane(resultats.getString("plane_name")); p.setAirline(airline); Airport airportDeparture = Factory.createAirport(resultats.getString("airport_departure")); Airport airportArrival = Factory.createAirport(resultats.getString("airport_arrival")); FlightDuration fd = Factory.createFlightDuration(airportDeparture, airportArrival, resultats.getInt("duration")); FlightPlan a = Factory.createFlightPlan(p, fd, resultats.getDate("departure_time")); lstFlightPlans.add(a); } } catch (SQLException e) { throw new MyDBException("Erreur lors de la rcupration des donnes du select"); } // fermeture du ResultSet ainsi que de la connexion try { preparedStmt.close(); } catch (SQLException e1) { throw new MyDBException("Erreur lors de la fermeture du statement de selection"); } try { resultats.close(); } catch (SQLException e) { throw new MyDBException("Erreur lors de la fermeture du ResultSet"); } close(); return lstFlightPlan; } public List<FlightPlan> selectFlightToAirport(String airport) throws MyDBException { List<FlightPlan> lstFlightPlan = new ArrayList<FlightPlan>(); ResultSet resultats = null; List<FlightPlan> lstFlightPlans = new ArrayList<FlightPlan>(); String requete = "SELECT P.plane_name, A.airline_name, Ai1.airport_name AS airport_departure, Ai2.airport_name AS airport_arrival, FD.duration, FP.departure_time" + "FROM rechercheultime.flight_plan FP" + "INNER JOIN rechercheultime.plane P ON FP.fk_id_plane = P.id_plane" + "INNER JOIN rechercheultime.flight_duration FD ON FP.fk_id_flight_duration = FD.id_flight_duration" + "INNER JOIN rechercheultime.airline A ON P.fk_id_airline = A.id_airline" + "INNER JOIN rechercheultime.airport Ai1 ON FD.fk_id_airport_departure = Ai1.id_airport" + "INNER JOIN rechercheultime.airport Ai2 ON FD.fk_id_airport_arrival = Ai2.id_airport" + "WHERE Ai2.airport_name = ?;"; PreparedStatement preparedStmt = null; // connexion la base de donnes getConnection(); // envoi de la requete try { preparedStmt = dbaccess.getConnection().prepareStatement(requete); preparedStmt.setString(1, airport); resultats = preparedStmt.executeQuery(); } catch (SQLException e1) { throw new MyDBException("Erreur lors de la cration ou de l'excution da la requete de selection"); } // traitement des rsultats try { while (resultats.next()) { Airline airline = Factory.createAirline(resultats.getString("airline_name")); Plane p = Factory.createPlane(resultats.getString("plane_name")); p.setAirline(airline); Airport airportDeparture = Factory.createAirport(resultats.getString("airport_departure")); Airport airportArrival = Factory.createAirport(resultats.getString("airport_arrival")); FlightDuration fd = Factory.createFlightDuration(airportDeparture, airportArrival, resultats.getInt("duration")); FlightPlan a = Factory.createFlightPlan(p, fd, resultats.getDate("departure_time")); lstFlightPlans.add(a); } } catch (SQLException e) { throw new MyDBException("Erreur lors de la rcupration des donnes du select"); } // fermeture du ResultSet ainsi que de la connexion try { preparedStmt.close(); } catch (SQLException e1) { throw new MyDBException("Erreur lors de la fermeture du statement de selection"); } try { resultats.close(); } catch (SQLException e) { throw new MyDBException("Erreur lors de la fermeture du ResultSet"); } close(); return lstFlightPlan; } public List<FlightPlan> selectFlightBetweenAirports(String airportDeparture, String airportArrival) throws MyDBException { List<FlightPlan> lstFlightPlan = new ArrayList<FlightPlan>(); ResultSet resultats = null; List<FlightPlan> lstFlightPlans = new ArrayList<FlightPlan>(); String requete = "SELECT P.plane_name, A.airline_name, Ai1.airport_name AS airport_departure, Ai2.airport_name AS airport_arrival, FD.duration, FP.departure_time" + "FROM rechercheultime.flight_plan FP" + "INNER JOIN rechercheultime.plane P ON FP.fk_id_plane = P.id_plane" + "INNER JOIN rechercheultime.flight_duration FD ON FP.fk_id_flight_duration = FD.id_flight_duration" + "INNER JOIN rechercheultime.airline A ON P.fk_id_airline = A.id_airline" + "INNER JOIN rechercheultime.airport Ai1 ON FD.fk_id_airport_departure = Ai1.id_airport" + "INNER JOIN rechercheultime.airport Ai2 ON FD.fk_id_airport_arrival = Ai2.id_airport" + "WHERE Ai1.airport_name = ? AND Ai2.airport_name = ?;"; PreparedStatement preparedStmt = null; // connexion la base de donnes getConnection(); // envoi de la requete try { preparedStmt = dbaccess.getConnection().prepareStatement(requete); preparedStmt.setString(1, airportDeparture); preparedStmt.setString(2, airportArrival); resultats = preparedStmt.executeQuery(); } catch (SQLException e1) { throw new MyDBException("Erreur lors de la cration ou de l'excution da la requete de selection"); } // traitement des rsultats try { while (resultats.next()) { Airline airline = Factory.createAirline(resultats.getString("airline_name")); Plane p = Factory.createPlane(resultats.getString("plane_name")); p.setAirline(airline); Airport airportD = Factory.createAirport(resultats.getString("airport_departure")); Airport airportA = Factory.createAirport(resultats.getString("airport_arrival")); FlightDuration fd = Factory.createFlightDuration(airportD, airportA, resultats.getInt("duration")); FlightPlan a = Factory.createFlightPlan(p, fd, resultats.getDate("departure_time")); lstFlightPlans.add(a); } } catch (SQLException e) { throw new MyDBException("Erreur lors de la rcupration des donnes du select"); } // fermeture du ResultSet ainsi que de la connexion try { preparedStmt.close(); } catch (SQLException e1) { throw new MyDBException("Erreur lors de la fermeture du statement de selection"); } try { resultats.close(); } catch (SQLException e) { throw new MyDBException("Erreur lors de la fermeture du ResultSet"); } close(); return lstFlightPlan; } public List<FlightPlan> selectFlightIntoTimeInterval(Date date1, Date date2) throws MyDBException { List<FlightPlan> lstFlightPlan = new ArrayList<FlightPlan>(); ResultSet resultats = null; List<FlightPlan> lstFlightPlans = new ArrayList<FlightPlan>(); String requete = "SELECT P.plane_name, A.airline_name, Ai1.airport_name AS airport_departure, Ai2.airport_name AS airport_arrival, FD.duration, FP.departure_time" + "FROM rechercheultime.flight_plan FP" + "INNER JOIN rechercheultime.plane P ON FP.fk_id_plane = P.id_plane" + "INNER JOIN rechercheultime.flight_duration FD ON FP.fk_id_flight_duration = FD.id_flight_duration" + "INNER JOIN rechercheultime.airline A ON P.fk_id_airline = A.id_airline" + "INNER JOIN rechercheultime.airport Ai1 ON FD.fk_id_airport_departure = Ai1.id_airport" + "INNER JOIN rechercheultime.airport Ai2 ON FD.fk_id_airport_arrival = Ai2.id_airport" + "WHERE FP.departure_time BETWEEN date1 AND date2;"; PreparedStatement preparedStmt = null; // connexion la base de donnes getConnection(); // envoi de la requete try { preparedStmt = dbaccess.getConnection().prepareStatement(requete); preparedStmt.setDate(1, date1); preparedStmt.setDate(2, date2); resultats = preparedStmt.executeQuery(); } catch (SQLException e1) { throw new MyDBException("Erreur lors de la cration ou de l'excution da la requete de selection"); } // traitement des rsultats try { while (resultats.next()) { Airline airline = Factory.createAirline(resultats.getString("airline_name")); Plane p = Factory.createPlane(resultats.getString("plane_name")); p.setAirline(airline); Airport airportD = Factory.createAirport(resultats.getString("airport_departure")); Airport airportA = Factory.createAirport(resultats.getString("airport_arrival")); FlightDuration fd = Factory.createFlightDuration(airportD, airportA, resultats.getInt("duration")); FlightPlan a = Factory.createFlightPlan(p, fd, resultats.getDate("departure_time")); lstFlightPlans.add(a); } } catch (SQLException e) { throw new MyDBException("Erreur lors de la rcupration des donnes du select"); } // fermeture du ResultSet ainsi que de la connexion try { preparedStmt.close(); } catch (SQLException e1) { throw new MyDBException("Erreur lors de la fermeture du statement de selection"); } try { resultats.close(); } catch (SQLException e) { throw new MyDBException("Erreur lors de la fermeture du ResultSet"); } close(); return lstFlightPlan; } }
true
d05852d3e002dff006622e0c5ee25f65687851e1
Java
sanguolingzi/desk
/sysmanage/src/main/java/com/cunw/cloud/familydesk/sysmanage/controller/SysAppBindResultController.java
UTF-8
1,191
1.867188
2
[]
no_license
package com.cunw.cloud.familydesk.sysmanage.controller; import com.cunw.cloud.framework.controller.BaseRESTfulController; import com.cunw.cloud.framework.controller.dto.RESTfulResult; import com.cunw.cloud.familydesk.sysmanage.service.ISysAppBindResultService; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; /** * SysAppBindResult RESTful接口: * @author generator * @version 1.0-SNAPSHORT 2019-01-22 03:41 * 类描述 * 修订历史: * 日期:2019-01-22 * 作者:generator * 参考: * 描述:SysAppBindResult RESTful接口 * @see null * 湖南新云网科技有限公司版权所有. */ @RestController @RequestMapping("/${api.version}/sysAppBindResults") public class SysAppBindResultController extends BaseRESTfulController { @Autowired ISysAppBindResultService sysAppBindResultService; @ApiOperation(value="获取App绑定结果") @GetMapping(value = "/getAppBindResult") public RESTfulResult get(@RequestParam("deviceNo") String deviceNo){ return success(sysAppBindResultService.getAppBindResult(deviceNo)); } }
true
839dd2d2abe8d010e82b12f9429dc43d9b1d74a5
Java
colorfulgrayscale/rofl
/src/database/DatabaseMessage.java
UTF-8
648
2.8125
3
[]
no_license
package database; public enum DatabaseMessage { UPDATE_TABLES("updateTables"), UPDATE_ORDERS("updateOrders"), UPDATE_WALLS( "updateWalls"); private String message; private DatabaseMessage(final String aMessage) { message = aMessage; } public String getListener() { return "LISTEN " + message + "; "; } public String getUnlistener() { return "UNLISTEN " + message + "; "; } public String getNotifier() { return "NOTIFY " + message + "; "; } public String getMessage() { return message; } public boolean equals(final String aString) { return message.equalsIgnoreCase(aString); } }
true
2c2ffffc6ad98c0b736fa52207e787e8028037fb
Java
clorenz/WatchCheck
/src/de/uhrenbastler/watchcheck/ui/LogDialog.java
UTF-8
6,562
1.898438
2
[]
no_license
/* ------------------------------------------------------------------------- * $Source:$ $Author:$ $Date: $ $Revision: $ (C) 2006 Christoph Lorenz, <mail@christophlorenz.de> All rights reserved. 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ** ------------------------------------------------------------------------- */ package de.uhrenbastler.watchcheck.ui; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.GregorianCalendar; import org.apache.commons.lang3.ArrayUtils; import android.app.Dialog; import android.content.ContentValues; import android.content.Context; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import de.uhrenbastler.watchcheck.R; import de.uhrenbastler.watchcheck.data.Log; import de.uhrenbastler.watchcheck.data.Log.Logs; import de.uhrenbastler.watchcheck.tools.Logger; public class LogDialog extends Dialog { private static final String[] POSITIONARR = { "","DU","DD","0U","3U","6U","9U" }; private static final int[] TEMPARR = { -273, 4, 20, 36 }; boolean saved =false; private int watchId; private double deviation; private boolean modeNtp; private GregorianCalendar localTime; private GregorianCalendar ntpTime; private Spinner positionSpinner; private Spinner temperatureSpinner; private CheckBox startFlag; private EditText comment; private Log lastLog; protected static final String ATTR_DEVIATION = "attrDeviation"; protected static final String ATTR_WATCH_ID = "attrWatchId"; protected static final String ATTR_MODE_NTP = "attrModeNtp"; protected static final String ATTR_LOCAL_TIME = "attrLocalTime"; protected static final String ATTR_NTP_TIME = "attrNtpTime"; protected static final String ATTR_LAST_LOG = "lastLog"; public LogDialog(Context context, Bundle logData) { super(context); setContentView(R.layout.log_dialog); setTitle(getContext().getString(R.string.enterLog)); setCancelable(true); Button buttonSave = (Button) findViewById(R.id.buttonSave); buttonSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { makeLogEntry(); saved=true; dismiss(); } }); watchId = logData.getInt(ATTR_WATCH_ID); deviation = logData.getDouble(ATTR_DEVIATION); modeNtp = logData.getBoolean(ATTR_MODE_NTP); localTime = (GregorianCalendar) logData.get(ATTR_LOCAL_TIME); ntpTime = (GregorianCalendar) logData.get(ATTR_NTP_TIME); lastLog = (Log) logData.get(ATTR_LAST_LOG); Logger.debug("watchId="+watchId+", deviation="+deviation +", modeNtp="+modeNtp+", localTime="+localTime.getTime() +", ntpTime="+(ntpTime!=null?ntpTime.getTime():"NULL") +", lastLog="+lastLog); TextView textDeviation = (TextView) findViewById(R.id.textViewDeviationValue); DecimalFormat df = new DecimalFormat("#.#"); textDeviation.setText( (deviation>0?"+":deviation<0?"-":"+-") + df.format(Math.abs(deviation)) +" sec." ); positionSpinner = (Spinner) findViewById(R.id.logSpinnerPosition); ArrayAdapter<?> positionAdapter = ArrayAdapter.createFromResource( getContext(), R.array.positions,android.R.layout.simple_spinner_item); positionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); positionSpinner.setAdapter(positionAdapter); if ( lastLog!=null && lastLog.getPosition()!=null) positionSpinner.setSelection(ArrayUtils.indexOf(POSITIONARR, lastLog.getPosition())); else positionSpinner.setSelection(0); temperatureSpinner = (Spinner) findViewById(R.id.logSpinnerTemperature); ArrayAdapter<?> temperatureAdapter = ArrayAdapter.createFromResource( getContext(), R.array.temperatures,android.R.layout.simple_spinner_item); temperatureAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); temperatureSpinner.setAdapter(temperatureAdapter); if ( lastLog!=null ) temperatureSpinner.setSelection(ArrayUtils.indexOf(TEMPARR, lastLog.getTemperature())); else temperatureSpinner.setSelection(0); comment = (EditText) findViewById(R.id.logComment); startFlag = (CheckBox) findViewById(R.id.logCheckBoxNewPeriod); startFlag.setChecked(lastLog==null); startFlag.setEnabled(lastLog!=null); } /* (non-Javadoc) * @see android.app.Dialog#setOnCancelListener(android.content.DialogInterface.OnCancelListener) */ @Override public void setOnCancelListener(OnCancelListener listener) { saved=false; dismiss(); } public boolean isSaved() { return saved; } /** * Creates the log entry in the content provider */ protected void makeLogEntry() { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); double ntpDiff = modeNtp?((double)(localTime.getTimeInMillis() - ntpTime.getTimeInMillis())) / 1000d:0; // Really??? ContentValues values = new ContentValues(); values.put(Logs.COMMENT, comment.getEditableText().toString()); values.put(Logs.DEVIATION, deviation); values.put(Logs.FLAG_RESET, startFlag.isChecked()); values.put(Logs.LOCAL_TIMESTAMP, dateFormat.format(localTime.getTime())); values.put(Logs.MODUS, modeNtp); values.put(Logs.NTP_DIFF, ntpDiff); if ( positionSpinner.getSelectedItemId() > 0) values.put(Logs.POSITION, POSITIONARR[(int)positionSpinner.getSelectedItemId()]); if ( temperatureSpinner.getSelectedItemId() > 0 ) values.put(Logs.TEMPERATURE, TEMPARR[(int)temperatureSpinner.getSelectedItemId()]); values.put(Logs.WATCH_ID, watchId); Logger.debug("values="+values); getContext().getContentResolver().insert(Logs.CONTENT_URI, values); } }
true
f100331d402ab2968f303038eee249d767680821
Java
Timo-H/Dijkstra_Shortest_Path_en_Datastructuren
/src/Unit_Tests/ShortestPath/ReisTest.java
UTF-8
1,783
2.90625
3
[]
no_license
package ShortestPath; import org.junit.Test; import java.util.ArrayList; import static org.junit.Assert.*; public class ReisTest { @Test public void getStappen() { Vlucht vlucht = new Vlucht(30, 10); Rit rit = new Rit(20); Treinrit treinrit = new Treinrit(25); ArrayList<Stap> stappen1 = new ArrayList<>(); stappen1.add(vlucht); ArrayList<Stap> stappen2 = new ArrayList<>(); stappen2.add(rit); stappen2.add(treinrit); Reis reis1 = new Reis(stappen1); Reis reis2 = new Reis(stappen2); assertEquals(1, reis1.getStappen().size()); assertEquals(2, reis2.getStappen().size()); } @Test public void getZwaarte() { Vlucht vlucht = new Vlucht(30, 10); Rit rit = new Rit(20); Treinrit treinrit = new Treinrit(25); ArrayList<Stap> stappen1 = new ArrayList<>(); stappen1.add(vlucht); ArrayList<Stap> stappen2 = new ArrayList<>(); stappen2.add(rit); stappen2.add(treinrit); Reis reis1 = new Reis(stappen1); Reis reis2 = new Reis(stappen2); assertEquals(40, reis1.getZwaarte()); assertEquals(90, reis2.getZwaarte()); } @Test public void compareTo() { Vlucht vlucht = new Vlucht(30, 10); Rit rit = new Rit(20); Treinrit treinrit = new Treinrit(25); ArrayList<Stap> stappen1 = new ArrayList<>(); stappen1.add(vlucht); ArrayList<Stap> stappen2 = new ArrayList<>(); stappen2.add(rit); stappen2.add(treinrit); Reis reis1 = new Reis(stappen1); Reis reis2 = new Reis(stappen2); assertEquals(-1, reis1.compareTo(reis2)); assertEquals(1, reis2.compareTo(reis1)); } }
true
f6c24207402bdf6550dbade6f440e6f24dd0ecb9
Java
AntoninoAN/CustomConsumer
/app/src/main/java/com/example/tony/consumercontentprovider/MainActivity.java
UTF-8
2,353
2.34375
2
[]
no_license
package com.example.tony.consumercontentprovider; import android.content.ContentProviderClient; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.RemoteException; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.Map; import java.util.Set; public class MainActivity extends AppCompatActivity { public static final String TAG= MainActivity.class.getSimpleName()+"_TAG"; Uri uriContentProvider; ContentProviderClient contentProviderClient; public static final String TABLE_MOVIE="movie"; public static final String TABLE_GENRE="genre"; public static final String COLUMN_DATE=TABLE_MOVIE+"/date"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); uriContentProvider= Uri.parse("content://com.example.tony.w5d3ex01/"); contentProviderClient= getContentResolver().acquireContentProviderClient( uriContentProvider ); readContent(); } public void readContent(){ this.grantUriPermission("com.example.tony.w5d3ex01",uriContentProvider, Intent.FLAG_GRANT_READ_URI_PERMISSION| Intent.FLAG_GRANT_WRITE_URI_PERMISSION); Cursor cursor= getContentResolver().query( uriContentProvider.buildUpon().appendPath(TABLE_MOVIE).build(), null,null,null,null ); Log.d(TAG, "readContent: "+cursor+"//"+uriContentProvider); /*cursor. Map<String,String> movieSet; movieSet.put(cursor.) ListView newListView= new ListView(this); newListView.setAdapter(new ArrayAdapter<>());*/ } public void insertContent(){ //TODO some day ContentValues values= new ContentValues(); values.put(uriContentProvider.buildUpon().appendPath(TABLE_MOVIE).appendPath("name").build() .toString(), "STAR WARS THE RETURN OF THE JEDI"); values.put(uriContentProvider.buildUpon().appendPath(COLUMN_DATE).build().toString(), "08-16-1986"); } }
true
6d18ab6591c157a369743360c246701dcefdedd4
Java
hoaingo/new-project
/portal-service-new/src/main/java/com/pms/portal/model/Account.java
UTF-8
2,664
1.820313
2
[]
no_license
package com.pms.portal.model; import com.fasterxml.jackson.annotation.JsonIgnore; import com.pms.jdbc.orm.Key; import java.util.List; /** * * @author conan */ public class Account { @Key(value = "user_id") private long userId; @Key(value = "user_name") private String userName; @Key(value = "full_name") private String fullName; @JsonIgnore @Key(value = "user_password") private String password; @JsonIgnore @Key(value = "permissions") private String lstPermissions; @Key(value = "dept_name", required = false) private String departmentName; @JsonIgnore @Key(value = "associated_roles") private String lstRoles; @Key(value = "user_setting_theme", required = false) private String userSettingTheme; @Key(value = "user_setting_language", required = false) private String userSettingLanguage; public String getUserSettingTheme() { return userSettingTheme; } public void setUserSettingTheme(String userSettingTheme) { this.userSettingTheme = userSettingTheme; } public String getUserSettingLanguage() { return userSettingLanguage; } public void setUserSettingLanguage(String userSettingLanguage) { this.userSettingLanguage = userSettingLanguage; } private List<String> permissions; public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getDepartmentName() { return departmentName; } public void setDepartmentName(String departmentName) { this.departmentName = departmentName; } public String getLstPermissions() { return lstPermissions; } public void setLstPermissions(String lstPermissions) { this.lstPermissions = lstPermissions; } public List<String> getPermissions() { return permissions; } public void setPermissions(List<String> permissions) { this.permissions = permissions; } public String getLstRoles() { return lstRoles; } public void setLstRoles(String lstRoles) { this.lstRoles = lstRoles; } }
true
a1718774dcb56d913a963e86d2834a1895ed66c6
Java
amerrin/Portfolio
/Agent-Based Toy Factory (Group Project)/src/ServerClient/PrintsStringMessageToServer.java
UTF-8
412
2.703125
3
[]
no_license
package ServerClient; /* Test message class to print string on server. */ public class PrintsStringMessageToServer implements MessageToServer { String myString; public PrintsStringMessageToServer (String s) { if (s!= null) myString = s; else myString = new String("No message set"); } public void doIt(HandleAClient hac) { System.out.println(myString); } } //written by Alex Jones
true
5f56460f8ca2d992b91c668973f3a33288a60207
Java
evgeniy-panferov/you-promocode-bot
/src/main/java/ru/youpromocodebot/controller/ImageController.java
UTF-8
1,245
2.421875
2
[]
no_license
package ru.youpromocodebot.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import java.io.IOException; import static org.springframework.util.ResourceUtils.getFile; @RestController @CrossOrigin(value = "https://tg-bot-site.herokuapp.com/") public class ImageController { private static final Logger log = LoggerFactory.getLogger(ImageController.class); @RequestMapping("api/image/{imageName}") @ResponseBody public HttpEntity<byte[]> getPhoto(@PathVariable String imageName) { log.info("ImageController getPhoto imageName - {}", imageName); byte[] image = new byte[0]; try { image = org.apache.commons.io.FileUtils.readFileToByteArray(getFile("classpath:image/" + imageName + ".jpg")); } catch (IOException e) { log.error(e.getMessage()); } HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.IMAGE_JPEG); headers.setContentLength(image.length); return new HttpEntity<byte[]>(image, headers); } }
true
d13b75feffd5e7a1692c1e529d10b7e710698a20
Java
noisyle/crowbar
/crowbar-core/src/main/java/com/noisyle/crowbar/core/util/CryptoUtils.java
UTF-8
4,899
2.9375
3
[]
no_license
package com.noisyle.crowbar.core.util; import java.security.MessageDigest; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.noisyle.crowbar.core.constant.SystemConstant; public class CryptoUtils { private final static Logger logger = LoggerFactory.getLogger(CryptoUtils.class); public enum Option { ENCRYPT, DECRYPT; } public final static String md5(String s) { char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; try { byte[] btInput = s.getBytes(); // 获得MD5摘要算法的 MessageDigest 对象 MessageDigest mdInst = MessageDigest.getInstance("MD5"); // 使用指定的字节更新摘要 mdInst.update(btInput); // 获得密文 byte[] md = mdInst.digest(); // 把密文转换成十六进制的字符串形式 int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } catch (Exception e) { logger.error("生成md5出错", e); return null; } } /** * AES加密解密 * * @param str * 明文或密文字符串 * @param key * 密钥字符串 * @param op * 操作类型 * @return */ public static String aes(String str, String key, Option op) { if (op == Option.ENCRYPT) { return byte2Hex(encryptAES(str, key)); } else if (op == Option.DECRYPT) { return new String(decryptAES(hex2Byte(str), key)); } else { return null; } } /** * 加密 * * @param content * 需要加密的内容 * @param password * 加密密码 * @return */ private static byte[] encryptAES(String content, String password) { try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES");// 创建密码器 byte[] byteContent = content.getBytes("utf-8"); cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化 byte[] result = cipher.doFinal(byteContent); return result; } catch (Exception e) { logger.error("AES加密出错", e); } return null; } /** * 解密 * * @param content * 待解密内容 * @param password * 解密密钥 * @return */ private static byte[] decryptAES(byte[] content, String password) { try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES");// 创建密码器 cipher.init(Cipher.DECRYPT_MODE, key);// 初始化 byte[] result = cipher.doFinal(content); return result; } catch (Exception e) { logger.error("AES解密出错", e); } return null; } /** * 将二进制转换成16进制 * * @param buf * @return */ private static String byte2Hex(byte buf[]) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } /** * 将16进制转换为二进制 * * @param hexStr * @return */ private static byte[] hex2Byte(String hexStr) { if (hexStr.length() < 1) return null; byte[] result = new byte[hexStr.length() / 2]; for (int i = 0; i < hexStr.length() / 2; i++) { int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); result[i] = (byte) (high * 16 + low); } return result; } public static String cipher(String s) { if (s == null) { return null; } return "`".concat(aes(s, SystemConstant.SYSTEM_IDENTIFIER, Option.ENCRYPT)); } public static String decipher(String s) { if (s == null) { return null; } else if (!s.startsWith("`")) { return s; } return aes(s.substring(1), SystemConstant.SYSTEM_IDENTIFIER, Option.DECRYPT); } public static void main(String[] args) { if (args.length >= 2) { if (args[0].equals("-e")) { System.out.println(cipher(args[1])); return; } else if (args[0].equals("-d")) { System.out.println(decipher(args[1])); return; } } System.out.println("options:\n\t-e:\t加密\n\t-d:\t解密"); } }
true
4724c21069c5fa021f6ea35bc7477c12d3c78e0a
Java
alexandraback/datacollection
/solutions_5731331665297408_0/java/framalex/C.java
UTF-8
3,288
2.78125
3
[]
no_license
import java.io.*; import java.util.*; import java.math.*; public class C implements Runnable { private String rec(int pos, int mask, ArrayList<Integer> list) { if (Integer.bitCount(mask) == n) { String ans = ""; int mm = 0; for (int i = 0; i < list.size(); ++i) { if ((mm & (1 << list.get(i))) == 0) { mm |= 1 << list.get(i); ans += zip[list.get(i)]; } } return ans; } String ans = null; for (int j = 0; j < list.size(); ++j) { int start = list.get(j); for (int i = 0; i < n; ++i) { if ((mask & (1<<i)) == 0 && g[start].contains(i)) { ArrayList<Integer> l = (ArrayList<Integer>)list.clone(); l.add(i); String tmp = rec(i, mask | (1<<i), l); if (tmp != null) { if (ans == null || ans.compareTo(tmp) > 0) { ans = tmp; } } } } } return ans; } int n; HashSet<Integer>[] g; String[] zip; public void run() { int cases = nextInt(); for (int cs = 0; cs < cases; ++cs) { n = nextInt(); int m = nextInt(); zip = new String[n]; for (int i = 0; i < n; ++i) { zip[i] = nextWord(); } g = new HashSet[n]; for (int i = 0; i < n; ++i) { g[i] = new HashSet<Integer>(); } for (int i = 0; i < m; ++i) { int a = nextInt() - 1; int b = nextInt() - 1; g[a].add(b); g[b].add(a); } String ans = null; if (m == n*(n-1)/2) { Arrays.sort(zip); ans = ""; for (int i = 0; i < n; ++i) { ans += zip[i]; } } else { int min = 0; for (int i = 0; i < n; ++i) { if (zip[i].compareTo(zip[min]) < 0) { min = i; } } for (int i = min; i <= min; ++i) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(i); String tmp = rec(i, 1<<i, list); if (tmp != null) { if (ans == null || ans.compareTo(tmp) > 0) { ans = tmp; } } } } System.err.println(cs + " " + n + " " + ans + " "); out.println("Case #" + (cs+1) + ": " + ans); } out.flush(); } private static BufferedReader br = null; private static StringTokenizer stk = null; private static PrintWriter out = null; public static void main(String[] args) throws IOException { br = new BufferedReader(new FileReader(new File("D:\\C.txt"))); out = new PrintWriter("D:\\CC.txt"); (new Thread(new C())).start(); } public void loadLine() { try { stk = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } public String nextLine() { try { return (br.readLine()); } catch (IOException e) { e.printStackTrace(); } return null; } public int nextInt() { while (stk==null || !stk.hasMoreTokens()) loadLine(); return Integer.parseInt(stk.nextToken()); } public long nextLong() { while (stk==null || !stk.hasMoreTokens()) loadLine(); return Long.parseLong(stk.nextToken()); } public double nextDouble() { while (stk==null || !stk.hasMoreTokens()) loadLine(); return Double.parseDouble(stk.nextToken()); } public String nextWord() { while (stk==null || !stk.hasMoreTokens()) loadLine(); return (stk.nextToken()); } }
true
00a57399b504647108abce1e28fd12b9e2e39824
Java
DomingosCastro/LPOO1617_T4G5
/DungeonKeep/src/dungeon/cli/Input.java
UTF-8
199
2.484375
2
[]
no_license
package dungeon.cli; import java.util.Scanner; public class Input { Scanner input = new Scanner(System.in); public char read() { char letter= input.next().charAt(0); return letter; } }
true
1d2e21f245d7a709696ebbc8f22b2b48fc7b87dc
Java
izabelaugrevska/das-project
/Homework4/backend-docker/object-catalog/src/main/java/mk/finki/ukim/das/objectcatalog/repository/ObjectRepository.java
UTF-8
949
2.25
2
[]
no_license
package mk.finki.ukim.das.objectcatalog.repository; import mk.finki.ukim.das.objectcatalog.model.Category; import mk.finki.ukim.das.objectcatalog.model.Object; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Set; public interface ObjectRepository extends JpaRepository<Object, Long> { // returns a Set of Objects with the given name, ignores string's case Set<Object> findByNameIgnoreCaseContaining(String name); // returns a Set of Objects with the given address, ignores string's case Set<Object> findByAddressIgnoreCaseContaining(String city); // returns a Set of Objects with the given category Set<Object> findByCategory(Category category); // returns a Set of Objects with the given SmokingType Set<Object> findBySmokingType(Boolean smokingType); // returns a Set of Objects with the given OutdoorSeating type Set<Object> findByOutdoorSeating(Boolean seating); }
true
1b8b49e5c8f8d26c61231cab1f21a0e0e5b75e97
Java
AmitVermadotcom/DSA_pepcoding
/Foundation/StackandQueue/queue/client.java
UTF-8
409
2.109375
2
[]
no_license
public class client { public static void main(String[] args){ dynamicQueue dq=new dynamicQueue(6); for(int i=0;i<15;i++){ dq.push_(i*10); } System.out.println(dq.pop()); System.out.println(dq.pop()); System.out.println(dq.pop()); System.out.println(dq.pop()); System.out.println(dq.pop()); System.out.println(dq); } }
true
3d3225f31b69e306b9dc9c9877cc1b62f2ec4455
Java
Aroddo/oca
/src/wbs/operatoren/TestDemo.java
UTF-8
525
2.890625
3
[]
no_license
package wbs.operatoren; public class TestDemo { public static void main(String[] args) { double x41 = 1.0e51; double x42 = -1.0e51; double x43 = 1.0e-51; System.out.println(x41); System.out.println(x42); System.out.println(x43); String s1 = "abc"; s1+="A"; s1 += 0xde; System.out.println(s1); double x = 3.2; double rest = x % 1.5; System.out.println(rest); double d = 1.0/3; System.out.println(d); System.out.println(d*3); } }
true
b171a03446838f95a4d6a73eb6e3e92ada777b8c
Java
taufiqjack/praxis-academy
/novice/02-01/kasus/app/src/main/java/kasusuji/Bicycle.java
UTF-8
777
3.109375
3
[]
no_license
package kasusuji; public abstract class Bicycle { public int cadence = 0; public int speed = 0; public int gear = 1; public Bicycle(int cadence, int speed, int gear) { this.cadence = cadence; this.speed = speed; this.gear = gear; } public static void main(String[] args) { BicycleUpgrade bike1 = new BicycleUpgrade(); BicycleUpgrade bike2 = new BicycleUpgrade(); bike1.changeCadence(50); bike1.speedUp(10); bike1.changeGear(2); bike1.printStates(); bike2.changeCadence(50); bike2.speedUp(10); bike2.changeGear(2); bike2.changeCadence(40); bike2.speedUp(10); bike2.changeGear(3); bike2.printStates(); ; } }
true
ab51c0426e606ac1705df082ca693c12a649cec1
Java
dkovzan/applitools
/src/main/java/model/DataSet.java
UTF-8
2,270
2.984375
3
[]
no_license
package model; import java.util.List; public class DataSet { private String label; private String backgroundColor; private String borderColor; private Long borderWidth; private List<Long> data; @Override public String toString() { return "DataSet{" + "label='" + label + '\'' + ", backgroundColor='" + backgroundColor + '\'' + ", borderColor='" + borderColor + '\'' + ", borderWidth=" + borderWidth + ", data=" + data + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DataSet dataSet = (DataSet) o; if (label != null ? !label.equals(dataSet.label) : dataSet.label != null) return false; if (backgroundColor != null ? !backgroundColor.equals(dataSet.backgroundColor) : dataSet.backgroundColor != null) return false; if (borderColor != null ? !borderColor.equals(dataSet.borderColor) : dataSet.borderColor != null) return false; if (borderWidth != null ? !borderWidth.equals(dataSet.borderWidth) : dataSet.borderWidth != null) return false; return data != null ? data.equals(dataSet.data) : dataSet.data == null; } @Override public int hashCode() { int result = label != null ? label.hashCode() : 0; result = 31 * result + (backgroundColor != null ? backgroundColor.hashCode() : 0); result = 31 * result + (borderColor != null ? borderColor.hashCode() : 0); result = 31 * result + (borderWidth != null ? borderWidth.hashCode() : 0); result = 31 * result + (data != null ? data.hashCode() : 0); return result; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public String getBackgroundColor() { return backgroundColor; } public void setBackgroundColor(String backgroundColor) { this.backgroundColor = backgroundColor; } public String getBorderColor() { return borderColor; } public void setBorderColor(String borderColor) { this.borderColor = borderColor; } public Long getBorderWidth() { return borderWidth; } public void setBorderWidth(Long borderWidth) { this.borderWidth = borderWidth; } public List<Long> getData() { return data; } public void setData(List<Long> data) { this.data = data; } }
true
8c95995fffd73cc23cc458f2f7c590f395aff4ab
Java
iqbalkg/pbo1-pertemuan2
/model/MataKuliah.java
UTF-8
269
2.125
2
[]
no_license
package model; public class Dosen{ public static void tampilanInfo(){ System.out.println(); System.out.println(==Data Mata Kuliah==): System.out.println("Kode : TIF3402"); System.out.println("Nama : Pemprograman Berbasis Objek"); System.out.println("==========="); } }
true
1f20ff88a6d5729f340288b7078d27afaa861072
Java
xindawang/batteryDD
/src/main/java/com/iot/dd/dao/entity/weixin/Menu.java
UTF-8
333
2.078125
2
[]
no_license
package com.iot.dd.dao.entity.weixin; /** * Created by huanglin on 2017/7/15. * 整个菜单对象的封装 */ public class Menu { private ComplexButton[] button; public ComplexButton[] getButton() { return button; } public void setButton(ComplexButton[] button) { this.button = button; } }
true
81c3f307f49bfaf8b17005ad358fa615943c53a3
Java
Psychedelic9/GofStudy
/src/iteratorPattern/CEOManager.java
UTF-8
589
3.09375
3
[]
no_license
package iteratorPattern; public class CEOManager extends AbstractLeaveHandler { public CEOManager(String name) { this.handlerManager = name; } @Override void handLeave(LeaveRequest request) { if (request.getLeaveDays()>MIDDLE && request.getLeaveDays()<MAX){ System.out.println("CEO:"+handlerManager+"批准假期"+request.getLeaveDays()+"天"); return; } if (null!=this.nextHandler){ this.nextHandler.handLeave(request); }else { System.out.println("拒绝请假"); } } }
true
dc0970e919728de830fbe1091525d54e2606ab19
Java
CedricNF/Essais-lundi-septembre
/src/main/java/com/inti/service/impl/ArticleService.java
UTF-8
827
2.046875
2
[]
no_license
package com.inti.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.inti.entites.Article; import com.inti.repositories.ArticleRepository; import com.inti.service.interfaces.IArticleService; @Service public class ArticleService implements IArticleService { @Autowired ArticleRepository articlerepository; @Override public List<Article> findAll() { return articlerepository.findAll(); } @Override public Article findOne(Long id_article) { return articlerepository.findById(id_article).orElse(null); } @Override public Article save(Article article) { return articlerepository.save(article); } @Override public void delete(Long id_article) { articlerepository.deleteById(id_article); } }
true
51dc6c8433e11afc9f1f175ebe8a541722bb9df3
Java
Jeff-Playground/LeetCode
/src/com/wen/FourthFifty/ExcelSheetColumnTitle.java
UTF-8
287
2.671875
3
[]
no_license
package com.wen.FourthFifty; public class ExcelSheetColumnTitle { public static String convertToTitle(int n) { String result=""; while(n!=0){ n--; result=(char)('A'+(n%26))+result; n=n/26; } return result; } }
true
5f548af273a165a6a4af9bf88b1bff49ad038a65
Java
marekzet/bdd-example-java
/test/integration/runners/PlacingOrderStepsRunner.java
UTF-8
1,315
1.96875
2
[ "MIT" ]
permissive
package test.integration.runners; import org.jbehave.core.Embeddable; import org.jbehave.core.configuration.Configuration; import org.jbehave.core.configuration.MostUsefulConfiguration; import org.jbehave.core.io.CodeLocations; import org.jbehave.core.junit.JUnitStories; import org.jbehave.core.reporters.FilePrintStreamFactory; import org.jbehave.core.reporters.StoryReporterBuilder; import test.integration.steps.PlacingOrderSteps; import java.util.Arrays; import java.util.List; /** * Created by Marek on 2015-04-23. */ public class PlacingOrderStepsRunner extends JUnitStories { public PlacingOrderStepsRunner() { super(); this.configuredEmbedder().candidateSteps().add(new PlacingOrderSteps()); } @Override protected List<String> storyPaths() { return Arrays.asList("test/integration/stories/PlacingOrderStory.story"); } @Override public Configuration configuration() { return new MostUsefulConfiguration() .useStoryReporterBuilder( new StoryReporterBuilder() { public StoryReporterBuilder withDefaultFormats() { return withFormats(Format.STATS, Format.TXT); } } ); } }
true
a53584aa0ecd53249f9d47ef86064c9fbc9e7fb0
Java
lzybluee/Reeforge
/forge/src/forge/ai/ability/ControlExchangeAi.java
UTF-8
4,564
2.28125
2
[]
no_license
package forge.ai.ability; import com.google.common.base.Predicate; import com.google.common.collect.Lists; import forge.ai.ComputerUtil; import forge.ai.ComputerUtilCard; import forge.ai.SpellAbilityAi; import forge.game.ability.AbilityUtils; import forge.game.card.Card; import forge.game.card.CardCollection; import forge.game.card.CardCollectionView; import forge.game.card.CardLists; import forge.game.player.Player; import forge.game.spellability.SpellAbility; import forge.game.spellability.TargetRestrictions; import forge.game.zone.ZoneType; import forge.util.MyRandom; public class ControlExchangeAi extends SpellAbilityAi { /* (non-Javadoc) * @see forge.card.abilityfactory.SpellAiLogic#canPlayAI(forge.game.player.Player, java.util.Map, forge.card.spellability.SpellAbility) */ @Override protected boolean canPlayAI(Player ai, final SpellAbility sa) { Card object1 = null; Card object2 = null; final TargetRestrictions tgt = sa.getTargetRestrictions(); sa.resetTargets(); CardCollection list = CardLists.getValidCards(ComputerUtil.getOpponentFor(ai).getCardsIn(ZoneType.Battlefield), tgt.getValidTgts(), ai, sa.getHostCard(), sa); // AI won't try to grab cards that are filtered out of AI decks on // purpose list = CardLists.filter(list, new Predicate<Card>() { @Override public boolean apply(final Card c) { return !c.hasSVar("RemAIDeck") && c.canBeTargetedBy(sa); } }); object1 = ComputerUtilCard.getBestAI(list); if (sa.hasParam("Defined")) { final CardCollection definedCards = AbilityUtils.getDefinedCards(sa.getHostCard(), sa.getParam("Defined"), sa); if(definedCards.isEmpty()) { return false; } object2 = definedCards.get(0); } else if (tgt.getMinTargets(sa.getHostCard(), sa) > 1) { CardCollectionView list2 = ai.getCardsIn(ZoneType.Battlefield); list2 = CardLists.getValidCards(list2, tgt.getValidTgts(), ai, sa.getHostCard(), sa); object2 = ComputerUtilCard.getWorstAI(list2); sa.getTargets().add(object2); } if (object1 == null || object2 == null) { return false; } if (ComputerUtilCard.evaluateCreature(object1) > ComputerUtilCard.evaluateCreature(object2) + 40) { sa.getTargets().add(object1); return MyRandom.getRandom().nextFloat() <= Math.pow(.6667, sa.getActivationsThisTurn()); } return false; } @Override protected boolean doTriggerAINoCost(Player aiPlayer, SpellAbility sa, boolean mandatory) { if (!sa.usesTargeting()) { if (mandatory) { return true; } } else { if (mandatory) { return chkAIDrawback(sa, aiPlayer); } else { return canPlayAI(aiPlayer, sa); } } return true; } @Override public boolean chkAIDrawback(SpellAbility sa, Player aiPlayer) { if (!sa.usesTargeting()) { return true; } final TargetRestrictions tgt = sa.getTargetRestrictions(); CardCollection list = CardLists.getValidCards(aiPlayer.getGame().getCardsIn(ZoneType.Battlefield), tgt.getValidTgts(), aiPlayer, sa.getHostCard(), sa); // only select the cards that can be targeted list = CardLists.getTargetableCards(list, sa); if (list.isEmpty()) return false; Card best = ComputerUtilCard.getBestAI(list); // if Param has Defined, check if the best Target is better than the Defined if (sa.hasParam("Defined")) { final CardCollection definedCards = AbilityUtils.getDefinedCards(sa.getHostCard(), sa.getParam("Defined"), sa); if(definedCards.isEmpty()) { return false; } final Card object = definedCards.get(0); // TODO add evaluate Land if able final Card realBest = ComputerUtilCard.getBestAI(Lists.newArrayList(best, object)); // Defined card is better than this one, try to avoid trade if (!best.equals(realBest)) { return false; } } // add best Target sa.getTargets().add(best); return true; } }
true
aa2a1a05e41e052b94c203dfd76b624885e8c85b
Java
santieduardo/PDV-Android
/app/src/test/java/eduardosanti/com/br/pdv/dao/db/UserDAODB.java
UTF-8
3,601
2.65625
3
[]
no_license
package eduardosanti.com.br.pdv.dao.db; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import eduardosanti.com.br.pdv.dao.UserDAO; import eduardosanti.com.br.pdv.model.User; public class UserDAODB implements UserDAO { private DataBaseOpenHelper dataBaseOpenHelper; public UserDAODB(Context context) { this.dataBaseOpenHelper = new DataBaseOpenHelper(context); } @Override public void create(User user) { SQLiteDatabase dataBase = dataBaseOpenHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("email", user.getEmail()); values.put("password", user.getPassword()); dataBase.insert("user", null, values); dataBase.close(); } @Override public void delete(User user) { SQLiteDatabase dataBase = dataBaseOpenHelper.getWritableDatabase(); dataBase.delete("user", "id=?", new String[]{String.valueOf(user.getId())}); dataBase.close(); } @Override public void update(User user) { SQLiteDatabase dataBase = dataBaseOpenHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("email", user.getEmail()); values.put("password", user.getPassword()); dataBase.update("user", values,"id=?", new String[]{String.valueOf(user.getId())}); dataBase.close(); } @Override public ArrayList<User> findAll() { SQLiteDatabase dataBase = dataBaseOpenHelper.getReadableDatabase(); Cursor cursor = dataBase.query("user", new String[]{"id", "email", "password"}, null,null,null,null,"email"); ArrayList<User> users = new ArrayList<>(); while(cursor.moveToNext()){ int id = cursor.getInt(cursor.getColumnIndex("id")); String email = cursor.getString(cursor.getColumnIndex("email")); String password = cursor.getString(cursor.getColumnIndex("password")); User user = new User(id, email, password); users.add(user); } return users; } @Override public User findById(int id) { SQLiteDatabase dataBase = dataBaseOpenHelper.getReadableDatabase(); Cursor cursor = dataBase.query("user", new String[]{"id", "email", "password"}, "id = ?",new String[]{String.valueOf(id)}, null,null,null); if(cursor.moveToNext()){ int userId = cursor.getInt(cursor.getColumnIndex("id")); String email = cursor.getString(cursor.getColumnIndex("email")); String password = cursor.getString(cursor.getColumnIndex("password")); User user = new User(userId, email, password); return user; } return null; } @Override public User findByEmail(String value) { SQLiteDatabase dataBase = dataBaseOpenHelper.getReadableDatabase(); Cursor cursor = dataBase.query("user", new String[]{"id", "email", "password"}, "email = ?",new String[]{value}, null,null,null); if(cursor.moveToNext()){ int userId = cursor.getInt(cursor.getColumnIndex("id")); String email = cursor.getString(cursor.getColumnIndex("email")); String password = cursor.getString(cursor.getColumnIndex("password")); User user = new User(userId, email, password); return user; } return null; } }
true
48212b960f7732dad0a07c19300038eeaf439cfd
Java
Hexabinome/devoo
/src/main/java/modele/donneesxml/Livraison.java
UTF-8
2,411
3.21875
3
[]
no_license
package modele.donneesxml; import java.io.Serializable; /** * Représente une livraison à effectuer. * * @author mhaidara / maxou */ public class Livraison implements Serializable { /** L'horaire de passe de la livraison, une fois que la tournée a été calculée */ private int horaireDePassage; /** * Si la livraison a du retard, après que la tournée ait été calculée */ private boolean retard = false; /** * @return L'horaire de passage */ public int getHoraireDePassage() { return horaireDePassage; } /** Affecte l'heure de passage de la livraison * @param horaireDePassage La nouvelle horaire de passage */ public void setHoraireDePassage(int horaireDePassage) { this.horaireDePassage = horaireDePassage; } /** * Identifiant de la livraison */ private final int id; /** * Identifiant du client de la livraison */ private final int clientId; /** * Identifiant de l'intersection où s'effectue la livraison */ private final int adresse; /** Constructeur de la livraison * @param idLivraison Identifiant de la livraison * @param clientId Identifiant du client à livrer * @param idIntersection Identifiant de l'intersection où se situe la livraison */ public Livraison(int idLivraison, int clientId, int idIntersection) { this.id = idLivraison; this.clientId = clientId; this.adresse = idIntersection; } /** * @return L'identifiant de la livraison */ public int getId() { return id; } /** * @return L'identifiant du client à livrer */ public int getClientId() { return clientId; } /** * @return L'identifiant de l'intersection où se situe la livraison */ public int getAdresse() { return adresse; } @Override public String toString() { return "Livraison{" + "id=" + id + ", clientId=" + clientId + ", adresse=" + adresse + '}'; } /** * @return Vrai si le passage à la livraison sera en retard */ public boolean estEnRetard() { return retard; } /** Détermine si la livraison est en retard * @param retard Le retard */ public void setRetard(boolean retard) { this.retard = retard; } }
true
bfa0618671ef75b8dd9a9436a18ef6ed91507041
Java
BackupTheBerlios/projetp2s
/sources/p2s/P2S/Model/Projet.java
UTF-8
5,514
2.65625
3
[]
no_license
package P2S.Model; import java.util.*; /** * * @author Fabien - Nicolas */ public class Projet { //ATTRIBUTS private String nom; private String description; private Date dateDebut; private Date dateFin; private IndicateursProjet indicateursProjet; private Vector listeMesures; private String Commentaire; private Vector listeIt; private Vector listeMembres; private Vector listeRisques; private Vector listeProblemes; private SeuilsFixes seuilFixes; //CONSTRUCTEURS //Constructeur seulement avec le nom public Projet(String nom, Vector listeMesures) { this.nom = nom; this.description = new String(""); this.dateDebut = new Date(); this.dateFin = new Date(); this.listeMesures = new Vector(); this.listeIt = new Vector(); this.listeMembres = new Vector(); this.listeRisques = new Vector(); this.listeProblemes = new Vector() ; this.indicateursProjet = new IndicateursProjet(); } //Constructeur sans listes public Projet(String nom, String description, Date dateDebut, Date dateFin) { this.nom = nom; this.description = description; this.dateDebut = dateDebut; this.dateFin = dateFin; this.listeMesures = new Vector(); this.listeIt = new Vector(); this.listeMembres = new Vector(); this.listeRisques = new Vector(); this.listeProblemes = new Vector() ; this.indicateursProjet = new IndicateursProjet(); } //Constructeur avec indicateur public Projet(String nom, String description, Date dateDebut, Date dateFin, IndicateursProjet indicateursProjet) { this.nom = nom; this.description = description; this.dateDebut = dateDebut; this.dateFin = dateFin; this.listeMesures = new Vector(); this.listeIt = new Vector(); this.listeMembres = new Vector(); this.listeRisques = new Vector(); this.listeProblemes = new Vector() ; this.indicateursProjet = indicateursProjet; } public Projet(String nom, String description, Date dateDebut, Date dateFin, Vector listeMesure, Vector listeIt, Vector listeMembres) { this.nom = nom; this.description = description; this.dateDebut = dateDebut; this.dateFin = dateFin; this.listeMesures = new Vector(listeMesure); this.listeIt = new Vector(listeIt); this.listeMembres = new Vector(listeMembres); this.listeRisques = new Vector(); this.listeProblemes = new Vector() ; this.indicateursProjet = new IndicateursProjet(); } //METHODES public void ajouterMesure(Mesure mesure) { this.listeMesures.add(mesure); } //GETTEURS ET SETTEURS /** * Getter for property _dateDebut. * @return Value of property _dateDebut. */ public java.util.Date getDateDebut() { return dateDebut; } /** * Setter for property _dateDebut. * @param _dateDebut New value of property _dateDebut. */ public void setDateDebut(java.util.Date _dateDebut) { this.dateDebut = _dateDebut; } /** * Getter for property _nom. * @return Value of property _nom. */ public java.lang.String getNom() { return nom; } /** * Setter for property _nom. * @param _nom New value of property _nom. */ public void setNom(java.lang.String _nom) { this.nom = _nom; } /** * Getter for property _dateFin. * @return Value of property _dateFin. */ public java.util.Date getDateFin() { return dateFin; } /** * Setter for property _dateFin. * @param _dateFin New value of property _dateFin. */ public void setDateFin(java.util.Date _dateFin) { this.dateFin = _dateFin; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Vector getListeIt() { return listeIt; } public void setListeIt(Vector listeIt) { this.listeIt = listeIt; } public Vector getListeMembres() { return listeMembres; } public void setListeMembres(Vector listeMembres) { this.listeMembres = listeMembres; } public Vector getListeRisques() { return listeRisques; } public void setListeRisques(Vector listeRisques) { this.listeRisques = listeRisques; } public Vector getListeProblemes() { return listeProblemes; } public void setListeProblemes(Vector listeProblemes) { this.listeProblemes = listeProblemes; } public IndicateursProjet getIndicateursProjet(){ return indicateursProjet; } public void setIndicateursProjet(IndicateursProjet indicateursProjet){ this.indicateursProjet = indicateursProjet; } public SeuilsFixes getSeuilFixes() { return seuilFixes; } public void setSeuilFixes(SeuilsFixes seuilFixes) { this.seuilFixes = seuilFixes; } public String getCommentaire() { return Commentaire; } public void setCommentaire(String Commentaire) { this.Commentaire = Commentaire; } }
true
56ea442b7fbb3413e5c52f1940ee6403a0abe2e6
Java
Lee-sungheon/java8
/src/Day01_11/Day0202.java
UHC
432
3.359375
3
[]
no_license
package Day01_11; import java.util.*; public class Day0202 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num1, num2; System.out.print("num1,2 Է : "); num1 = sc.nextInt(); num2 = sc.nextInt(); int result = num1 + num2; System.out.print(" հ "); System.out.print(result); System.out.print("Դϴ."); sc.close(); } }
true
b6273e5771416202530c020d8f3fc39b68cddefa
Java
terhol/test2-2
/src/se/terhol/pisemka22/Airplane.java
UTF-8
1,816
3.296875
3
[ "MIT" ]
permissive
package se.terhol.pisemka22; /** * Airplane with given number of seats. * * @author Ludek Bartek */ public interface Airplane { /** * Returns passenger having reservation on the given seat. * * @param seat seat number (>= 0) * @return passenger having reservation on the given seat or null * @throws IndexOutOfBoundsException if the seat number is out of the array size */ public Passenger getPassenger(int seat); /** * @return airplane capacity */ public int getCapacity(); /** * Returns seat number of given passenger. * * @param pas passenger * @return seat number >= 0 * @throws ReservationException with "No such passenger" decription if there is * no reservation in the plane for given passenger or if the passenger is null */ public int getPassengerReservation(Passenger pas) throws ReservationException; /** * Makes reservation of a seat. Every passenger can have only one * reservation in the plane. * * @param pas reserving passenger * @throws ReservationException with the "Airplane is full" description * if the airplane is full * @throws ReservationException with the "Duplicate reservation" description * if the passsenger already has reservation in the plane */ public void makeReservation(Passenger pas) throws ReservationException; /** * Canceles reservation. * * @param pas passenger * @throws ReservationException with the "No such passenger" description * if the passenger has no reservation in the airplane */ public void cancelReservation(Passenger pas) throws ReservationException; }
true
a383c7710933451d7d0be00e3b8f8f20954e280f
Java
danyalwalker/Java-Programming
/src/OfficeHours/Practice/certification/JavaStatements.java
UTF-8
1,923
3.671875
4
[]
no_license
package OfficeHours.Practice.certification; public class JavaStatements { public static void main(String[] args) { boolean a = true; int x = 2, y = 3,z; if(a) z=x+y; else z=x-y; System.out.println("z = " + z); if(a) z=x+y; z=x-y; System.out.println("z = " + z); z = a? x+y : x-y; System.out.println("z = " + z); System.out.println((y < 5) ? 21 : "Zebra"); // 21 is converted into String System.out.println((y < 5) ? 8 : 3); // 21 is converted into String // String animal = (y < 91) ? 9 : "Horse"; // DOES NOT COMPILE since 9 cannot be assigned to String // int animal = (y < 91) ? 9 : "Horse"; // DOES NOT COMPILE since Horse cannot be assigned to int y = 1; z = 1; x = y<10 ? y++ : z++; System.out.println(y+","+z); // only one right hand expression is run y = 1; z = 1; x = y>=10 ? y++ : z++; System.out.println(y+","+z); // only one right hand expression is run x = 2; y = 5; while(x < 6) x++; y++; System.out.println("x = " + x); System.out.println("y = " + y); x = 2; y = 5; while(x < 6){ x++; y++;} System.out.println("x = " + x); System.out.println("y = " + y); x = 0; do x++; while(false); //it will never execute System.out.println("x: " + x); //statement after while loop exited x=20; while(x > 10) { x--; System.out.print("x = " + x);} System.out.println(); x=20; do { x--; System.out.print("x = " + x); } while(x > 10); int counter = 1; do { System.out.print(", counter = " + counter); counter++; } while(counter <= 10); } }
true
9f81ebbf99f239d634cb8fec07b0db05cc0075b6
Java
dfiera/blackhole-api
/src/main/java/com/dfiera/blackholeapi/repository/StockDataCSVRepository.java
UTF-8
396
1.929688
2
[]
no_license
package com.dfiera.blackholeapi.repository; import com.dfiera.blackholeapi.entity.StockDataCSV; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface StockDataCSVRepository extends MongoRepository<StockDataCSV, String> { List<StockDataCSV> findByCompany(String company); }
true
3df4aef9acbbe4817029226828b054abdbdee0a3
Java
P79N6A/lambda-xxoo
/01SourceCode/lambda-mls/lambda-core/src/main/java/com/yatop/lambda/core/mgr/workflow/component/ComponentMgr.java
UTF-8
1,077
1.976563
2
[]
no_license
package com.yatop.lambda.core.mgr.workflow.component; import com.yatop.lambda.base.model.WfCfgComponent; import com.yatop.lambda.base.model.WfCfgComponentExample; import com.yatop.lambda.core.enums.LambdaExceptionEnum; import com.yatop.lambda.core.mgr.base.BaseMgr; import com.yatop.lambda.core.enums.DataStatusEnum; import com.yatop.lambda.core.exception.LambdaException; import org.springframework.stereotype.Service; import java.util.List; @Service public class ComponentMgr extends BaseMgr { /* * * 查询组件信息 * 返回结果集 * * */ public List<WfCfgComponent> queryComponent() { try { WfCfgComponentExample example = new WfCfgComponentExample(); example.createCriteria().andStatusEqualTo(DataStatusEnum.NORMAL.getStatus()); return wfCfgComponentMapper.selectByExample(example); } catch (Throwable e) { throw new LambdaException(LambdaExceptionEnum.G_COMPUTE_DEFAULT_ERROR, "Query component info failed.", "查询组件信息失败", e); } } }
true
271fdfbbe07ce0b8821f86f6f03443c2fe96000f
Java
Davoleo/Java-GUI
/src/net/davoleo/javagui/forms/controls/JListGui.java
UTF-8
1,233
2.859375
3
[]
no_license
package net.davoleo.javagui.forms.controls; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; /************************************************* * Author: Davoleo * Date / Hour: 04/01/2019 / 15:47 * Class: JListGui * Project: JavaGUI * Copyright - © - Davoleo - 2018 **************************************************/ public class JListGui extends JFrame { private JList list; private static String[] colornames = {"black", "blue", "red", "white", "cyan", "yellow"}; private static Color[] colors = {Color.BLACK, Color.BLUE, Color.RED, Color.WHITE, Color.CYAN, Color.YELLOW}; public JListGui() { super("JList"); setLayout(new FlowLayout()); list = new JList(colornames); list.setVisibleRowCount(6); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); add(new JScrollPane(list)); list.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { getContentPane().setBackground(colors[list.getSelectedIndex()]); } }); } }
true
ade89cee6f78889959467e385bfc8c724e293632
Java
kwonmin123/test02
/day08/src/encap/obj/Employee.java
UTF-8
124
2.21875
2
[]
no_license
package encap.obj; public class Employee { public void cooking() { System.out.println("요리합니다"); } }
true
ea5bbfb73bc7690ab505b2d55d03e73451d9f10d
Java
qq316577877/sys-admin-web
/src/main/java/com/fruit/sys/admin/action/LoginAction.java
UTF-8
3,488
1.890625
2
[]
no_license
/* * Copyright (c) 2017-2022 by Ovfintech (Wuhan) Technology Co., Ltd. * All right reserved. */ package com.fruit.sys.admin.action; import com.fruit.sys.admin.model.JsonResult; import com.fruit.sys.admin.model.UserInfo; import com.fruit.sys.admin.service.EnvService; import com.fruit.sys.admin.service.admin.AdminService; import com.fruit.sys.admin.utils.BizConstants; import com.fruit.sys.admin.utils.CookieUtil; import com.fruit.sys.admin.utils.UrlUtils; import com.ovfintech.arch.web.mvc.dispatch.UriMapping; import com.ovfintech.arch.web.mvc.interceptor.WebContext; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.servlet.http.Cookie; @Component @UriMapping("/") public class LoginAction extends BaseAction { private static final Logger LOGGER = LoggerFactory.getLogger(LoginAction.class); @Autowired private AdminService adminService; @Autowired private EnvService envService; @UriMapping(value = "/login") public String show() { String redir = StringUtils.trimToEmpty(super.getStringParameter("redir")); if (StringUtils.isBlank(redir)) { redir = "/admin/index"; } int sysId = super.getLoginUserId(); if (sysId > 0) { UserInfo userInfo = this.adminService.loadUserInfo(sysId); if (null != userInfo) // 已登录用户直接进主页 { return "redirect:" + redir; } else // 非法用户强制登出 { this.logout(); } } WebContext.getRequest().setAttribute("login_ajax_url", UrlUtils.getLoginAjaxUrl(super.getDomain())); WebContext.getRequest().setAttribute("redir_url", redir); return "login/login"; } @UriMapping(value = "/login_ajax") public JsonResult loginAjax() { String username = StringUtils.trimToEmpty(super.getStringParameter("username")); String password = StringUtils.trimToEmpty(super.getStringParameter("password")); int auto = super.getIntParameter("auto", 0); try { Validate.isTrue(StringUtils.isNotBlank(username), "用户名不能为空!"); Validate.isTrue(StringUtils.isNotBlank(password), "密码不能为空!"); UserInfo userInfo = this.adminService.adminUserLogin(username, password); this.addUserCookie(auto, userInfo); return new JsonResult(); } catch (IllegalArgumentException e) { super.log(0, username + "," + password + " 登录失败:" + e.getMessage()); return new JsonResult(e.getMessage()); } } protected void addUserCookie(int auto, UserInfo userInfo) { Cookie cookie = new Cookie(BizConstants.COOKIE_USER, CookieUtil.generatePassportByUserInfo(userInfo)); cookie.setDomain(this.envService.getCookieDomain()); cookie.setPath("/"); cookie.setMaxAge(auto == 1 ? BizConstants.COOKIE_USER_TIMEOUT : -1); WebContext.getResponse().addCookie(cookie); } @UriMapping(value = "/logout") public String logout() { clearCookie(BizConstants.COOKIE_USER); return "redirect:" + UrlUtils.getLoginUrl(super.getDomain()); } }
true
9292ec35915549295c06686672ee6442934644b5
Java
cuijiehui/doubao
/app/src/main/java/com/xinspace/csevent/sweepstake/weiget/ReceivSucDialog.java
UTF-8
1,181
1.882813
2
[]
no_license
package com.xinspace.csevent.sweepstake.weiget; import android.app.Dialog; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.xinspace.csevent.R; public class ReceivSucDialog extends Dialog { private TextView tv_yes; Context context; public ReceivSucDialog(Context context) { super(context, R.style.dialog); this.context = context; setCustomDialog(); } private void setCustomDialog() { // TODO Auto-generated method stub View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_receiv_suc, null); tv_yes = (TextView) view.findViewById(R.id.btn_yes); super.setContentView(view); } @Override public void setContentView(int layoutResID) { } @Override public void setContentView(View view, LayoutParams params) { } @Override public void setContentView(View view) { } /** * 确定键监听器 * * @param listener */ public void setOnPositiveListener(View.OnClickListener listener) { tv_yes.setOnClickListener(listener); } }
true
b1856d05646c2b616f27fbdcd4b4499e29770613
Java
Alexandelphi/leetcode
/src/main/java/com/alexandelphi/leetcode/easy/FindTheDifference.java
UTF-8
816
3.53125
4
[]
no_license
package com.alexandelphi.leetcode.easy; import java.util.HashMap; import java.util.Map; public class FindTheDifference { // my naive version public char findTheDifference(String s, String t) { Map<Character, Integer> map = new HashMap<>(); for (char c : s.toCharArray()) { map.put(c, map.getOrDefault(c, 0) + 1); } for (char c : t.toCharArray()) { map.put(c, map.getOrDefault(c, 0) - 1); } for (char c : map.keySet()) { if (map.get(c) < 0) { return c; } } return '?'; } // improved version public char findTheDifferenceV2(String s, String t) { int s1 = 0; int s2 = 0; for (char c : s.toCharArray()) { s1 += (int) c; } for (char c : t.toCharArray()) { s2 += (int) c; } return (char) (s2 - s1); } }
true
1909b3b7cd7f93e341db52924417adabb5cfa152
Java
RUPANSHURAMAN/CORE-JAVA
/27Exception/src/finalkeyword/C.java
UTF-8
243
2.6875
3
[]
no_license
package finalkeyword; //DIFFERENT public class C { public static void main(String[] args) { C c1 = new C(); c1.test(10); } public void test(final int i) { //i = 30; ERROR as final var can't be changed System.out.println(i); } }
true
13b043ca4d7a3c010739bc67e633a305954e71b9
Java
KristiansKaneps/OneInTheChamber
/src/main/java/lv/kaneps/oitc/scoreboard/Scoreboard.java
UTF-8
1,246
3.28125
3
[ "MIT" ]
permissive
package lv.kaneps.oitc.scoreboard; public class Scoreboard { protected final ScoreboardEntry[] entries; protected int validEntries = 0; protected final int size; public Scoreboard(int size) { this.size = size; entries = new ScoreboardEntry[size]; } public boolean isFull() { return validEntries == size; } public ScoreboardEntry[] getEntries() { return entries; } public ScoreboardEntry getEntry(int index) { return entries[index]; } public ScoreboardEntry getEntry(String player) { for(ScoreboardEntry e : entries) if(player.equalsIgnoreCase(e.player)) return e; return null; } /** * @param entry - entry to add * @return -1 if couldn't add (scoreboard full) or index in entries array */ public int add(ScoreboardEntry entry) { for(int i = 0; i < size; i++) { if(entries[i] != null) continue; entries[i] = entry; validEntries++; return i; } return -1; } public void remove(String player) { for(int i = 0; i < size; i++) { ScoreboardEntry e = entries[i]; if(!player.equalsIgnoreCase(e.player)) continue; entries[i] = null; validEntries--; } } public void clear() { for(int i = 0; i < size; i++) entries[i] = null; validEntries = 0; } }
true
b4eae31f394a3704a69a1f6e4a8311c1b2d3e4a9
Java
tkirschenheiter/assignment3
/Apple.java
UTF-8
227
3.078125
3
[]
no_license
public class Apple extends Fruit { public Apple (String name, String taste, Double size) { super(name,taste,size); } public Apple () { } public void eat() { System.out.printf("Apples taste sweet \n"); } }
true
73a17a05979ef259d5bba6c6440db8ea927b5ef2
Java
SwiftOSSite/SwiftFrameWork
/src/main/java/net/gy/SwiftFrameWork/MVVM/Entity/ViewBinderLevel.java
UTF-8
629
2.109375
2
[]
no_license
package net.gy.SwiftFrameWork.MVVM.Entity; import java.lang.reflect.Field; import java.util.Map; /** * Created by pc on 16/8/30. */ public class ViewBinderLevel { private Map<Field,ViewBindEntity> elements; private Map<Field,ViewBinderLevel> objs; public Map<Field, ViewBindEntity> getElements() { return elements; } public void setElements(Map<Field, ViewBindEntity> elements) { this.elements = elements; } public Map<Field, ViewBinderLevel> getObjs() { return objs; } public void setObjs(Map<Field, ViewBinderLevel> objs) { this.objs = objs; } }
true
01f30fbc852a9d757048487f9a0c085ef6433b8f
Java
richardpuma/ProjectsWordPress
/src/CoreJavaApi/DemoCoreJavaApi.java
UTF-8
454
2.8125
3
[]
no_license
package CoreJavaApi; public class DemoCoreJavaApi { public static void main(String[] args) { StringBuilder sb= new StringBuilder("Hola Mundo"); StringBuilder sb2= new StringBuilder("Hola Mundo"); System.out.println("equals en StringBuilder"); System.out.println(sb.equals(sb2)); System.out.println("equals con toString() en StringBuilder"); System.out.println(sb.toString().equals(sb2.toString())); } }
true
49ab1eacfad2bc0eab4b07ed20985cb7c76f06f3
Java
lschuetze/Alf-Reference-Implementation
/org.modeldriven.alf/src/org/modeldriven/alf/syntax/statements/impl/IfStatementImpl.java
UTF-8
12,401
2.25
2
[]
no_license
/******************************************************************************* * Copyright 2011, 2012 Data Access Technologies, Inc. (Model Driven Solutions) * Copyright 2013 Ivar Jacobson International SA * * All rights reserved worldwide. This program and the accompanying materials * are made available for use under the terms of the GNU General Public License * (GPL) version 3 that accompanies this distribution and is available at * http://www.gnu.org/licenses/gpl-3.0.html. *******************************************************************************/ package org.modeldriven.alf.syntax.statements.impl; import org.modeldriven.alf.syntax.common.*; import org.modeldriven.alf.syntax.expressions.QualifiedName; import org.modeldriven.alf.syntax.statements.*; import org.modeldriven.alf.syntax.units.*; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; /** * A conditional statement that executes (at most) one of a set of clauses based * on boolean conditions. **/ public class IfStatementImpl extends StatementImpl { private List<ConcurrentClauses> nonFinalClauses = new ArrayList<ConcurrentClauses>(); private Block finalClause = null; private Boolean isAssured = null; // DERIVED private Boolean isDeterminate = null; // DERIVED private NamespaceDefinition currentScope = null; public IfStatementImpl(IfStatement self) { super(self); } public IfStatement getSelf() { return (IfStatement) this.self; } public List<ConcurrentClauses> getNonFinalClauses() { return this.nonFinalClauses; } public void setNonFinalClauses(List<ConcurrentClauses> nonFinalClauses) { this.nonFinalClauses = nonFinalClauses; for (ConcurrentClauses clauses: nonFinalClauses) { clauses.getImpl().setEnclosingStatement(this.getSelf()); } } public void addNonFinalClauses(ConcurrentClauses nonFinalClauses) { this.nonFinalClauses.add(nonFinalClauses); nonFinalClauses.getImpl().setEnclosingStatement(this.getSelf()); } public Block getFinalClause() { return this.finalClause; } public void setFinalClause(Block finalClause) { this.finalClause = finalClause; if (finalClause != null) { finalClause.getImpl().setEnclosingStatement(this.getSelf()); } } public Boolean getIsAssured() { if (this.isAssured == null) { this.setIsAssured(this.deriveIsAssured()); } return this.isAssured; } public void setIsAssured(Boolean isAssured) { this.isAssured = isAssured; } public Boolean getIsDeterminate() { if (this.isDeterminate == null) { this.setIsDeterminate(this.deriveIsDeterminate()); } return this.isDeterminate; } public void setIsDeterminate(Boolean isDetermined) { this.isDeterminate = isDetermined; } /** * An if statement is assured if it has an @assured annotation. **/ protected Boolean deriveIsAssured() { return this.hasAnnotation("assured"); } /** * An if statement is determinate if it has an @determinate annotation. **/ protected Boolean deriveIsDeterminate() { return this.hasAnnotation("determinate"); } /** * The assignments before all the non-final clauses of an if statement are * the same as the assignments before the if statement. If the statement has * a final clause, then the assignments before that clause are also the same * as the assignments before the if statement. * * If an if statement does not have a final else clause, then any name that * is unassigned before the if statement is unassigned after the if * statement. If an if statement does have a final else clause, then names * assigned in any clause of the if statement have a type after the if * statement that is the effective common ancestor of the types of the name * in each clause with a multiplicity lower bound that is the minimum of the * lower bound for the name in each clause and a multiplicity upper bound * that is the maximum for the name in each clause. For a name that has an * assigned source after any clause of an if statement that is different * than before that clause, then the assigned source after the if statement * is the if statement. Otherwise, the assigned source of a name after the * if statement is the same as before the if statement. **/ @Override protected Map<String, AssignedSource> deriveAssignmentAfter() { IfStatement self = this.getSelf(); Map<String, AssignedSource> assignmentsBefore = this.getAssignmentBeforeMap(); Collection<Block> blocks = new ArrayList<Block>(); for (ConcurrentClauses clauses: self.getNonFinalClauses()) { clauses.getImpl().setAssignmentBefore(assignmentsBefore); blocks.addAll(clauses.getImpl().getBlocks()); } Block finalClause = self.getFinalClause(); if (finalClause != null) { finalClause.getImpl().setAssignmentBefore(assignmentsBefore); blocks.add(finalClause); } Map<String, AssignedSource> assignmentsAfter = new HashMap<String, AssignedSource>(super.deriveAssignmentAfter()); assignmentsAfter.putAll(this.mergeAssignments(blocks, assignmentsBefore)); /* if (finalClause == null) { for (Object name: assignmentsAfter.keySet().toArray()) { if (!(assignmentsBefore.containsKey(name) || this.isParameter((String)name))) { assignmentsAfter.remove(name); } } } */ return assignmentsAfter; } /* * Derivations */ public boolean ifStatementIsAssuredDerivation() { this.getSelf().getIsAssured(); return true; } public boolean ifStatementIsDeterminateDerivation() { this.getSelf().getIsDeterminate(); return true; } /* * Constraints */ /** * The assignments before all the non-final clauses of an if statement are * the same as the assignments before the if statement. If the statement has * a final clause, then the assignments before that clause are also the same * as the assignments before the if statement. **/ public boolean ifStatementAssignmentsBefore() { // Note: This is handled by deriveAssignmentsAfter. return true; } /** * If an if statement does not have a final else clause, then any name that * is not an out parameter and is unassigned before the if statement is * unassigned after the if statement. If an if statement does have a final * else clause, then any name that is unassigned before the if statement and * is assigned after any one clause of the if statement must also be * assigned after every other clause. The type of such names after the if * statement is the effective common ancestor of the types of the name in * each clause with a multiplicity lower bound that is the minimum of the * lower bound for the name in each clause and a multiplicity upper bound * that is the maximum for the name in each clause. For a name that has an * assigned source after any clause of an if statement that is different * than before that clause, then the assigned source after the if statement * is the if statement. Otherwise, the assigned source of a name after the * if statement is the same as before the if statement. **/ public boolean ifStatementAssignmentsAfter() { // Note: This is partly handled by overriding deriveAssignmentAfter. IfStatement self = this.getSelf(); Map<String, AssignedSource> assignmentsBefore = this.getAssignmentBeforeMap(); Map<String, AssignedSource> assignmentsAfter = this.getAssignmentAfterMap(); if (self.getFinalClause() == null) { for (String name: assignmentsAfter.keySet()) { if (!(assignmentsBefore.containsKey(name) || this.isParameter(name))) { return false; } } } else { Collection<Block> blocks = this.getAllBlocks(); if (blocks.size() > 1) { Map<String, Integer> definitionCount = new HashMap<String, Integer>(); for (Block block: blocks) { for (AssignedSource assignment: block.getImpl().getNewAssignments()) { String name = assignment.getName(); Integer count = definitionCount.get(name); if (count == null) { definitionCount.put(name, 1); } else { definitionCount.put(name, count+1); } } } int n = blocks.size(); for (String name: definitionCount.keySet()) { if (!assignmentsBefore.containsKey(name) && definitionCount.get(name) != n) { return false; } } } } return true; } /** * The enclosing statement of all the statements in the bodies of all * non-final clauses and in the final clause (if any) of an if statement is * the if statement. **/ public boolean ifStatementEnclosedStatements() { // Note: This is handled by overriding setEnclosingStatement. return true; } /* * Helper Methods */ /** * In addition to an @isolated annotation, an if statement may have @assured * and @determinate annotations. They may not have arguments. **/ public Boolean annotationAllowed(Annotation annotation) { String identifier = annotation.getIdentifier(); return super.annotationAllowed(annotation) || (identifier.equals("assured") || identifier.equals("determinate")) && annotation.getArgument().isEmpty(); } // annotationAllowed public void setCurrentScope(NamespaceDefinition currentScope) { this.currentScope = currentScope; IfStatement self = this.getSelf(); for (ConcurrentClauses clause: self.getNonFinalClauses()) { clause.getImpl().setCurrentScope(currentScope); } Block finalClause = self.getFinalClause(); if (finalClause != null) { finalClause.getImpl().setCurrentScope(currentScope); } } private boolean isParameter(String name) { QualifiedName qualifiedName = new QualifiedName(); qualifiedName.getImpl().addName(name); qualifiedName.getImpl().setCurrentScope(currentScope); return qualifiedName.getImpl().getParameterReferent() != null; } private Collection<Block> getAllBlocks() { IfStatement self = this.getSelf(); Collection<Block> blocks = new ArrayList<Block>(); for (ConcurrentClauses clauses: self.getNonFinalClauses()) { blocks.addAll(clauses.getImpl().getBlocks()); } Block finalClause = self.getFinalClause(); if (finalClause != null) { blocks.add(finalClause); } return blocks; } @Override protected void bindTo(SyntaxElement base, List<ElementReference> templateParameters, List<ElementReference> templateArguments) { super.bindTo(base, templateParameters, templateArguments); if (base instanceof IfStatement) { IfStatement self = this.getSelf(); IfStatement baseStatement = (IfStatement)base; Block finalClause = baseStatement.getFinalClause(); for (ConcurrentClauses nonFinalClauses: baseStatement.getNonFinalClauses()) { self.addNonFinalClauses ((ConcurrentClauses)nonFinalClauses.getImpl(). bind(templateParameters, templateArguments)); } if (finalClause != null) { self.setFinalClause((Block)finalClause.getImpl(). bind(templateParameters, templateArguments)); } } } } // IfStatementImpl
true
8a5c20e44526a3bfd4239cb70fb972a2d6d3ba40
Java
pict-sdl-grp/TripPlanner
/app/src/main/java/com/project/sdl/tripplanner/TripsPackage/Trip.java
UTF-8
636
2.234375
2
[]
no_license
package com.project.sdl.tripplanner.TripsPackage; import com.google.firebase.database.IgnoreExtraProperties; /** * Created by Manish Chougule on 02-08-2019. */ @IgnoreExtraProperties public class Trip { public String tripName; public String createdBy; public int noOfItems; public String id; public Trip() { // Default constructor required for calls to DataSnapshot.getValue(User.class) } public Trip(String tripName,String createdBy,int noOfItems,String id) { this.tripName = tripName; this.createdBy = createdBy; this.noOfItems = noOfItems; this.id = id; } }
true
91ff0ddb57c76bf65b8dab73cdb84450d62a8466
Java
veeravilla/apr2018
/springjpademo/src/main/java/com/test/springjpademo/dao/AccountRepository.java
UTF-8
410
1.882813
2
[]
no_license
package com.test.springjpademo.dao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import com.test.springjpademo.entity.Account; @Repository public interface AccountRepository extends JpaRepository<Account, Integer>{ public Account findByUsername(String username); }
true
e31fe9ddcf8880c0898b50b34a381c68d299caa4
Java
BrandtRobert/RayTracer
/Colorable.java
UTF-8
131
2.15625
2
[]
no_license
/** * Defines an object that has a matlib material property. */ public interface Colorable { public Material getMaterial(); }
true
fcf370f7847011550b23fd88c00a6160dc8a019e
Java
qiyuanzhao/la-conllector
/src/main/java/com/lavector/collector/crawler/kafka/Consumer.java
UTF-8
2,110
2.546875
3
[]
no_license
package com.lavector.collector.crawler.kafka; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.common.serialization.IntegerDeserializer; import org.apache.kafka.common.serialization.StringDeserializer; import java.time.Duration; import java.util.Collections; import java.util.Properties; import java.util.concurrent.TimeUnit; /** * Created on 2018/11/19. * * @author zeng.zhao */ public class Consumer implements Runnable { private final KafkaConsumer<Integer, String> consumer; private final String topic; public Consumer(String topic) { Properties properties = new Properties(); properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); properties.put(ConsumerConfig.GROUP_ID_CONFIG, "DemoConsumer"); properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true"); properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000"); properties.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "30000"); properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class.getName()); properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); consumer = new KafkaConsumer<>(properties); this.topic = topic; } @Override public void run() { consumer.subscribe(Collections.singletonList(this.topic)); for (int i = 0; i < 10; i++) { ConsumerRecords<Integer, String> records = consumer.poll(5); for (ConsumerRecord<Integer, String> record : records) { System.out.println("Received message: (" + record.key() + ", " + record.value() + ") at offset " + record.offset()); } try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } } } }
true
0e712166c4f8d0fc55b041b35d11217ec016b944
Java
sano91/breadth-first-search
/src/main/java/com/codecool/bfsexample/service/DistanceBelowZeroException.java
UTF-8
191
1.984375
2
[]
no_license
package com.codecool.bfsexample.service; class DistanceBelowZeroException extends RuntimeException { DistanceBelowZeroException() { super("Distance cannot be under 0"); } }
true
5795edd393ce8c159e9f5d360ddb5a8f81e618e8
Java
mlechnyput/3-1-2-bootstrap
/src/main/java/app/service/UserServiceImpl.java
UTF-8
1,865
2.3125
2
[]
no_license
package app.service; import app.dao.RoleDao; //import app.dao.RoleDaoImpl; import app.dao.UserDao; import app.models.Role; import app.models.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; @Service public class UserServiceImpl implements UserService { private UserDao userDao; private RoleDao roleDao; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @Autowired public UserServiceImpl(UserDao userDao, RoleDao roleDao) { this.userDao = userDao; this.roleDao = roleDao; } @Transactional @Override public void createAndUpdate(User user) { Set<Role> set = new HashSet<>(); if (user.isIsadmin()) { Role roleAdmin = roleDao.findByRole("ADMIN"); set.add(roleAdmin); } if (user.isIsuser()){ Role roleUser = roleDao.findByRole("USER"); set.add(roleUser); } user.setRoles(set); user.setPassword(bCryptPasswordEncoder.encode(user.getPassword())); userDao.save(user); } @Transactional(readOnly = true) @Override public List<User> getAllUsers() { return (List<User>) userDao.findAll(); } @Transactional @Override public void delete(long id) { userDao.deleteById(id); } @Transactional @Override public User findUserById(long id) { return userDao.findById(id).get(); } @Transactional @Override public User findUserByEmail(String email) { return userDao.findUserByEmail(email); } }
true
c2e0f75657532a9edf2a58708495cb1b88174efc
Java
edanca/java-traditional-test-framework
/src/main/java/components/Recommendations.java
UTF-8
201
1.601563
2
[]
no_license
package components; import base.Base; import org.openqa.selenium.WebDriver; public class Recommendations extends Base { public Recommendations(WebDriver driver) { super(driver); } }
true
f3fdc5ac6c6fe3c741ae1f503c911b6be3bbe829
Java
on-the-roads/LeetCode
/src/com/Solution/LinkedList/IntersectionOfTwoLinkedList160.java
UTF-8
1,273
4.09375
4
[]
no_license
package com.Solution.LinkedList; /** * 题目:求两个链表相交的第一个结点,要求时间复杂度为O(n),空间复杂度为O(1)。若无相交结点则返回null。 * 思路:假设链表A和链表B的公共部分长度为c,A和B私有部分的长度分别为a和b,则a+c+b=b+c+a. * 这个表达式的意思是A和B同时从他们的头结点开始向后访问, * 当A访问到链表末尾时开始从B头结点访问;同样,当B访问到链表末尾时开始从A头结点访问。 * 最终,他们会在第一个相交结点相遇。若AB没有相交结点,那么他们会最终同时指向null. * */ public class IntersectionOfTwoLinkedList160 { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { ListNode A=headA; ListNode B=headB; while(A!=B) { A=(A==null)?headB:A.next; B=(B==null)?headA:B.next; } return A; } public static void main(String[] args) { ListNode A=new ListNode(1); A.next=new ListNode(2); A.next.next=new ListNode(3); ListNode B=new ListNode(4); B.next=new ListNode(3); ListNode ans=new IntersectionOfTwoLinkedList160().getIntersectionNode(A,B); } }
true
16a663f639193d9abcaf3b7915075e80a3584b3b
Java
13dec2537/LionMonitoringDemo
/app/src/main/java/com/example/kuybeer26092016/lionmonitoringdemo/activitys/HistoryActivity.java
UTF-8
7,814
1.625
2
[]
no_license
package com.example.kuybeer26092016.lionmonitoringdemo.activitys; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Typeface; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.example.kuybeer26092016.lionmonitoringdemo.R; import com.example.kuybeer26092016.lionmonitoringdemo.adapters.AdapterHistory; import com.example.kuybeer26092016.lionmonitoringdemo.manager.ManagerRetrofit; import com.example.kuybeer26092016.lionmonitoringdemo.models.Mis_history; import com.squareup.picasso.MemoryPolicy; import com.squareup.picasso.NetworkPolicy; import com.squareup.picasso.Picasso; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class HistoryActivity extends AppCompatActivity { private SharedPreferences spApp_Gone; private SharedPreferences.Editor editor_App_Gone; private static SharedPreferences sp; private static SharedPreferences.Editor editor; private static final String IMAGEURL = "http://www.thaidate4u.com/service/json/img/"; private Toolbar toolbar; private RecyclerView mRecyclerView; private ManagerRetrofit mManeger; private AdapterHistory mAdapter; private Thread thread; /************** Global *****************************/ private ProgressBar progressBar; private String mMo_id, mMc_name, mMc_id, mMin, mMax, mPram,mAnim; private TextView mProcessname,mParametername,mStandardvalue,mHeadername; private ImageView mImageToobar; /************** Global *****************************/ @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_history); setIntents(); setAnimation(); setSharedPreferences(); } private void setAnimation() { this.overridePendingTransition(R.anim.anim_silde_out_left,R.anim.anim_silde_out_left); if(mAnim.equals("1")){ this.overridePendingTransition(R.anim.anim_silde_out_left,R.anim.anim_silde_out_left); }else if(mAnim.equals("2")){ this.overridePendingTransition(R.anim.anim_silde_in_left,R.anim.anim_silde_in_left); } } private void setIntents() { mAnim = getIntent().getExtras().getString("Ianim",""); Intent call = getIntent(); if(call != null){ mMc_name = call.getStringExtra("mc_name"); mMc_id = call.getStringExtra("mc_id"); mPram = call.getStringExtra("mo_pram"); mMin = call.getStringExtra("mo_min"); mMax= call.getStringExtra("mo_max"); } } private void setSharedPreferences() { spApp_Gone = getSharedPreferences("App_Gone", Context.MODE_PRIVATE); editor_App_Gone = spApp_Gone.edit(); sp = getSharedPreferences("DataAccount",Context.MODE_PRIVATE); editor = sp.edit(); } @Override public void onStart() { super.onStart(); editor_App_Gone.putString("History_Gone" , "0"); editor_App_Gone.commit(); setToolbar(); setUsingClass(); setFindbyid(); setRecyclerView(); setXML(); /************** put Data to XML *****************************/ thread = new Thread() { @Override public void run() { try { while(true) { CallData(); sleep(5000); } } catch (InterruptedException e) { e.printStackTrace(); } } }; thread.start(); } private void setXML() { mHeadername.setText(mMc_name.toUpperCase()); mProcessname.setText(mMc_name.toUpperCase()); mParametername.setText(mPram.toUpperCase()); mStandardvalue.setText(mMin+mMax); Picasso.with(this).load(IMAGEURL + mMc_id + ".jpg") .memoryPolicy(MemoryPolicy.NO_CACHE) .networkPolicy(NetworkPolicy.NO_CACHE) .resize(128, 128) .centerCrop() .into(mImageToobar); } private void setRecyclerView() { mRecyclerView.setHasFixedSize(true); mRecyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool()); mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)); mRecyclerView.setAdapter(mAdapter); } private void setUsingClass() { mManeger = new ManagerRetrofit(); mAdapter = new AdapterHistory(); } private void setToolbar() { toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setTitle(mMc_name); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(HistoryActivity.this,DescripActivity.class); i.putExtra("mc_name",mMc_name); i.putExtra("mc_id",mMc_id); i.putExtra("Ianim","2"); startActivity(i); finish(); } }); } private void setFindbyid() { progressBar = (ProgressBar) findViewById(R.id.progressBar); mHeadername = (TextView)findViewById(R.id.XML_Headername); mProcessname = (TextView) findViewById(R.id.XML_Processname); mParametername = (TextView)findViewById(R.id.XML_Parametername); mStandardvalue = (TextView)findViewById(R.id.XML_Standardvalue); mImageToobar = (ImageView) findViewById(R.id.imageToobar); mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView); } @Override public void onBackPressed() { super.onBackPressed(); thread.interrupt(); Intent i = new Intent(HistoryActivity.this,DescripActivity.class); i.putExtra("Ianim","2"); i.putExtra("mc_name",mMc_name); i.putExtra("mc_id",mMc_id); editor.putBoolean("Runanim",true); editor.commit(); startActivity(i); finish(); } private void CallData() { Call<List<Mis_history>> call = mManeger.getmService().Callback_History(mPram); call.enqueue(new Callback<List<Mis_history>>() { @Override public void onResponse(Call<List<Mis_history>> call, Response<List<Mis_history>> response) { if (response.isSuccessful()) { progressBar.setVisibility(View.GONE); List<Mis_history> Listhistory = response.body(); mAdapter.addList(Listhistory); if(Listhistory.size() == 0){ mRecyclerView.setBackgroundResource(R.drawable.notthingfound); } } } @Override public void onFailure(Call<List<Mis_history>> call, Throwable t) { } }); } @Override protected void onStop() { super.onStop(); thread.interrupt(); editor_App_Gone.putString("History_Gone" , "1"); editor_App_Gone.commit(); } @Override protected void onResume() { super.onResume(); setIntents(); } }
true
09b40c2f8b26ac83f7e74d77a4583575c416923a
Java
dongwan47/Bizpoll_504
/bizpoll/src/com/bizpoll/action/BoardAction.java
UTF-8
595
1.96875
2
[]
no_license
package com.bizpoll.action; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.bizpoll.dao.BoardDAO; public class BoardAction implements Action{ @Override public ActionFoward excute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String url = "board/boardList.jsp" BoardDAO bDao = BoardDAO.getInstance(); List<BoardDTO> boardList = bDao.boardlist(); request.setAttribute(name, o); return null; } } }
true
50848c674084f77b83beaaa9b0087a21ecb281ab
Java
taquy/PRJ311-MartManager
/src/View/Update/UpdateStock.java
UTF-8
13,285
1.929688
2
[]
no_license
package View.Update; import Cache.cStock; import Cache.cUser; import Entity.Product; import Entity.Stock; import Entity.User; import Middleware.Validation; import Model.StockModel; import Model.UserModel; import View.Dialog; import View.Interface.IBundle; import View.VValidate; import java.text.ParseException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; public class UpdateStock extends Dialog implements UpdateFrame, VValidate, IBundle { private StockModel stock_mdl; private cStock xStock; public UpdateStock() { super("Update"); this.stock_mdl = new StockModel(); initComponents(); language_transform(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); stockName2 = new javax.swing.JTextField(); stockCost = new javax.swing.JTextField(); submitUpdateStock = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); stockOrigin = new javax.swing.JTextField(); jLabel13 = new javax.swing.JLabel(); stockProducer = new javax.swing.JTextField(); jLabel14 = new javax.swing.JLabel(); stockAmount = new javax.swing.JTextField(); stockID = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("Language/ViewUpdate"); // NOI18N jLabel1.setText(bundle.getString("UpdateStock.jLabel1.text")); // NOI18N jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel2.setText(bundle.getString("UpdateStock.jLabel2.text")); // NOI18N stockName2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N stockName2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { stockName2ActionPerformed(evt); } }); stockCost.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N submitUpdateStock.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N submitUpdateStock.setText(bundle.getString("UpdateStock.submitUpdateStock.text")); // NOI18N submitUpdateStock.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { submitUpdateStockActionPerformed(evt); } }); jLabel4.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel4.setText(bundle.getString("UpdateStock.jLabel4.text")); // NOI18N jLabel12.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel12.setText(bundle.getString("UpdateStock.jLabel12.text")); // NOI18N stockOrigin.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel13.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel13.setText(bundle.getString("UpdateStock.jLabel13.text")); // NOI18N stockProducer.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel14.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel14.setText(bundle.getString("UpdateStock.jLabel14.text")); // NOI18N stockAmount.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N stockID.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N stockID.setText(bundle.getString("UpdateStock.stockID.text")); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel1)) .addGap(32, 32, 32) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(stockName2) .addGroup(layout.createSequentialGroup() .addComponent(stockCost, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel14) .addGap(18, 18, 18) .addComponent(stockAmount)))) .addGroup(layout.createSequentialGroup() .addComponent(jLabel12) .addGap(33, 33, 33) .addComponent(stockOrigin)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(stockID) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel13) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(submitUpdateStock, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(stockProducer, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(stockID)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(stockName2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(stockCost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel14) .addComponent(stockAmount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel12) .addComponent(stockOrigin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel13) .addComponent(stockProducer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(submitUpdateStock) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void stockName2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stockName2ActionPerformed }//GEN-LAST:event_stockName2ActionPerformed private void submitUpdateStockActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitUpdateStockActionPerformed cStock newStock = new cStock(); newStock.setId(this.xStock.getId()); newStock.setName(stockName2.getText()); newStock.setCost(Float.parseFloat(stockCost.getText())); newStock.setOrigin(stockOrigin.getText()); newStock.setProducer(stockProducer.getText()); newStock.setRemaining(Integer.parseInt(stockAmount.getText())); newStock.setStockOut(this.xStock.getStockOut()); newStock.setLastImportedDate(this.xStock.getLastImportedDate()); newStock.setLastExportedDate(this.xStock.getLastExportedDate()); Stock oldcStock = (Stock) this.mainFrame.data.stocks.get(this.xStock.getId()); oldcStock.setData(newStock); this.mainFrame.data.stocks.replace(this.xStock.getId(), oldcStock); // UPDATE STOCK FOR PRODUCTS HashMap products = this.mainFrame.data.products; Iterator it2 = products.entrySet().iterator(); while (it2.hasNext()) { Map.Entry pair = (Map.Entry)it2.next(); int prdID = (int) pair.getKey(); Product prd = (Product) pair.getValue(); Stock stock = prd.getStock(); if (stock != null) { cStock xstock = (cStock) stock.getData(); if (xstock.getId() == this.xStock.getId()) { stock.setData(newStock); prd.setStock(stock); products.replace(prdID, prd); } } } this.mainFrame.productController.load_ram_data(); this.stock_mdl.setXstock(this.xStock); this.stock_mdl.update(newStock); this.mainFrame.stockController.load_ram_data(); this.setVisible(false); }//GEN-LAST:event_submitUpdateStockActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel4; private javax.swing.JTextField stockAmount; private javax.swing.JTextField stockCost; private javax.swing.JLabel stockID; private javax.swing.JTextField stockName2; private javax.swing.JTextField stockOrigin; private javax.swing.JTextField stockProducer; private javax.swing.JButton submitUpdateStock; // End of variables declaration//GEN-END:variables @Override public void setFrameData(Object data) { cStock xStock = (cStock) data; this.xStock = xStock; stockID.setText("#" + xStock.getId()); stockName2.setText(xStock.getName()); stockCost.setText(xStock.getCost() + ""); stockOrigin.setText(xStock.getOrigin()); stockProducer.setText(xStock.getProducer()); stockAmount.setText(xStock.getRemaining() + ""); } @Override public boolean validating() { return (Validation.v_require(stockAmount.getText()) && Validation.v_require(stockCost.getText()) && Validation.v_require(stockName2.getText()) && Validation.v_require(stockOrigin.getText()) && Validation.v_require(stockProducer.getText()) && Validation.v_int(stockAmount.getText()) && Validation.v_float(stockCost.getText()) ); } @Override public void language_transform() { stockID.setText(bundle.get("UpdateStock.stockID.text")); jLabel2.setText(bundle.get("UpdateStock.jLabel2.text")); jLabel1.setText(bundle.get("UpdateStock.jLabel1.text")); jLabel14.setText(bundle.get("UpdateStock.jLabel14.text")); jLabel13.setText(bundle.get("UpdateStock.jLabel13.text")); jLabel12.setText(bundle.get("UpdateStock.jLabel12.text")); jLabel4.setText(bundle.get("UpdateStock.jLabel4.text")); submitUpdateStock.setText(bundle.get("UpdateStock.submitUpdateStock.text")); } }
true
b7dbd518f78e40e6f834ef2168d3bddc9d927f97
Java
achowdhury80/leetcode
/src/com/leet/algo/Prob692.java
UTF-8
1,414
3.34375
3
[]
no_license
package com.leet.algo; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * Created by ayanc on 12/7/17. */ public class Prob692 { public List<String> topKFrequent(String[] words, int k) { List<String> result = new ArrayList<>(); if(words == null || words.length < 1 || k < 1) return result; Map<String, Integer> map = new HashMap<>(); Arrays.stream(words).forEach(word -> { map.put(word, map.get(word) == null ? 1 : map.get(word) + 1); }); List<Map.Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(map.entrySet()); Collections.sort( list, new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { int cmp1 = o2.getValue().compareTo(o1.getValue()); if(cmp1 != 0) return cmp1; return o1.getKey().compareTo(o2.getKey()); } }); int count = 0; for(int i = 0; i < list.size() && count < k; i++){ result.add(list.get(i).getKey()); count++; } return result; } public static void main(String[] args){ System.out.println(new Prob692().topKFrequent(new String[]{"the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"}, 4)); } }
true
b42a1d24770295a90cfcfc55c231735b40b6af8b
Java
ctripcorp/x-pipe
/redis/redis-console/src/main/java/com/ctrip/xpipe/redis/console/spring/XPipeServletInvocableHandlerMethod.java
UTF-8
3,912
1.914063
2
[ "Apache-2.0" ]
permissive
package com.ctrip.xpipe.redis.console.spring; import com.ctrip.xpipe.api.command.Command; import com.ctrip.xpipe.api.monitor.EventMonitor; import com.ctrip.xpipe.api.sso.UserInfoHolder; import com.ctrip.xpipe.redis.console.controller.Health; import com.ctrip.xpipe.redis.console.controller.api.migrate.MigrationApi; import com.ctrip.xpipe.redis.console.controller.api.migrate.MigrationApi4Beacon; import com.ctrip.xpipe.redis.console.controller.api.migrate.MigrationInfoApi; import com.ctrip.xpipe.redis.console.controller.consoleportal.MigrationController; import org.springframework.util.ReflectionUtils; import org.springframework.web.context.request.async.DeferredResult; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod; import java.lang.reflect.InvocationTargetException; import java.util.concurrent.Executor; /** * @author Slight * <p> * Mar 16, 2022 4:05 PM */ public class XPipeServletInvocableHandlerMethod extends ServletInvocableHandlerMethod { public final Executor executor; public final long timeout; public static String EVENT_TYPE_SERVLET_HANDLER = "Servlet.Handler"; public XPipeServletInvocableHandlerMethod(HandlerMethod handlerMethod, Executor executor, long timeout) { super(handlerMethod); this.executor = executor; this.timeout = timeout; } @Override protected Object doInvoke(Object... args) throws Exception { ReflectionUtils.makeAccessible(getBridgedMethod()); try { /* <<-- ONLY THIS PART IS MODIFIED -- */ if (getBean() instanceof MigrationApi || getBean() instanceof MigrationApi4Beacon || getBean() instanceof Health || getBean() instanceof MigrationInfoApi || getBean() instanceof MigrationController) { EventMonitor.DEFAULT.logEvent(EVENT_TYPE_SERVLET_HANDLER, "Sync"); return getBridgedMethod().invoke(getBean(), args); } else { EventMonitor.DEFAULT.logEvent(EVENT_TYPE_SERVLET_HANDLER, "Async"); DeferredResult<Object> result = new DeferredResult<>(timeout); Command<Object> command = new XPipeHandlerMethodCommand(getBridgedMethod(), getBean(), UserInfoHolder.DEFAULT, args); command.execute(executor).addListener(commandFuture -> { if (commandFuture.isSuccess()) { result.setResult(commandFuture.get()); } else { result.setErrorResult(commandFuture.cause()); } }); return result; } /* -- ONLY THIS PART IS MODIFIED -->> */ /* ORIGIN CODE: return getBridgedMethod().invoke(getBean(), args); */ } catch (IllegalArgumentException ex) { assertTargetBean(getBridgedMethod(), getBean(), args); String text = (ex.getMessage() != null ? ex.getMessage() : "Illegal argument"); throw new IllegalStateException(formatInvokeError(text, args), ex); } catch (InvocationTargetException ex) { // Unwrap for HandlerExceptionResolvers ... Throwable targetException = ex.getTargetException(); if (targetException instanceof RuntimeException) { throw (RuntimeException) targetException; } else if (targetException instanceof Error) { throw (Error) targetException; } else if (targetException instanceof Exception) { throw (Exception) targetException; } else { throw new IllegalStateException(formatInvokeError("Invocation failure", args), targetException); } } } }
true
17e29790cd519e530c1ab58b8a7654c1f37a8dff
Java
QYJS007/JavaProject02
/PDF/src/cg/main/pdfDomainVO.java
UTF-8
435
1.609375
2
[]
no_license
package cg.main; import java.io.File; public class pdfDomainVO { public File getInputfile() { // TODO Auto-generated method stub return null; } public int getPageno() { // TODO Auto-generated method stub return 0; } public void setContent(String content) { // TODO Auto-generated method stub } public String getPosition() { // TODO Auto-generated method stub return null; } }
true
0280ef7d42b497f89ecb1eb3728b682f308e8fb5
Java
ALJet/MVPDemoTest
/app/src/main/java/indi/aljet/mvpdemotest/ui/activity/WeatherActivity.java
UTF-8
787
1.921875
2
[]
no_license
package indi.aljet.mvpdemotest.ui.activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import butterknife.BindView; import indi.aljet.mvpdemotest.R; import indi.aljet.mvpdemotest.bean.WeatherData; import indi.aljet.mvpdemotest.view.WeatherView; /** * Created by PC-LJL on 2017/9/8. */ public class WeatherActivity extends AppCompatActivity implements WeatherView{ @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void showProgress() { } @Override public void hideProgress() { } @Override public void loadWeather(WeatherData weatherData) { } }
true
abaecec921b19df01b418ab3deac716271b38a17
Java
dschadow/JavaSecurity
/crypto-tink/src/test/java/de/dominikschadow/javasecurity/tink/hybrid/EciesWithAwsKmsSavedKeyTest.java
UTF-8
2,854
2.28125
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2023 Dominik Schadow, dominikschadow@gmail.com * * This file is part of the Java Security project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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 de.dominikschadow.javasecurity.tink.hybrid; import com.google.crypto.tink.KeysetHandle; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.io.File; import java.nio.charset.StandardCharsets; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; @Disabled("These tests require AWS KMS configuration") class EciesWithAwsKmsSavedKeyTest { private static final byte[] INITIAL_TEXT = "Some dummy text to work with".getBytes(StandardCharsets.UTF_8); private static final byte[] CONTEXT_INFO = "Some additional data".getBytes(StandardCharsets.UTF_8); private static final String PRIVATE_KEYSET_FILENAME = "src/test/resources/keysets/hybrid-ecies-kms-private.json"; private static final String PUBLIC_KEYSET_FILENAME = "src/test/resources/keysets/hybrid-ecies-kms-public.json"; private final File privateKeysetFile = new File(PRIVATE_KEYSET_FILENAME); private final File publicKeysetFile = new File(PUBLIC_KEYSET_FILENAME); private KeysetHandle publicKey; private KeysetHandle privateKey; private EciesWithAwsKmsSavedKey ecies; @BeforeEach protected void setup() throws Exception { ecies = new EciesWithAwsKmsSavedKey(); ecies.generateAndStorePrivateKey(privateKeysetFile); privateKey = ecies.loadPrivateKey(privateKeysetFile); ecies.generateAndStorePublicKey(privateKey, publicKeysetFile); publicKey = ecies.loadPublicKey(publicKeysetFile); } @Test void encryptionAndDecryptionWithValidInputsIsSuccessful() throws Exception { byte[] cipherText = ecies.encrypt(publicKey, INITIAL_TEXT, CONTEXT_INFO); byte[] plainText = ecies.decrypt(privateKey, cipherText, CONTEXT_INFO); Assertions.assertAll( () -> assertNotEquals(new String(INITIAL_TEXT, StandardCharsets.UTF_8), new String(cipherText, StandardCharsets.UTF_8)), () -> assertEquals(new String(INITIAL_TEXT, StandardCharsets.UTF_8), new String(plainText, StandardCharsets.UTF_8)) ); } }
true
da56f5f486c132a8bee80b40bff65bbb16863ea5
Java
MilanPatel718/Android-Photo-App
/app/src/main/java/photos/photosandroid/displayPhoto.java
UTF-8
21,115
1.828125
2
[]
no_license
package photos.photosandroid; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.Image; import android.net.Uri; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.support.v4.app.NavUtils; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; import org.w3c.dom.Text; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.net.URI; import java.util.ArrayList; import static photos.photosandroid.AlbumActivity.getDataColumn; import static photos.photosandroid.AlbumActivity.isGooglePhotosUri; import static photos.photosandroid.AlbumActivity.isMediaDocument; /** * @author Milan Patel * Displays Photo once selected from album */ public class displayPhoto extends AppCompatActivity{ TableLayout TTable; ImageView ImgView; PhotoLibrary photoLib= new PhotoLibrary(); final Context context=this; String testDecode="test"; Photo photo; int pos; String AlbumName; int photoCount; Album temp=new Album("temp"); /** * Creates Photo Display View * @param savedInstanceState */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.photo); ImgView=(ImageView) findViewById(R.id.imageView); Intent intent=getIntent(); Bundle b=intent.getExtras(); try { String path=context.getFilesDir()+"/"+"library.bin"; photoLib = readApp(new File(path)); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } pos=b.getInt("GRID_POS"); AlbumName=b.getString("ALBUM_NAME"); photo =findPhotoInAlbum(AlbumName, pos); String s=photo.getTitle(); String FileName=""; if(Uri.parse(photo.getImage())==null){ FileName="No Title"; } else{ FileName = s.substring(s.lastIndexOf("/") + 1); } getSupportActionBar().setTitle(FileName); photoCount=b.getInt("PHOTO_NUM"); setTagView(photo); setImageView(photo); for(int i=0; i<photoLib.getAlbums().size(); i++){ if(photoLib.getAlbums().get(i).getTitle().equals(AlbumName)){ temp=photoLib.getAlbums().get(i); } } Button addTag=(Button) findViewById(R.id.addtag); Button nextPhoto=(Button) findViewById(R.id.Next); Button previousPhoto=(Button) findViewById(R.id.Previous); Button movePhoto=(Button) findViewById(R.id.move); movePhoto.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ final AlertDialog builder=new AlertDialog.Builder(context).create(); ScrollView Scroller=new ScrollView(context); builder.setTitle("Select Album to Move Photo to"); final LinearLayout LL= new LinearLayout(context); LL.setOrientation(LinearLayout.VERTICAL); Scroller.addView(LL); Button cancel=new Button(context); cancel.setText("Cancel"); cancel.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { builder.dismiss(); } }); for(int i=0; i<photoLib.getAlbums().size();i++) { TextView text = new TextView(context); text.setText(photoLib.getAlbums().get(i).getTitle()); text.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView text=(TextView) v; String moveAlbum=text.getText().toString(); for(int i=0; i<photoLib.getAlbums().size();i++){ if(moveAlbum.equals(photoLib.getAlbums().get(i).getTitle())){ Photo P=photo; photoLib.getAlbums().get(i).addPhoto(P); int origPos=pos; if(getNumPhotos()==1){ deletePhotoInAlbum(origPos); try { writeApp(photoLib, context); } catch (IOException e) { e.printStackTrace(); } Log.d("debug", "entered"); Bundle send=new Bundle(); Intent intent=new Intent(context, AlbumActivity.class); send.putString("ALBUM_NAME", AlbumName); send.putSerializable("PHOTO_LIB", photoLib ); intent.putExtras(send); startActivity(intent); builder.dismiss(); return; } deletePhotoInAlbum(origPos); try { writeApp(photoLib, context); } catch (IOException e) { e.printStackTrace(); } builder.dismiss(); Intent newIntent=getIntent(); Bundle oldBundle=newIntent.getExtras(); if(pos==0) oldBundle.putInt("GRID_POS", pos); else oldBundle.putInt("GRID_POS", pos-1); newIntent.putExtras(oldBundle); startActivity(newIntent); } } } }); if (photoLib.getAlbums().get(i).getTitle().equals(AlbumName)) { } else { LL.addView(text); } } LL.addView(cancel); builder.setView(Scroller); builder.show(); } }); nextPhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(pos==temp.getNumPhotos()-1){ pos=0; Photo next=temp.getPhotos().get(pos); String s=next.getTitle(); String FileName=""; if(Uri.parse(next.getImage())==null){ FileName="No Title"; } else{ FileName = s.substring(s.lastIndexOf("/") + 1); } getSupportActionBar().setTitle(FileName); setImageView(next); setTagView(next); photo=next; } else{ pos++; Photo next=temp.getPhotos().get(pos); String s=next.getTitle(); String FileName=""; if(Uri.parse(next.getImage())==null){ FileName="No Title"; } else{ FileName = s.substring(s.lastIndexOf("/") + 1); } getSupportActionBar().setTitle(FileName); setImageView(next); setTagView(next); photo=next; } AlbumName=temp.getTitle(); } }); previousPhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(pos==0){ pos=temp.getNumPhotos()-1; Photo next=temp.getPhotos().get(pos); setImageView(next); setTagView(next); photo=next; } else{ pos--; Photo next=temp.getPhotos().get(pos); setImageView(next); setTagView(next); photo=next; } AlbumName=temp.getTitle(); } }); addTag.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view){ AlertDialog.Builder builder=new AlertDialog.Builder(context); builder.setTitle("Enter Tag Name and Tag Value"); LinearLayout LL= new LinearLayout(context); LL.setOrientation(LinearLayout.VERTICAL); final EditText input=new EditText(context); input.setHint("Tag Name"); final EditText input1=new EditText(context); input1.setHint("Tag Value"); LL.addView(input); LL.addView(input1); builder.setView(LL); builder.setPositiveButton("CREATE", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String tagName=input.getText().toString(); String tagValue=input1.getText().toString(); Log.d("debugging", tagName+" "+tagValue); boolean duplicate=false; if(!(tagName.equals("person") || tagName.equals("location"))){ AlertDialog alertDialog = new AlertDialog.Builder(context).create(); alertDialog.setTitle("Alert"); alertDialog.setMessage("Invalid Tag, Try Again"); alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); duplicate=true; alertDialog.show(); } for(int i=0; i<photo.getTags().size();i++){ if((tagName.equals(photo.getTags().get(i).getTagName())) && (tagValue.equals(photo.getTags().get(i).getTagValue()))){ AlertDialog alertDialog = new AlertDialog.Builder(context).create(); alertDialog.setTitle("Alert"); alertDialog.setMessage("Duplicate Tag, please try again"); alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); duplicate=true; alertDialog.show(); } } if(duplicate==false){ photo.getTags().add(new Tag(tagName, tagValue)); setPhotoInAlbum(photo); try { writeApp(photoLib, context); } catch (IOException e) { e.printStackTrace(); } setTagView(photo); } else{} } }); builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which){ dialog.cancel(); } }); builder.show(); } }); } /** * Finds Photo Given Album Name and grid position * @param AlbumName * @param pos * @return */ public Photo findPhotoInAlbum(String AlbumName, int pos){ for(int i=0; i<photoLib.getAlbums().size(); i++){ if(photoLib.getAlbums().get(i).getTitle().equals(AlbumName)){ return photoLib.getAlbums().get(i).getPhotos().get(pos); } } return null; } /** * Deletes Photo given grid position * @param pos */ public void deletePhotoInAlbum(int pos) { for (int i = 0; i < photoLib.getAlbums().size(); i++) { if (photoLib.getAlbums().get(i).getTitle().equals(AlbumName)) { photoLib.getAlbums().get(i).getPhotos().remove(pos); } } } /** * Gets Number of Photos in album * @return */ public int getNumPhotos(){ for (int i = 0; i < photoLib.getAlbums().size(); i++) { if (photoLib.getAlbums().get(i).getTitle().equals(AlbumName)) { return photoLib.getAlbums().get(i).getPhotos().size(); } } return 0; } /** * Sets Photo in album given Photo * @param P */ public void setPhotoInAlbum(Photo P){ for(int i=0; i<photoLib.getAlbums().size(); i++){ if(photoLib.getAlbums().get(i).getTitle().equals(AlbumName)){ photoLib.getAlbums().get(i).getPhotos().set(pos, P); } } } /** * Sets Table of Tag Values given Photo * @param P */ public void setTagView(final Photo P){ ArrayList<Tag> tags=P.getTags(); TTable=(TableLayout) findViewById(R.id.TagTable); TTable.removeAllViews(); for(int i=0; i<tags.size();i++){ TableRow row=new TableRow(this); String Name=tags.get(i).getTagName(); String Value=tags.get(i).getTagValue(); TextView nameView=new TextView(this); nameView.setText(Name); TextView spacing=new TextView(this); spacing.setText(" "); TextView valueView=new TextView(this); valueView.setText(Value); Button tagDelete=new Button(this); tagDelete.setText("Delete"); tagDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int id=pos; Photo temp=P; View row=(View) v.getParent(); ViewGroup Container=((ViewGroup) row.getParent()); Container.removeView(row); Container.invalidate(); TableRow tempRow=(TableRow) row; TextView nameView=(TextView) tempRow.getChildAt(0); TextView valueView=(TextView) tempRow.getChildAt(2); String tagName=nameView.getText().toString(); String tagValue=valueView.getText().toString(); for(int i=0; i<temp.getTags().size();i++){ if((tagName.equals(temp.getTags().get(i).getTagName())) && (tagValue.equals(temp.getTags().get(i).getTagValue()))){ Log.d("Debug", temp.getTags().get(i).getTagName() + " "+ temp.getTags().get(i).getTagValue()); temp.getTags().remove(i); setPhotoInAlbum(temp); try { writeApp(photoLib, context); } catch (IOException e) { e.printStackTrace(); } } } } }); row.addView(nameView); row.addView(spacing); row.addView(valueView); row.addView(tagDelete); TTable.addView(row); } } /** * Refreshes GridView of Parent Activity upon clicking back button * @param menuItem * @return */ @Override public boolean onOptionsItemSelected(MenuItem menuItem) { switch (menuItem.getItemId()) { case android.R.id.home: { Log.d("Debugger", "Back Button Refresh"); Bundle send=new Bundle(); Intent intent=new Intent(context, AlbumActivity.class); send.putString("ALBUM_NAME", AlbumName); send.putSerializable("PHOTO_LIB", photoLib ); intent.putExtras(send); startActivity(intent); finish(); } } return (super.onOptionsItemSelected(menuItem)); } /** * Sets Image View of Display Screen * @param P */ public void setImageView(Photo P){ Uri uri=Uri.parse(P.getImage()); String filePath=getPath(uri); Bitmap bitmap =BitmapFactory.decodeFile(filePath); ImgView.setImageBitmap(bitmap); } /** * Gets file path of uri * @param uri * @return */ public String getPath(Uri uri) { if( uri == null ) { return null; } if (isMediaDocument(uri)){ final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; final String selection = "_id=?"; final String[] selectionArgs = new String[] { split[1] }; return getDataColumn(context, contentUri, selection, selectionArgs); }else if("content".equalsIgnoreCase(uri.getScheme())){ if (isGooglePhotosUri(uri)) return uri.getLastPathSegment(); return getDataColumn(context, uri, null, null); } return null; } /** * Serializes PhotoLibrary * @param photoLib * @param context * @throws IOException */ public static void writeApp(PhotoLibrary photoLib, Context context) throws IOException { File outFile = new File(context.getFilesDir(), "library.bin"); ObjectOutput oos = new ObjectOutputStream(new FileOutputStream(outFile)); oos.writeObject(photoLib); oos.close(); } /** * Reads Serialized Library * @param F * @return * @throws IOException * @throws ClassNotFoundException */ public static PhotoLibrary readApp(File F) throws IOException, ClassNotFoundException { if(F.length() == 0){ return new PhotoLibrary(); } ObjectInputStream ois = new ObjectInputStream(new FileInputStream(F)); PhotoLibrary photoLib = (PhotoLibrary)ois.readObject(); ois.close(); return photoLib; } }
true
c1ef90a56e407138f23610d44449a7d94bed251b
Java
Searay-330/ReviewSessionExamples
/code reading/src/human/Driver.java
UTF-8
1,290
3.78125
4
[]
no_license
package human; import java.util.ArrayList; public class Driver { public static void main(String[] args) { human humanOne = new human(5, 110, 20, "blue", "Glenn"); human humanTwo = new human(6, 180, 35, "green", "Carl"); human humanThree = new human(4, 95, 40, "brown", "Jessie"); human humanFour = new human(5, 120, 15, "black", "Dave"); human humanFive = new human(7, 200, 25, "hazel", "Luke"); ArrayList<human> TitanFood = new ArrayList<human>(); ArrayList<human> humansAlive = new ArrayList<human>(); ArrayList<human> humansDead = new ArrayList<human>(); TitanFood.add(humanOne); TitanFood.add(humanTwo); TitanFood.add(humanThree); TitanFood.add(humanFour); TitanFood.add(humanFive); for (int i = 0; i < TitanFood.size(); i++) { if (TitanFood.get(i).getAge() > 20 && TitanFood.get(i).getWeight() > 130) { humansDead.add(TitanFood.get(i)); } else { humansAlive.add(TitanFood.get(i)); } } System.out.println("Humans Alive"); for (int i = 0; i < humansAlive.size(); i++) { System.out.print(" " + "-" + " " + humansAlive.get(i).getName()); } System.out.println(); System.out.println("Humans Dead"); for (int i = 0; i < humansDead.size(); i++) { System.out.print(" " + "-" + " " + humansDead.get(i).getName()); } } }
true
3b9536698e33eae5993dd3cb6b34783f6610b0b7
Java
Zoran-Han/java
/demo0729/src/com/demo/oop/impl/Circle.java
UTF-8
1,803
3.4375
3
[]
no_license
package com.demo.oop.impl; import com.demo.oop.IShape; import com.demo.oop.ParentInterface2; /** * @ClassName Circle * @Description TODO * @Author Hzrobo * @CreateDate 2019年07月29日 16:13:13 * @Version 1.0.0 */ /* public class Circle implements IShape ,ParentInterface2 {//实现类可以实现多个接口 @Override public double calculatePerimeter() { return 0; } @Override public double calculateArea() { return 0; } @Override public void method() { } }*/ public class Circle implements IShape { // IShape iShape = new Circle();//接口引用可以指向实现该接口的对象 private double r; public Circle(){ } public Circle(double r){ this.r = r; } @Override public double calculatePerimeter() { // PI = 3.1415;//不允许修改值 System.out.println("半径为:"+r); return 2 * PI * r; } @Override public double calculateArea() { // Circle.show();//访问接口中的静态方法 return PI * r * r ; } @Override public void printMsg(){ System.out.println("实现类中重写默认方法!"); } //@Override 不算重写 ,只是实现类的自定义,访问的时候覆盖父接口中的方法 public static void show(){ System.out.println("实现类中的静态方法!"); } public void method(){ //无法使用super访问接口中的成员 //super.printMsg();编译出错 //super.show();编译出错 //double PI = super.PI;编译出错 this.printMsg();//访问默认方法 double PI = this.PI;//访问静态变量 //this.show(); //访问静态方法,在没有继承的情况下编译报错 } }
true
1d8ad63fd9badcf98fb8fdbcc8d5b2b15aa673d0
Java
linseycurrie/CClan_Week_12
/Day03/Lab/src/main/java/Customer.java
UTF-8
654
2.8125
3
[]
no_license
import java.util.ArrayList; public class Customer { private ArrayList<IProduct> purchases; private ArrayList<Double> balance; private ArrayList<Double> currentSpent; public Customer(ArrayList<IProduct> purchases, ArrayList<Double> balance, ArrayList<Double> currentSpent) { this.purchases = purchases; this.balance = balance; this.currentSpent = currentSpent; } public ArrayList<IProduct> getPurchases() { return purchases; } public ArrayList<Double> getBalance() { return balance; } public ArrayList<Double> getCurrentSpent() { return currentSpent; } }
true
1d863aadf2300a5e9ca0a8c604685b0435b23406
Java
chenyantaoaaa/MyJavaResearchDemos
/src/com/mybatis/imitateMybatis/TestM.java
UTF-8
469
1.851563
2
[]
no_license
package com.mybatis.imitateMybatis; import org.junit.Test; /** * @author chenyantao * @date 2017/11/10. */ public class TestM { @Test public void test1(){ MySqlSession mySqlSession = new MySqlSession("mybatis-config.xml","com/mybatis/mapper/UserMapper.xml"); // List<String> param = new ArrayList<>(); // param.add("chen"); String result = mySqlSession.select2("selectUserDetail"); System.out.println(result); } }
true
ff5344207e14d4476c4691c0b0ae5e92faeec8ec
Java
MeenuVNair/CodingSkills
/src/main/java/com/meenu/codingskills/datastructures/stack/ReverseStringWithStack.java
UTF-8
1,100
3.890625
4
[]
no_license
package com.meenu.codingskills.datastructures.stack; /** * @author Meenu V Nair * */ public class ReverseStringWithStack { static int MAX_SIZE = 101; static char arr[] = new char[MAX_SIZE]; static int top = -1; public void findSolution() { String input = "Hello"; /*Scanner input = new Scanner(System.in); while(input.hasNext()) { push(input.next()); } input.close();*/ for(int i = 0; i < input.length(); i++) { push(input.charAt(i)); } System.out.print("String : "); print(); String reverse = ""; while(top != -1) { reverse = reverse + top(); } System.out.println("\nReverse : " + reverse); } private void push(char value) { if(top == MAX_SIZE - 1) { System.err.println("Stack overflow"); return; } arr[++top] = value; } private void pop() { if(top == -1) { System.err.println("Stack empty"); return; } top--; } private char top() { if(top == -1) { System.err.println("Stack empty"); } return arr[top--]; } private void print() { for(int i = 0; i <= top; i++) { System.out.print(arr[i]); } } }
true
38db85e0d8ca3d0bbff5da5167634f9dcc1a14d5
Java
blairjackson/Java-file-handler
/src/file_handler/Input.java
UTF-8
791
3.609375
4
[]
no_license
package file_handler; import java.util.Scanner; /** * * @author blairjackson */ public class Input { //get user input and pass to check if valid int get_choice() { Scanner sc = new Scanner(System.in); System.out.println("Select an option: "); int choice = sc.nextInt(); if (valid_choice(choice)) { return choice; } else { System.out.println("Invalid choice, try again"); get_choice(); } return 0; } //check input is within range boolean valid_choice(int choice) { if (choice < 1 || choice > 4) { return false; } else { return true; } } //write a function to handle input that is not an integer }
true
b7cd61c06f478fc7dbd4ef5970cf9833cf4f5272
Java
yongjin5184/jpa_example
/src/main/java/com/example/jpa_example/model/entity/instagram/post/Post.java
UTF-8
1,492
1.945313
2
[]
no_license
package com.example.jpa_example.model.entity.instagram.post; import java.util.List; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToOne; import javax.persistence.OrderColumn; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.SecondaryTable; import javax.persistence.Table; import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; @Entity @Getter @SecondaryTable(name = "location", pkJoinColumns = @PrimaryKeyJoinColumn(name = "post_id")) @NoArgsConstructor(access = AccessLevel.PROTECTED) @Table(name = "post") public class Post { @Id @GeneratedValue private PostId id; @ManyToOne(fetch = FetchType.LAZY, optional = false) @JoinColumn(name = "author_id") private Author author; @Embedded private Content content; @Embedded @Column(table = "location") private Location location; @ElementCollection @JoinTable(name = "comment", joinColumns = @JoinColumn(name = "post_id")) @OrderColumn(name = "comment_idx") private List<Comment> comments; @ElementCollection @JoinTable(name = "post_like", joinColumns = @JoinColumn(name = "post_id")) private List<Like> likes; }
true
6c8ad458bf0be92ccbe8aaf00916d2b636f3709f
Java
syncwt/personal
/src/main/java/com/beust/AssistedTest.java
UTF-8
4,061
2.984375
3
[]
no_license
package com.beust; import com.google.inject.Binder; import com.google.inject.Binding; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.Singleton; import com.google.inject.assistedinject.Assisted; import com.google.inject.assistedinject.AssistedInjectBinding; import com.google.inject.assistedinject.AssistedInjectTargetVisitor; import com.google.inject.assistedinject.AssistedMethod; import com.google.inject.assistedinject.FactoryModuleBuilder; import com.google.inject.name.Named; import com.google.inject.name.Names; import com.google.inject.spi.DefaultBindingTargetVisitor; @Singleton class Data { public String getData() { return "injected data " + hashCode(); } } interface IPerson { public String getName(); } class BasePerson implements IPerson { private String name; private Data data; @Inject public BasePerson(@Assisted String name, Data data) { this.name = name; this.data = data; } @Override public String getName() { return name + " data:" + data.getData(); } } class Adult extends BasePerson { @Inject public Adult(@Assisted("name") String name, @Assisted("nick") String nickName, Data data) { super(name + " nick:" + nickName + " (adult)", data); } } class Child extends BasePerson { @Inject public Child(@Assisted("name") String name, @Assisted("nick") String nickName, Data data) { super(name + " nick:" + nickName + " (child)", data); } } interface IPersonFactory { public @Named("adult") IPerson createAdult(@Assisted("name") String name, @Assisted("nick") String nick); public @Named("child") IPerson createChild(@Assisted("name") String name, @Assisted("nick") String nick); } /** * Build with * <groupId>com.google.inject.extensions</groupId> * <artifactId>guice-assistedinject</artifactId> * <version>3.0</version> */ public class AssistedTest { @Inject private IPersonFactory factory; private void run() { System.out.println(factory.createAdult("Cedric", "foo").getName()); System.out.println(factory.createAdult("Alois", "bar").getName()); System.out.println(factory.createChild("Christopher", "baz").getName()); } public static void main(String[] args) { final Module module = new FactoryModuleBuilder() .implement(IPerson.class, Names.named("adult"), Adult.class) .implement(IPerson.class, Names.named("child"), Child.class) .build(IPersonFactory.class); // Or install in an existing module: Module module2 = new Module() { @Override public void configure(Binder binder) { binder.install(module); } }; Injector injector = Guice.createInjector(module); injector.getInstance(AssistedTest.class).run(); displayBindings(injector); } static class Visitor extends DefaultBindingTargetVisitor<Object, Void> implements AssistedInjectTargetVisitor<Object, Void> { @Override public Void visit(AssistedInjectBinding<?> binding) { // Loop over each method in the factory... for (AssistedMethod method : binding.getAssistedMethods()) { System.out.println("Non-assisted Dependencies: " + method.getDependencies() + ", Factory Method: " + method.getFactoryMethod() + ", Implementation Constructor: " + method.getImplementationConstructor() + ", Implementation Type: " + method.getImplementationType()); } return null; } } private static void displayBindings(Injector injector) { Binding<IPersonFactory> binding = injector.getBinding(IPersonFactory.class); binding.acceptTargetVisitor(new Visitor()); } }
true
0605827639df4cd22b37a0a6465eb44733fcbe8f
Java
ChaoYongAtom/applibrary
/lib_webview/src/main/java/com/wcy/app/lib/web/js/JsEntraceAccess.java
UTF-8
224
1.617188
2
[]
no_license
package com.wcy.app.lib.web.js; import android.webkit.ValueCallback; public interface JsEntraceAccess extends QuickCallJs { void callJs(String js, ValueCallback<String> callback); void callJs(String js); }
true
e38c287ec74e3a1cd4d8d06efcca9b7ecd87ce40
Java
AkinoriNoujima/NoughtsAndCrosses2
/src/com/example/noughtsandcrosses2/MarubatsuBoard.java
UTF-8
2,047
3.375
3
[]
no_license
package com.example.noughtsandcrosses2; public class MarubatsuBoard { // 012 // 345 // 678 /** ゲーム盤の選択状況 */ public String[] board = { "-", "-", "-", "-", "-", "-", "-", "-", "-" }; /** 現在のターン数 */ public int turn = 0; /** * ゲーム盤のnで指定された箇所が空欄であるか? * @param n 0~8までの数値 * @return 空欄の場合true, 誰かが選択済みの場合false */ public boolean isBlank(int n) { // TODO フェーズ1で記述 //一度選択しているとboard[]の中はラベルが入るので"-"だとまだ未選択、それ以外は選択済み if (board[n].equals("-")) { return true; } return false; } /** * ゲーム盤のnで指定された箇所を選択する * @param n 0~8までの数値 * @param player nの箇所を選択するプレイヤー */ public void select(int n, Player player) { // TODO フェーズ1で記述 //盤board[]のn番目にその時のターンのプレーヤーのラベルを入れる board[n] = player.getLabel(); } /** * 指定プレイヤーが勝利しているか、ゲーム盤の状態を確認する * @param player 勝利を確認するプレイヤー * @return 勝利している場合にtrue, それ以外はfalse */ //masterPlayerで使用するためにpublicでここに記載 public int[][] checkLines = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, { 0, 3, 6 }, { 1, 4, 7 }, { 2, 5, 8 }, { 0, 4, 8 }, { 2, 4, 6 } }; public String isWin(Player player) { // TODO フェーズ1で記述 //isWinの中身は元のmarubatsuを少し改変 //現時点ターンでのプレーヤーのラベルを取得してcheckLinesと照合して戻り値を返す String winnerLabel = player.getLabel(); for (int i = 0; i < checkLines.length; i++) { int[] ck = checkLines[i]; if (board[ck[0]].equals(winnerLabel) && board[ck[1]].equals(winnerLabel) && board[ck[2]].equals(winnerLabel)) { return "" + ck[0] + ck[1] + ck[2]; } } return null; } }
true
1dc33ca5608b8d8a6dafe64266edf3d1f78228a1
Java
Viral-patel703/Testyourbond-aut0
/lib/selenium-server-standalone-3.4.0/com/gargoylesoftware/htmlunit/javascript/host/event/MessageEvent.java
UTF-8
4,739
1.953125
2
[]
no_license
package com.gargoylesoftware.htmlunit.javascript.host.event; import com.gargoylesoftware.htmlunit.BrowserVersion; import com.gargoylesoftware.htmlunit.BrowserVersionFeatures; import com.gargoylesoftware.htmlunit.javascript.configuration.JsxClass; import com.gargoylesoftware.htmlunit.javascript.configuration.JsxConstructor; import com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction; import com.gargoylesoftware.htmlunit.javascript.configuration.JsxGetter; import com.gargoylesoftware.htmlunit.javascript.host.Window; import com.gargoylesoftware.htmlunit.javascript.host.WindowProxy; import net.sourceforge.htmlunit.corejs.javascript.Context; import net.sourceforge.htmlunit.corejs.javascript.ScriptableObject; import net.sourceforge.htmlunit.corejs.javascript.Undefined; @JsxClass public class MessageEvent extends Event { private Object data_; private String origin_; private String lastEventId_; private Window source_; private Object ports_; public MessageEvent() { setType("message"); origin_ = ""; lastEventId_ = ""; data_ = Undefined.instance; } public MessageEvent(Object data) { this(); data_ = data; } @JsxConstructor({@com.gargoylesoftware.htmlunit.javascript.configuration.WebBrowser(com.gargoylesoftware.htmlunit.javascript.configuration.BrowserName.CHROME), @com.gargoylesoftware.htmlunit.javascript.configuration.WebBrowser(com.gargoylesoftware.htmlunit.javascript.configuration.BrowserName.FF), @com.gargoylesoftware.htmlunit.javascript.configuration.WebBrowser(com.gargoylesoftware.htmlunit.javascript.configuration.BrowserName.EDGE)}) public void jsConstructor(String type, ScriptableObject details) { super.jsConstructor(type, details); if (getBrowserVersion().hasFeature(BrowserVersionFeatures.EVENT_ONMESSAGE_DEFAULT_DATA_NULL)) { data_ = null; } String origin = ""; String lastEventId = ""; if ((details != null) && (!Undefined.instance.equals(details))) { data_ = details.get("data"); String detailOrigin = (String)details.get("origin"); if (detailOrigin != null) { origin = detailOrigin; } Object detailLastEventId = details.get("lastEventId"); if (detailLastEventId != null) { lastEventId = Context.toString(detailLastEventId); } source_ = null; Object detailSource = details.get("source"); if ((detailSource instanceof Window)) { source_ = ((Window)detailSource); } else if ((detailSource instanceof WindowProxy)) { source_ = ((WindowProxy)detailSource).getDelegee(); } ports_ = details.get("ports"); } origin_ = origin; lastEventId_ = lastEventId; } @JsxFunction({@com.gargoylesoftware.htmlunit.javascript.configuration.WebBrowser(com.gargoylesoftware.htmlunit.javascript.configuration.BrowserName.CHROME), @com.gargoylesoftware.htmlunit.javascript.configuration.WebBrowser(com.gargoylesoftware.htmlunit.javascript.configuration.BrowserName.IE), @com.gargoylesoftware.htmlunit.javascript.configuration.WebBrowser(com.gargoylesoftware.htmlunit.javascript.configuration.BrowserName.FF)}) public void initMessageEvent(String type, boolean canBubble, boolean cancelable, Object data, String origin, String lastEventId, Window source, Object ports) { initEvent(type, canBubble, cancelable); data_ = data; origin_ = origin; lastEventId_ = lastEventId; source_ = source; ports_ = ports; } @JsxGetter public Object getData() { return data_; } @JsxGetter public String getOrigin() { return origin_; } public void setOrigin(String origin) { origin_ = origin; } @JsxGetter({@com.gargoylesoftware.htmlunit.javascript.configuration.WebBrowser(com.gargoylesoftware.htmlunit.javascript.configuration.BrowserName.FF), @com.gargoylesoftware.htmlunit.javascript.configuration.WebBrowser(com.gargoylesoftware.htmlunit.javascript.configuration.BrowserName.CHROME)}) public String getLastEventId() { return lastEventId_; } @JsxGetter public Window getSource() { return source_; } @JsxGetter({@com.gargoylesoftware.htmlunit.javascript.configuration.WebBrowser(com.gargoylesoftware.htmlunit.javascript.configuration.BrowserName.CHROME), @com.gargoylesoftware.htmlunit.javascript.configuration.WebBrowser(com.gargoylesoftware.htmlunit.javascript.configuration.BrowserName.IE), @com.gargoylesoftware.htmlunit.javascript.configuration.WebBrowser(com.gargoylesoftware.htmlunit.javascript.configuration.BrowserName.FF)}) public Object getPorts() { return ports_; } }
true
294c0bfedda0e5c331561b2c28a3364884300dda
Java
SabinaRe/Food-App
/app/src/main/java/com/example/tab/Sign_frag.java
UTF-8
926
1.875
2
[]
no_license
package com.example.tab; import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; public class Sign_frag extends Fragment { Button btn_sig; @Nullable @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_sign, container, false); btn_sig = root.findViewById(R.id.btn_sig); btn_sig.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(getActivity(), DashboardActivity.class)); } }); return root; } }
true
eae8dca0809633c7a6026a52a542fbf98110f30b
Java
joejames1996/Cinemagic
/src/main/java/org/softwire/training/cinemagic/controllers/CinemaController.java
UTF-8
1,764
2.390625
2
[]
no_license
package org.softwire.training.cinemagic.controllers; import org.softwire.training.cinemagic.exceptions.NotFoundException; import org.softwire.training.cinemagic.models.Cinema; import org.softwire.training.cinemagic.models.Showing; import org.softwire.training.cinemagic.services.CinemaService; import org.softwire.training.cinemagic.services.ShowingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping(value = "/api/cinemas") public class CinemaController { private final CinemaService cinemaService; private final ShowingService showingService; @Autowired public CinemaController(CinemaService cinemaService, ShowingService showingService) { this.cinemaService = cinemaService; this.showingService = showingService; } @RequestMapping(method = RequestMethod.GET) public List<Cinema> listCinemas() { return cinemaService.list(); } @RequestMapping(method = RequestMethod.GET, value = "/{id}") public Cinema getCinema(@PathVariable Integer id) throws NotFoundException { Cinema cinema = cinemaService.get(id); if (cinema == null) { throw new NotFoundException("Cinema", id); } return cinema; } @RequestMapping(method = RequestMethod.GET, value = "/{id}/showings") public List<Showing> listShowings(@PathVariable Integer id) { return showingService.listCinemaShowings(id); } }
true
126234938da07aac872e2e3a0330acd519bc97ec
Java
TannerJack/Introduction-to-Algorithms-Data-Structures-and-Program-Development
/Lab4/Lab4.java
UTF-8
927
3.75
4
[]
no_license
class Zillion { private int digits[] ; //array of digits public Zillion(int size) { digits = new int[size]; //set digits to size parameter } public void increment() { int length = digits.length; //Length of array int counter = 0; int index = length - 1; //Index in counter while (counter < length) // While within the length of the array { if(digits[index] == 9)//For last digit in index, if equal to 9, set to 0 { digits[index] = 0; index--; //go to next digit in index counter++; } else { digits[index] ++; break; } //int num = Integer.parseInt(digit); } } public String toString() { String numStr = ""; for(int i=0; i<digits.length; i++) { numStr += digits[i]; //adds each element of the array to the string } return numStr; // returns integer array as a string } }
true
0bf6d56432558dd5d7199b1c2beb645af5e7c3c0
Java
fix27/SwingJS-Examples
/src/test/Test_Or.java
UTF-8
757
2.609375
3
[]
no_license
package test; class Test_Or extends Test_ { public static void main(String[] args) { int count = 0; boolean ok = true; ok |= (count++ == 0); ok |= (count++ == 0); System.out.println(count); assert (count == 2); ok = false; ok &= (count++ == 0); ok &= (count++ == 0); System.out.println(count); assert (count == 4); ok = true; ok = ok | (count++ == 0); ok = ok | (count++ == 0); System.out.println(count); assert (count == 6); ok = false; ok = ok & (count++ == 0); ok = ok & (count++ == 0); System.out.println(count); assert (count == 8); ok = false; ok = ok && (count++ == 0); ok = ok && (count++ == 0); System.out.println(count); assert (count == 8); } }
true
9a84ea1fa0a02f229b03bfe9c8ef83bd863fcd7c
Java
dev4love/Weather-Android
/app/src/main/java/cn/lovexiaov/weather/presentation/main/daily/DailyFragment.java
UTF-8
2,020
2.09375
2
[]
no_license
package cn.lovexiaov.weather.presentation.main.daily; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.BindView; import butterknife.ButterKnife; import cn.lovexiaov.weather.R; import cn.lovexiaov.weather.data.remote.model.WeatherInfo; import cn.lovexiaov.weather.presentation.base.BaseFragment; import cn.lovexiaov.weather.presentation.main.RecycleViewDivider; import java.util.List; /** * Created by lovexiaov on 09-13 0013. * Copyright reserved. */ public class DailyFragment extends BaseFragment { @BindView(R.id.rv_daily)RecyclerView recyclerView; private static List<WeatherInfo.DailyForecastBean> dailyForecasts; private static String mTitle; public static DailyFragment newInstance(List<WeatherInfo.DailyForecastBean> dailyForecastList, String title) { dailyForecasts = dailyForecastList; mTitle = title; return new DailyFragment(); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_daily, container, false); ButterKnife.bind(this, view); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initRecyclerView(); } private void initRecyclerView() { //RecyclerView recyclerView = (RecyclerView) getActivity().findViewById(R.id.rv_daily); recyclerView.addItemDecoration( new RecycleViewDivider(getContext(), LinearLayoutManager.HORIZONTAL)); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); recyclerView.setAdapter(new DailyAdapter(getContext(), dailyForecasts)); } @Override public String getTitle() { return mTitle; } }
true
fb72c65e70e53f05fa361a0ff97c6c828bb42215
Java
caojinlin/crm-ssm
/myspring/src/main/java/org/myspring/beans/factory/support/GenericBeanDefinition.java
UTF-8
823
2.234375
2
[]
no_license
package org.myspring.beans.factory.support; import org.myspring.beans.BeanDefinition; public class GenericBeanDefinition implements BeanDefinition { private String id; private String beanClassName; private String scope; public GenericBeanDefinition(String id, String beanClassName) { this.id = id; this.beanClassName = beanClassName; } public String getId() { return id; } public void setId(String id) { this.id = id; } public void setBeanClassName(String beanClassName) { this.beanClassName = beanClassName; } public String getScope() { return scope; } public void setScope(String scope) { this.scope = scope; } public String getBeanClassName() { return this.beanClassName; } }
true
d4d1ec393404b8a206f4e0b64bde0df83ae9749e
Java
kelvinrk/RU-Hungry
/src/com/example/myfood/RestaurantActivity.java
UTF-8
7,373
2.140625
2
[]
no_license
package com.example.myfood; import java.io.InputStream; import java.util.ArrayList; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.utils.MealDBManager; import com.example.utils.StreamTool; import com.example.utils.MyApplication; public class RestaurantActivity extends Activity { private MyApplication myapplication1; private MealDBManager goodsDBManager1; private ImageView ImageView1; // 图像 private TextView TextView1; // 店名 private TextView TextView2; // 地址 private Button Button1; // 预订餐厅 private Button Button2; // 餐厅简介 private Button Button3; // 经典菜品 private Button Button4; // 地图位置 private Button Button5; // 热线电话 private Bundle Bundle1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_canting); myapplication1 = (MyApplication) getApplication(); myapplication1.getInstance().addActivity(this); goodsDBManager1 = new MealDBManager(RestaurantActivity.this); ImageView1 = (ImageView) findViewById(R.id.imageView1); TextView1 = (TextView) findViewById(R.id.textView1); TextView2 = (TextView) findViewById(R.id.textView2); Button1 = (Button) findViewById(R.id.button1); Button2 = (Button) findViewById(R.id.button2); Button3 = (Button) findViewById(R.id.button3); Button4 = (Button) findViewById(R.id.button4); Button5 = (Button) findViewById(R.id.button5); Bundle1 = RestaurantActivity.this.getIntent().getExtras(); ImageView1.setImageBitmap(bitmap(Bundle1.getString("img_url") .toString())); TextView1.setText(Bundle1.getString("title")); TextView2.setText(Bundle1.getString("seo_title")); try { String[] spStr = Bundle1.getString("seo_keywords").toString() .split(","); Button5.setText("Tel: " + spStr[0]); } catch (Exception e) { Button5.setText("Tel: " + Bundle1.getString("seo_keywords").toString()); e.printStackTrace(); } Button1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent Intent1 = new Intent(); Intent1.setClass(RestaurantActivity.this, MenuActivity.class); Bundle Bundle1 = new Bundle(); Bundle1.putString("tg", "1"); Intent1.putExtras(Bundle1); startActivity(Intent1); overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left); } }); /*** * 餐厅简介 */ Button2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent Intent1 = new Intent(); Intent1.setClass(RestaurantActivity.this, ResInfoActivity.class); Bundle bundle_content = new Bundle(); bundle_content.putString("content", Bundle1.getString("content")); Intent1.putExtras(bundle_content); startActivity(Intent1); overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left); } }); /** * 经典菜品 */ Button3.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent Intent1 = new Intent(); Intent1.setClass(RestaurantActivity.this, MenuActivity.class); Bundle Bundle1 = new Bundle(); Bundle1.putString("tg", "0"); Intent1.putExtras(Bundle1); startActivity(Intent1); overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left); } }); Button4.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub qdmap(); } }); Button5.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub calltel(Bundle1.getString("seo_keywords").toString()); } }); } /** * 读取图片 * * @param url * @return */ public Bitmap bitmap(String url) { StreamTool StreamTool1 = new StreamTool(); try { // InputStream isInputStream = StreamTool1.getis(myapplication1 // .getlocalhost() + url); InputStream isInputStream = StreamTool1.getis(url); Bitmap bitmap = BitmapFactory.decodeStream(isInputStream); isInputStream.close(); return bitmap; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 打电话 * * @param tel */ public void calltel(String tel) { try { final String[] spStr = tel.split(","); new AlertDialog.Builder(this).setItems(spStr, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub Intent intent = new Intent( "android.intent.action.CALL", Uri .parse("tel:" + spStr[which])); startActivity(intent); } }).show(); } catch (Exception e) { e.printStackTrace(); } } /** * 启动地图 */ private void qdmap() { ArrayList<String> arrayList = new ArrayList<String>(); if (!"".equals(Bundle1.getString("link_url").toString())) { arrayList.add(Bundle1.getString("link_url").toString() + "," + Bundle1.getString("title").toString() + "," + Bundle1.getString("seo_title").toString()); Intent intent = new Intent(); Bundle bundle = new Bundle(); intent.setClass(RestaurantActivity.this, MapActivity.class); bundle.putStringArrayList("map", arrayList); intent.putExtras(bundle); startActivity(intent); overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left); } else { Toast.makeText(RestaurantActivity.this, "No map postion found...", 1).show(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN && KeyEvent.KEYCODE_BACK == keyCode) { if (goodsDBManager1.query().size() > 0) { new AlertDialog.Builder(RestaurantActivity.this) .setTitle("Caution") .setMessage("Are you sure to Exit? Press Yes will delete all items in your cart.") .setIcon(android.R.drawable.ic_dialog_info) .setPositiveButton("No", null) .setNegativeButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { // 数据获取 ,顺序不要改 myapplication1.settotalgoods("0"); goodsDBManager1.alldelete(); finish(); overridePendingTransition( R.anim.in_from_right, R.anim.out_to_left); } }).show(); return true; } else { finish(); overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left); return true; } } return super.onKeyDown(keyCode, event); } /* * @Override public void onBackPressed() { super.onBackPressed(); * overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left); * finish(); } */ }
true
79fba9c1c46df46d17aa4e85a308be2096e9bd3c
Java
w52ddz/simple_android
/app/src/main/java/com/example/simpleandroidproject/MainActivity.java
UTF-8
2,765
2.328125
2
[]
no_license
package com.example.simpleandroidproject; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.example.simpleandroidproject.activities.LayoutsTest; import com.example.simpleandroidproject.util.PageEntity; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; public class MainActivity extends AppCompatActivity { private ListView listViewLv; private List<PageEntity> list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); setView(); } private void setView() { // 绑定点击事件 listViewLv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { PageEntity pageEntity = list.get(i); if (pageEntity.cls != null) { goNextPage(MainActivity.this, pageEntity.cls); return; } Toast.makeText(getApplicationContext(), ""+pageEntity.name, Toast.LENGTH_SHORT).show(); } }); Intent intent = new Intent(); intent.setClass(getApplicationContext(), LayoutsTest.class); /*listViewLv.setOnItemClickListener((parent, view, position, id) -> Toast.makeText(getApplicationContext(), ""+list.get(position), Toast.LENGTH_SHORT).show() );*/ } public void initView() { listViewLv = findViewById(R.id.list_view_lv); list = new ArrayList<>(); list.add(new PageEntity("数字加减", LayoutsTest.class)); list.add(new PageEntity("数据2")); list.add(new PageEntity("数据3")); final ArrayList<String> nameList = new ArrayList<>(); list.forEach(new Consumer<PageEntity>() { @Override public void accept(PageEntity pageEntity) { nameList.add(pageEntity.name); } }); ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>( getApplicationContext(), android.R.layout.simple_expandable_list_item_1, nameList ); listViewLv.setAdapter(arrayAdapter); } // 跳转页面 public void goNextPage(Context context, Class cls) { Intent intent = new Intent(); intent.setClass(context, cls); startActivity(intent); } }
true
584dd5b8a69951bb2c492185fb6cf1dd7da666e2
Java
VSanchezBarre/Obligatoriojuego2s
/ObligatorioJuegoFinal/src/PackageJuego/Sistema.java
UTF-8
13,526
3.015625
3
[]
no_license
//author Valentin Sanchez Ignacio Pigatto package PackageJuego; import static PackageJuego.JuegoMain.pedirUnIntValidado; import static PackageJuego.Tablero1.*; import java.util.ArrayList; import java.io.*; import java.util.Scanner; public class Sistema implements Serializable { private ArrayList<Jugador> listaJugadores; private ArrayList<Partida> listaPartidas; private ArrayList<Ficha> listaFichas; public Sistema() { this.listaJugadores = new ArrayList<>(); this.listaPartidas = new ArrayList<>(); this.listaFichas = new ArrayList<>(); Ficha rojas = new Ficha("rojo", generarPosicionesAbajoFila(), generarPosicionesAbajoColumnas(),new Partida()); listaFichas.add(rojas); Ficha azules = new Ficha("azul", generarPosicionesArribaFila(), generarPosicionesArribaColumnas(),new Partida()); listaFichas.add(azules); } public void setListaFichas(ArrayList<Ficha> listaFichas) { this.listaFichas = listaFichas; } public ArrayList<Ficha> getListaFichas() { return listaFichas; } public ArrayList<Jugador> getListaJugadores() { return listaJugadores; } public ArrayList<Partida> getListaPartidas() { return listaPartidas; } public void setListaJugadores(ArrayList<Jugador> unalistaJugadores) { this.listaJugadores = unalistaJugadores; } public void setListaPartidas(ArrayList<Partida> unalistaPartidas) { this.listaPartidas = listaPartidas; } public static Jugador[] elegirJugador(Sistema sistema, String color1, String color2) { Jugador[] jugadoresElegidos = new Jugador[3]; ArrayList<Jugador> auxiliar = sistema.getListaJugadores(); System.out.println("Quien sera el jugador " + " " + color1 + " " + "?"); for (int i = 0; i < auxiliar.size(); i++) { System.out.println(" - " + i + " " + auxiliar.get(i)); } int elegido1 = pedirUnIntValidado(0, auxiliar.size() - 1, "Seleccione de la lista un jugador " + " " + color1 + " ", " Jugador no valido, ingrese denuevo"); jugadoresElegidos[1] = auxiliar.get(elegido1); Jugador jugadorRemovido = auxiliar.get(elegido1); auxiliar.remove(auxiliar.get(elegido1)); for (int i = 0; i < auxiliar.size(); i++) { System.out.println(" - " + i + " " + auxiliar.get(i)); } int elegido2 = pedirUnIntValidado(0, auxiliar.size() - 1, "Seleccione de la lista un jugador " + " " + color2 + " ", " Jugador no valido, ingrese denuevo"); jugadoresElegidos[2] = auxiliar.get(elegido2); auxiliar.add(jugadorRemovido); return jugadoresElegidos; } public static int elegirTerminacion() { Scanner in = new Scanner(System.in); System.out.println("METODOS DE TERMINACION"); System.out.println("1- Movimientos totales a eleccion"); System.out.println("2- Alcanzar con una ficha el lado opuesto"); System.out.println("3- Alcanzar con todas las fichas el lado opuesto"); int opcion = pedirUnIntValidado(1, 3, "Eliga un metodo de terminacion", "Valor fuera de rango, intente denuevo"); return opcion; } public static void jugar(Sistema sistema, int unaCantidadFilas, int unaCantidadColumnas) { Jugador[] jugadoresElegidos = elegirJugador(sistema, "rojo", "azul"); Jugador jugadorRojo = jugadoresElegidos[1]; Jugador jugadorAzul = jugadoresElegidos[2]; int[][] tablero = crearTableroPred(unaCantidadFilas, unaCantidadColumnas); int opcion = elegirTerminacion(); Partida partida = new Partida(jugadorRojo, jugadorAzul); Ficha rojas = new Ficha("rojo", generarPosicionesAbajoFila(), generarPosicionesAbajoColumnas(),partida); sistema.getListaFichas().add(rojas); Ficha azules = new Ficha("azul", generarPosicionesArribaFila(), generarPosicionesArribaColumnas(),partida); sistema.getListaFichas().add(azules); jugadorRojo.setFichasJugador(rojas); jugadorAzul.setFichasJugador(azules); int ganador = 0; Jugador jugadorGanador = new Jugador(); boolean ver = false; if (opcion == 1) { System.out.println("Con cuantos movimientos desea jugar?"); Scanner in = new Scanner(System.in); int maximo = in.nextInt(); int contador = 0; boolean salir = false; while (contador < maximo && !salir) { imprimir(tablero, ver); Posibles unPosibles = movimiento(tablero, azules.getPosicionesi(), azules.getPosicionesj(), 0, rojas.getPosicionesi(), rojas.getPosicionesj(), rojas, partida, ver); salir = unPosibles.getEsPosible(); tablero = unPosibles.getMatriz(); ver = unPosibles.getVer(); contador++; if (contador < maximo && !salir) { imprimir(tablero, ver); Posibles unPosible2 = movimiento(tablero, rojas.getPosicionesi(), rojas.getPosicionesj(), 1, azules.getPosicionesi(), azules.getPosicionesj(), azules, partida, ver); tablero = unPosible2.getMatriz(); salir = unPosible2.getEsPosible(); ver = unPosible2.getVer(); contador++; } } jugadorGanador = ganador(jugadorRojo, jugadorAzul, 1, tablero); } if (opcion == 2) { boolean nopaso = true; boolean seguir = true; while (nopaso) { imprimir(tablero, ver); Posibles esPosible = movimiento(tablero, rojas.getPosicionesi(), rojas.getPosicionesj(), 1, azules.getPosicionesi(), azules.getPosicionesj(), azules, partida, ver); tablero = esPosible.getMatriz(); ver = esPosible.getVer(); nopaso = verificarPaso(tablero, jugadorRojo, jugadorAzul); if (!nopaso) { jugadorGanador = jugadorRojo; } imprimir(tablero, ver); seguir = nopaso; if (seguir) { Posibles esPosible2 = movimiento(tablero, azules.getPosicionesi(), azules.getPosicionesj(), 0, rojas.getPosicionesi(), rojas.getPosicionesj(), rojas, partida, ver); tablero = esPosible2.getMatriz(); ver = esPosible2.getVer(); nopaso = verificarPaso(tablero, jugadorRojo, jugadorAzul); } if (!nopaso) { jugadorGanador = jugadorAzul; } } } if (opcion == 3) { boolean paso = false; boolean seguir = false; while (!paso && !seguir) { int rojaspasadas = 0; int azulespasadas = 0; imprimir(tablero, ver); Posibles esPosible = movimiento(tablero, rojas.getPosicionesi(), rojas.getPosicionesj(), 1, azules.getPosicionesi(), azules.getPosicionesj(), azules, partida, ver); tablero = esPosible.getMatriz(); seguir = esPosible.getEsPosible(); ver = esPosible.getVer(); imprimir(tablero, ver); jugadorGanador = ganador(jugadorRojo, jugadorAzul, 3, tablero); if (!seguir) { Posibles esPosible2 = movimiento(tablero, azules.getPosicionesi(), azules.getPosicionesj(), 0, rojas.getPosicionesi(), rojas.getPosicionesj(), rojas, partida, ver); tablero = esPosible2.getMatriz(); seguir = esPosible2.getEsPosible(); ver = esPosible2.getVer(); jugadorGanador = ganador(jugadorRojo, jugadorAzul, 3, tablero); imprimir(tablero, ver); } for (int i = 1; i < 9; i++) { int[] posicionesrojas = recorrerMatrizValida(tablero, jugadorAzul.getFichasJugador().getPosicionesi(), jugadorAzul.getFichasJugador().getPosicionesj(), i); int[] posicionesazules = recorrerMatrizValida(tablero, jugadorRojo.getFichasJugador().getPosicionesi(), jugadorRojo.getFichasJugador().getPosicionesj(), i); if (posicionesrojas[0] <= 3) { rojaspasadas++; } if (posicionesazules[0] > 3) { azulespasadas++; } } if (rojaspasadas == 8) { jugadorGanador = jugadorRojo; paso = true; } if (azulespasadas == 8) { jugadorGanador = jugadorAzul; paso = true; } } } System.out.println(" La partida acabo "); if (!jugadorGanador.getAlias().equals("Empate")) { System.out.println(" El ganador es : " + " " + jugadorGanador); if (jugadorGanador.getAlias().equals(jugadorRojo.getAlias())) { int partidasGanadas = jugadorRojo.getPartidasGanadas(); jugadorRojo.setPartidasGanadas(partidasGanadas + 1); } else { int partidasGanadas = jugadorAzul.getPartidasGanadas(); jugadorAzul.setPartidasGanadas(partidasGanadas + 1); } } else { System.out.println("La partida acabo en empate! "); } System.out.println(" GRACIAS POR JUGAR!"); sistema.getListaPartidas().add(partida); } public static String pedirUnString(String textoInstruccion) { System.out.println(textoInstruccion); Scanner scan = new Scanner(System.in); return scan.nextLine(); } // Metodo para agregar un jugador al sistema, corrobora que no hayan dos con el mismo alias public static void altaJugador(Sistema system) { String nombre = pedirUnString("Ingrese el nombre del jugador :"); String alias = pedirUnString("Ingrese el alias del jugador:"); int edad = pedirUnIntValidado(0, 100, "Ingrese la edad del Jugador :", "Edad incorrecta (0-100) Ingrese nuevamente :"); while (system.existeAlias(alias)) { System.out.println("---Ya existe un Jugador con Dicho Alias!---"); alias = pedirUnString("Ingrese Nuevamente el alias :"); } system.agregarJugador(nombre, alias, edad, 0, new Ficha()); System.out.println("\nJugador Agregado con Exito!"); } /* public static void historial(Sistema sistema) { boolean vacia; vacia = sistema.getListaFichas().isEmpty() && sistema.getListaPartidas().isEmpty(); if (!vacia) { boolean fichasVacias = false; int[][] tablero = crearTableroPred(8, 9); // Partida elegida = partidas.get(pedirUnIntValidado(0, partidas.size(), "Elegir una de las partidas", "Partida no valida, ingrese de nuevo")); System.out.println("Partida elegida" + elegida); imprimir(tablero, false); if (!elegida.getListaMovimientos().isEmpty()) { System.out.println("Movimientos de la partida, presione enter para mostrar cada movimiento"); for (int i = 0; i < elegida.getListaMovimientos().size(); i++) { System.out.println("Movimiento numero" + i + 1); // tablero = movimientoParm(tablero, elegida, rojas, azules); } System.out.println("Todos los movimientos mostrados"); } else { System.out.println("No hay movimientos para mostrar"); } } else { System.out.println("No hay partidas en su historial!"); } } //*/ public static void imprimirRanking(Sistema unSistema) { boolean vacia = unSistema.getListaJugadores().isEmpty(); if (!vacia) { for (int i = 0; i < unSistema.getListaJugadores().size(); i++) { System.out.println(unSistema.getListaJugadores().get(i)); } } else { System.out.println("No hay jugadores registrados!"); } } public void agregarJugador(String nombre, String alias, int edad, int partidasGanadas, Ficha fichas) { Jugador jugador = new Jugador(nombre, alias, edad, partidasGanadas, fichas); if (!alias.equals("Empate")) { listaJugadores.add(jugador); } } public void agregarJugador(Jugador unJugador) { if (!unJugador.getAlias().equals("Empate") && !this.existeAlias(unJugador.getAlias())) { listaJugadores.add(unJugador); } } public boolean existeAlias(String alias) { Jugador auxPlayer = new Jugador(); auxPlayer.setAlias(alias); return this.getListaJugadores().contains(auxPlayer); } public Jugador traerJugador(String alias) { Jugador unJugador = new Jugador(); unJugador.setAlias(alias); for (Jugador p : listaJugadores) { if (p.equals(unJugador)) { unJugador = p; break; } } return unJugador; } }
true
0856f0e3973b1d3906cdd08b05f0c0290c58958f
Java
dennisvoliver/minecraft
/net/minecraft/command/argument/GameProfileArgumentType.java
UTF-8
5,102
2.046875
2
[]
no_license
package net.minecraft.command.argument; import com.google.common.collect.Lists; import com.mojang.authlib.GameProfile; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.arguments.ArgumentType; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import com.mojang.brigadier.suggestion.Suggestions; import com.mojang.brigadier.suggestion.SuggestionsBuilder; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.concurrent.CompletableFuture; import net.minecraft.command.CommandSource; import net.minecraft.command.EntitySelector; import net.minecraft.command.EntitySelectorReader; import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.text.TranslatableText; public class GameProfileArgumentType implements ArgumentType<GameProfileArgumentType.GameProfileArgument> { private static final Collection<String> EXAMPLES = Arrays.asList("Player", "0123", "dd12be42-52a9-4a91-a8a1-11c01849e498", "@e"); public static final SimpleCommandExceptionType UNKNOWN_PLAYER_EXCEPTION = new SimpleCommandExceptionType(new TranslatableText("argument.player.unknown")); public static Collection<GameProfile> getProfileArgument(CommandContext<ServerCommandSource> commandContext, String string) throws CommandSyntaxException { return ((GameProfileArgumentType.GameProfileArgument)commandContext.getArgument(string, GameProfileArgumentType.GameProfileArgument.class)).getNames((ServerCommandSource)commandContext.getSource()); } public static GameProfileArgumentType gameProfile() { return new GameProfileArgumentType(); } public GameProfileArgumentType.GameProfileArgument parse(StringReader stringReader) throws CommandSyntaxException { if (stringReader.canRead() && stringReader.peek() == '@') { EntitySelectorReader entitySelectorReader = new EntitySelectorReader(stringReader); EntitySelector entitySelector = entitySelectorReader.read(); if (entitySelector.includesNonPlayers()) { throw EntityArgumentType.PLAYER_SELECTOR_HAS_ENTITIES_EXCEPTION.create(); } else { return new GameProfileArgumentType.SelectorBacked(entitySelector); } } else { int i = stringReader.getCursor(); while(stringReader.canRead() && stringReader.peek() != ' ') { stringReader.skip(); } String string = stringReader.getString().substring(i, stringReader.getCursor()); return (serverCommandSource) -> { GameProfile gameProfile = serverCommandSource.getMinecraftServer().getUserCache().findByName(string); if (gameProfile == null) { throw UNKNOWN_PLAYER_EXCEPTION.create(); } else { return Collections.singleton(gameProfile); } }; } } public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> context, SuggestionsBuilder builder) { if (context.getSource() instanceof CommandSource) { StringReader stringReader = new StringReader(builder.getInput()); stringReader.setCursor(builder.getStart()); EntitySelectorReader entitySelectorReader = new EntitySelectorReader(stringReader); try { entitySelectorReader.read(); } catch (CommandSyntaxException var6) { } return entitySelectorReader.listSuggestions(builder, (suggestionsBuilder) -> { CommandSource.suggestMatching((Iterable)((CommandSource)context.getSource()).getPlayerNames(), suggestionsBuilder); }); } else { return Suggestions.empty(); } } public Collection<String> getExamples() { return EXAMPLES; } public static class SelectorBacked implements GameProfileArgumentType.GameProfileArgument { private final EntitySelector selector; public SelectorBacked(EntitySelector entitySelector) { this.selector = entitySelector; } public Collection<GameProfile> getNames(ServerCommandSource serverCommandSource) throws CommandSyntaxException { List<ServerPlayerEntity> list = this.selector.getPlayers(serverCommandSource); if (list.isEmpty()) { throw EntityArgumentType.PLAYER_NOT_FOUND_EXCEPTION.create(); } else { List<GameProfile> list2 = Lists.newArrayList(); Iterator var4 = list.iterator(); while(var4.hasNext()) { ServerPlayerEntity serverPlayerEntity = (ServerPlayerEntity)var4.next(); list2.add(serverPlayerEntity.getGameProfile()); } return list2; } } } @FunctionalInterface public interface GameProfileArgument { Collection<GameProfile> getNames(ServerCommandSource serverCommandSource) throws CommandSyntaxException; } }
true
22b21cda3c12a3f981c9c5cee22d6ab810266382
Java
Krasnyanskiy/cassandra-playground
/cassandra-basic/src/main/java/il/arri/cassandra/playground/model/User.java
UTF-8
253
1.765625
2
[]
no_license
package il.arri.cassandra.playground.model; import lombok.Data; /** * @author Arri Goldberg */ @Data public class User { private String id; private String firstName; private String lastName; private Integer age; private String email; }
true