file_id
stringlengths
4
9
content
stringlengths
146
15.9k
repo
stringlengths
9
113
path
stringlengths
6
76
token_length
int64
34
3.46k
original_comment
stringlengths
14
2.81k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
excluded
bool
1 class
file-tokens-Qwen/Qwen2-7B
int64
30
3.35k
comment-tokens-Qwen/Qwen2-7B
int64
3
624
file-tokens-bigcode/starcoder2-7b
int64
34
3.46k
comment-tokens-bigcode/starcoder2-7b
int64
3
696
file-tokens-google/codegemma-7b
int64
36
3.76k
comment-tokens-google/codegemma-7b
int64
3
684
file-tokens-ibm-granite/granite-8b-code-base
int64
34
3.46k
comment-tokens-ibm-granite/granite-8b-code-base
int64
3
696
file-tokens-meta-llama/CodeLlama-7b-hf
int64
36
4.12k
comment-tokens-meta-llama/CodeLlama-7b-hf
int64
3
749
excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool
2 classes
excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool
2 classes
excluded-based-on-tokenizer-google/codegemma-7b
bool
2 classes
excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool
2 classes
excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool
2 classes
include-for-inference
bool
2 classes
224814_1
package library.users; import static app.Constants.PREMIUM_CREDIT; import static app.monetization.subscription.UserPremiumState.FREE; import app.audio.player.AudioPlayer; import app.helpers.ConnectionStatus; import app.helpers.UserType; import app.history.History; import app.io.nodes.input.InputNode; import app.monetization.Monetization; import app.monetization.payment.PremiumPaymentStrategy; import app.monetization.subscription.PremiumHistory; import app.monetization.subscription.UserPremiumState; import app.notifications.Notification; import app.notifications.observer.Observer; import app.notifications.observer.Subject; import app.pagination.Page; import app.pagination.PageHistory; import app.pagination.concretepages.ArtistPage; import app.pagination.concretepages.HostPage; import app.pagination.enums.PageType; import app.pagination.factory.PageFactory; import app.recommendations.Recommendations; import app.searchbar.SearchBar; import app.searchbar.SearchType; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.ArrayList; import java.util.List; import library.Library; import library.entities.Announcement; import library.entities.Event; import library.entities.Merch; import library.entities.audio.audio.collections.Album; import library.entities.audio.audio.collections.Playlist; import library.entities.audio.audio.collections.Podcast; import library.entities.audio.audioFiles.Song; import lombok.Getter; import lombok.Setter; /** Represents a User in the music player application. */ @Getter @Setter public final class User implements Subject, Observer { private String username; private int age; private String city; @JsonIgnore private SearchBar searchBar; @JsonIgnore private AudioPlayer audioPlayer; @JsonIgnore private List<Song> likedSongs; @JsonIgnore private List<Playlist> ownedPlaylists; @JsonIgnore private List<Playlist> followedPlaylists; @JsonIgnore private ConnectionStatus connectionStatus; @JsonIgnore private UserType userType; @JsonIgnore private Page currentPage; @JsonIgnore private List<Event> events; @JsonIgnore private List<Merch> merch; @JsonIgnore private List<Announcement> announcements; @JsonIgnore private long addOnPlatformTimestamp; @JsonIgnore private History history; @JsonIgnore private Monetization monetization; @JsonIgnore private List<Merch> boughtMerch; @JsonIgnore private Recommendations recommendations; @JsonIgnore private PageHistory pageHistory; @JsonIgnore private List<Observer> observers; @JsonIgnore private List<User> subscribedUsers; @JsonIgnore private List<Notification> notifications; @JsonIgnore private PremiumHistory premiumHistory; public User() { this.setSearchBar(new SearchBar()); this.setAudioPlayer(new AudioPlayer()); getAudioPlayer().setOwner(this); this.setLikedSongs(new ArrayList<>()); this.setOwnedPlaylists(new ArrayList<>()); this.setFollowedPlaylists(new ArrayList<>()); this.setConnectionStatus(ConnectionStatus.ONLINE); this.setUserType(UserType.NORMAL); this.setHistory(new History()); this.setMonetization(new Monetization()); this.setBoughtMerch(new ArrayList<>()); this.setRecommendations(new Recommendations()); this.setPageHistory(new PageHistory()); this.setObservers(new ArrayList<>()); this.setSubscribedUsers(new ArrayList<>()); this.setNotifications(new ArrayList<>()); this.setPremiumHistory(new PremiumHistory()); changePage(PageType.HOME_PAGE, true); } public User(final InputNode command) { this.setUsername(command.getUsername()); this.setAge(command.getAge()); this.setCity(command.getCity()); this.setSearchBar(new SearchBar()); this.setAudioPlayer(new AudioPlayer()); getAudioPlayer().setOwner(this); this.setLikedSongs(new ArrayList<>()); this.setOwnedPlaylists(new ArrayList<>()); this.setFollowedPlaylists(new ArrayList<>()); this.setHistory(new History()); this.setMonetization(new Monetization()); this.setBoughtMerch(new ArrayList<>()); this.setRecommendations(new Recommendations()); this.setPageHistory(new PageHistory()); this.setObservers(new ArrayList<>()); this.setSubscribedUsers(new ArrayList<>()); this.setNotifications(new ArrayList<>()); this.setPremiumHistory(new PremiumHistory(command.getTimestamp())); this.setConnectionStatus(ConnectionStatus.ONLINE); this.setAddOnPlatformTimestamp(command.getTimestamp()); switch (command.getType()) { case "user": this.setUserType(UserType.NORMAL); changePage(PageType.HOME_PAGE, true); break; case "artist": this.setUserType(UserType.ARTIST); this.setEvents(new ArrayList<>()); this.setMerch(new ArrayList<>()); this.changePage(PageType.ARTIST_PAGE, true); ((ArtistPage) this.getCurrentPage()).setArtistName(getUsername()); break; case "host": this.setUserType(UserType.HOST); this.changePage(PageType.HOST_PAGE, true); this.setAnnouncements(new ArrayList<>()); ((HostPage) this.getCurrentPage()).setHostName(getUsername()); break; default: } } /** * Changes the current page of the user to the specified page type. The page type is used to * create a new page using the PageFactory. The new page is then set as the current page of the * user. * * @param type The type of the page to be set as the current page. */ public void changePage(final PageType type, final boolean addToHistory) { Page newPage = PageFactory.createPage(type); if (type == PageType.HOST_PAGE) { String hostName = null; if (getAudioPlayer().hasLoadedTrack() && getAudioPlayer().getLoadedTrack().getType() == SearchType.PODCAST) { hostName = ((Podcast) getAudioPlayer().getLoadedTrack()).getOwner(); } ((HostPage) newPage).setHostName(hostName); } else if (type == PageType.ARTIST_PAGE) { String artistName = null; if (getAudioPlayer().hasLoadedTrack() && getAudioPlayer().getLoadedTrack().getType() == SearchType.ALBUM) { artistName = ((Podcast) getAudioPlayer().getLoadedTrack()).getOwner(); } ((ArtistPage) newPage).setArtistName(artistName); } if (addToHistory) { pageHistory.addPage(newPage); } this.setCurrentPage(newPage); } /** * Changes the current page of the user to the specified page. The provided page is directly set * as the current page of the user. * * @param newPage The page to be set as the current page. */ public void changePage(final Page newPage, final boolean addToHistory) { this.setCurrentPage(newPage); if (addToHistory) { pageHistory.addPage(newPage); } } /** * Retrieves an announcement by its name from the list of announcements of the user. Iterates over * the list of announcements and returns the first announcement that matches the provided name. If * no announcement is found with the provided name, returns null. * * @param name The name of the announcement to be retrieved. * @return The announcement with the provided name, or null if no such announcement is found. */ public Announcement getAnnouncementByName(final String name) { for (Announcement announcement : this.getAnnouncements()) { if (announcement.getName().equals(name)) { return announcement; } } return null; } /** * Retrieves an event by its name from the list of events of the user. Iterates over the list of * events and returns the first event that matches the provided name. If no event is found with * the provided name, returns null. * * @param name The name of the event to be retrieved. * @return The event with the provided name, or null if no such event is found. */ public Event getEventByName(final String name) { for (Event event : this.getEvents()) { if (event.getName().equals(name)) { return event; } } return null; } /** * Retrieves a Merch object by its name from the list of merch of the user. Iterates over the list * of merch and returns the first merch that matches the provided name. If no merch is found with * the provided name, returns null. * * @param name The name of the merch to be retrieved. * @return The merch with the provided name, or null if no such merch is found. */ public Merch getMerchByName(final String name) { for (Merch currentMerch : this.getMerch()) { if (currentMerch.getName().equals(name)) { return currentMerch; } } return null; } /** * Retrieves a list of Album objects owned by a specific user. This method iterates over all the * albums in the library and adds to the list those that are owned by the user. * * @return A list of Album objects owned by the user. */ public List<Album> getAlbums() { List<Album> albums = new ArrayList<>(); for (Album album : Library.getInstance().getAlbums()) { if (album.getOwner().equals(this.getUsername())) { albums.add(album); } } return albums; } /** * Checks if the user owns an album with the specified name. This method iterates over all the * albums owned by the user and returns true if an album with the provided name is found. * * @param albumName The name of the album to search for. * @return True if the user owns an album with the specified name, false otherwise. */ public boolean hasAlbum(final String albumName) { List<Album> albums = getAlbums(); for (Album album : albums) { if (album.getName().equals(albumName)) { return true; } } return false; } @Override public void addObserver(final Observer observer) { getObservers().add(observer); } @Override public void removeObserver(final Observer observer) { getObservers().remove(observer); } @Override public void notifyObservers(final Notification notification) { for (Observer observer : observers) { observer.update(notification); } } @Override public void update(final Notification notification) { getNotifications().add(notification); } public UserPremiumState getPremiumState() { return getPremiumHistory().getCurrentState(); } /** * Toggles the premium state of the user. If the user is currently a free user, their state is * changed to premium. If the user is currently a premium user, their state is changed to free, * and a payment is made using the PremiumPaymentStrategy. * * @param currentTimestamp The current timestamp, used to record when the state change occurred. */ public void togglePremiumState(final long currentTimestamp) { if (getPremiumState() == FREE) { getPremiumHistory().addState(UserPremiumState.PREMIUM, currentTimestamp); } else { getPremiumHistory().addState(UserPremiumState.FREE, currentTimestamp); new PremiumPaymentStrategy().pay(this, PREMIUM_CREDIT); } } }
Robert2003/GlobalWaves
src/library/users/User.java
2,750
/** * Changes the current page of the user to the specified page type. The page type is used to * create a new page using the PageFactory. The new page is then set as the current page of the * user. * * @param type The type of the page to be set as the current page. */
block_comment
en
false
2,409
73
2,750
71
2,844
77
2,750
71
3,234
78
false
false
false
false
false
true
225768_1
/* A Naive recursive implementation of LCS problem in java*/ public class LongestCommonSubsequence { /* Returns length of LCS for X[0..m-1], Y[0..n-1] */ int lcs(char[] X, char[] Y, int m, int n) { if (m == 0 || n == 0) return 0; if (X[m - 1] == Y[n - 1]) return 1 + lcs(X, Y, m - 1, n - 1); else return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); } /* Utility function to get max of 2 integers */ int max(int a, int b) { return (a > b) ? a : b; } public static void main(String[] args) { LongestCommonSubsequence lcs = new LongestCommonSubsequence(); String s1 = "AGGTAB"; String s2 = "GXTXAYB"; char[] X = s1.toCharArray(); char[] Y = s2.toCharArray(); int m = X.length; int n = Y.length; System.out.println("Length of LCS is" + " " + lcs.lcs(X, Y, m, n)); } }
MaintanerProMax/HacktoberFest2022
LCS.java
334
/* Returns length of LCS for X[0..m-1], Y[0..n-1] */
block_comment
en
false
332
23
334
24
378
23
334
24
427
24
false
false
false
false
false
true
226155_0
import java.util.*; public class ExactKCenter { private int[][] distances; private int numVertices; private int k; private int minMaxDistance; private int[] bestCenters; public ExactKCenter(int[][] distances, int k) { this.distances = distances; this.numVertices = distances.length; this.k = k; this.minMaxDistance = Integer.MAX_VALUE; this.bestCenters = new int[k]; } public int[] solve(long timeLimitMillis) { Thread solverThread = new Thread(() -> { int[] combination = new int[k]; generateCombinations(combination); }); solverThread.start(); try { solverThread.join(timeLimitMillis); if (solverThread.isAlive()) { solverThread.interrupt(); solverThread.join(); // Indicate that it did not complete within the time limit return new int[] { -1 }; } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return bestCenters; } private void generateCombinations(int[] combination) { int[] indices = new int[k]; for (int i = 0; i < k; i++) { indices[i] = i; } while (indices[0] <= numVertices - k) { if (Thread.currentThread().isInterrupted()) { return; } for (int i = 0; i < k; i++) { combination[i] = indices[i]; } int maxDistance = findMaxDistance(combination); if (maxDistance < minMaxDistance) { minMaxDistance = maxDistance; System.arraycopy(combination, 0, bestCenters, 0, k); } int t = k - 1; while (t != 0 && indices[t] == numVertices - k + t) { t--; } indices[t]++; for (int i = t + 1; i < k; i++) { indices[i] = indices[i - 1] + 1; } } } private int findMaxDistance(int[] centers) { int maxDistance = 0; for (int i = 0; i < numVertices; i++) { int minDistance = Integer.MAX_VALUE; for (int center : centers) { minDistance = Math.min(minDistance, distances[i][center]); } maxDistance = Math.max(maxDistance, minDistance); } return maxDistance; } public static void main(String[] args) { // Example usage int[][] distances = { { 0, 10, 20, 30 }, { 10, 0, 25, 35 }, { 20, 25, 0, 15 }, { 30, 35, 15, 0 } }; int k = 2; ExactKCenter solver = new ExactKCenter(distances, k); int[] centers = solver.solve(5000); // Time limit: 5000 milliseconds (5 seconds) System.out.println(Arrays.toString(centers)); } }
thiagoteixas/TP02
ExactKCenter.java
740
// Indicate that it did not complete within the time limit
line_comment
en
false
693
12
740
12
813
11
740
12
880
12
false
false
false
false
false
true
228919_3
import java.util.*; import java.awt.Point; import java.awt.Dimension; /** A creature evolved from Flytrap with advanced abilities such as vision and memory. <p>Hai Zhou <br>hz1@cs.williams.edu <br>5/1/2011 */ public class TeddyBearBM extends Creature { static private Random r = new Random(); /** Turns left or right with equal probability.*/ public void turn90Random() { switch (r.nextInt(2)) { case 0: turnLeft(); break; case 1: turnRight(); break; } } public void run() { while (true) { Observation obs = look(); if (isEnemy(obs)) { int d = distance(obs.position); if (obs != null && obs.classId == APPLE_CLASS_ID) { moveForward(d - 1); attack(); } else { if (d == 1) { attack(); } else if (obs.direction == getDirection().opposite()) { delay(); } } } else { turn90Random(); } } } public String toString() { return "Miawoo~"; } /** Allows GUI browsers to display your name as author of this creature.*/ public String getAuthorName() { return "Bunny Miaw"; } /** Allows GUI browsers to display information and credits about your creature.*/ public String getDescription() { return "A creature evolved from Flytrap with advanced abilities such as vision and memory."; } }
brodermar/darwin
src/TeddyBearBM.java
398
/** Allows GUI browsers to display information and credits about your creature.*/
block_comment
en
false
342
14
398
13
449
13
398
13
509
16
false
false
false
false
false
true
228968_2
/* * Copyright 2002-2018 the original author or authors. * * 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 org.springframework.web.servlet.tags; import jakarta.servlet.jsp.JspException; import jakarta.servlet.jsp.tagext.BodyTagSupport; import org.springframework.lang.Nullable; /** * The {@code <param>} tag collects name-value parameters and passes them to a * {@link ParamAware} ancestor in the tag hierarchy. * * <p>This tag must be nested under a param aware tag. * * <table> * <caption>Attribute Summary</caption> * <thead> * <tr> * <th>Attribute</th> * <th>Required?</th> * <th>Runtime Expression?</th> * <th>Description</th> * </tr> * </thead> * <tbody> * <tr> * <td>name</td> * <td>true</td> * <td>true</td> * <td>The name of the parameter.</td> * </tr> * <tr> * <td>value</td> * <td>false</td> * <td>true</td> * <td>The value of the parameter.</td> * </tr> * </tbody> * </table> * * @author Scott Andrews * @author Nicholas Williams * @since 3.0 * @see Param * @see UrlTag */ @SuppressWarnings("serial") public class ParamTag extends BodyTagSupport { private String name = ""; @Nullable private String value; private boolean valueSet; /** * Set the name of the parameter (required). */ public void setName(String name) { this.name = name; } /** * Set the value of the parameter (optional). */ public void setValue(String value) { this.value = value; this.valueSet = true; } @Override public int doEndTag() throws JspException { Param param = new Param(); param.setName(this.name); if (this.valueSet) { param.setValue(this.value); } else if (getBodyContent() != null) { // Get the value from the tag body param.setValue(getBodyContent().getString().trim()); } // Find a param aware ancestor ParamAware paramAwareTag = (ParamAware) findAncestorWithClass(this, ParamAware.class); if (paramAwareTag == null) { throw new JspException("The param tag must be a descendant of a tag that supports parameters"); } paramAwareTag.addParam(param); return EVAL_PAGE; } @Override public void release() { super.release(); this.name = ""; this.value = null; this.valueSet = false; } }
chiluen/springframework-webmvc-servlet
tags/ParamTag.java
850
/** * Set the name of the parameter (required). */
block_comment
en
false
701
14
850
14
788
16
850
14
943
16
false
false
false
false
false
true
230492_3
package org.springframework.boot.autoconfigure.jackson; import java.lang.reflect.Field; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.cfg.ConstructorDetector; import com.fasterxml.jackson.module.paramnames.ParameterNamesModule; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.jackson.JacksonProperties.ConstructorDetectorStrategy; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.jackson.JsonComponentModule; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Scope; import org.springframework.core.Ordered; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; /** * Auto configuration for Jackson. The following auto-configuration will get applied: * <ul> * <li>an {@link ObjectMapper} in case none is already configured.</li> * <li>a {@link Jackson2ObjectMapperBuilder} in case none is already configured.</li> * <li>auto-registration for all {@link Module} beans with all {@link ObjectMapper} beans * (including the defaulted ones).</li> * </ul> * * @author Oliver Gierke * @author Andy Wilkinson * @author Marcel Overdijk * @author Sebastien Deleuze * @author Johannes Edmeier * @author Phillip Webb * @author Eddú Meléndez * @since 1.1.0 */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass(ObjectMapper.class) public class JacksonAutoConfiguration { private static final Map<?, Boolean> FEATURE_DEFAULTS; static { Map<Object, Boolean> featureDefaults = new HashMap<>(); featureDefaults.put(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); featureDefaults.put(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS, false); FEATURE_DEFAULTS = Collections.unmodifiableMap(featureDefaults); } @Bean public JsonComponentModule jsonComponentModule() { return new JsonComponentModule(); } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(Jackson2ObjectMapperBuilder.class) static class JacksonObjectMapperConfiguration { @Bean @Primary @ConditionalOnMissingBean ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) { return builder.createXmlMapper(false).build(); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(ParameterNamesModule.class) static class ParameterNamesModuleConfiguration { @Bean @ConditionalOnMissingBean ParameterNamesModule parameterNamesModule() { return new ParameterNamesModule(JsonCreator.Mode.DEFAULT); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(Jackson2ObjectMapperBuilder.class) static class JacksonObjectMapperBuilderConfiguration { @Bean @Scope("prototype") @ConditionalOnMissingBean Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder(ApplicationContext applicationContext, List<Jackson2ObjectMapperBuilderCustomizer> customizers) { Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); builder.applicationContext(applicationContext); customize(builder, customizers); return builder; } private void customize(Jackson2ObjectMapperBuilder builder, List<Jackson2ObjectMapperBuilderCustomizer> customizers) { for (Jackson2ObjectMapperBuilderCustomizer customizer : customizers) { customizer.customize(builder); } } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(Jackson2ObjectMapperBuilder.class) @EnableConfigurationProperties(JacksonProperties.class) static class Jackson2ObjectMapperBuilderCustomizerConfiguration { @Bean StandardJackson2ObjectMapperBuilderCustomizer standardJacksonObjectMapperBuilderCustomizer( ApplicationContext applicationContext, JacksonProperties jacksonProperties) { return new StandardJackson2ObjectMapperBuilderCustomizer(applicationContext, jacksonProperties); } static final class StandardJackson2ObjectMapperBuilderCustomizer implements Jackson2ObjectMapperBuilderCustomizer, Ordered { private final ApplicationContext applicationContext; private final JacksonProperties jacksonProperties; StandardJackson2ObjectMapperBuilderCustomizer(ApplicationContext applicationContext, JacksonProperties jacksonProperties) { this.applicationContext = applicationContext; this.jacksonProperties = jacksonProperties; } @Override public int getOrder() { return 0; } @Override public void customize(Jackson2ObjectMapperBuilder builder) { if (this.jacksonProperties.getDefaultPropertyInclusion() != null) { builder.serializationInclusion(this.jacksonProperties.getDefaultPropertyInclusion()); } if (this.jacksonProperties.getTimeZone() != null) { builder.timeZone(this.jacksonProperties.getTimeZone()); } configureFeatures(builder, FEATURE_DEFAULTS); configureVisibility(builder, this.jacksonProperties.getVisibility()); configureFeatures(builder, this.jacksonProperties.getDeserialization()); configureFeatures(builder, this.jacksonProperties.getSerialization()); configureFeatures(builder, this.jacksonProperties.getMapper()); configureFeatures(builder, this.jacksonProperties.getParser()); configureFeatures(builder, this.jacksonProperties.getGenerator()); configureDateFormat(builder); configurePropertyNamingStrategy(builder); configureModules(builder); configureLocale(builder); configureDefaultLeniency(builder); configureConstructorDetector(builder); } private void configureFeatures(Jackson2ObjectMapperBuilder builder, Map<?, Boolean> features) { features.forEach((feature, value) -> { if (value != null) { if (value) { builder.featuresToEnable(feature); } else { builder.featuresToDisable(feature); } } }); } private void configureVisibility(Jackson2ObjectMapperBuilder builder, Map<PropertyAccessor, JsonAutoDetect.Visibility> visibilities) { visibilities.forEach(builder::visibility); } private void configureDateFormat(Jackson2ObjectMapperBuilder builder) { // We support a fully qualified class name extending DateFormat or a date // pattern string value String dateFormat = this.jacksonProperties.getDateFormat(); if (dateFormat != null) { try { Class<?> dateFormatClass = ClassUtils.forName(dateFormat, null); builder.dateFormat((DateFormat) BeanUtils.instantiateClass(dateFormatClass)); } catch (ClassNotFoundException ex) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat); // Since Jackson 2.6.3 we always need to set a TimeZone (see // gh-4170). If none in our properties fallback to the Jackson's // default TimeZone timeZone = this.jacksonProperties.getTimeZone(); if (timeZone == null) { timeZone = new ObjectMapper().getSerializationConfig().getTimeZone(); } simpleDateFormat.setTimeZone(timeZone); builder.dateFormat(simpleDateFormat); } } } private void configurePropertyNamingStrategy(Jackson2ObjectMapperBuilder builder) { // We support a fully qualified class name extending Jackson's // PropertyNamingStrategy or a string value corresponding to the constant // names in PropertyNamingStrategy which hold default provided // implementations String strategy = this.jacksonProperties.getPropertyNamingStrategy(); if (strategy != null) { try { configurePropertyNamingStrategyClass(builder, ClassUtils.forName(strategy, null)); } catch (ClassNotFoundException ex) { configurePropertyNamingStrategyField(builder, strategy); } } } private void configurePropertyNamingStrategyClass(Jackson2ObjectMapperBuilder builder, Class<?> propertyNamingStrategyClass) { builder.propertyNamingStrategy( (PropertyNamingStrategy) BeanUtils.instantiateClass(propertyNamingStrategyClass)); } private void configurePropertyNamingStrategyField(Jackson2ObjectMapperBuilder builder, String fieldName) { // Find the field (this way we automatically support new constants // that may be added by Jackson in the future) Field field = findPropertyNamingStrategyField(fieldName); Assert.notNull(field, () -> "Constant named '" + fieldName + "' not found"); try { builder.propertyNamingStrategy((PropertyNamingStrategy) field.get(null)); } catch (Exception ex) { throw new IllegalStateException(ex); } } private Field findPropertyNamingStrategyField(String fieldName) { try { return ReflectionUtils.findField(com.fasterxml.jackson.databind.PropertyNamingStrategies.class, fieldName, PropertyNamingStrategy.class); } catch (NoClassDefFoundError ex) { // Fallback pre Jackson 2.12 return ReflectionUtils.findField(PropertyNamingStrategy.class, fieldName, PropertyNamingStrategy.class); } } private void configureModules(Jackson2ObjectMapperBuilder builder) { Collection<Module> moduleBeans = getBeans(this.applicationContext, Module.class); builder.modulesToInstall(moduleBeans.toArray(new Module[0])); } private void configureLocale(Jackson2ObjectMapperBuilder builder) { Locale locale = this.jacksonProperties.getLocale(); if (locale != null) { builder.locale(locale); } } private void configureDefaultLeniency(Jackson2ObjectMapperBuilder builder) { Boolean defaultLeniency = this.jacksonProperties.getDefaultLeniency(); if (defaultLeniency != null) { builder.postConfigurer((objectMapper) -> objectMapper.setDefaultLeniency(defaultLeniency)); } } private void configureConstructorDetector(Jackson2ObjectMapperBuilder builder) { ConstructorDetectorStrategy strategy = this.jacksonProperties.getConstructorDetector(); if (strategy != null) { builder.postConfigurer((objectMapper) -> { switch (strategy) { case USE_PROPERTIES_BASED: objectMapper.setConstructorDetector(ConstructorDetector.USE_PROPERTIES_BASED); break; case USE_DELEGATING: objectMapper.setConstructorDetector(ConstructorDetector.USE_DELEGATING); break; case EXPLICIT_ONLY: objectMapper.setConstructorDetector(ConstructorDetector.EXPLICIT_ONLY); break; default: objectMapper.setConstructorDetector(ConstructorDetector.DEFAULT); } }); } } private static <T> Collection<T> getBeans(ListableBeanFactory beanFactory, Class<T> type) { return BeanFactoryUtils.beansOfTypeIncludingAncestors(beanFactory, type).values(); } } } }
AnWeber/bluepaint
demo/java.java
2,858
// Since Jackson 2.6.3 we always need to set a TimeZone (see
line_comment
en
false
2,370
18
2,858
20
2,770
19
2,858
20
3,750
19
false
false
false
false
false
true
231246_0
class Solution{ //Function to find the leaders in the array. static ArrayList<Integer> leaders(int arr[], int n){ // Your code here int max=arr[n-1]; ArrayList<Integer> a = new ArrayList<>(); for(int i=n-1;i>=0;i--) { if(max<=arr[i]) { max=arr[i]; a.add(max); } } Collections.reverse(a); return a; } }
KAUSTUBHDUBEY790/Geeksforgeeks-sol
leader in array.java
118
//Function to find the leaders in the array.
line_comment
en
false
100
10
118
11
132
10
118
11
135
10
false
false
false
false
false
true
232356_4
/* * 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 biotracker; /** * Only works for years 1993 - 2023 // updated SA04TS: leap years fixed; works until 2100 * * @author SA02MB */ public class ISO_datestr { private int day; private int month; private int year; private final int[][] monthDays = new int[][]{{1, 31}, {2, 28}, {3, 31}, {4, 30}, {5, 31}, {6, 30}, {7, 31}, {8, 31}, {9, 30}, {10, 31}, {11, 30}, {12, 31}}; public ISO_datestr(int inDay, int inMonth, int inYear) { this.day = inDay; this.month = inMonth; this.year = inYear; monthDays[1][1] = this.isLeapYear() ? 29 : 28; } public ISO_datestr(String dateString) { this.year = Integer.parseInt(dateString.substring(0, 4)); this.month = Integer.parseInt(dateString.substring(4, 6)); this.day = Integer.parseInt(dateString.substring(6, 8)); monthDays[1][1] = this.isLeapYear() ? 29 : 28; } public ISO_datestr(ISO_datestr datestr) { this.year = datestr.getYear(); this.month = datestr.getMonth(); this.day = datestr.getDay(); monthDays[1][1] = this.isLeapYear() ? 29 : 28; } public String getDateStr() { return String.format("%04d", this.year) + String.format("%02d", this.month) + String.format("%02d", this.day); } public int getDateNum() { // date integer with ref point year 1992, well why ever not? int yearDaysTot = (this.year - 1992) * 365; int leapYearDaysTot = (int) Math.floor((float) (this.year - 1992) / 4) + 1; int monthDaysTot = 0; if (this.month > 1) { for (int i = 0; i <= month - 2; i++) { monthDaysTot = monthDaysTot + monthDays[i][1]; } } return yearDaysTot + leapYearDaysTot + monthDaysTot + this.day; } public void addDay() { if (this.day == this.monthDays[this.month - 1][1]) { this.day = 1; if (this.month == 12) { this.month = 1; this.year++; monthDays[1][1] = this.isLeapYear() ? 29 : 28; } else { this.month++; } } else { this.day++; } } public static ISO_datestr getTomorrow(ISO_datestr today) { ISO_datestr tomorrow = new ISO_datestr(today.getDay(), today.getMonth(), today.getYear()); if (tomorrow.day == tomorrow.monthDays[tomorrow.month - 1][1]) { tomorrow.day = 1; if (tomorrow.month == 12) { tomorrow.month = 1; tomorrow.year++; tomorrow.monthDays[1][1] = tomorrow.isLeapYear() ? 29 : 28; } else { tomorrow.month++; } } else { tomorrow.day++; } return tomorrow; } public static ISO_datestr getYesterday(ISO_datestr today) { ISO_datestr yesterday = new ISO_datestr(today.getDay(), today.getMonth(), today.getYear()); // If first of month, need to set day to be last day of previous month if (yesterday.day == 1) { if (yesterday.month == 1) { yesterday.month = 12; yesterday.year--; yesterday.monthDays[1][1] = yesterday.isLeapYear() ? 29 : 28; } else { yesterday.month--; } yesterday.day = yesterday.monthDays[yesterday.month - 1][1]; } else { yesterday.day--; } return yesterday; } public void takeDay() { if (this.day == 1) { if (this.month == 1) { this.month = 12; this.day = this.monthDays[this.month - 1][1]; this.year--; monthDays[1][1] = this.isLeapYear() ? 29 : 28; } else { this.month--; this.day = this.monthDays[this.month][1]; } } else { this.day--; } } public int getYear() { return year; } public int getMonth() { return month; } public int getDay() { return day; } public boolean isLeapYear() { return this.year % 4 == 0; } public boolean isLaterThan(ISO_datestr dateCompare) { return this.getDateNum() > dateCompare.getDateNum(); } /** * work out the date from an integer in format YYYYMMDD - Mike Bedington * method */ public static int[] dateIntParse(int ymd) { double start_ymd_mod = ymd; int startYear = (int) Math.floor(start_ymd_mod / 10000); start_ymd_mod = start_ymd_mod - startYear * 10000; int startMonth = (int) Math.floor(start_ymd_mod / 100); start_ymd_mod = start_ymd_mod - startMonth * 100; int startDay = (int) start_ymd_mod; return new int[]{startDay, startMonth, startYear}; } public static int[] dateIntParse(ISO_datestr datestr) { return new int[]{datestr.getDay(), datestr.getMonth(), datestr.getYear()}; } @Override public String toString() { return this.year + "-" + (this.month < 10 ? "0" : "") + this.month + "-" + (this.day < 10 ? "0" : "") + this.day; } public String toStringShort() { return this.year + (this.month < 10 ? "0" : "") + this.month + (this.day < 10 ? "0" : "") + this.day; } }
Sz-Tim/biotracker
biotracker/ISO_datestr.java
1,678
/** * work out the date from an integer in format YYYYMMDD - Mike Bedington * method */
block_comment
en
false
1,512
26
1,678
26
1,782
27
1,678
26
1,881
30
false
false
false
false
false
true
232562_12
// RobotBuilder Version: 2.0 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc2017.RI3D; import org.usfirst.frc2017.RI3D.commands.*; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * This class is the glue that binds the controls on the physical operator * interface to the commands and command groups that allow control of the robot. */ public class OI { //// CREATING BUTTONS // One type of button is a joystick button which is any button on a joystick. // You create one by telling it which joystick it's on and which button // number it is. // Joystick stick = new Joystick(port); // Button button = new JoystickButton(stick, buttonNumber); // There are a few additional built in buttons you can use. Additionally, // by subclassing Button you can create custom triggers and bind those to // commands the same as any other Button. //// TRIGGERING COMMANDS WITH BUTTONS // Once you have a button, it's trivial to bind it to a button in one of // three ways: // Start the command when the button is pressed and let it run the command // until it is finished as determined by it's isFinished method. // button.whenPressed(new ExampleCommand()); // Run the command while the button is being held down and interrupt it once // the button is released. // button.whileHeld(new ExampleCommand()); // Start the command when the button is released and let it run the command // until it is finished as determined by it's isFinished method. // button.whenReleased(new ExampleCommand()); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public Joystick left; public Joystick right; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public OI() { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS right = new Joystick(0); left = new Joystick(1); // SmartDashboard Buttons SmartDashboard.putData("Autonomous Command", new AutonomousCommand()); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS } // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS public Joystick getLeft() { return left; } public Joystick getRight() { return right; } // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS }
churley862/RI3D
RI3D/OI.java
691
// You create one by telling it which joystick it's on and which button
line_comment
en
false
678
16
689
17
779
17
691
17
942
19
false
false
false
false
false
true
233170_2
import java.util.ArrayList; /** * This class stores all the heroes in this game. */ public class HeroList { private static ArrayList<Hero> list; // List of all the heroes in this game public HeroList() {} private static void setHeroes() { list = new ArrayList<>(); list.add(new Warrior("Neville", 2, 100, 700, 400, 400, 1354, 7)); list.add(new Warrior("Ron", 4, 600, 800, 600, 400, 1204, 8)); list.add(new Warrior("Harry Potter", 7, 750, 850, 400, 600, 2800, 6)); list.add(new Warrior("Hermione", 8, 300, 400, 250, 600, 4000, 9)); list.add(new Warrior("Luna", 5, 300, 600, 400, 350, 1111, 5)); list.add(new Warrior("Albus Dumbledore", 10, 900, 1100, 600, 900, 3821, 10)); list.add(new Sorcerer("Gilderoy Lockhart", 2, 600, 200, 444, 250, 2500, 5)); list.add(new Sorcerer("Remus Lupin", 4, 800, 350, 500, 300, 1900, 6)); list.add(new Sorcerer("Severus Snape", 6, 820, 550, 700, 550, 2800, 6)); list.add(new Sorcerer("Sybill Trelawney", 5, 700, 280, 666, 460, 3000, 7)); list.add(new Sorcerer("Nicolas Flamel", 8, 1200, 200, 1500, 650, 2400, 10)); list.add(new Paladin("Mad-Eye", 5, 500, 700, 850, 250, 2500, 5)); list.add(new Paladin("Filius Flitwick", 4, 430, 650, 750, 350, 1203, 7)); list.add(new Paladin("Horace Slughorn", 4, 300, 800, 640, 200, 3023, 6)); list.add(new Paladin("Quirinus Quirrell", 2, 350, 470, 120, 250, 1111, 5)); list.add(new Paladin("Professor McGonagall", 8, 620, 900, 900, 400, 900, 8)); } public static ArrayList<Hero> getList() { return list; } /* Print the list of all 3 kinds of heroes */ public static void printHeroList() { setHeroes(); // Initialize the ArrayList heroes String name; double hp, strength, dexterity, agility, money, mana; int level, exp; NotificationCenter.heroesInfo(4); // A line to split different kinds of heroes (i.e. warriors/sorcerers/paladins) String splitLine = Colors.YELLOW_BG + Colors.BLACK + "--><-><-><-><-><-><-><-><-><-><-><-><-><-><-><-><-><-><-><-><-><-><-><-><-><-><-><-><-><-><-><-><--" + Colors.RESET + "\n"; String title = "Name HP Level Mana Strength Dexterity Agility Money Exp"; NotificationCenter.heroesInfo(5); System.out.println(title); System.out.print(splitLine); for (int i = 0; i < list.size(); ++i) { if (list.get(i) instanceof Sorcerer && list.get(i - 1) instanceof Warrior) { // If the class type has changed (i.e. from Warrior to Sorcerer), print the title and the split line again NotificationCenter.heroesInfo(6); System.out.println(title); System.out.print(splitLine); } else if (list.get(i) instanceof Paladin && list.get(i - 1) instanceof Sorcerer) { // If the class type has changed (i.e. from Sorcerer to Paladin), print the title and the split line again NotificationCenter.heroesInfo(7); System.out.println(title); System.out.print(splitLine); } name = (i + 1) + ". " + list.get(i).name; hp = list.get(i).hp; level = list.get(i).level; mana = list.get(i).mana; strength = list.get(i).strength; dexterity = list.get(i).dexterity; agility = list.get(i).agility; money = list.get(i).money; exp = list.get(i).exp; System.out.printf("%-25s %-8.0f %-6d %-9.0f %-12.0f %-11.0f %-9.0f %-8.0f %-5d", name, hp, level, mana, strength, dexterity, agility , money, exp); System.out.println(); // Java Reflection implementation if ((i + 1 < list.size()) && (!list.get(i).getClass().getName().equals (list.get(i + 1).getClass().getName()))) { // If the class type has changed, print the split line again System.out.println(splitLine); } } System.out.println(splitLine); } }
Superkakayong/Legends_OO_Design-pattern
HeroList.java
1,593
/* Print the list of all 3 kinds of heroes */
block_comment
en
false
1,408
15
1,593
15
1,560
16
1,593
15
1,703
17
false
false
false
false
false
true
233919_3
import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; /*************************** Diagonal Constant Matrix Shahzore Qureshi ****************************/ public class DCM { public static void main (String[] args) { ArrayList<ArrayList<Integer>> matrix = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> tempRow = new ArrayList<Integer>(); int rowNumber = 0; for(int i = 0; i < args.length; i++) { try { Integer integer = Integer.valueOf(args[i]); tempRow.add(integer); } catch (Exception e) { //If input is not a number, treat the input as an "End of Row" character. matrix.add(rowNumber, tempRow); tempRow = new ArrayList<Integer>(); rowNumber++; } } //Print out matrix for(ArrayList<Integer> r : matrix) { System.out.print("["); for(Integer integer : r) { System.out.print(" " + integer + " "); } System.out.println("]"); } Queue<Integer> queue = new LinkedList<Integer>(); for(int i = 0; i < matrix.size(); i++) { ArrayList<Integer> row = matrix.get(i); for(int j = 0; j < row.size(); j++) { if(i == 0) { //If this is the first row in the matrix, //add integer to queue if it is not at //the end of the row. if(j != row.size() - 1) { queue.add(row.get(j)); //System.out.println("added " + row.get(j) + " to queue"); } } else if(i > 0 && i < matrix.size() - 1) { //If this is a row that is neither first nor last, //and the integer is the first of the row, add it //to the queue. if(j == 0) { queue.add(row.get(j)); //System.out.println("added " + row.get(j) + " to queue"); } else { Integer integer = queue.remove(); if(row.get(j) != integer) { System.out.println("Matrix is not diagonal constant."); return; } if(j != row.size() - 1) { queue.add(integer); } } } else if(i == matrix.size() - 1) { if(j > 0) { Integer integer = queue.remove(); if(row.get(j) != integer) { System.out.println("Matrix is not diagonal constant."); return; } } } } } if(queue.size() == 0) { System.out.println("Matrix is diagonal constant."); } else { System.out.println("Matrix is not diagonal constant."); } } }
shahzore-qureshi/DiagonalConstantMatrix
DCM.java
760
//If this is the first row in the matrix,
line_comment
en
false
631
11
760
11
759
11
760
11
1,028
11
false
false
false
false
false
true
235121_1
/* Copyright 2012 m6d.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.hiveswarm.hive.udf; import org.apache.hadoop.hive.ql.exec.UDFArgumentException; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.udf.generic.GenericUDF; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory.ObjectInspectorOptions; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Writable; public class Rank extends GenericUDF { private long counter; private Object[] previousKey; private ObjectInspector[] ois; private final LongWritable result = new LongWritable(); @Override public Object evaluate(DeferredObject[] currentKey) throws HiveException { if (!sameAsPreviousKey(currentKey)) { this.counter = 0; copyToPreviousKey(currentKey); } result.set(++this.counter); return result.get(); } @Override public String getDisplayString(String[] currentKey) { return "Rank-Udf-Display-String"; } @Override public ObjectInspector initialize(ObjectInspector[] arg0) throws UDFArgumentException { ois=arg0; return PrimitiveObjectInspectorFactory.javaLongObjectInspector; } /** * This will help us copy objects from currrentKey to previousKeyHolder. * * @param currentKey * @throws HiveException */ private void copyToPreviousKey(DeferredObject[] currentKey) throws HiveException { if (currentKey != null) { if (previousKey == null) { previousKey = new Object[currentKey.length]; } for (int index = 0; index < currentKey.length; index++) { if (currentKey[index] == null) { previousKey[index]=null; continue; } previousKey[index]= ObjectInspectorUtils .copyToStandardObject(currentKey[index].get(),this.ois[index]); } } } /** * This will help us compare the currentKey and previousKey objects. * * @param currentKey * @return - true if both are same else false * @throws HiveException */ private boolean sameAsPreviousKey(DeferredObject[] currentKey) throws HiveException { boolean status = false; //if both are null then we can classify as same if (currentKey == null && previousKey == null) { status = true; } //if both are not null and there legnth as well as //individual elements are same then we can classify as same if (currentKey != null && previousKey != null && currentKey.length == previousKey.length) { for (int index = 0; index < currentKey.length; index++) { if (ObjectInspectorUtils.compare(currentKey[index].get(), this.ois[index], previousKey[index], ObjectInspectorFactory.getReflectionObjectInspector(previousKey[index].getClass(), ObjectInspectorOptions.JAVA)) != 0) { return false; } } status = true; } return status; } }
nielubowicz/livingsocial-HiveSwarm
src/Rank.java
944
/** * This will help us copy objects from currrentKey to previousKeyHolder. * * @param currentKey * @throws HiveException */
block_comment
en
false
855
36
944
34
1,005
39
944
34
1,154
41
false
false
false
false
false
true
236014_1
/** * A second, stronger weapons class * * @author Sonia */ public class Laser extends Weapon { // instance variables - replace the example below with your own private int damage; /** * Constructor for objects of class Laser */ public Laser() { destroyedArea = 350; weaponDecorator = new StrongBlast(new WideBlast((new ConcreteBlast()))); damage = 40; } public void act() { super.act(); } // Overide the default damage public int getDamage() { return damage; } }
nguyensjsu/fa19-202-firebirds
Greenfoot/Laser.java
144
// instance variables - replace the example below with your own
line_comment
en
false
134
11
144
11
157
11
144
11
177
11
false
false
false
false
false
true
238505_2
/* * 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 P2; /** * * @author BATIN */ public class ShipTest { /** * @param args the command line arguments */ public static void main(String[] args) { Ship []s1 = new Ship[3]; s1[0]=new Ship("Wisconsin","1991"); s1[1]=new CargoShip(1500,"Jersey","1987"); s1[2]=new Cruise(1001,"Donald","2001"); for (Ship ship : s1) { System.out.println(ship); } } }
batin/JavaBaby
Homeworks/HW4/ShipTest.java
195
/** * @param args the command line arguments */
block_comment
en
false
173
13
195
12
197
14
195
12
214
14
false
false
false
false
false
true
240642_26
/* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (props, 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 Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package models; import javax.persistence.*; import java.util.*; import java.math.BigInteger; import play.Logger; import play.db.jpa.*; import play.data.validation.*; import com.vividsolutions.jts.geom.MultiPolygon; import org.hibernate.annotations.Type; @Entity public class GtfsFeed extends Model implements Cloneable { /** The name of this agency, customer-facing */ @Required public String agencyName; /** The human-readable area description, from Data Exchange, generally */ public String areaDescription; /** The country where this agency operates. */ // TODO: should we use some sort of stable identifier, like internet country code public String country; /** The GTFS Data Exchange ID */ public String dataExchangeId; /** The GTFS Data Exchange URL */ @URL public String dataExchangeUrl; /** The time zone */ public TimeZone timezone; // TODO: on these dates, should they be relative to GTFS Data Exchange or to this site? /** The date added to Data Exchange */ public Date dateAdded; /** The date this feed was last updated */ public Date dateUpdated; /** Is this feed disabled? */ public boolean disabled; /** * Machine readable problem type requiring human review - picked up in the admin interface. */ @Enumerated(EnumType.STRING) public ReviewType review; /** * The URL where this feed may be found. This may be the feed itself, or may be a * developer site (e.g. http://developer.metro.net). */ @URL public String feedBaseUrl; /** * This is the URL to download this feed. Generally it's a GTFS Data Exchange * file URL. */ public String downloadUrl; /** * The URL of the GTFS Realtime feed for this feed, if available. */ @URL @Deprecated public String realtimeUrl; /** * The URLs of the GTFS Realtime feeds for this feed, if available. */ @ElementCollection public List<String> realtimeUrls; /** * Does this feed allow bikes on transit with unspecified bike rules in GTFS? */ @Enumerated(EnumType.STRING) public DefaultBikesAllowedType defaultBikesAllowed; /** * Was the parsing of this feed successful? */ @Enumerated(EnumType.STRING) public FeedParseStatus status; /** Is this feed a feed officially provided by the transit agency? */ @Required public boolean official; /** The URL of the license for this feed */ @URL public String licenseUrl; // TODO: this should probably use abbreviations to avoid spelling variations // e.g. Hawaii v. Hawai'i /** The US state of this feed */ public String state; /** * The URL of the agency producing this feed. This should be the stable URL, not a marketing * URL (e.g., http://wmata.com not http://metroopensdoors.com) */ @Required @URL public String agencyUrl; // TODO: time period /** The number of trips in this GTFS */ public int trips; /** The expiration date of this feed */ //@Required public Date expirationDate; // TODO: what exactly does this mean /** The number of trips per calendar, on average */ public int tripsPerCalendar; @Type(type = "org.hibernatespatial.GeometryUserType") public MultiPolygon the_geom; /** * Was this feed superseded? */ @OneToOne public GtfsFeed supersededBy; /** * The ID of this file in storage. Exact contents is storage backend dependent. */ public String storedId; /** * The number of stops in this GTFS. */ public Integer stops; /** * The date this schedule becomes valid. */ public Date startDate; /** A note for manual review by a human */ public String note; /** * Get the agencies this feed refers to. */ public List<NtdAgency> getAgencies () { // modified from http://stackoverflow.com/questions/7898960 return NtdAgency.find("SELECT a FROM NtdAgency a INNER JOIN a.feeds feeds WHERE ? IN feeds", this) .fetch(); } /** * Get the enabled agencies this feed refers to. */ public List<NtdAgency> getEnabledAgencies () { // modified from http://stackoverflow.com/questions/7898960 return NtdAgency.find("SELECT a FROM NtdAgency a INNER JOIN a.feeds feeds WHERE ? IN feeds AND a.disabled <> true", this) .fetch(); } public String toString () { return "GTFS for " + agencyName; } public GtfsFeed () { this(null, null, null, null, null, null, null, null, null, null, false, null, null, null); }; public GtfsFeed (String agencyName, String agencyUrl, String country, String dataExchangeId, String dataExchangeUrl, Date dateAdded, Date dateUpdated, Date expirationDate, String feedBaseUrl, String licenseUrl, boolean official, String state, String areaDescription, MultiPolygon the_geom) { this.agencyName = agencyName; this.areaDescription = areaDescription; this.country = country; this.dataExchangeId = dataExchangeId; this.dataExchangeUrl = dataExchangeUrl; this.dateAdded = dateAdded; this.dateUpdated = dateUpdated; this.expirationDate = expirationDate; this.feedBaseUrl = feedBaseUrl; this.official = official; this.licenseUrl = licenseUrl; this.state = state; this.agencyUrl = agencyUrl; this.the_geom = the_geom; this.supersededBy = null; this.storedId = null; this.downloadUrl = null; this.defaultBikesAllowed = DefaultBikesAllowedType.WARN; this.realtimeUrl = null; this.realtimeUrls = new ArrayList<String>(); this.disabled = false; this.status = null; this.stops = null; this.timezone = null; } public GtfsFeed clone () { // can't just clone, because of IDs &c; JPA gives us the 'detached entity passed to persist' GtfsFeed ret = new GtfsFeed(); ret.agencyName = this.agencyName; ret.agencyUrl = this.agencyUrl; ret.areaDescription = this.areaDescription; ret.country = this.country; ret.dataExchangeId = this.dataExchangeId; ret.dataExchangeUrl = this.dataExchangeUrl; ret.dateAdded = this.dateAdded; ret.dateUpdated = this.dateUpdated; ret.downloadUrl = this.downloadUrl; ret.expirationDate = this.expirationDate; ret.feedBaseUrl = this.feedBaseUrl; ret.licenseUrl = this.licenseUrl; ret.official = this.official; ret.state = this.state; ret.supersededBy = this.supersededBy; ret.the_geom = this.the_geom; ret.trips = this.trips; ret.tripsPerCalendar = this.tripsPerCalendar; ret.storedId = this.storedId; ret.realtimeUrl = this.realtimeUrl; ret.defaultBikesAllowed = this.defaultBikesAllowed; ret.disabled = this.disabled; // this should always be overwritten ret.status = this.status; ret.stops = this.stops; ret.timezone = this.timezone; ret.realtimeUrls = new ArrayList<String>(this.realtimeUrls); // TODO if the clone is not saved, will this leave the DB in an inconsistent state? // add it to agencies as appropriate for (NtdAgency agency : getAgencies()) { agency.feeds.add(ret); agency.save(); } return ret; } /** * Attempt to automatically find and link this feed to agencies. * @return true if matching was successful, false otherwise */ public boolean findAgency() { Query q = JPA.em().createNativeQuery("SELECT a.id FROM NtdAgency a WHERE regexp_replace(LOWER(?), " + // that regular expression strips the protocol, // strips pathinfo, // and strips www. to get a hopefully LCD domain name "'(?:\\W*)(?:https?://)?(?:www\\.)?([a-zA-Z0-9\\-_\\.]*)(?:/.*)?(?:\\W*)'," + "'\\1') = " + "regexp_replace(LOWER(a.url)," + "'(?:\\W*)(?:https?://)?(?:www\\.)?([a-zA-Z0-9\\-_\\.]*)(?:/.*)?(?:\\W*)'," + "'\\1');"); q.setParameter(1, this.agencyUrl); List<Object> results = q.getResultList(); if (results.size() == 0) return false; else { NtdAgency agency; for (Object result : results) { agency = NtdAgency.findById(((BigInteger) result).longValue()); agency.feeds.add(this); agency.save(); } return true; } } }
conveyal/transit-data-dashboard
app/models/GtfsFeed.java
2,346
/** The number of trips in this GTFS */
block_comment
en
false
2,181
10
2,346
11
2,557
10
2,346
11
2,881
12
false
false
false
false
false
true
240949_4
/** * Name : YEO WEI TECK VICTOR * Matric No. : A0154004X * Plab Acct. : */ import java.util.*; public class Storage { private ArrayList<Box> remoteStorage; private ArrayList<Item> ownItem; private ArrayList<Item> allItem; private int _numBox; private int _boxSize; private int _numCarry; public Storage(){ remoteStorage = new ArrayList<Box>(); ownItem = new ArrayList<Item>(); allItem = new ArrayList<Item>(); } public void run() { Scanner sc = new Scanner (System.in); _numBox = sc.nextInt(); _numCarry = sc.nextInt(); _boxSize = sc.nextInt(); createBox(); int numQueries = sc.nextInt(); sc.nextLine(); for (int i=0; i<numQueries; i++){ String[] command = sc.nextLine().split(" "); switch (command[0]){ case "purchase": purchaseItem(command[1], Integer.parseInt(command[2])); break; case "deposit": depositItem(command[1]); break; case "withdraw": withdrawItem(command[1]); break; case "location": locateItem(command[1]); break; case "valuable": mostValuable(); break; } } } //this method allows the purchase of item and keep them with Evan if he still can hold or deposit them in remote storage public void purchaseItem(String name, int value){ Item item = new Item (name, value); allItem.add(item); if (ownItem.size() + 1 <= _numCarry){ ownItem.add(item); System.out.println ("item " + item.getName() + " is now being held"); } else{ depositItem(name); } } public static void main(String[] args) { Storage myStorageSystem = new Storage(); myStorageSystem.run(); } public void depositItem(String name){ for (int i=0; i<ownItem.size(); i++){ if (ownItem.get(i).getName().equals(name)) ownItem.remove(i); } //check whether the item is already in storage boolean inStorage = false; for (int i=0; i<remoteStorage.size(); i++){ for (int j=0; j<remoteStorage.get(i).getItemList().size(); j++){ if (remoteStorage.get(i).getItemList().get(j).getName().equals(name)) inStorage = true; } } if (inStorage) System.out.println("item " + name + " is already in storage"); else { Item item = null; for (int i=0; i<allItem.size(); i++){ if (allItem.get(i).getName().equals(name)){ item = allItem.get(i); break; } else item = null; } //if item was not bought, it will not be in all item list. Hence, item reference will still be null if (item == null) System.out.println("item " + name + " does not exist"); else{ for (int i=0; i< remoteStorage.size(); i++){ if (remoteStorage.get(i).getItemList().size() + 1 <= _boxSize){ remoteStorage.get(i).getItemList().add(item); System.out.println("item " + name + " has been deposited to box " + (i+1)); break; } } } } } //this method withdraws an item from remote storage, only if it is present public void withdrawItem(String name){ //checks whether the item is on the hand already boolean onHand = false; for (int i=0; i<ownItem.size(); i++){ if (ownItem.get(i).getName().equals(name)) onHand = true; } if(onHand) System.out.println("item " + name + " is already being held"); else{ Item item = null; for (int i=0; i<allItem.size(); i++){ if (allItem.get(i).getName().equals(name)){ item = allItem.get(i); break; } else item = null; } if (item == null) System.out.println("item " + name + " does not exist"); else { if (ownItem.size() + 1 <= _numCarry){ ownItem.add(item); for (int i=0; i<remoteStorage.size(); i++){ if (remoteStorage.get(i).getItemList().contains(item)) remoteStorage.get(i).getItemList().remove(item); } System.out.println("item " + name + " has been withdrawn"); } else{ System.out.println("cannot hold any more items"); } } } } //this method determines where the item is currently located public void locateItem(String name){ //check whether the item is already in storage Item item = null; for (int i=0; i<allItem.size(); i++){ if (allItem.get(i).getName().equals(name)){ item = allItem.get(i); break; } else item = null; } //if item was not bought, it will not be in all item list. Hence, item reference will still be null if (item == null) System.out.println("item " + name + " does not exist"); else{ if (ownItem.contains(item)) System.out.println("item " + name + " is being held"); else{ for (int i=0; i<remoteStorage.size(); i++){ if (remoteStorage.get(i).getItemList().contains(item)){ System.out.println("item " + name + " is in box " + (1+i)); break; } } } } } public void createBox(){ for (int i=0; i<_numBox; i++){ Box box = new Box(_boxSize); remoteStorage.add(box); } } //this method checks for the most valuable item, and prints out the maximum value item with lexicographically smallest name public void mostValuable(){ int max = 0; Item mostValuableItem = new Item ("a", 0); for (int i=0 ;i< allItem.size(); i++){ if (allItem.get(i).getValue() > max){ mostValuableItem = allItem.get(i); max = mostValuableItem.getValue(); } else if (allItem.get(i).getValue() == max){ if (allItem.get(i).getName().compareTo(mostValuableItem.getName()) < 0) mostValuableItem = allItem.get(i); } } System.out.println(mostValuableItem.getName()); } } class Box { private int _size; private ArrayList<Item> itemList; public Box (int size){ _size = size; itemList = new ArrayList<Item>(); } public int getSize (){ return _size; } public void addItem(Item item) { this.itemList.add(item); } public ArrayList<Item> getItemList(){ return this.itemList; } } class Item { private String _name; private int _value; public Item(String name, int value) { _name = name; _value = value; } public String getName(){ return _name; } public int getValue(){ return _value; } }
vywt/CS1020-DataStructures-Algorithms
Storage.java
1,821
//this method withdraws an item from remote storage, only if it is present
line_comment
en
false
1,677
16
1,821
16
2,016
15
1,821
16
2,187
16
false
false
false
false
false
true
243348_2
/** * @file Kablewie.java * @author Hal * @date 23 Nov 2015 * * @brief Launches Kablewie game */ import javax.swing.JFrame; /** * @class Kablewie * @brief Launches Kablewie game */ public class Kablewie { /** * Launches MenuForm, which takes game details and then starts game * @param args Command line arguments */ public static void main(String[] args) { java.awt.EventQueue.invokeLater(() -> { //Create and display menu form MenuForm menu = new MenuForm(); menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); menu.setVisible(true); }); } }
NoodinAhmed/Group-Green-
Kablewie.java
188
/** * Launches MenuForm, which takes game details and then starts game * @param args Command line arguments */
block_comment
en
false
153
28
188
26
198
30
188
26
219
33
false
false
false
false
false
true
245386_13
import java.util.HashMap; /** * Created by matt on 20/03/2017. */ public class Location implements LocationInterface { private int number; private String name; private boolean mixed; private HashMap<Colour, Integer> pieces; public Location(String name){ this.name = name; this.pieces = new HashMap<Colour, Integer>(); } public Location(String name, int number){ this.number = number; this.name = name; this.pieces = new HashMap<Colour, Integer>(); } public String getName(){ return this.name; } public void setName(String name){ this.name = name; } public int getNumber(){ return this.number; } public void setNumber(int number){ this.number = number; } /** * @return true if and only if the location allows pieces of both colours */ public boolean isMixed(){ return this.mixed; } /** * @param isMixed true if and only if the location allows pieces of both colours */ public void setMixed(boolean isMixed){ this.mixed = isMixed; } /** * @return true if and only if the location has no pieces in it */ public boolean isEmpty(){ int counter = 0; for(int i : pieces.values()){ counter += i; } return counter == 0; } /** * @param colour the colour of pieces to count * @return the number of pieces of that colour **/ public int numberOfPieces(Colour colour){ if(pieces.containsKey(colour)){ return pieces.get(colour); } else { return 0; } } public String stringNumberOfPieces(Colour colour){ int number; if(pieces.containsKey(colour)){ number = pieces.get(colour); } else { number = 0; } if(number < 10){ return "0" + Integer.toString(number); } else { return Integer.toString(number); } } /** * @param colour the colour of the piece to add * @return true if and only if a piece of that colour can be added (i.e. no IllegalMoveException) **/ public boolean canAddPiece(Colour colour){ if(isMixed()) return true; for(Colour c : pieces.keySet()){ if((c != colour) && numberOfPieces(c) > 1) { return false; } } return true; } /** * @param colour the colour of the piece to add * * @throws IllegalMoveException if the location is not mixed and already contains two or more pieces * of the other colour * * @return null if nothing has been knocked off, otherwise the colour of the piece that has been knocked off **/ public Colour addPieceGetKnocked(Colour colour) throws IllegalMoveException{ if(!canAddPiece(colour)){ throw new IllegalMoveException("Location Already Contains More Than One Piece of The Other Colour!"); } if(isMixed()) { //If it's mixed, add one to the location if (pieces.containsKey(colour)) { pieces.put(colour, pieces.get(colour) + 1); } else { pieces.put(colour, 1); } return null; } else { //If it's not mixed, add one to the location, and: if(pieces.containsKey(colour)) { pieces.put(colour, pieces.get(colour) + 1); } else { pieces.put(colour, 1); } try { removePiece(colour.otherColour()); //If a piece of the colour cannot be removed.. } catch (IllegalMoveException e){ return null; //There must only be this colour on the location, so return null } return colour.otherColour(); //Else there must have been a single piece of the other colour on this location, which is returned } } /** * @param colour the colour of the piece to remove * @return true if and only if a piece of that colour can be removed (i.e. no IllegalMoveException) **/ public boolean canRemovePiece(Colour colour){ //canAddPiece() ensures that all the constraints are satisfied, so all we need to check is if there any pieces of that colour. if(pieces.containsKey(colour)){ return pieces.get(colour) > 0; } return false; } /** * @param colour the colour of the piece to remove * * @throws IllegalMoveException if there are no pieces of that colour int the location * **/ public void removePiece(Colour colour) throws IllegalMoveException{ if(!canRemovePiece(colour)){ throw new IllegalMoveException("No Counter of this Colour at this Location!"); } else { pieces.put(colour, pieces.get(colour) - 1); } } /** * @return true if and only if the Location is in a valid state depending on the number of each colour and whether or not it is a mixed location */ public boolean isValid(){ if(isMixed()){ return true; } else { int counter = 0; for(int i : pieces.values()){ if(i > 0){ counter++; } } if(counter > 1){ return false; } else { return true; } } } public void setPieces(HashMap<Colour, Integer> pieces){ this.pieces.putAll(pieces); } public HashMap<Colour, Integer> getPieces(){ return this.pieces; } }
marwahaha/Tabula
Location.java
1,284
//canAddPiece() ensures that all the constraints are satisfied, so all we need to check is if there any pieces of that colour.
line_comment
en
false
1,240
28
1,284
28
1,439
28
1,284
28
1,600
31
false
false
false
false
false
true
245722_0
public class Queen extends Piece{ public Queen(String color, Square currentPosition) { super(PieceColor.valueOf(color), currentPosition); } @Override public boolean isValidMove(Square destination) { int rowDiff = Math.abs(destination.getRow() - getCurrentPosition().getRow()); int colDiff = Math.abs(destination.getCol() - getCurrentPosition().getCol()); // Queen can move horizontally, vertically, or diagonally return rowDiff == 0 || colDiff == 0 || rowDiff == colDiff; } @Override public boolean canMove(Board board, Square start, Square end) { // Check if the destination square is a valid move for the Queen if (!isValidMove(end)) { return false; } // Check if there are no pieces in the path of the Queen int rowDirection = Integer.compare(end.getRow(), start.getRow()); int colDirection = Integer.compare(end.getCol(), start.getCol()); int currentRow = start.getRow() + rowDirection; int currentCol = start.getCol() + colDirection; while (currentRow != end.getRow() || currentCol != end.getCol()) { if (board.getSquare(currentRow, currentCol).getPiece() != null) { // There is a piece in the path return false; } currentRow += rowDirection; currentCol += colDirection; } return true; } @Override public String getSymbol() { return null; } }
anshpreetlayal/Chess_Game
Queen.java
349
// Queen can move horizontally, vertically, or diagonally
line_comment
en
false
321
11
349
15
377
10
349
15
407
15
false
false
false
false
false
true
246505_2
import java.io.File; import java.io.FileNotFoundException; import java.util.NoSuchElementException; import java.util.Scanner; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import Shapes.Cone; import Shapes.Cylinder; import Shapes.OctagonalPrism; import Shapes.PentagonalPrism; import Shapes.Pyramid; import Shapes.Shape; import Shapes.ShapeComparator; import Shapes.SquarePrism; import Shapes.TriangularPrism; public class Sort { // Flag constants private static final String FLAG_FILE = "-f"; private static final String FLAG_SORT_CRITERIA = "-t"; private static final String FLAG_SORT_METHOD = "-s"; public static void main(String[] args) { String fileName = null; String sortingCriteria = null; String sortingMethod = null; for (String arg : args) { arg = arg.toLowerCase(); // Convert the argument to lowercase for case-insensitive comparison if (arg.startsWith(FLAG_FILE)) { fileName = arg.replaceFirst(FLAG_FILE + "(\"?)(.*?)\\1", "$2"); } else if (arg.startsWith(FLAG_SORT_CRITERIA)) { sortingCriteria = arg.substring(2); } else if (arg.startsWith(FLAG_SORT_METHOD)) { sortingMethod = arg.substring(2); } } if (fileName == null || sortingCriteria == null || sortingMethod == null) { System.out.println( "Missing arguments. Usage: java -jar sort.jar -f <file_name> -t <sorting_criteria> -s <sorting_method>"); return; } System.out.println("------------------- Arguments -----------------"); System.out.println("-> File Name: " + fileName); System.out.println("-> Sorting Criteria: " + sortingCriteria); System.out.println("-> Sorting Method: " + sortingMethod + "\n"); // Read shapes from the file and store them in an array try { File file = new File(fileName); Scanner scanner = new Scanner(file); int numOfObjects = scanner.nextInt(); Shape[] shapes = new Shape[numOfObjects]; for (int i = 0; i < numOfObjects; i++) { String shapeType = scanner.next(); double height = scanner.nextDouble(); double value = scanner.nextDouble(); Shape shape = null; switch (shapeType.toLowerCase()) { case "cylinder": shape = new Cylinder(height, value); break; case "cone": shape = new Cone(height, value); break; case "pyramid": shape = new Pyramid(height, value); break; case "squareprism": shape = new SquarePrism(height, value); break; case "triangularprism": shape = new TriangularPrism(height, value); break; case "pentagonalprism": shape = new PentagonalPrism(height, value); break; case "octagonalprism": shape = new OctagonalPrism(height, value); break; default: System.out.println("Unknown shape type: " + shapeType); } if (shape != null) { shapes[i] = shape; } } scanner.close(); // Create a comparator based on the sorting criteria Comparator<Shape> comparator; long startTime = System.currentTimeMillis(); switch (sortingCriteria) { case "h": Arrays.sort(shapes, Collections.reverseOrder()); break; case "v": comparator = new VolumeComparator(); Utility.sortShapes(shapes, comparator, sortingMethod); break; case "a": comparator = new AreaComparator(); Utility.sortShapes(shapes, comparator, sortingMethod); break; default: System.out.println("Unknown sorting criteria: " + sortingCriteria); } long endTime = System.currentTimeMillis(); long elapsedTime = endTime - startTime; System.out.println("------------------ Sorting Time ----------------"); System.out.println("-> Time taken to sort: " + elapsedTime + " milliseconds \n"); // Print the sorted values and benchmarking results System.out.println("-------------------- Shapes --------------------"); printSortedShapes(shapes); } catch (FileNotFoundException e) { System.out.println("An error occurred: " + e.getMessage()); } catch (NoSuchElementException e) { System.out.println("Error while reading input: " + e.getMessage()); } } public static void printSortedShapes(Shape[] shapes) { for (int i = 0; i < shapes.length; i++) { // Only prints the first item, the last item and every thousandth value in between if (i == 0 || i == shapes.length - 1 || (i + 1) % 1000 == 0) { Shape shape = shapes[i]; System.out.println("Shape number: " + (i + 1)); System.out.println("-> Shape Type: " + shape.getClass().getSimpleName()); System.out.println("-> Height: " + shape.getHeight()); System.out.println("-> Base Area: " + shape.getBaseArea()); System.out.println("-> Volume: " + shape.getVolume()); System.out.println(); } } } }
AnaJoselynAlarcon/OOP3_Assignment1_new
src/Sort.java
1,232
// Read shapes from the file and store them in an array
line_comment
en
false
1,103
12
1,232
12
1,332
12
1,232
12
1,549
12
false
false
false
false
false
true
248542_7
package riverAI; import java.util.ArrayList; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.Stack; /** * this class does cool stuff. it is a generalized Depth first searching class that works with the node and state class defined in this package to * find solutions to state space problems. to change the functionality of this only the state class and expand function need to change. * @author ben LEONE * @author Harry Moreno * */ public class DFS { /** * searches a tree to find a solution through depth first searching * @param start the starting state * @param goal the goal state * @return a list of all the states made to reach the solution or null in no solution was found */ static public String search(State start, State goal){ ArrayList<State> solution = null; //will hold the states that lead to the solution later boolean solutionCTL=true; //used to control a loop that builds the solution list Stack<Node> frontier = new Stack<Node>(); // holds the frontier (nodes that have not yet been expanded Node tree = new Node(0, null, start,null); // the base node of the tree (i.e. the start conditions) boolean notSolved=true; // a variable that controls the main search loop frontier.push(tree); // loads the root node into the frontier, this is needed due to the way the no solution case is handled List<Node> expanded; // this variable with hold the nodes that are expanded from the current node before they are loaded into the frontier Node Active=null; //this with hold the current node being looked at by the tree. it is loaded from the frontier int numOfNodesExpanded=1; int totalCost=0; while(notSolved){ if(frontier.isEmpty()){ notSolved = false; }else{ Active = frontier.pop(); numOfNodesExpanded++; } if(Active.getState().equals(goal)){ notSolved=true; break; }else{ expanded = Active.expand(); for(Node n: expanded){ frontier.push(n); } } } solution = new ArrayList<State>(); totalCost = Active.getCost(); while(solutionCTL){ // System.out.println(Active.getState().toString()); solution.add(Active.getState()); if(Active.getParent()==null){ solutionCTL=false; break; }else{ Active = Active.getParent(); } } StringBuilder sb = new StringBuilder(); sb.append("DFS "+totalCost+" "+numOfNodesExpanded+"\n"); for(State s : solution){ sb.append(s.toString()+"\n"); } return sb.toString(); } }
morenoh149/riverCrossingAI
src/riverAI/DFS.java
691
// loads the root node into the frontier, this is needed due to the way the no solution case is handled
line_comment
en
false
597
22
691
23
677
22
691
23
806
23
false
false
false
false
false
true
248905_18
// Festival and classes Ended // Description // You are given an abstract classfestivalhaving the following functions // 1. boolean winter() - This function returns true if the festival is celebrated in winter // 2. boolean summer() - This function returns true if the festival is celebrated in Summer // 3. boolean multidays() - This function returns true if the festival lasts for more than 1 day // 4. boolean panIndia() - This function returns true if the festival is celebrated across India // You have to create the following classes, which extend the above abstract class // diwali // 1. This festival is celebrated in winter // 2. This festival lasts for multiple days // 3. This festival is celebrated all across the country // - Apart from the inherited functions, this class has another function // - boolean festivalOfLights() // - This function returns true if the festival is known as the festival of lights // holi // 1. This festival is celebrated in summers // 2. This festival lasts for a single day // 3. This festival is celebrated all across the country // - Apart from the inherited functions, this class has another function // - festivalOfColors() // - This function returns true if the festival is known as the festival of colors // pongal // 1. This festival is celebrated in winter // 2. This festival lasts for a single day // 3. This festival is celebrated all across the country // There's no need to take the input or the output. Just implement the classes, according to the explanation in the problem statement // Input // - There's no need to take the input or the output. Just implement the classes, according to the explanation in the problem statement // Output // - There's no need to take the input or the output. Just implement the classes, according to the explanation in the problem statement package conceptofjava; /* abstract class festival{ abstract boolean winter(); abstract boolean summer(); abstract boolean multidays(); abstract boolean panIndia(); } */ class diwali extends festival { // complete the class as mentioned in the problem statement boolean winter() { return true; } boolean summer() { return false; } boolean multidays() { return true; } boolean panIndia() { return true; } boolean festivalOfLights() { return true; } } class holi extends festival { // complete the class as mentioned in the problem statement boolean winter() { return false; } boolean summer() { return true; } boolean multidays() { return false; } boolean panIndia() { return true; } boolean festivalOfColors() { return true; } } class pongal extends festival { // complete the class as mentioned in the problem statement above boolean winter() { return true; } boolean summer() { return false; } boolean multidays() { return false; } boolean panIndia() { return true; } }
hoshiyarjyani/Masai-School-Assignments
dsa401/conceptofjava/FestivalAbstractClass.java
763
// 3. This festival is celebrated all across the country
line_comment
en
false
670
12
763
15
727
12
763
15
776
12
false
false
false
false
false
true
239_3
import java.util.*; import java.awt.*; import javax.swing.*; /* This is a class with several static methods which can used to draw * simples shapes in 3D */ public class D3{ private static double fl = 250.0; public static int centerX = Global.WIDTH/2; public static int centerY = Global.HEIGHT/2; public static double depth(double n){ // 3 dimensional coordinate visual point multiplier // gives a back a certain value that scales size and position of an object to give a 3D illusion return (fl+n)/fl; } public static double zX (double x,double z){ // returns a 3d point in 2d form double scale_factor = depth(z); x = (x-centerX)*(scale_factor)+centerX; return x; } public static double zY ( double y, double z){ // returns a 3d point in 2d form double scale_factor = depth(z); y = (y-centerY)*(scale_factor)+centerY; return y; } public static void circle3D (double X, double Y,double Z, double rad,Color colour, Graphics g,JFrame canvas){ // draw a filled circle int rad3D = (int)(depth(Z)*rad); g.setColor(colour); g.fillOval((int)(zX(X,Z)-rad3D),(int)(zY(Y,Z)-rad3D),2*rad3D,2*rad3D); } public static void drawCircle3D (double X, double Y,double Z, double rad,Color colour, Graphics g,JFrame canvas){ // draw an outline of a circle int rad3D = (int)(depth(Z)*rad); g.setColor(colour); g.drawOval((int)(zX(X,Z)-rad3D),(int)(zY(Y,Z)-rad3D),2*rad3D,2*rad3D); } public static void line3D(double X1, double Y1, double Z1, double X2, double Y2, double Z2, Color colour,Graphics g,JFrame canvas){ // draw a 3d line g.setColor(colour); g.drawLine((int)zX(X1,Z1),(int)zY(Y1,Z1),(int)zX(X2,Z2),(int)zY(Y2,Z2)); } }
shaon0000/Tower-Defense
D3.java
593
// returns a 3d point in 2d form
line_comment
en
false
526
13
597
13
634
13
593
13
664
13
false
false
false
false
false
true
12139_0
// Java program to print DFS traversal from a given given graph import java.io.*; import java.util.*; // This class represents a directed graph using adjacency list // representation class Graph { private int V; // No. of vertices // Array of lists for Adjacency List Representation private LinkedList<Integer> adj[]; // Constructor @SuppressWarnings("unchecked") Graph(int v) { V = v; adj = new LinkedList[v]; for (int i=0; i<v; ++i) adj[i] = new LinkedList(); } //Function to add an edge into the graph void addEdge(int v, int w) { adj[v].add(w); // Add w to v's list. } // A function used by DFS void DFSUtil(int v,boolean visited[]) { // Mark the current node as visited and print it visited[v] = true; System.out.print(v+" "); // Recur for all the vertices adjacent to this vertex Iterator<Integer> i = adj[v].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) DFSUtil(n, visited); } } // The function to do DFS traversal. It uses recursive DFSUtil() void DFS(int v) { // Mark all the vertices as not visited(set as // false by default in java) boolean visited[] = new boolean[V]; // Call the recursive helper function to print DFS traversal DFSUtil(v, visited); } public static void main(String args[]) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); System.out.println("Following is Depth First Traversal "+ "(starting from vertex 2)"); g.DFS(2); } } /* OUTPUT: Following is Depth First Traversal (starting from vertex 2) 2 0 1 3 */
Harsh2255/Basic-Data-Structure
DFS.java
572
// Java program to print DFS traversal from a given given graph
line_comment
en
false
526
13
572
13
614
13
572
13
719
15
false
false
false
false
false
true
33466_3
package samples.ui; import java.util.Vector; import javax.microedition.lcdui.Canvas; import javax.microedition.lcdui.Font; import javax.microedition.lcdui.Graphics; import javax.microedition.lcdui.Image; /** * This class implements user interface chat message display class. */ public class ChatBox extends Component { private Vector messageList; private Vector colorList; private Vector cookedMessageList; private Vector cookedColorList; private Vector tmpList; private int cursor; private int history; private int numLines; private int widthOffset; /** * Create a new ChatBox instance. */ ChatBox() { widthOffset = 2; focusable = true; messageList = new Vector(); colorList = new Vector(); cookedMessageList = new Vector(); cookedColorList = new Vector(); tmpList = new Vector(); } /** * Create a new ChatBox instance with the provided history buffer size. * * @param history The history buffer size. */ public ChatBox(int history) { this(); callMyFun(); this.history = history; } /** * Set the width offset (left/right margin) of this instance. * * @param widthOffset The width offset (left/right margin) of this instance. */ public void setWidthOffset(int widthOffset) { this.widthOffset = widthOffset; breakLines(); } }
david04/Multitudo
F3.java
343
/** * Set the width offset (left/right margin) of this instance. * * @param widthOffset The width offset (left/right margin) of this instance. */
block_comment
en
false
312
38
343
40
375
44
343
40
406
44
false
false
false
false
false
true
35390_1
public class Trie { static class Node { Node[] children = new Node[26]; boolean eow = false; Node() { for(int i=0; i<26; i++) { children[i] = null; } } } public static Node root = new Node(); //Insert operation public static void insert(String word) { Node curr = root; for(int i=0; i<word.length(); i++) { int idx = word.charAt(i) - 'a'; if(curr.children[idx] == null) { curr.children[idx] = new Node(); } curr = curr.children[idx]; } curr.eow = true; } //Search operation public static boolean search(String key) { Node curr = root; for(int i=0; i<key.length(); i++) { int idx = key.charAt(i) - 'a'; if(curr.children[idx] == null) { return false; } curr = curr.children[idx]; } return curr.eow; } public static void main(String[] args) { String[] word = {"the", "a", "there", "their", "any", "thee"}; for(int i=0; i<word.length; i++) { insert(word[i]); } System.out.println(search("the")); System.out.println(search("a")); } }
tapas20/Java
Trie.java
347
//Search operation
line_comment
en
false
309
3
347
3
387
3
347
3
398
3
false
false
false
false
false
true
46654_11
//Fettes Sameer, Cai Kitty //June 13th, 2019 //Final Project: Agar.io Game //ISC3U7 //Import java classes import java.awt.*; import javax.swing.*; import java.awt.event.*; //this is the class for the pieces of food public class Circle{ //variables Color colour; protected int radius, x, y; static int minXs = 40; static int maxXs = 910; static int minYs = 40; static int maxYs = 500; public Circle (int minX, int maxX, int minY, int maxY){ colour = makeColour(); radius = 5; x = (int)(Math.random()*(maxX-minX)) + minX; y = (int)(Math.random()*(maxY-minY)) + minY; //generate x and y values within range } public Circle() { //overloading constructor //do the same thing as first constructor and use constants for the values this(minXs, maxXs, minYs, maxYs); } public void drawCircle(Graphics g){ //method for drawing the circle g.setColor(colour); g.fillOval(x, y, radius *2, radius*2); g.setColor(Color.black); g.drawOval(x, y, radius *2, radius*2); } public Color makeColour() { //To generate random colour int n = (int)(Math.random()*12); switch(n) { case 0: return Color.yellow; case 1: return Color.blue; case 2: return Color.cyan; case 3: return Color.darkGray; case 4: return Color.gray; case 5: return Color.green; case 6: return Color.lightGray; case 7: return Color.magenta; case 8: return Color.orange; case 9: return Color.pink; case 10: return Color.red; case 11: return Color.white; default: return Color.red; } } }
cat-kitty/Agar.io
Circle.java
571
//To generate random colour
line_comment
en
false
498
7
571
6
613
6
571
6
702
6
false
false
false
false
false
true
52457_2
/* ********************************************************************************* * dev23jjl DLM: 9/30/2022 FinancialOperations.java * * Description: These are the basic required components of a simple Java program * The program declares and manipulates variables using assignment, mathematical, * and comparison operators to compute various information for the financials of * three different employees and prints out this information in the terminal. * ********************************************************************************* */ public class FinancialOperations { public static void main(String[] financialOperation) { //Initialize Variables for basic setup float hrsWorked = 40; double payRate = 10.00; double taxRate1 = 0.25; double taxRate2 = 0.50; double grossPay = 0.00; double taxAmt = 0.00; double netPay = 0.00; //Prints out the name of the variable and it's value System.out.println("Initial Setup"); System.out.println("hrsWorked= " + hrsWorked); System.out.println("payRate= $" + payRate); System.out.println("taxRate1 = " + taxRate1); System.out.println("taxRate2 = " + taxRate2); System.out.println("grossPay = " + grossPay); System.out.println("taxAmt = " + taxAmt); System.out.println("****************"); //Computes information for the first employee, Bob Basic //Changes the values of grossPay, taxAmt, and netPay based on other variables //Checks if the grossPay is large (greater than/equal to 500) or small (less than/equal to 500) grossPay = payRate * hrsWorked; boolean bigGrossPay = (grossPay >= 500); taxAmt = grossPay * taxRate1; boolean littleGrossPay = (grossPay <= 500); taxAmt = grossPay * taxRate2; netPay = grossPay - taxAmt; //Prints out information for the first employee: Bob Basic System.out.println("Employee Name: Bob Basic"); System.out.println("hrsWorked = " + hrsWorked); System.out.println("payRate = $" + payRate); System.out.println("taxRate1 = " + taxRate1); System.out.println("taxRate2 = " + taxRate2); System.out.println("grossPay = $" + grossPay); System.out.println("taxAmt = $" + taxAmt); System.out.println("netPay = $" + netPay); System.out.println("bigGrossPay = " + bigGrossPay); System.out.println("littleGrossPay = " + littleGrossPay); System.out.println("****************"); //Changes information for the second employee, William Workmore hrsWorked = 60; payRate = 12; grossPay = 0.00; taxAmt = 0.00; netPay = 0.00; //Prints out the name of the variable and it's value after further manipulation System.out.println("More hours and better pay"); System.out.println("hrsWorked= " + hrsWorked); System.out.println("payRate= $" + payRate); System.out.println("taxRate1 = " + taxRate1); System.out.println("taxRate2 = " + taxRate2); System.out.println("grossPay = " + grossPay); System.out.println("taxAmt = " + taxAmt); System.out.println("****************"); //Computes information for the second employee, William Workmore grossPay = payRate * hrsWorked; bigGrossPay = (grossPay >= 500); taxAmt = grossPay * taxRate1; littleGrossPay = (grossPay <= 500); taxAmt = grossPay * taxRate2; netPay = grossPay - taxAmt; //Prints out information for the second employee: William Workmore System.out.println("Employee Name: William Workmore"); System.out.println("hrsWorked = " + hrsWorked); System.out.println("payRate = $" + payRate); System.out.println("taxRate1 = " + taxRate1); System.out.println("taxRate2 = " + taxRate2); System.out.println("grossPay = $" + grossPay); System.out.println("taxAmt = $" + taxAmt); System.out.println("netPay = $" + netPay); System.out.println("bigGrossPay = " + bigGrossPay); System.out.println("littleGrossPay = " + littleGrossPay); System.out.println("****************"); //Changes out information for the third employee, Mandy Makesalot hrsWorked = 30; payRate = 50; grossPay = 0.00; taxAmt = 0.00; netPay = 0.00; //Prints out the name of the variable and it's value after further manipulation System.out.println("Less hours and way better pay"); System.out.println("hrsWorked= " + hrsWorked); System.out.println("payRate= $" + payRate); System.out.println("taxRate1 = " + taxRate1); System.out.println("taxRate2 = " + taxRate2); System.out.println("grossPay = " + grossPay); System.out.println("taxAmt = " + taxAmt); System.out.println("****************"); //Computes information for the second employee, Mandy Makesalot grossPay = payRate * hrsWorked; bigGrossPay = (grossPay >= 500); taxAmt = grossPay * taxRate1; littleGrossPay = (grossPay <= 500); taxAmt = grossPay * taxRate2; netPay = grossPay - taxAmt; //Prints out information for the first employee: Mandy Makesalot System.out.println("Employee Name: Mandy Makesalot"); System.out.println("hrsWorked = " + hrsWorked); System.out.println("payRate = $" + payRate); System.out.println("taxRate1 = " + taxRate1); System.out.println("taxRate2 = " + taxRate2); System.out.println("grossPay = $" + grossPay); System.out.println("taxAmt = $" + taxAmt); System.out.println("netPay = $" + netPay); System.out.println("bigGrossPay = " + bigGrossPay); System.out.println("littleGrossPay = " + littleGrossPay); System.out.println("****************"); } }
dev23jjl/JavaPrograms
FinancialOperations.java
1,665
//Prints out the name of the variable and it's value
line_comment
en
false
1,497
13
1,665
13
1,680
13
1,665
13
1,835
14
false
false
false
false
false
true
64203_1
/** * CampCommitteeMember represents a member of the camp committee, inheriting from the Student class. * @version 1.0 * @author Oh ShuYi * @since 24/11/2023 */ public class CampCommitteeMember extends Student { /** * Constructor for the CampCommitteeMember class. It initializes a CampCommitteeMember object with the provided Camp Committee Member information. * @param userName This camp committee member's name * @param userID This camp committee member's name * @param password This camp committee member's name * @param faculty This camp committee member's name * @param email This camp committe member's name * @param profile This camp committee member's profile. 1 for Participant. 2 for Camp Committee Member */ public CampCommitteeMember(String userName, String userID, String password, String faculty, String email, int profile) { super(userName, userID, password, faculty, email, profile); } /** * This method allows Camp Committee Members to manage a specific camp. It provides options to reply to inquiries, view camp details, manage suggestions, generate camp reports, or return to the main menu. * @param camp CampInformation object * @param student Camp Committee Member object */ public void campManagementC(CampInformation camp, CampCommitteeMember student) { int choice = 0; do { System.out.println("====== " + camp.getCampName() + " ======"); System.out.println("1. Reply Enquiry"); System.out.println("2. View Camp Details"); System.out.println("3. Suggestion Management"); System.out.println("4. Generate Camp Report"); System.out.println("5. Return to Main Menu"); choice = sc.nextInt(); switch (choice) { case 1: ManageEnquiryCM manageEnquiryCM = new ManageEnquiryCM(this.getUserName(), this.getUserID(), this.getPassword(), this.getFaculty(), this.getEmail(), this.getProfile()); manageEnquiryCM.replyEnquiryCM(camp); break; case 2: ListCampDetails campDetails = new ListCampDetails(camp.getCampName(), camp.getStartCampDate(), camp.getEndCampDates(), camp.getClosingRegDates(), camp.getFaculty(), camp.getLocation(), camp.getTotalSlots(), camp.getRemainingSlots(), camp.getCampCommitteeSlots(), camp.getCampCommitteeRemainingSlots(), camp.getDescription(), camp.getStaffInCharge(), camp.getVisibility()); campDetails.campDetails(camp); break; case 3: ManageSuggestionCM manageSuggestionCM = new ManageSuggestionCM(this.getUserName(), this.getUserID(), this.getPassword(), this.getFaculty(), this.getEmail(), this.getProfile()); manageSuggestionCM.suggestionMenuCM(camp); break; case 4: ManageReportCM manageCampCM = new ManageReportCM(this.getUserName(), this.getUserID(), this.getPassword(), this.getFaculty(), this.getEmail(), this.getProfile()); manageCampCM.generateCampReport(camp); break; case 5: return; } } while (choice != 5); return; } }
keith-ang23/SC2002-OODP-project
src/CampCommitteeMember.java
751
/** * Constructor for the CampCommitteeMember class. It initializes a CampCommitteeMember object with the provided Camp Committee Member information. * @param userName This camp committee member's name * @param userID This camp committee member's name * @param password This camp committee member's name * @param faculty This camp committee member's name * @param email This camp committe member's name * @param profile This camp committee member's profile. 1 for Participant. 2 for Camp Committee Member */
block_comment
en
false
690
116
751
116
786
123
751
116
937
136
false
false
false
false
false
true
66248_9
import java.util.HashSet; import java.util.Random; import java.util.Set; import java.util.function.Function; // A probabilistic monotonic set that is extremely space efficient even for large n, // but allows for a small chance of false positives. False negatives are impossible. // This is good enough for many practical applications of such a space-efficient set. public class BloomFilter<E> { // Needed to randomly initialize the parameters as and bs. private static final Random rng = new Random(); // Family of multiplicative hash functions h(x) = (a*x + b) % M private final int[] as; private final int[] bs; private final boolean[] bits; // Function to convert element into an integer. If null, the result of // calling the method hashCode() is used instead. private final Function<E, Integer> conv; /** * Constructor to initialize the Bloom filter. * @param k The number of hash functions to use. * @param m The number of bits to use to store the element hashes. * @param conv The function to convert each element into an integer. */ public BloomFilter(int k, int m, Function<E, Integer> conv) { this.conv = conv; bits = new boolean[m]; as = new int[k]; bs = new int[k]; for(int i = 0; i < k; i++) { as[i] = rng.nextInt(); bs[i] = rng.nextInt(); } } public BloomFilter(int k, int m) { this(k, m, null); } /** * Add the given element to this Bloom filter. * @param elem The new element to be added. */ public void add(E elem) { int h = conv == null ? elem.hashCode() : conv.apply(elem); for(int i = 0; i < as.length; i++) { bits[Math.abs(as[i] * h + bs[i]) % bits.length] = true; } } /** * Check if the given element has been added to this Bloom filter. * @param elem The element to search for. * @return Whether the element is currently in this Bloom filter. */ public boolean probablyContains(E elem) { int h = conv == null ? elem.hashCode() : conv.apply(elem); for(int i = 0; i < as.length; i++) { if(!bits[Math.abs(as[i] * h + bs[i]) % bits.length]) { return false; // negative answer is guaranteed correct } } return true; // true with high probability } // A utility method needed for the demonstration done in the main method. private static String createWord(Set<String> already) { StringBuilder word; do { word = new StringBuilder(); int len = rng.nextInt(10) + 2; for(int j = 0; j < len; j++) { word.append((char) ('a' + rng.nextInt(26))); } } while(already.contains(word.toString())); return word.toString(); } // For amusement and demonstration purposes. public static void main(String[] args) { // Our Bloom filter uses 128 kilobytes (plus some spare change) to store // the bits, the size of element type E makes no difference to anything. // Also try out how changing k and m affects the false positive percentage. BloomFilter<String> wordBloom = new BloomFilter<>(20, 128 * 1024 * 8); // The hash set will take a lot more memory than 128 kb to store the same // strings in the 100% accurately retrievable and exact fashion. HashSet<String> wordHash = new HashSet<>(); // Populate both collections with the same set of randomly created "words". for(int i = 0; i < 50000; i++) { String word = createWord(wordHash); wordBloom.add(word); wordHash.add(word); } // Just to make sure that our filter works, check that it says yes to all added words. for(String word: wordHash) { if(!wordBloom.probablyContains(word)) { System.out.println("Bloom filter implementation is broken!"); return; } } // Create one million random "words" that are different from our earlier words, and // count for how many of those new words our Bloom filter returns a false positive. int falsePosCount = 0; for(int i = 0; i < 1000000; i++) { String word = createWord(wordHash); if(wordBloom.probablyContains(word)) { falsePosCount++; } } double falsePosProb = falsePosCount / 1000000.0; System.out.printf("Got %d false positives out of one million words, so P(posAns | neg) = %.6f.\n", falsePosCount, falsePosProb); } }
ikokkari/JavaExamples
BloomFilter.java
1,203
/** * Check if the given element has been added to this Bloom filter. * @param elem The element to search for. * @return Whether the element is currently in this Bloom filter. */
block_comment
en
false
1,102
43
1,203
45
1,282
47
1,203
45
1,347
49
false
false
false
false
false
true
68705_2
/* in 5 declare 10 var and assign values to the var using the method reference*/ public class Country { static String name; static int population; static String capital; static int establishmentYear; static double gdp; // in trillions static String continent; static String president; static int area; // in square kilometers static boolean isDeveloped; static double literacyRate; // in percentage public static void setName() { name = "Freedonia"; System.out.println("Name: " + name); } public static void setPopulation() { population = 50000000; System.out.println("Population: " + population); } public static void setCapital() { capital = "Libertapolis"; System.out.println("Capital: " + capital); } public static void setEstablishmentYear() { establishmentYear = 1776; System.out.println("Establishment Year: " + establishmentYear); } public static void setGdp() { gdp = 3.5; System.out.println("GDP: " + gdp + " trillion USD"); } public static void setContinent() { continent = "North America"; System.out.println("Continent: " + continent); } public static void setPresident() { president = "Jane Smith"; System.out.println("President: " + president); } public static void setArea() { area = 950000; // in square kilometers System.out.println("Area: " + area + " square kilometers"); } public static void setIsDeveloped() { isDeveloped = true; System.out.println("Is Developed: " + isDeveloped); } public static void setLiteracyRate() { literacyRate = 99.5; System.out.println("Literacy Rate: " + literacyRate + "%"); } public static void main(String[] args) { Country.setName(); Country.setPopulation(); Country.setCapital(); Country.setEstablishmentYear(); Country.setGdp(); Country.setContinent(); Country.setPresident(); Country.setArea(); Country.setIsDeveloped(); Country.setLiteracyRate(); } }
TaufiqXworkz/Java
JULY_11/Country.java
559
// in square kilometers
line_comment
en
false
498
4
559
6
576
4
559
6
635
5
false
false
false
false
false
true
75612_5
public enum Exposure { /** * Automatic exposure mode. */ AUTO, /** * Exposure for night shooting. */ NIGHT, NIGHTPREVIEW, /** * Exposure for back lit subject. */ BACKLIGHT, SPOTLIGHT, /** * Exposure for sports (fast shutter etc) */ SPORTS, /** * Exposure for snowy scenery. */ SNOW, /** * Exposure for beach scenes. */ BEACH, /** * Exposure for long takes. */ VERYLONG, /** * Exposure for constraining FPS to fixed value. */ FIXEDFPS, /** * Exposure for antishake mode. */ ANTISHAKE, FIREWORKS; /** * Returns enum in lowercase. */ public String toString() { String id = name(); return id.toLowerCase(); } }
Pankaj-Baranwal/DRDO-Robot
Java/src/Exposure.java
220
/** * Exposure for beach scenes. */
block_comment
en
false
193
10
220
12
236
12
220
12
307
14
false
false
false
false
false
true
91490_3
public class CarLoan { public static void main(String[] args) { // user's car loan amount int carLoan = 10000; // length of the loan in years int loanLength = 3; // interest rate for the car loan int interestRate = 5; //down payment amount the user put int downPayment = 2000; // if the loan length or the interest rate isn't greater than or equal to zero if(loanLength <= 0 || interestRate <= 0){ // this would not be a valid car loan System.out.println("Error! You must take out a valid car loan."); } // if the downPayment put down is greater than the amount of the car loan else if(downPayment >= carLoan){ // the car can just be paid off in full System.out.println("The car can be paid in full."); } //if neither of those scenarios else{ // set the remaining balance int remainingBalance = carLoan - downPayment; // how many months the user has to pay int months = loanLength * 12; // find the mongthly balance before interest int monthlyBalance = remainingBalance/months; // calculate how much interest the user must pay int interest = (monthlyBalance * interestRate)/100; // get the final monthly payment the user has to pay int monthlyPayment = monthlyBalance + interest; // how much the user has to pay per month System.out.println(monthlyPayment); } } }
yasarlabib/Java-Practice
CarLoan.java
347
//down payment amount the user put
line_comment
en
false
354
8
347
8
393
8
347
8
419
8
false
false
false
false
false
true
97881_6
/* * This file comes from SISO STD-004-2004 for HLA 1.3 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * * It is provided as-is by CERTI project. */ package hla.rti; /** * * Represents a Region in federate's space. A federate creates a Region by * calling RTIambassador.createRegion. The federate mdifies the Region by * invoking Region methods on it. The federate modifies a Region by first * modifying its local instance, then supplying the modified instance to * RTIambassador.notifyOfRegionModification. * * The Region is conceptually an array, with the extents addressed by index * running from 0 to getNumberOfExtents()-1. */ public interface Region { /** * @return long Number of extents in this Region */ long getNumberOfExtents(); /** * @return long Lower bound of extent along indicated dimension * @param extentIndex int * @param dimensionHandle int * @exception hla.rti.ArrayIndexOutOfBounds */ long getRangeLowerBound(int extentIndex, int dimensionHandle) throws ArrayIndexOutOfBounds; /** * @return long Upper bound of extent along indicated dimension * @param extentIndex int * @param dimensionHandle int * @exception hla.rti.ArrayIndexOutOfBounds */ long getRangeUpperBound(int extentIndex, int dimensionHandle) throws ArrayIndexOutOfBounds; /** * @return int Handle of routing space of which this Region is a subset */ int getSpaceHandle(); /** * Modify lower bound of extent along indicated dimension. * * @param extentIndex int * @param dimensionHandle int * @param newLowerBound long * @exception hla.rti.ArrayIndexOutOfBounds */ void setRangeLowerBound(int extentIndex, int dimensionHandle, long newLowerBound) throws ArrayIndexOutOfBounds; /** * Modify upper bound of extent along indicated dimension. * * @param extentIndex int * @param dimensionHandle int * @param newUpperBound long * @exception hla.rti.ArrayIndexOutOfBounds The exception description. */ void setRangeUpperBound(int extentIndex, int dimensionHandle, long newUpperBound) throws ArrayIndexOutOfBounds; }
hla-certi/jcerti1516e
src/hla/rti/Region.java
557
/** * Modify lower bound of extent along indicated dimension. * * @param extentIndex int * @param dimensionHandle int * @param newLowerBound long * @exception hla.rti.ArrayIndexOutOfBounds */
block_comment
en
false
520
56
557
52
561
58
557
52
623
64
false
false
false
false
false
true
100667_1
import java.util.Arrays; import java.util.ArrayList; import java.util.Vector; class Main { public static int NO_OF_TIMES = 1000; // Returns the kth percentile for the responses. public int getPercentile(int k) { double index = NO_OF_TIMES * k /100; index = Math.abs(index); return (int)index - 1; } // Returns the mean for the responses. public long getMean(Long[] responses) { long sum = 0; for (int i=0; i<responses.length; i++) { sum += responses[i]; } return sum / NO_OF_TIMES; } // Returns the standar deviation for the responses. public double getStandarDeviation(Long[] responses, long mean) { double sumOfDiff = 0; for (int i=0; i<responses.length; i++) { double diff = responses[i] - mean; sumOfDiff += diff * diff; } return Math.sqrt(sumOfDiff / NO_OF_TIMES); } public static void main(String[] args) throws InterruptedException { Main m = new Main(); Long[] responses = new Long[NO_OF_TIMES]; Vector<Long> responseTime = new Vector<Long>(); ArrayList<FetchURL> threads = new ArrayList<FetchURL>(); for (int i=0; i<NO_OF_TIMES; i++) { FetchURL f = new FetchURL(responseTime); f.start(); threads.add(f); } for (FetchURL f : threads) { f.join(); } responseTime.toArray(responses); Arrays.sort(responses); // Print. System.out.println("==10th Percentile==" + responses[m.getPercentile(10)]); System.out.println("==50th Percentile==" + responses[m.getPercentile(50)]); System.out.println("==90th Percentile==" + responses[m.getPercentile(90)]); System.out.println("==95th Percentile==" + responses[m.getPercentile(95)]); System.out.println("==99th Percentile==" + responses[m.getPercentile(99)]); long mean = m.getMean(responses); System.out.println("==Mean==" + mean); System.out.println("==Standard Deviation==" + m.getStandarDeviation(responses, mean)); } }
ankitjain87/FetchURL
Main.java
589
// Returns the mean for the responses.
line_comment
en
false
517
8
589
8
635
8
589
8
680
8
false
false
false
false
false
true
119499_3
import java.util.*; public class PhoneList { private final List<Phone> allPhones = new ArrayList<>(); private final Set<Phone> bestPhones = new HashSet<>(); /* * Adds a phone to the list. */ public void addPhone(Phone phone) { allPhones.add(phone); // remove from bestPhones if dominated by the new phone Iterator<Phone> iter = bestPhones.iterator(); while(iter.hasNext()) { Phone other = iter.next(); if(phone.dominates(other)) { iter.remove(); } } // only add the new phone to bestPhones if it's not dominated if(!phoneIsDominated(phone)) { bestPhones.add(phone); } } /* * Determines whether a phone is dominated by any other phone. */ public boolean phoneIsDominated(Phone phone) { // only need to compare with the undominated phones for(Phone other : bestPhones) { if(other.dominates(phone)) { return true; } } return false; } /* * Gets all phones. The list returned is unmodifiable. */ public List<Phone> getAllPhones() { // TODO: return an unmodifiable view of the list return Collections.unmodifiableList(allPhones); } /* * Gets all phones which are not dominated by another phone. The * collection returned is unmodifiable. */ public Collection<Phone> getBestPhones() { // TODO: return an unmodifiable view of the set return Collections.unmodifiableCollection(bestPhones); } }
VishaljiODEDRA/bestPhoneFinder-JAVA
src/PhoneList.java
416
/* * Determines whether a phone is dominated by any other phone. */
block_comment
en
false
355
16
416
17
420
18
416
17
496
21
false
false
false
false
false
true
121240_3
package FTCEngine.Math; public class Mathf { public static final float Degree2Radian = (float)(Math.PI / 180d); public static final float Radian2Degree = (float)(180d / Math.PI); /** * Returns true if value1 and value2 are approximately the same * Use this instead of the double equals sign */ public static boolean almostEquals(float value1, float value2) { return almostEquals(value1, value2, 0.00001f); } /** * Returns true if value1 and value2 are approximately the same * Use this instead of the double equals sign * * @param epsilon The amount of tolerance for the comparision, default is 0.00001f */ public static boolean almostEquals(float value1, float value2, float epsilon) { if (value1 == value2) return true; final float Min = (1L << 23) * Float.MIN_VALUE; float difference = Math.abs(value1 - value2); if (value1 == 0d || value2 == 0d || difference < Min) return difference < epsilon * Min; return difference / (Math.abs(value1) + Math.abs(value2)) < epsilon; } /** * Clamps value to be not lower than min and not higher than max */ public static int clamp(int value, int min, int max) { return Math.min(max, Math.max(min, value)); } /** * Clamps value to be not lower than min and not higher than max */ public static float clamp(float value, float min, float max) { return Math.min(max, Math.max(min, value)); } /** * Clamps value to be not lower than 0 and not higher than 1 */ public static int clamp01(int value) { return clamp(value, 0, 1); } /** * Clamps value to be not lower than 0 and not higher than 1 */ public static float clamp01(float value) { return clamp(value, 0f, 1f); } /** * Linear-interpolation, returns a value between START and end based on the percentage of time */ public static float lerp(float start, float end, float time) { return lerpUnclamped(start, end, clamp01(time)); } /** * Linear-interpolation without clamping the time variable between 0 and 1 */ public static float lerpUnclamped(float start, float end, float time) { return (end - start) * time + start; } /** * Inverse linear-interpolation */ public static float inverseLerp(float start, float end, float value) { return (value - start) / (end - start); } /** * Returns -1 if value is negative; 1 if value is positive; 0 if value is 0 */ public static int normalize(float value) { return almostEquals(value, 0f) ? 0 : (value < 0f ? -1 : 1); } /** * Returns -1 if value is negative; 1 if value is positive; 0 if value is 0 */ public static int normalize(int value) { if (value == 0) return 0; return value / Math.abs(value); } /** * Convert value to an angle between -180 (Exclusive) and 180 (Inclusive) with the same rotational value as input. */ public static float toSignedAngle(float value) { return -repeat(180f - value, 360f) + 180f; } /** * Convert value to an angle between -179 and 180 with the same rotational value as input. */ public static int toSignedAngle(int value) { return -repeat(180 - value, 360) + 180; } /** * Convert value to an angle between 0f (Inclusive) and 360f (Exclusive) with the same rotational value as input. */ public static float toUnsignedAngle(float value) { return repeat(value, 360f); } /** * Convert value to an angle between 0 and 359 with the same rotational value as input. */ public static int toUnsignedAngle(int value) { return repeat(value, 360); } /** * Wraps value around length so it is always between 0f (Inclusive) and length (Exclusive) */ public static float repeat(float value, float length) { float result = value % length; return result < 0f ? result + length : result; } /** * Wraps value around length so it is always between 0 (Inclusive) and length (Exclusive) */ public static int repeat(int value, int length) { int result = value % length; return result < 0 ? result + length : result; } /** * Returns the a value between zero to one by sampling a sigmoid curve at value. */ public static float sigmoid(float value) { value = clamp01(value) * (float)Math.PI - (float)Math.PI / 2f; return (float)Math.sin(value) / 2f + 0.5f; } }
us-robotics/FTCEngine
Math/Mathf.java
1,387
/** * Clamps value to be not lower than min and not higher than max */
block_comment
en
false
1,216
20
1,387
20
1,411
21
1,387
20
1,529
21
false
false
false
false
false
true
134212_5
/** * WeddingCake class. * * Project_09. * @author Zejian Zhong - COMP 1210 - 008 * @version 4/13/2017 */ public class WeddingCake extends Cake { private int tiers; /** * The class variable - base rate. */ public static final double BASE_RATE = 15.0; /** * @param nameIn the input name. * @param flavorIn the input flavor. * @param quantityIn the input quantity. * @param layersIn the input layers. * @param tiersIn the input tiers. * @param ingredientsIn the input ingredients. */ public WeddingCake(String nameIn, String flavorIn, int quantityIn, int layersIn, int tiersIn, String ... ingredientsIn) { super(nameIn, flavorIn, quantityIn, layersIn, ingredientsIn); tiers = tiersIn; } /** * @return the tiers. */ public int getTiers() { return tiers; } /** * @param tiersIn the input tiers. */ public void setTiers(int tiersIn) { tiers = tiersIn; } /** * @return the calculated price. */ public double price() { return (BASE_RATE * layers * tiers) * quantity; } }
teenight/JavaOne
Project_09/WeddingCake.java
332
/** * @return the calculated price. */
block_comment
en
false
300
11
332
11
350
13
332
11
397
14
false
false
false
false
false
true
134870_9
/** * SimpleDFS.java * This file is part of JaCoP. * * JaCoP is a Java Constraint Programming solver. * * Copyright (C) 2000-2008 Krzysztof Kuchcinski and Radoslaw Szymanek * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * Notwithstanding any other provision of this License, the copyright * owners of this work supplement the terms of this License with terms * prohibiting misrepresentation of the origin of this work and requiring * that modified versions of this work be marked in reasonable ways as * different from the original version. This supplement of the license * terms is in accordance with Section 7 of GNU Affero General Public * License version 3. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ import org.jacop.constraints.Not; import org.jacop.constraints.PrimitiveConstraint; import org.jacop.constraints.XeqC; import org.jacop.core.FailException; import org.jacop.core.IntDomain; import org.jacop.core.IntVar; import org.jacop.core.Store; /** * Implements Simple Depth First Search . * * @author Krzysztof Kuchcinski * @version 4.1 */ public class VSM { boolean trace = false; /** * Store used in search */ Store store; /** * Defines varibales to be printed when solution is found */ IntVar[] variablesToReport; /** * It represents current depth of store used in search. */ int depth = 0; /** * It represents the cost value of currently best solution for FloatVar cost. */ public int costValue = IntDomain.MaxInt; /** * It represents the cost variable. */ public IntVar costVariable = null; /* * Visited nodes */ int visited = 0; /* * Erroneous visits */ int wrongs = 0; public VSM(Store s) { store = s; } /** * This function is called recursively to assign variables one by one. */ public boolean label(IntVar[] vars) { if (trace) { for (int i = 0; i < vars.length; i++) System.out.print (vars[i] + " "); System.out.println (); } visited++; ChoicePoint choice = null; boolean consistent; // Instead of imposing constraint just restrict bounds // -1 since costValue is the cost of last solution if (costVariable != null) { try { if (costVariable.min() <= costValue - 1) costVariable.domain.in(store.level, costVariable, costVariable.min(), costValue - 1); else return false; } catch (FailException f) { return false; } } consistent = store.consistency(); if (!consistent) { // Failed leaf of the search tree wrongs++; return false; } else { // consistent if (vars.length == 0) { // solution found; no more variables to label // update cost if minimization if (costVariable != null) costValue = costVariable.min(); reportSolution(); return costVariable == null; // true is satisfiability search and false if minimization } choice = new ChoicePoint(vars); levelUp(); store.impose(choice.getConstraint()); // choice point imposed. consistent = label(choice.getSearchVariables()); if (consistent) { levelDown(); return true; } else { restoreLevel(); store.impose(new Not(choice.getConstraint())); // negated choice point imposed. consistent = label(vars); levelDown(); if (consistent) { return true; } else { return false; } } } } void levelDown() { store.removeLevel(depth); store.setLevel(--depth); } void levelUp() { store.setLevel(++depth); } void restoreLevel() { store.removeLevel(depth); store.setLevel(store.level); } public void reportSolution() { if (costVariable != null) System.out.println ("Cost is " + costVariable); for (int i = 0; i < variablesToReport.length; i++) System.out.print (variablesToReport[i] + " "); System.out.println ("\n---------------"); } public void setVariablesToReport(IntVar[] v) { variablesToReport = v; } public void setCostVariable(IntVar v) { costVariable = v; } public class ChoicePoint { IntVar var; IntVar[] searchVariables; int value; public ChoicePoint (IntVar[] v) { var = selectVariable(v); value = selectValue(var); } public IntVar[] getSearchVariables() { return searchVariables; } /** * example variable selection; small interval first */ IntVar selectVariable(IntVar[] v) { int low = 0; int dom = Integer.MAX_VALUE; for (int i = 0; i < v.length; i++) { int thisdom = v[i].max()-v[i].min(); if(thisdom < dom) { low = i; dom = thisdom; } } if (v.length != 0) { searchVariables = new IntVar[v.length-1]; int j = 0; for (int i = 0; i < v.length-1; i++) { if (low == j) { j++; i--; } else { searchVariables[i] = v[j++]; } } return v[low]; } else { System.err.println("Zero length list of variables for labeling"); return new IntVar(store); } } /** * example value selection; indomain_min */ int selectValue(IntVar v) { return v.min(); } /** * example constraint assigning a selected value */ public PrimitiveConstraint getConstraint() { return new XeqC(var, value); } } }
tfla/edan01
lab3/VSM.java
1,700
/** * This function is called recursively to assign variables one by one. */
block_comment
en
false
1,496
17
1,700
17
1,799
19
1,700
17
2,043
20
false
false
false
false
false
true
138104_4
package ggc.core; import java.io.Serializable; import java.util.Optional; import ggc.core.util.Pair; /** Partner status */ public interface PartnerStatus extends Serializable, WarehouseFormattable { /** * Calculates the discount of this status (0.0 to 1.0) for a given date * * @param date * The date to calculate the discount at * @param paymentDate * the payment date of the transaction * @param factor * The product payment factor * @return The discount */ double getDiscount(int date, int paymentDate, int factor); /** * Calculates the penalty of this status (>= 0.0) for a given date * * @param date * The date to calculate the penalty at * @param paymentDate * the payment date of the transaction * @param factor * The product payment factor * @return The penalty */ double getPenalty(int date, int paymentDate, int factor); /** * Possibly promotes this status, if the amount of points is enough * * @param points * The amount of points of the partner * @return The promoted partner status, if promoted */ Optional<PartnerStatus> checkPromotion(double points); /** * Demotes this partner and returns their new points * * @param points * The amount of points of the partner * @param date * The date to calculate the penalty at * @param paymentDate * the payment date of the transaction * @return The demoted partner status, and their new points */ Pair<PartnerStatus, Double> checkDemotion(double points, int date, int paymentDate); }
Zenithsiz/po-proj
ggc/core/PartnerStatus.java
405
/** * Demotes this partner and returns their new points * * @param points * The amount of points of the partner * @param date * The date to calculate the penalty at * @param paymentDate * the payment date of the transaction * @return The demoted partner status, and their new points */
block_comment
en
false
402
84
405
75
438
86
405
75
463
86
false
false
false
false
false
true
143539_9
/** * The Class Student. */ public class Student { /** The id. */ private int id; /** The first name. */ private String firstName; /** The last name. */ private String lastName; /** The age. */ private int age; /** The gender. */ private String gender; /** The departmant name. */ private String departmantName; /** The joined year. */ private int joinedYear; /** The city. */ private String city; /** The rank. */ private int rank; /** * Instantiates a new employee. * * @param id the id * @param firstName the first name * @param lastName the last name * @param age the age * @param gender the gender * @param departmantName the departmant name * @param joinedYear the joined year * @param city the city * @param rank the rank */ public Student(int id, String firstName, String lastName, int age, String gender, String departmantName, int joinedYear, String city, int rank) { super(); this.id = id; this.firstName = firstName; this.lastName = lastName; this.age = age; this.gender = gender; this.departmantName = departmantName; this.joinedYear = joinedYear; this.city = city; this.rank = rank; } /** * Gets the id. * * @return the id */ public int getId() { return id; } /** * Sets the id. * * @param id the new id */ public void setId(int id) { this.id = id; } /** * Gets the first name. * * @return the first name */ public String getFirstName() { return firstName; } /** * Sets the first name. * * @param firstName the new first name */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * Gets the last name. * * @return the last name */ public String getLastName() { return lastName; } /** * Sets the last name. * * @param lastName the new last name */ public void setLastName(String lastName) { this.lastName = lastName; } /** * Gets the age. * * @return the age */ public int getAge() { return age; } /** * Sets the age. * * @param age the new age */ public void setAge(int age) { this.age = age; } /** * Gets the gender. * * @return the gender */ public String getGender() { return gender; } /** * Sets the gender. * * @param gender the new gender */ public void setGender(String gender) { this.gender = gender; } /** * Gets the departmant name. * * @return the departmant name */ public String getDepartmantName() { return departmantName; } /** * Sets the departmant name. * * @param departmantName the new departmant name */ public void setDepartmantName(String departmantName) { this.departmantName = departmantName; } /** * Gets the joined year. * * @return the joined year */ public int getJoinedYear() { return joinedYear; } /** * Sets the joined year. * * @param joinedYear the new joined year */ public void setJoinedYear(int joinedYear) { this.joinedYear = joinedYear; } /** * Gets the city. * * @return the city */ public String getCity() { return city; } /** * Sets the city. * * @param city the new city */ public void setCity(String city) { this.city = city; } /** * Gets the rank. * * @return the rank */ public int getRank() { return rank; } /** * Sets the rank. * * @param rank the new rank */ public void setRank(int rank) { this.rank = rank; } /** * To string. * * @return the string */ @Override public String toString() { return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + ", gender=" + gender + ", departmantName=" + departmantName + ", joinedYear=" + joinedYear + ", city=" + city + ", rank=" + rank + "]"; } }
tigerbalm62/stream
Student.java
1,104
/** The rank. */
block_comment
en
false
1,082
5
1,104
5
1,281
5
1,104
5
1,395
5
false
false
false
false
false
true
152662_1
package week11; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.TreeSet; public class TopK { /** * Collect the k maximum values by inserting candidates into a binary tree. * * @param candidates - the items to 'sort' into the tree. * @param k - the number of maximum elements to select. * @return a list of the k largest elements in candidates. */ public List<Integer> binaryTreeTopK(List<Integer> candidates, int k) { TreeSet<Integer> tree = new TreeSet<>(candidates); List<Integer> output = new ArrayList<>(); Iterator<Integer> it = tree.descendingIterator(); for (int i = 0; i < k && it.hasNext(); i++) { output.add(it.next()); } Collections.reverse(output); return output; } /** * Collect the top-k elements from a list by sorting; with * {@linkplain Collections#sort}. * * @param candidates - the items to 'rank' * @param k - the number of elements to take * @return the k maximum elements of candidates. */ public List<Integer> sortAllTopK(List<Integer> candidates, int k) { Collections.sort(candidates); return candidates.subList(candidates.size() - k, candidates.size()); } /** * Find the k largest items from a list. * * Time: O(nlog(n)) * Space: O(k) * * @param candidates - the list to consider. * @param k - the number of elements to choose. * @return a list of the k largest elements. */ public static List<Integer> heapTopK(List<Integer> candidates, int k) { IntMinHeap heap = new IntMinHeap(); for (int c : candidates) { heap.insert(c); // Don't let the heap get too big: if (heap.size() > k) { heap.removeMin(); } } return heap.drain(); } }
sujaybanerjee/data-structures
TopK.java
502
/** * Collect the top-k elements from a list by sorting; with * {@linkplain Collections#sort}. * * @param candidates - the items to 'rank' * @param k - the number of elements to take * @return the k maximum elements of candidates. */
block_comment
en
false
454
66
502
65
551
73
502
65
577
74
false
false
false
false
false
true
154478_1
import javax.swing.*; /** * Creates the frame * @author Crystal Chun ID #012680952 * */ public class Frame extends JFrame { /**The panel to be placed on the frame*/ private Panel panel; /** * The frame constructor, constructs the window */ public Frame() { setBounds(50, 40, 1300, 800); panel = new Panel(); getContentPane().add(panel); } public static void main(String[] args) { //Creates the frame, allows it to be closed, and sets it to visible Frame frame = new Frame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
CrystalChun/Missile-Defender
src/Frame.java
198
/**The panel to be placed on the frame*/
block_comment
en
false
164
10
198
10
199
10
198
10
225
10
false
false
false
false
false
true
167389_1
import java.util.ArrayList; import java.util.GregorianCalendar; public class ReservationData{ private ArrayList<Reservation> list = new ArrayList<Reservation>(); public ReservationData(){ } /* Populates the List of reservations from the res.csv file. */ public ReservationData(String[][] resData, Hotels hot){ ArrayList<Room> rum; for(int i = 1; i< resData.length; i++){ int number = Integer.parseInt(resData[i][0]); int count = 0; for(int z = 0; z< list.size(); z++){ if(number == list.get(z).getNumber()){ count++; } } if(count == 0){ if(resData[i][7].equals("Classic Single") || resData[i][7].equals("Classic Twin") || resData[i][7].equals("Classic Double")){ rum = hot.getArray("3"); }else if(resData[i][7].equals("Executie Double") || resData[i][7].equals("Executive Twin") || resData[i][7].equals("Executive Single")){ rum = hot.getArray("4"); }else{ rum = hot.getArray("5"); } String name = resData[i][1]; boolean resType = Boolean.parseBoolean(resData[i][2]); String dateFrom = resData[i][3]; int nights = Integer.parseInt(resData[i][5]); int rooms = Integer.parseInt(resData[i][6]); String roomType = resData[i][7]; int adults = Integer.parseInt(resData[i][8]); int children = Integer.parseInt(resData[i][9]); boolean breakfast = Boolean.parseBoolean(resData[i][10]); double deposit = Double.parseDouble(resData[i][11]); Reservation res = new Reservation(number, name, dateFrom, resType, nights, rooms, roomType, adults, children, breakfast, deposit); int loop = 1; for(int j = 0; j < rum.size(); j++){ if((roomType.equals(rum.get(j).getRoomType())) == true){ if(loop <= rooms){ rum.get(j).getBooked().add(res); loop++; }else{ list.add(res); break; } } } } } } /* Checks if a room is available and adds a reservation object to both the list of reservations and to the rooms associated with the object. */ public boolean checkAvailability(Reservation res, Hotels hot, GregorianCalendar dateFrom, GregorianCalendar dateTo, String roomType){// Get rid of SString parameter GregorianCalendar from = null; GregorianCalendar to = null; int pos = 0; for(int i = 0; i < hot.getArray(hot.getChoice()).size(); i++){ if((roomType.equals(hot.getArray(hot.getChoice()).get(i).getRoomType())) == true){ if(hot.getArray(hot.getChoice()).get(i).getBooked().size() > 0){ for(int j = 0; j < hot.getArray(hot.getChoice()).get(i).getBooked().size(); j++){ from = hot.getArray(hot.getChoice()).get(i).getBooked().get(j).getDateFrom(); to = hot.getArray(hot.getChoice()).get(i).getBooked().get(j).getDateTo(); if((dateFrom.before(from) && dateTo.before(from)) || (dateFrom.after(to) && dateTo.after(to))){ if(hot.getArray(hot.getChoice()).get(i).getBooked().size() == j+1){ pos = i; hot.getArray(hot.getChoice()).get(pos).getBooked().add(res); return true; } }else{ break; } } }else{ hot.getArray(hot.getChoice()).get(i).getBooked().add(res); return true; } } } return false; } /* Gets the rates for the roomType associated with the Reservation object passed in. */ public double[] getRates(Reservation res, Hotels hot){ for(int i = 0; i < hot.getArray(hot.getChoice()).size(); i++){ if((res.getRoomType().equals(hot.getArray(hot.getChoice()).get(i).getRoomType())) == true){ return hot.getArray(hot.getChoice()).get(i).getRates(); } } return null; } /* Finds a Reservation and cancels it removes it from the Reservation List and removes it from the rooms associates it. Doesn't write to files. */ public boolean findRoom(int num, Hotels hot){ GregorianCalendar greg = new GregorianCalendar(); for(int i = 0; i < hot.getArray(hot.getChoice()).size(); i++){ for(int j = 0; j < hot.getArray(hot.getChoice()).get(i).getBooked().size(); j++){ if(num == hot.getArray(hot.getChoice()).get(i).getBooked().get(j).getNumber()){ if(hot.getArray(hot.getChoice()).get(i).getBooked().get(j).isResType()){ if((hot.getArray(hot.getChoice()).get(i).getBooked().get(j).getDateFrom().getTimeInMillis() - greg.getTimeInMillis()) > 172800000 ){ hot.getArray(hot.getChoice()).get(i).getBooked().remove(j); }else{ System.out.println("Too close to checkin date to cancel!"); return false; } }else{ System.out.println("Not allowed cancel AP reservations!"); return false; } } } } for(int i = 0; i < list.size(); i++){ if(list.get(i).getNumber() == num){ if((list.get(i).getDateFrom().getTimeInMillis() - greg.getTimeInMillis()) > 172800000 ){ list.remove(i); } } } return true; } /* Finds a Reservation and removes it from the Reservation List and removes it from the rooms associates it. Adds it to the cancellation list Then write to csv files. */ public boolean cancellations(int num, Hotels hot, Mainsys mainsys){ GregorianCalendar greg = new GregorianCalendar(); boolean flip = false; Reservation cancelled = null; for(int i = 0; i < hot.getArray(hot.getChoice()).size(); i++){ for(int j = 0; j < hot.getArray(hot.getChoice()).get(i).getBooked().size(); j++){ if(num == hot.getArray(hot.getChoice()).get(i).getBooked().get(j).getNumber()){ if(hot.getArray(hot.getChoice()).get(i).getBooked().get(j).isResType()){ if((hot.getArray(hot.getChoice()).get(i).getBooked().get(j).getDateFrom().getTimeInMillis() - greg.getTimeInMillis()) > 172800000 ){ cancelled = hot.getArray(hot.getChoice()).get(i).getBooked().get(j); hot.getArray(hot.getChoice()).get(i).getBooked().remove(j); flip = true; }else{ System.out.println("Too close to checkin date to cancel!"); return false; } }else{ System.out.println("Not allowed cancel AP reservations!"); return false; } } } } if(flip == false){ return false; } mainsys.getCheckData().getCancellations().add(cancelled); mainsys.getRead().writeCancellations(hot, mainsys.getCheckData()); for(int i = 0; i < list.size(); i++){ if(list.get(i).getNumber() == num){ if((list.get(i).getDateFrom().getTimeInMillis() - greg.getTimeInMillis()) > 172800000 ){ list.remove(i); } } } return true; } public ArrayList<Reservation> getList() { return list; } }
ShaneWhelan/Hotel-Reservation-System
ReservationData.java
2,195
/* Checks if a room is available and adds a reservation object to both the list of reservations and to the rooms associated with the object. */
block_comment
en
false
1,825
31
2,195
33
2,132
33
2,195
33
2,758
37
false
false
false
false
false
true
169863_4
import javax.swing.*; import java.awt.*; public class Panel extends JPanel { public Panel() { setLayout(new BorderLayout()); // Top panel with GridBagLayout to respect preferred sizes JPanel topPanel = new JPanel(new GridBagLayout()); topPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 10)); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.insets = new Insets(0, 0, 5, 0); // Add padding between components JLabel dayLabel = new JLabel("Date today"); dayLabel.setPreferredSize(new Dimension(300, 50)); dayLabel.setHorizontalAlignment(SwingConstants.CENTER); dayLabel.setBorder(BorderFactory.createLineBorder(Color.black)); gbc.gridx = 0; gbc.gridy = 0; topPanel.add(dayLabel, gbc); JLabel calendarLabel = new JLabel("Calendar"); calendarLabel.setPreferredSize(new Dimension(300, 50)); calendarLabel.setHorizontalAlignment(SwingConstants.CENTER); calendarLabel.setBorder(BorderFactory.createLineBorder(Color.black)); gbc.gridx = 0; gbc.gridy = 1; topPanel.add(calendarLabel, gbc); add(topPanel, BorderLayout.NORTH); // Task panel with GridBagLayout to respect preferred sizes JPanel taskPanel = new JPanel(new GridBagLayout()); taskPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); GridBagConstraints gbcTask = new GridBagConstraints(); gbcTask.fill = GridBagConstraints.HORIZONTAL; gbcTask.insets = new Insets(5, 5, 5, 5); // Add padding between components // Activity panel with GridBagLayout to respect preferred sizes JPanel activityPanel = new JPanel(new GridBagLayout()); activityPanel.setBorder(BorderFactory.createLineBorder(Color.red)); GridBagConstraints gbcActivity = new GridBagConstraints(); gbcActivity.fill = GridBagConstraints.HORIZONTAL; gbcActivity.insets = new Insets(5, 5, 5, 5); // Add padding between components JLabel background = new JLabel("DO Anytime"); background.setPreferredSize(new Dimension(300, 100)); background.setHorizontalAlignment(SwingConstants.CENTER); background.setBorder(BorderFactory.createLineBorder(Color.black)); gbcActivity.gridx = 0; gbcActivity.gridy = 0; activityPanel.add(background, gbcActivity); JLabel progressBar = new JLabel("Progress"); progressBar.setPreferredSize(new Dimension(200, 100)); progressBar.setHorizontalAlignment(SwingConstants.CENTER); progressBar.setBorder(BorderFactory.createLineBorder(Color.black)); gbcActivity.gridx = 0; gbcActivity.gridy = 1; activityPanel.add(progressBar, gbcActivity); gbcTask.gridx = 0; gbcTask.gridy = 0; taskPanel.add(activityPanel, gbcTask); add(taskPanel, BorderLayout.CENTER); } }
Ejanng/javagui
Panel.java
717
// Activity panel with GridBagLayout to respect preferred sizes
line_comment
en
false
604
11
717
10
736
10
717
10
901
11
false
false
false
false
false
true
172675_7
/******************************************************************************* * This file is part of the Polyglot extensible compiler framework. * * Copyright (c) 2000-2012 Polyglot project group, Cornell University * Copyright (c) 2006-2012 IBM Corporation * All rights reserved. * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License v1.0 which accompanies this * distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * This program and the accompanying materials are made available under * the terms of the Lesser GNU Public License v2.0 which accompanies this * distribution. * * The development of the Polyglot project has been supported by a * number of funding sources, including DARPA Contract F30602-99-1-0533, * monitored by USAF Rome Laboratory, ONR Grants N00014-01-1-0968 and * N00014-09-1-0652, NSF Grants CNS-0208642, CNS-0430161, CCF-0133302, * and CCF-1054172, AFRL Contract FA8650-10-C-7022, an Alfred P. Sloan * Research Fellowship, and an Intel Research Ph.D. Fellowship. * * See README for contributors. ******************************************************************************/ package polyglot.ast; import java.util.List; /** * An immutable representation of a {@code try} block, one or more * {@code catch} blocks, and an optional {@code finally} block. * */ public interface Try extends CompoundStmt { /** The block to "try". */ Block tryBlock(); /** Set the block to "try". */ Try tryBlock(Block tryBlock); /** * List of catch blocks. * @return A list of {@link polyglot.ast.Catch Catch}. */ List<Catch> catchBlocks(); /** * Set the list of catch blocks. * @param catchBlocks A list of {@link polyglot.ast.Catch Catch}. */ Try catchBlocks(List<Catch> catchBlocks); /** The block to "finally" execute. */ Block finallyBlock(); /** Set the block to "finally" execute. */ Try finallyBlock(Block finallyBlock); }
polyglot-compiler/polyglot
src/polyglot/ast/Try.java
590
/** Set the block to "finally" execute. */
block_comment
en
false
529
11
590
11
591
11
590
11
650
12
false
false
false
false
false
true
177810_2
import java.util.ArrayList; /** * Represents a player in the AviBS project * * @author Avi, Susan */ public abstract class Player { private String name; private Hand currentHand; private boolean isHuman; /** * No-arg constructor for a new player * @author Avi */ public Player() { } /** * Constructs a new player with a given name that is either a Bot or a Human. Also * initializes the player's current hand * @param name the player's name * @param type whether it's a human or a bot * @author Avi */ public Player( String name, boolean type ) { this.name = name; this.currentHand = new Hand(); this.isHuman = type; } /** * Adds a card to the player's hand * @param c card to be added * @author Avi */ public void addCard( Card c ) { this.currentHand.addCard( c ); } /** * Prints the cards that are currently in the player's hand * @return a string with the cards that are currently in the player's hand * @author Avi */ public String viewHand() { return currentHand.viewHand(); } /** * Gets the current player's hand * @return the player's hand * @author Avi */ public ArrayList<Card> getHand() { return this.currentHand.getHand(); } /** * Gets the current player's name * @return the player's name * @author Avi */ public String getName() { return this.name; } /** * Adds the cards to the player's hand * @param cards cards to be added * @author Susan */ public void addCards( ArrayList<Card> cards ) { this.currentHand.addCards( cards ); } /** * Removes a card from the player's hand * @param c card to be removed * @author Susan */ public void removeCard( int c ) { this.currentHand.removeNum( c ); } /** * Checks whether the player is a bot or a human * @return true if the player is a bot, false otherwise * @author Susan */ public boolean isBot() { return !isHuman; } public abstract void sortCards(); public abstract ArrayList<Card> BotPlayCurrentCard( int c, Pile p ); public abstract ArrayList<Card> BotPlayHighest(); }
TheCurryMan/AviBS
Player.java
592
/** * Constructs a new player with a given name that is either a Bot or a Human. Also * initializes the player's current hand * @param name the player's name * @param type whether it's a human or a bot * @author Avi */
block_comment
en
false
587
64
592
59
678
68
592
59
726
72
false
false
false
false
false
true
181028_5
// Given an array of numbers and an index i, return the index of the nearest larger number of the number at index i, // where distance is measured in array indices. // For example, given [4, 1, 3, 5, 6] and index 0, you should return 3. // If two distances to larger numbers are the equal, then return any one of them. // If the array at i doesn't have a nearest larger integer, then return null. // Follow-up: If you can preprocess the array, can you do this in constant time? public class Day46 { public static Integer getNearestLargest(int[] numbers, int index) { // traversing for(int i=0; i< numbers.length; i++) { // for storing relative distance for both left and right side int left= index-i; int right= index+i; if(left>=0 && numbers[left]> numbers[index]) return left; else if(right<numbers.length && numbers[right]>numbers[index]) return right; } // if nothing is returned yet, then queried index number is largest return null; } // Driver code public static void main(String args[]) { int numbers[]= {4, 1, 3, 5, 6}; System.out.println(getNearestLargest(numbers,0)); } }
sodeep105/100-Days-Of-Coding
Day46.java
352
// Follow-up: If you can preprocess the array, can you do this in constant time?
line_comment
en
false
310
20
352
21
368
20
352
21
419
22
false
false
false
false
false
true
198569_3
/* ** ${CLASS:emxManufacturingPlan} ** **Copyright (c) 1993-2016 Dassault Systemes. ** All Rights Reserved. **This program contains proprietary and trade secret information of **Dassault Systemes. ** Copyright notice is precautionary only and does not evidence any actual **or intended publication of such program */ import com.matrixone.apps.domain.util.EnoviaResourceBundle; import com.matrixone.apps.domain.util.i18nNow; import matrix.db.Context; /** * This JPO class has some methods pertaining to emxManufacturingPlan Extension. * @author IVU * @version R209 - Copyright (c) 1993-2016 Dassault Systemes. */ public class ManufacturingPlan_mxJPO extends ManufacturingPlanBase_mxJPO { /** * Create a new ${CLASS:emxManufacturingPlanBase} object from a given id. * * @param context the eMatrix <code>Context</code> object * @param args holds no arguments. * @throws Exception if the operation fails * @author IVU * @since R209 */ public ManufacturingPlan_mxJPO (Context context, String[] args) throws Exception { super(context, args); } /** * Main entry point. * * @param context the eMatrix <code>Context</code> object * @param args holds no arguments * @return an integer status code (0 = success) * @throws Exception if the operation fails * @author IVU * @since R209 */ public int mxMain(Context context, String[] args)throws Exception { if (!context.isConnected()){ String sContentLabel = EnoviaResourceBundle.getProperty(context,"DMCPlanning","DMCPlanning.Error.UnsupportedClient", context.getSession().getLanguage()); throw new Exception(sContentLabel); } return 0; } }
hellozjf/JPO
ManufacturingPlan_mxJPO.java
491
/** * Main entry point. * * @param context the eMatrix <code>Context</code> object * @param args holds no arguments * @return an integer status code (0 = success) * @throws Exception if the operation fails * @author IVU * @since R209 */
block_comment
en
false
437
76
491
71
515
82
491
71
572
88
false
false
false
false
false
true
205513_2
/* Copyright 2018 Mark P Jones, Portland State University This file is part of minitour. minitour 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 3 of the License, or (at your option) any later version. minitour 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 minitour. If not, see <https://www.gnu.org/licenses/>. */ package ast; import compiler.Failure; import compiler.Position; /** Abstract syntax for less than or equal expressions. */ public class Lte extends BinCompExpr { /** Default constructor. */ public Lte(Position pos, Expr left, Expr right) { super(pos, left, right); } /** Return a string that provides a simple description of this * particular type of operator node. */ String label() { return "Lte"; } /** Generate a pretty-printed description of this expression * using the concrete syntax of the mini programming language. */ public void print(TextOutput out) { binary(out, "<="); } /** Constant folding for binary operators with two known integer * arguments. */ Expr fold(int n, int m) { return new BoolLit(pos, n<=m); } /** Evaluate this expression. */ public int eval() throws Failure { return fromBool(left.eval() <= right.eval()); } }
zipwith/minitour
20/ast/Lte.java
396
/** Default constructor. */
block_comment
en
false
377
6
396
6
426
7
396
6
479
7
false
false
false
false
false
true
210760_4
import java.io.*; import java.util.ArrayList; /** class constructs basic functionality of nest */ public class Nest implements Serializable { /** max number of parts per nest */ public final int limit = 8; /** parts are in the nest */ public ArrayList<Part> nestedItems; /** true if nest is full */ private boolean nestFull; /** true if nest is up */ private boolean nestUp; /** Initialization */ public Nest(){ nestedItems = new ArrayList<Part>(); nestFull = false; nestUp = true; } /** returns whether nest is full */ public boolean isNestFull(){ return nestFull; } /** returns whether nest is empty */ public boolean isNestEmpty(){ return nestedItems.isEmpty(); } /** load part into nest, returns whether successful */ public boolean addPart( Part p ){ if (!nestUp) return true; // automatically dump part if nest is down if(nestedItems.size() < limit) { nestedItems.add(p); if(nestedItems.size() == limit){ nestFull = true; } return true; } else { //nest full return false; } } /** remove part from nest */ public Part removePart(){ if( nestedItems.size() > 0 ){ nestFull = false; return nestedItems.remove( 0 ); } else { return null; } } /** dump nest out */ public void dumpNest(){ nestedItems = new ArrayList<Part>(); nestFull = false; } /** setter for whether nest is up */ public void setNestUp(boolean newNestUp){ nestUp = newNestUp; if (!nestUp) dumpNest(); } /** returns if nest is up */ public boolean isNestUp(){ return nestUp; } }
claytonketner/CSCI200_FactorySim
Nest.java
472
/** true if nest is up */
block_comment
en
false
411
7
472
7
476
7
472
7
538
7
false
false
false
false
false
true
212524_2
/* Copyright 2010-2019 Urban Airship and Contributors */ package com.urbanairship.cordova; import android.os.Bundle; import android.service.notification.StatusBarNotification; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.urbanairship.push.PushMessage; import com.urbanairship.util.UAStringUtil; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; /** * Utility methods. */ public class Utils { /** * Parses a {@link PushMessage} from a status bar notification. * * @param statusBarNotification The status bar notification. * @return The push message from the status bar notification. */ @NonNull public static PushMessage messageFromNotification(@NonNull StatusBarNotification statusBarNotification) { Bundle extras = statusBarNotification.getNotification().extras; if (extras == null) { return new PushMessage(new Bundle()); } Bundle pushBundle = extras.getBundle(CordovaNotificationFactory.PUSH_MESSAGE_BUNDLE_EXTRA); if (pushBundle == null) { return new PushMessage(new Bundle()); } else { return new PushMessage(pushBundle); } } /** * Helper method to create a notification JSONObject. * * @param message The push message. * @param notificationTag The optional notification tag. * @param notificationId The optional notification ID. * @return A JSONObject containing the notification data. */ @NonNull public static JSONObject notificationObject(@NonNull PushMessage message, @Nullable String notificationTag, @Nullable Integer notificationId) throws JSONException { JSONObject data = new JSONObject(); Map<String, String> extras = new HashMap<>(); for (String key : message.getPushBundle().keySet()) { if ("android.support.content.wakelockid".equals(key)) { continue; } if ("google.sent_time".equals(key)) { extras.put(key, Long.toString(message.getPushBundle().getLong(key))); continue; } if ("google.ttl".equals(key)) { extras.put(key, Integer.toString(message.getPushBundle().getInt(key))); continue; } String value = message.getPushBundle().getString(key); if (value != null) { extras.put(key, value); } } data.putOpt("message", message.getAlert()); data.putOpt("title", message.getTitle()); data.putOpt("subtitle", message.getSummary()); data.putOpt("extras", new JSONObject(extras)); if (notificationId != null) { data.putOpt("notification_id", notificationId); data.putOpt("notificationId", getNotificationId(notificationId, notificationTag)); } return data; } @NonNull private static String getNotificationId(int notificationId, @Nullable String notificationTag) { String id = String.valueOf(notificationId); if (!UAStringUtil.isEmpty(notificationTag)) { id += ":" + notificationTag; } return id; } }
Chuckv01/urbanairship-cordova
src/android/Utils.java
731
/** * Parses a {@link PushMessage} from a status bar notification. * * @param statusBarNotification The status bar notification. * @return The push message from the status bar notification. */
block_comment
en
false
633
44
731
45
789
51
731
45
862
53
false
false
false
false
false
true
215981_1
import java.util.ArrayList; class Main { public static void main(String[] args) { ArrayList<String> languages= new ArrayList<>(); // Add elements in the arraylist languages.add("Java"); languages.add("Python"); languages.add("JavaScript"); System.out.println("ArrayList: " + languages); // Create a new array of String type String[] arr = new String[languages.size()]; // Convert ArrayList into the string array languages.toArray(arr); System.out.print("Array: "); for(String item:arr) { System.out.print(item+", "); } } }
vatsalcode/LLM_Transformer_Queue
day101.java
147
// Create a new array of String type
line_comment
en
false
129
8
147
8
162
8
147
8
170
8
false
false
false
false
false
true
219037_1
import java.io.PrintWriter; /** * Simple hash tables. */ public interface HashTable<K,V> extends SimpleMap<K,V>, Iterable<Pair<K,V>> { /** * Clear the whole table. */ public void clear(); /** * Dump the hash table. */ public void dump(PrintWriter pen); /** * Should we report basic calls? Intended mostly for tracing. */ public void reportBasicCalls(boolean report); } // interface HashTable<K,V>
Grinnell-CSC207/lab-hashtables
src/HashTable.java
121
/** * Clear the whole table. */
block_comment
en
false
101
10
121
10
130
12
121
10
142
12
false
false
false
false
false
true
225956_5
/** * Class representing the sub class of a Rogue character in the game * @author mfrankel8 * @version 1 */ public class Rogue extends Character { /** * Main contructor for Rogue type * @param name Name of Rogue * @param level Level to set Rogue * @param strength Strength of Rogue * @param dexterity Dexterity of Rogue * @param intelligence Intelligence of Rogue * @param wisdom Wisom of Rogue * */ public Rogue(String name, int level, int strength, int dexterity, int intelligence, int wisdom) { super(name, level, strength, dexterity, intelligence, wisdom); } /** * Second Rogue contructor * @param name Name of rogue * @param seed Random seed * */ public Rogue(String name, int seed) { super(name, seed); } /** * Level up function */ public void levelUp() { setLevel(getLevel() + 1); setHealth(getLevel() * 5); setStrength(getStrength() + 2); setDexterity(getDexterity() + 3); setIntelligence(getIntelligence() + 2); setWisdom(getWisdom() + 2); } /** * toString function for Rogue * @return string representation */ public String toString() { return String.format("Level %s rogue named %s with %s strength, " + "%s dexterity, %s intelligence, and %s wisdom.", getLevel(), getName(), getStrength(), getDexterity(), getIntelligence(), getWisdom()); } /** * Rouge Attack function * @param c character to attack */ public void attack(Character c) { if (c.getIsDead()) { System.out.println("Cannot attack a dead character"); } else { c.setHealth(c.getHealth() - (6 + getDexterity())); } } }
marcfrankel/HW4_Java_-DnD_Characters
Rogue.java
512
/** * Rouge Attack function * @param c character to attack */
block_comment
en
false
451
18
512
18
500
19
512
18
569
21
false
false
false
false
false
true
229817_0
import java.util.*; import java.io.*; public class AddressBook { // Storing all the contacts in an ArrayList private static ArrayList<Contact> contacts = new ArrayList<Contact>(); // Data file name to store the contacts private static String file = "data.bin"; // Scanner object for reading the user input private static Scanner sc = new Scanner(System.in); // The main function where the program starts public static void main(String[] args) throws Exception { // Load contacts from the file loadData(); try { // Display the menu in a loop until the user decides to quit while (true) { displayMenu(); } } finally { // Always close the Scanner if (sc != null) { sc.close(); } } } // Load the contact data from a file private static void loadData() { // Try-with-resources to auto-close streams try (FileInputStream fis = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(fis)) { // Reading the serialized ArrayList from the file contacts = (ArrayList<Contact>) ois.readObject(); // Set the ID counter to the last contact's ID if (!contacts.isEmpty()) { Contact.setCount(contacts.get(contacts.size()-1).getId()); } } catch (FileNotFoundException e) { // If the file doesn't exist, initialize contacts as an empty list. contacts = new ArrayList<Contact>(); } catch (IOException e) { // Handle any IO exceptions System.err.println("Error while loading data: " + e.getMessage()); contacts = new ArrayList<Contact>(); } catch (ClassNotFoundException e) { // Handle any class not found exceptions System.err.println("Error: The Contact class is not found: " + e.getMessage()); } } // Save the contact data to a file private static void saveData() { // Try-with-resources to auto-close streams try (FileOutputStream fos = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(fos)) { // Writing the ArrayList to the file oos.writeObject(contacts); } catch (IOException e) { // Handle any IO exceptions System.err.println("Error while saving data: " + e.getMessage()); } } // Display the main menu and handle user choice private static void displayMenu() { // Display the menu options System.out.println("\nMain Window"); System.out.println("============"); System.out.println("Choose one of the following options:"); System.out.println("\n(1) Add a new contact"); System.out.println("(2) Search for a contact"); System.out.println("(3) Display all contacts"); System.out.println("(4) Quit"); System.out.print("\nEnter Your Choice: "); // Read the user's choice int choice = -1; try { choice = sc.nextInt(); } catch (InputMismatchException e) { // Handle invalid user input System.out.println("\nInvalid input. Please enter a number between 1 and 4."); choice = 5; } sc.nextLine(); // Consume newline left-over // Perform an action based on the user's choice switch (choice) { case 1: // Add a new contact addContact(); break; case 2: // Search for a contact searchContact(); break; case 3: // Display all contacts displayAllContacts(); break; case 4: // Quit the program System.out.println("Goodbye..."); saveData(); sc.close(); System.exit(0); break; case 5: // Do nothing for invalid input break; default: // Handle invalid menu option System.out.println("\nInvalid option. Please choose a number between 1 and 4."); break; } } // Add a new contact private static void addContact() { // Prompt the user for contact details System.out.println("\nMain Window --> Add a new contact window: (Enter the following information)"); System.out.println("==========================================================================="); System.out.print("Name: "); String name = sc.nextLine(); System.out.print("Email: "); String email = sc.nextLine(); System.out.print("Phone: "); String phone = sc.nextLine(); System.out.print("Notes: "); String notes = sc.nextLine(); System.out.println("----------------------------------------------------------------------------"); // Create a new Contact object and add it to the ArrayList contacts.add(new Contact(name, email, phone, notes)); // Save the contact list to a file saveData(); System.out.println("Saved successfully... Press Enter to go back to the Main Window"); sc.nextLine(); } // Method to handle search functionality private static void searchContact() { // Present the user with search options System.out.println("\nMain Window —> Search for Contact Window: (Choose one of the following options)"); System.out.println("================================================================================"); System.out.println("(1) Search by Name"); System.out.println("(2) Search by Email"); System.out.println("(3) Search by Phone"); System.out.print("\nEnter Your Choice: "); // Read the user's choice int choice = -1; try { choice = sc.nextInt(); } catch (InputMismatchException e) { // Handle invalid user input System.out.println("\nInvalid input. Please enter a number between 1 and 3."); choice = 4; } sc.nextLine(); // Consume newline left-over List<Contact> results; switch (choice) { // Each case corresponds to a different search option case 1: System.out.println("\nMain Window --> Search for Contact Window --> Search by Name"); System.out.println("==============================================================="); System.out.print("Enter Name: "); String name = sc.nextLine(); results = findContactsByName(name); displaySearchResults(results); break; case 2: System.out.println("\nMain Window --> Search for Contact Window --> Search by Email"); System.out.println("==============================================================="); System.out.print("Enter Email: "); String email = sc.nextLine(); results = findContactsByEmail(email); displaySearchResults(results); break; case 3: System.out.println("\nMain Window --> Search for Contact Window --> Search by Phone"); System.out.println("==============================================================="); System.out.print("Enter Phone: "); String phone = sc.nextLine(); results = findContactsByPhone(phone); displaySearchResults(results); break; case 4: break; default: // Handle invalid option entries System.out.println("\nInvalid option. Please try again."); break; } } // Method to find contacts by name private static List<Contact> findContactsByName(String name) { List<Contact> results = new ArrayList<Contact>(); // Iterate through the list of contacts for (Contact contact : contacts) { if (contact.getName().equalsIgnoreCase(name)) { results.add(contact); } } return results; } // Method to find contacts by email private static List<Contact> findContactsByEmail(String email) { List<Contact> results = new ArrayList<Contact>(); // Iterate through the list of contacts for (Contact contact : contacts) { if (contact.getEmail().equalsIgnoreCase(email)) { results.add(contact); } } return results; } // Method to find contacts by phone private static List<Contact> findContactsByPhone(String phone) { List<Contact> results = new ArrayList<Contact>(); // Iterate through the list of contacts for (Contact contact : contacts) { if (contact.getPhone().equalsIgnoreCase(phone)) { results.add(contact); } } return results; } // Method to display search results private static void displaySearchResults(List<Contact> results) { if (results.size() == 0) { // Handle case with no search results System.out.println("\nNo contact found."); return; } System.out.println("........................................................................................."); System.out.println("ID\t| Name\t| Email\t| Phone\t| Notes\t"); System.out.println("........................................................................................."); for (Contact contact : results) { System.out.println(contact); } System.out.println("........................................................................................."); System.out.println("\nChoose one of these options:"); System.out.println("(1) To delete a contact"); System.out.println("(2) Back to main Window"); System.out.print("\nEnter Your Choice: "); int choice = sc.nextInt(); sc.nextLine(); // Consume newline left-over if (choice == 1) { System.out.println("\nMain Window --> Search for Contact Window --> Search by Name --> Delete a Contact"); System.out.println("==================================================================================="); System.out.print("Enter the Contact ID: "); int id = sc.nextInt(); sc.nextLine(); // Consume newline left-over deleteContact(id); } } // Method to delete a contact private static void deleteContact(int id) { // Remove the contact with the specified id contacts.removeIf(c -> c.getId() == id); saveData(); System.out.println("\nDeleted... press Enter to go back to main window"); sc.nextLine(); } // Method to display all contacts private static void displayAllContacts() { System.out.println("........................................................................................."); System.out.println("ID\t| Name\t| Email\t| Phone\t| Notes\t"); System.out.println("........................................................................................."); // Iterate through the list of contacts and display each one for (Contact contact : contacts) { System.out.println(contact); } System.out.println("........................................................................................."); System.out.println("\nPress Enter to go back to the Main Window"); sc.nextLine(); } }
liannnaa/AddressBook
AddressBook.java
2,322
// Storing all the contacts in an ArrayList
line_comment
en
false
2,135
9
2,322
9
2,603
8
2,322
9
2,757
9
false
false
false
false
false
true
245327_4
package q3; import java.util.Scanner; /** * Class MIXChar * <p>Reads a line from user input, if all the characters are valid MIXChar * convert them to have the correct numerical values. Then encode them into * a long array. Finally, convert the MIXChar characters to a Java string and * print out them. * </p> * * @author Zhang Yuanyuan * @version 2017-11-30 */ public class MIXChar { /**base of MIX computer.*/ private static final int BASE = 56; /**represents special symbol DELTA.*/ private static final char DELTA = '\u0394'; /**represents special symbol SIGMA.*/ private static final char SIGMA = '\u03A3'; /**represents special symbol PI.*/ private static final char PI = '\u03A0'; /**char array represents all MIXChar characters.*/ private static char[] mixChar = {' ', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', DELTA, 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', SIGMA, PI, 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', ',', '(', ')', '+', '-', '*', '/', '=', '$', '<', '>', '@', ';', ':', '\''}; /**char value of MIXChar.*/ private char mix; /** * Contructs MIXChar objects. * @param mix sets the char value for MIXChar */ public MIXChar(char mix) { this.mix = mix; } /** * <p>Drives the program.</p> * * @param args unused */ public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("input a line for encoding and decoding: "); String str = scan.nextLine(); try { MIXChar[] mc = toMIXChar(str); long[] l = encode(mc); System.out.println("the long[]:"); for (long l1 : l) { System.out.println(l1); } MIXChar[] mc1 = decode(l); System.out.println("\nJava string:"); for (int j = 0; j < mc1.length; j++) { System.out.print(mc1[j].toString()); } } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } scan.close(); System.out.println("\nQuestion three was called and ran sucessfully."); } /** * Checks if a input char is a MIXChar. * @param c sets the input to check * @return true if input corresponds to a MIXChar character, * false otherwise */ public static boolean isMIXChar(char c) { for (int i = 0; i < mixChar.length; i++) { if (c == mixChar[i]) { return true; } } return false; } /** * Converts a char to the corresponding MIXChar. * @param c sets the input char to convert to MIXChar * @return mc as a MIXChar */ public static MIXChar toMIXChar(char c) { MIXChar mc; for (int i = 0; i < mixChar.length; i++) { if (isMIXChar(c)) { mc = new MIXChar(c); return mc; } } throw new IllegalArgumentException("conversion not possible, " + "one or more characters are not in the MIXChar table"); } /** * Converts MIXChar character to corresponding Java char. * @param x sets the MIXChar to convert * @return c as a char */ public static char toChar(MIXChar x) { char c = ' '; for (int i = 0; i < mixChar.length; i++) { x = new MIXChar(c); if (c == mixChar[i]) { return c; } } return c; } /** * Converts MIXChar array to a string. * @param mixC sets MIXChar array to convert * @return str as a string */ public static String toString(MIXChar[] mixC) { String str = ""; for (MIXChar mc : mixC) { str += toChar(mc); } return str; } /** * Converts a string to array of MIXChar characters * corresponding to the chars in s. * @param s sets a string to convert * @return mc as a MIXChar array */ public static MIXChar[] toMIXChar(String s) { final int elements = s.length(); MIXChar[] mc = new MIXChar[elements]; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (isMIXChar(c)) { mc[i] = toMIXChar(c); } else { throw new IllegalArgumentException("conversion not " + "possible, one or more characters are not in the " + "MIXChar table"); } } return mc; } /** * Encodes the MIXChar array to a long array holding the values * of the m packed 11 MIXChar characters per long. * @param m sets a MIXChar array to encode * @return longArray as a long array */ public static long[] encode(MIXChar[] m) { final int pack = 11; int size = (int) Math.ceil(1.0 * m.length / pack); long[] longArray = new long[size]; for (int k = 0; k < m.length; k++) { int i = k / pack; int j = k % pack; longArray[i] += (long) Math.pow(BASE, j) * m[k].ordinal(); } return longArray; } /** * Decodes long array l to MIXChar array with characters corresponding * to unpacking the input array(assuming 11 characters are packed per long, * but the last long may having fewer than 11). * @param l sets the long array to decode * @return newMc as a MIXChar array */ public static MIXChar[] decode(long[] l) { final int pack = 11; int size = l.length * pack; MIXChar[] mc = new MIXChar[size]; for (int i = 0; i < l.length; i++) { long li = l[i]; for (int j = pack - 1; j >= 0; j--) { long divisor = (long) Math.pow(BASE, j); int k = i * pack + j; int index = (int) Long.divideUnsigned(li, divisor); mc[k] = toMIXChar(mixChar[index]); li = Long.remainderUnsigned(li, divisor); } } // Find the # of trailing spaces. int trailingSpaces = 0; for (int c = mc.length - 1; c >= 0; c--) { if (mc[c].ordinal() == 0) { trailingSpaces += 1; } else { break; } } // Create the array for the return - copy the chars with the // trailing spaces truncated. int newSize = size - trailingSpaces; MIXChar[] newMc = new MIXChar[newSize]; System.arraycopy(mc, 0, newMc, 0, newSize); return newMc; } /** * Returns the numerical value of a MIXChar. * @return value as an int */ public int ordinal() { int value = 0; for (int i = 0; i < mixChar.length; i++) { if (mix == mixChar[i]) { value = i; } } return value; } /** * Returns string containing this MIXChar as a Java char. * @return str an a string */ public String toString() { MIXChar mc = new MIXChar(mix); String str = "" + mc.mix; return str; } }
yuanyuan1104/JavaAssignment4
MIXChar.java
1,985
/**represents special symbol PI.*/
block_comment
en
false
1,899
8
1,985
7
2,171
6
1,985
7
2,345
10
false
false
false
false
false
true
246752_2
package EX2; import java.util.Arrays; import java.util.Comparator; public class Main { public static void main(String[] args) { Person[] people = { new Person("Bob", 30, true), new Person("Alice", 25, false), new Person("Charlie", 35, true), new Person("Dave", 20, false) }; // sort by name Arrays.sort(people); System.out.println("Sorted by name: " + Arrays.toString(people)); // find max by name Person maxByName = findMax(people); System.out.println("Max by name: " + maxByName); // sort by age Arrays.sort(people, new Person.AgeComparator()); System.out.println("Sorted by age: " + Arrays.toString(people)); // find max by age Person maxByAge = findMax(people, new Person.AgeComparator()); System.out.println("Max by age: " + maxByAge); // sort by married status Arrays.sort(people, new Person.MarriedComparator()); System.out.println("Sorted by married status: " + Arrays.toString(people)); // find max by married status Person maxByMarriedStatus = findMax(people, new Person.MarriedComparator()); System.out.println("Max by married status: " + maxByMarriedStatus); } public static <T extends Comparable<T>> T findMax(T[] array) { return Arrays.stream(array).max(T::compareTo).orElse(null); } public static <T> T findMax(T[] array, Comparator<? super T> comparator) { return Arrays.stream(array).max(comparator).orElse(null); } }
abdelgaffa/Lab4
src/EX2/Main.java
413
// sort by age
line_comment
en
false
367
5
413
5
457
5
413
5
501
5
false
false
false
false
false
true
11_0
public static void splitTheBlop(Monster curr) { if (!curr.canSplit()) { players[BLOPSPLIT] = new Player(); // Assuming Player is the appropriate class for players array curr.setHealth((int)(Math.random() * (101 - 50 + 1) + 50)); curr.setCanSplit(true); } else { if (curr.getHealth() == 100) { int Number = (int)(Math.random() * (76 - 25 + 1) + 25); curr.damage(Number); players[BLOPSPLIT] = new Blop(curr.getRow(), curr.getCol(), playerImages[4]); curr.setCanSplit(false); } } }
1588974/Array-List
e.java
180
// Assuming Player is the appropriate class for players array
line_comment
en
false
163
10
180
11
189
10
180
11
200
10
false
false
false
false
false
true
457_4
//ACHILLE Sagang Tanwouo AND Diane Niyibaruta // In the first part I import the modul for enter the varaibles that we need for IMC import java.util.Scanner; // And I creat the class that we need for our method public class A{ //creation of our method public static void main(String[] args) { // we create an input which neccesaire to introduice the vraiable neccesary for IMC calcul Scanner clavier = new Scanner(System.in); System.out.println("enter your name here:"); String name= clavier.nextLine(); //we ask to the system to print to the user the information System.out.println("enter your weight please :"); float weight= clavier.nextFloat(); System.out.println("enter your height in cm please:"); float height= clavier.nextFloat(); //Here we use the IMC formula . float division= weight / (height * height); System.out.println( name+ " your MBI is "+ division ); //we make a condition here because when someone have a BMI> 30 He consider obesy //so if during the calcul the person have a BMI>30 we have a print which indicate or not if(division>=30) { System.out.println(" you are obesy"); } else if (division < 30) System.out.println("you have a good BMI"); //this methode is neccesary or is consisted to main class so is necesary to make work the class p.java P pp= new P(); } }
alu-rwa-prog-2/assignment1-achille_diane
A.java
390
// we create an input which neccesaire to introduice the vraiable neccesary for IMC calcul
line_comment
en
false
352
25
390
25
393
24
390
25
432
26
false
false
false
false
false
true
547_8
import java.awt.Canvas; import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.WindowConstants; public class C extends Canvas { private static final long serialVersionUID = 1480902466428347458L; private static final int WIDTH = 400; private static final int HEIGHT = 400; private static final int RANGE = 30; private static final int INTERVAL = 5; private double[][] values = new double[WIDTH][HEIGHT]; private double inertia = 0.8; private double decay = 0.9995; private double dissipation = 0.92; @Override public void paint(Graphics g) { super.paint(g); // Initialize all pixels as blank for (int x = 0; x < WIDTH; x++) { for (int y = 0; y < HEIGHT; y++) { values[x][y] = 0.0; g.setColor(color(values[x][y])); g.drawLine(x, y, x, y); } } // Store co-ordinates of last rain-drop and time since falling int lastX = -1; int lastY = -1; int lastT = -1; while (true) { // ~20ms per step (i.e. 50/sec) try { Thread.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); } // With some probability, add a rain-drop on a random location and initialize the timer if (Math.random() < 1.0/INTERVAL) { lastX = (int) (Math.random() * WIDTH); lastY = (int) (Math.random() * HEIGHT); lastT = 0; } // Currently, simulate water inflow at last location for three time-steps // After, simply move drop off-canvas for simplicity else if (lastT >= 3) { lastX = -100; } lastT++; // Compute updated values at each point in time double[][] newValues = computeNewValues(lastX, lastY); // Draw new canvas for (int x = 0; x < WIDTH; x++) { for (int y = 0; y < HEIGHT; y++) { g.setColor(color(values[x][y])); g.drawLine(x, y, x, y); } } values = newValues; } } /* * Computes updated values given current state of canvas and last rain-drop */ private double[][] computeNewValues(int lastX, int lastY) { double[][] newValues = new double[WIDTH][HEIGHT]; // For each pixel (somewhat inefficient, but fine for small canvas) for (int i = 0; i < WIDTH; i++) { for (int j = 0; j < HEIGHT; j++) { double value = 0.0; int count = 0; // Compute distance to previous drop and if exist, simulate water inflow there double dist = Math.sqrt(Math.pow(Math.abs(i - lastX), 2) + Math.pow(Math.abs(j - lastY), 2)); if (dist < RANGE) { // Adjust new value by distance from drop ... double newValue = 1.0; while (dist-- > 0) newValue *= dissipation; // ... but make sure not to "destroy" water that's already there newValue = Math.max(newValue, values[i][j]); // Update new value using inertia from old value value = inertia * values[i][j] + (1 - inertia) * newValue; } // If not near new drop, simply simulate diffusion of water else { for (int x = i - 5; x <= i + 5; x++) { for (int y = j - 5; y <= j + 5; y++) { if (x < 0 || y < 0 || x >= WIDTH || y >= HEIGHT) continue; value += values[x][y]; count++; } } value /= count; } // Decay values to simulate water soaking into ground newValues[i][j] = value * decay; } } return newValues; } private float fromValue(double value) { return (float) (((300 * (1.0 - value) + 300) % 360) / 360.0); } private Color color(double value) { return Color.getHSBColor(fromValue(value), 1.0f, .5f); } public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(WIDTH, HEIGHT); frame.add(new C()); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setVisible(true); } }
enankerv/s22-rec12
C.java
1,276
/* * Computes updated values given current state of canvas and last rain-drop */
block_comment
en
false
1,105
18
1,276
18
1,253
21
1,276
18
1,561
21
false
false
false
false
false
true
845_0
// Increasing triplet subsequence class Solution { public boolean increasingTriplet(int[] nums) { if (nums == null || nums.length < 3) { return false; } int a = Integer.MAX_VALUE; int b = Integer.MAX_VALUE; for (int num : nums) { if(num <= a) a = num; else if(num <= b) b = num; else return true; } return false; } }
Aryan201903/Leetcode75
8.java
112
// Increasing triplet subsequence
line_comment
en
false
100
5
112
7
122
4
112
7
132
8
false
false
false
false
false
true
1300_6
public int[][] generateMaze() { int[][] maze = new int[height][width]; // Initialize for (int i = 0; i < height; i++) for (int j = 0; j < width; j++) maze[i][j] = 1; Random rand = new Random(); // r for row、c for column // Generate random r int r = rand.nextInt(height); while (r % 2 == 0) { r = rand.nextInt(height); } // Generate random c int c = rand.nextInt(width); while (c % 2 == 0) { c = rand.nextInt(width); } // Starting cell maze[r][c] = 0; // Allocate the maze with recursive method recursion(r, c); return maze; } public void recursion(int r, int c) { // 4 random directions int[] randDirs = generateRandomDirections(); // Examine each direction for (int i = 0; i < randDirs.length; i++) { switch(randDirs[i]){ case 1: // Up // Whether 2 cells up is out or not if (r - 2 <= 0) continue; if (maze[r - 2][c] != 0) { maze[r-2][c] = 0; maze[r-1][c] = 0; recursion(r - 2, c); } break; case 2: // Right // Whether 2 cells to the right is out or not if (c + 2 >= width - 1) continue; if (maze[r][c + 2] != 0) { maze[r][c + 2] = 0; maze[r][c + 1] = 0; recursion(r, c + 2); } break; case 3: // Down // Whether 2 cells down is out or not if (r + 2 >= height - 1) continue; if (maze[r + 2][c] != 0) { maze[r+2][c] = 0; maze[r+1][c] = 0; recursion(r + 2, c); } break; case 4: // Left // Whether 2 cells to the left is out or not if (c - 2 <= 0) continue; if (maze[r][c - 2] != 0) { maze[r][c - 2] = 0; maze[r][c - 1] = 0; recursion(r, c - 2); } break; } } } /** * Generate an array with random directions 1-4 * @return Array containing 4 directions in random order */ public Integer[] generateRandomDirections() { ArrayList<Integer> randoms = new ArrayList<Integer>(); for (int i = 0; i < 4; i++) randoms.add(i + 1); Collections.shuffle(randoms); return randoms.toArray(new Integer[4]); }
oshlern/9th-Grade-Programming
maze.js
750
// 4 random directions
line_comment
en
false
702
5
750
5
805
5
750
5
856
5
false
false
false
false
false
true
1836_4
// LeetCode 92 Reverse Linked List II // References:https://leetcode.com/problems/reverse-linked-list-ii/solutions/2311084/java-c-tried-to-explain-every-step/?envType=study-plan-v2&envId=top-interview-150 /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode reverseBetween(ListNode head, int left, int right) { ListNode dummy = new ListNode(0); // create dummy node dummy.next = head; ListNode prev = dummy; // Initialising prev pointer on dummy node for (int i = 0; i < left - 1; i++) prev = prev.next; // adjusting the prev pointer on it's actual index ListNode curr = prev.next; // curr pointer will be just after prev // reversing for (int i = 0; i < right - left; i++){ ListNode forw = curr.next; // forw pointer will be after curr curr.next = forw.next; forw.next = prev.next; prev.next = forw; } return dummy.next; } }
ElsaYilinWang/LeetCode
92.java
345
// Initialising prev pointer on dummy node
line_comment
en
false
304
8
345
8
355
8
345
8
388
8
false
false
false
false
false
true
2100_5
/** * */ package edu.wlu.cs.staufferl; /** * @author staufferl * * This class defines the compact disk class, a child class of MediaItem. * Has artist field and number of tracks field. */ public class CD extends MediaItem { private String artist; // Artist of CD private int numOfTracks; // Number of tracks in CD // Constructor for child class. Uses super to instantiate fields inherited from parent class. public CD(String title, boolean isPresent, double playingTime, int copyrightYear, String artist, int numOfTracks) { super(title, isPresent, playingTime, copyrightYear); this.artist = artist; this.numOfTracks = numOfTracks; } /** * @return the artist * Artist of the CD */ public String getArtist() { return artist; } /** * @return the numOfTracks * Number of tracks on the CD */ public int getNumOfTracks() { return numOfTracks; } /* (non-Javadoc) * @see java.lang.Object#toString() * toString() needs to include additional CD fields (ones that MediaItem doesn't have). */ @Override public String toString() { return "CD [title=" + getTitle() + ", isPresent=" + isPresent() + ", playingTime=" + getPlayingTime() + ", copyrightYear=" + getCopyrightYear() +", artist=" + getArtist() + ", numOfTracks=" + getNumOfTracks() + "]"; } /** * @param args * Testing CD child class. * Make sure it properly inherits from parent class/super class. */ public static void main(String[] args) { CD myCD = new CD("Currents", false, 51.00, 2015, "Tame Impala", 13); System.out.println("Getting title: " + myCD.getTitle()); System.out.println("Getting artist: " + myCD.getArtist()); System.out.println("Expect false: " + myCD.isPresent()); myCD.setStatus(true); System.out.println("Expect true: " + myCD.isPresent()); System.out.println("Getting playing time: " + myCD.getPlayingTime()); System.out.println("Getting copyright year: " + myCD.getCopyrightYear()); System.out.println("Getting number of tracks: " + myCD.getNumOfTracks()); System.out.println("String representation of CD: " + myCD.toString()); } }
staufferl16/CompSci209
CD.java
619
/** * @return the artist * Artist of the CD */
block_comment
en
false
539
17
619
15
633
18
619
15
726
19
false
false
false
false
false
true
2554_7
import java.util.*; //DFS : Depth First Search, means we have to go depth atfirst. public class DFS { //total number of vertices is V which is 6. static int V = 6; public static void main(String[] args) { // Creating HashMap to store the edges of each vertices. We can use ArrayList of ArrayList or Array of LinkedList as well to store edges. HashMap<Integer,ArrayList<Integer>> map = new HashMap<Integer,ArrayList<Integer>>(); //Stroring ArrayList at each vertices for(int i=0;i<V;i++) { map.put(i, new ArrayList<Integer>()); } DFS ob = new DFS(); //adding edges in the map ob.addEdge(map,0,1); ob.addEdge(map,0,2); ob.addEdge(map,1,2); ob.addEdge(map,2,5); ob.addEdge(map,3,2); ob.addEdge(map,4,1); ob.addEdge(map,4,3); //traversal method ob.DFSTraversal(map); } void travers(HashMap<Integer,ArrayList<Integer>> map, int data, boolean[] visited) { //checking if the vertex if visited then no need to visit or else it will give us TLE. if(visited[data] == true) { return; } //marked true as we visited this vertex. visited[data] = true; //getting the ArrayList through the map where we store the edges of this vertex. ArrayList<Integer> al = map.get(data); //iterating through those edges. for(int i=0 ; i<al.size() ;i++) { travers(map,al.get(i),visited); } //At the end printing the vertex. System.out.print(data+" "); } void DFSTraversal(HashMap<Integer,ArrayList<Integer>> map) { //created visited array to check taht if we have visited the vertices or not. boolean[] visited = new boolean[V]; //So, we are iterating from 0 to V-1 vertices & checking that the vertices is visited or not. for(int i=0; i< visited.length ;i++) { //if the vertices is not visited then travers it. if(visited[i] == false) { travers(map,i,visited); } } } // here 'i' is source & 'j' is destination. We are adding the destination in the ArrayList. void addEdge(HashMap<Integer,ArrayList<Integer>> map, int i, int j) { map.get(i).add(j); } }
prafulla-k-roy/algo-education
DFS.java
660
//marked true as we visited this vertex.
line_comment
en
false
569
9
660
9
688
9
660
9
751
10
false
false
false
false
false
true
2928_11
/** * @file GUI.java * @author Daniel Kelleher * @date 30 Jan 2014 * @see 'JAVA for everyone' - Cay Horstmann, Second edition, page 434 for * abstract class and abstract methods design. * * @brief This creates the abstract class GUI * which will be extended by the other GUI classes. * * This class is an abstract class to be inherited by subclasses of the GUI, * it has the methods of setting title, height and width of the window, * it takes the three variables for these methods as input in the constructor. */ import javax.swing.JFrame; public abstract class GUI extends JFrame { /**< variable storing the title of the display window */ protected String m_Title; // These are protected, so child classes can access them. - Jon /**< variable storing the width of the display window */ protected int m_Width; // These are protected, so child classes can access them. - Jon /**< variable storing the height of the display window */ protected int m_Height; // These are protected, so child classes can access them. - Jon /**< constant for checkig the maximum width of the display window */ private final int MAX_WIDTH = 800; /**< constant for checkig the maximum width of the display window */ private final int MIN_WIDTH = 450; //old 365 /**<constant for checkig the maximum height of the display window */ private final int MAX_HEIGHT = 600; /**< constant for checkig the minimum height of the display window */ private final int MIN_HEIGHT = 400; //old 295 /** * This is the constructor for the OthelloGameGui class. * * @param title -the variable storing the title of the window. * @param width -the variable storing width of the display window. * @param height -the variable storing height of the display window. */ public GUI(String title, int width, int height) { m_Title = title; setWidth(width); setHeight(height); } /** * This method sets the width of the display window. * * @param width -the variable storing width of the display window. * @return setWidth -a boolean variable returned as true if the width * was set or false if it was not. */ public boolean setWidth(int width) { boolean setWidth = false; if (width>=MIN_WIDTH && width<=MAX_WIDTH) { m_Width = width; setWidth = true; } else { if (width<MIN_WIDTH) { m_Width = MIN_WIDTH; System.out.println("The width of the Start Screen"+ " is out of the set below the bound."); System.out.println("The width has been set to the minimum: " + MIN_WIDTH); } else if (width>MAX_WIDTH) { m_Width = MAX_WIDTH; System.out.println("The width of the Start Screen"+ " is out of the set above the bound."); System.out.println("The width has been set to the maximum: " + MIN_WIDTH); } } return setWidth; } /** * This method sets the height of the display window. * * @param height -the variable storing height of the display window. * @return setHeight -a boolean variable returned as true if the height * was set or false if it was not. */ public boolean setHeight(int height) { boolean setHeight = false; if (height>=MIN_HEIGHT && height<=MAX_HEIGHT) { m_Height = height; setHeight = true; } else { if (height<MIN_HEIGHT) { m_Height = MIN_HEIGHT; System.out.println("The height of the Start Screen"+ " is out of the set below the bound."); System.out.println("The height has been set to the minimum: " + MIN_HEIGHT); } else if (height>MAX_HEIGHT) { m_Height = MAX_HEIGHT; System.out.println("The height of the Start Screen"+ " is out of the set above the bound."); System.out.println("The height has been set to the maximum: " + MAX_HEIGHT); } } return setHeight; } }
jbrookdale/GroupAGSAssignment5
GUI.java
1,116
/**< constant for checkig the minimum height of the display window */
block_comment
en
false
968
13
1,116
14
1,171
14
1,116
14
1,307
14
false
false
false
false
false
true
3142_1
class Solution { public int singleNumber(int[] nums) { int ones = 0, twos = 0, threes = 0; for (int i = 0; i < nums.length; i++) { // twos holds the num that appears twice twos |= ones & nums[i]; // ones holds the num that appears once ones ^= nums[i]; // threes holds the num that appears three times threes = ones & twos; // if num[i] appears three times doing this will clear ones and twos ones &= ~threes; twos &= ~threes; } return ones; } }
kalongn/LeetCode_Solution
137.java
156
// ones holds the num that appears once
line_comment
en
false
148
8
156
8
160
8
156
8
177
8
false
false
false
false
false
true
3594_12
/** * While a User just contains information carried by the Server about each user (name and connection instructions), * A Peer contains information carried by a client about another client. * A Peer object also has methods to send data and control packets to the peer and to respond to them. */ import java.io.*; import java.util.*; import java.net.*; import java.nio.*; import java.nio.charset.*; import java.math.*; public class Peer { /** * Basic connectivity information, and username */ public User user; /** * Set of messages this peer has. * Maps message creator ID -> (set of sequence numbers) */ public HashMap<Integer, HashSet<Integer>> messages = new HashMap<Integer, HashSet<Integer>>(); public Peer(User user) { this.user = user; } /** * @param message Message which could possibly request. * @return Boolean of whether this peer is interested (doesn't have it already). */ public boolean interestedIn(Message message) { synchronized (this.messages) { HashSet<Integer> messagesFromSender = this.messages.get(new Integer(message.senderID)); if (messagesFromSender == null) { return true; } return !messagesFromSender.contains(new Integer(message.sequenceNumber)); } } /** * Sends a control packet over UDP. * @param data The control packet to send */ public void sendControlData(byte[] data) { // first create socket to send packet DatagramSocket socket; try { socket = new DatagramSocket(); } catch (SocketException e) { e.printStackTrace(); return; } DatagramPacket packet = new DatagramPacket(data, data.length, this.user.address, this.user.port); try { socket.send(packet); socket.close(); } catch (IOException e) { e.printStackTrace(); } } /** * Have received notification that Peer has a new packet that I can request. * @param message The message in question that the peer now has. * @return boolean: false if Peer already knew about packet, true if this is new information */ public boolean has(Message message) { synchronized (this.messages) { HashSet<Integer> messagesFromSender = this.messages.get(new Integer(message.senderID)); if (messagesFromSender == null) { messagesFromSender = new HashSet<Integer>(); this.messages.put(new Integer(message.senderID), messagesFromSender); } if (!messagesFromSender.contains(new Integer(message.sequenceNumber))) { messagesFromSender.add(new Integer(message.sequenceNumber)); return true; } } // TODO store and use message creation date return false; } /** * Send my contact information to this peer. * @param user The contact information to send. */ public void giveBusinessCard(User user) { // System.out.println("Sending business card to "+this.user.username); // construct business card byte[] card = user.pack(); Socket socket; DataOutputStream outToServer; try { // System.out.println("Sending business card to IP "+this.user.address); socket = new Socket(this.user.address, this.user.dataPort); outToServer = new DataOutputStream(socket.getOutputStream()); // no input necessary, this is a one-way conversation outToServer.write(card); outToServer.flush(); // necessary? socket.close(); } catch (IOException ex) { //ex.printStackTrace(); return; } } /** * Keep track of whether this peer has choked or unchoked the current client, * per the https://wiki.theory.org/BitTorrentSpecification */ public boolean chokedMe = true; /** * Keep track of whether this peer is choked or unchoked from the point of view of the current client. */ public boolean chokedByMe = true; /** * Keep track of whether I'm currently making a request to this peer. * Never make more than one request at the same time to the same peer, because they will probably be refused. */ public boolean currentlyRequesting = false; }
vtsah/p2p-messenger
Peer.java
963
// no input necessary, this is a one-way conversation
line_comment
en
false
867
11
963
12
1,057
12
963
12
1,119
12
false
false
false
false
false
true
3882_4
package com.gradescope.hw6; /** * An adorable dog! */ public class Dog implements Comparable<Dog> { /** * The age */ int myAge; /** * Constructs a dog with the specified age. * * @param age The age */ public Dog(int age) { this.myAge = age; } /** * Compares two dogs' ages. * * The result is a negative integer if this dog is younger than the other dog. * The result is a positive integer if this dog is older than the other dog. The * result is zero if the two dogs are the same age. * * @return the difference between this dog's age and the other dog's age */ public int compareTo(Dog other) { return this.myAge - other.myAge; } /** * Compares this string to the specified object. The result is true if and only * if the specified object is also a dog, and both dogs have the same age. * * @param obj the object to be compared for equality with this dog * @return true if the specified object is equal to this dog */ public boolean equals(Object obj) { if (obj instanceof Dog) { Dog otherDog = (Dog) obj; return this.compareTo(otherDog) == 0; } return false; } }
Mehrin77/Java-Coding-Exercises-LinkedLists-Arrays-BST-Trees
Dog.java
342
/** * Compares this string to the specified object. The result is true if and only * if the specified object is also a dog, and both dogs have the same age. * * @param obj the object to be compared for equality with this dog * @return true if the specified object is equal to this dog */
block_comment
en
false
309
75
342
72
358
78
342
72
386
78
false
false
false
false
false
true
3941_18
package optimizationAlgorithms; import java.util.Random; public class GA { public void runGAAlgorithm() { //Set parameters int problemDimension = 10; //dimensionality of problem int maxEvaluations = problemDimension*10000; //computational budget for algorithm (function evaluations) int populationSize = 30; //algorithm population size. Must be even number to enable mating pool to have pairs. double mutationVariance = 0.005; //mutation standard deviation for Gaussian distribution as a percentage of problem bounds Random random = new Random(); // particle (the solution, i.e. "x") double[] best = new double[problemDimension]; double[] finalBest = new double[problemDimension]; double fBest = Double.NaN; int j = 0; //Set problem bounds double problemLowerBound = -5.12; double problemUpperBound = 5.12; double[][] bounds = new double[problemDimension][2]; for (int i = 0; i < problemDimension; i++) { bounds[i][0] = problemLowerBound; bounds[i][1]= problemUpperBound; } //Generate initial random solution for (int l = 0; l < problemDimension; l++) { best[l] = Math.random() * (bounds[l][1] - bounds[l][0]) + bounds[l][0]; } fBest = MiscMethods.f(best); j++; //Generate initial population double population[][] = new double[populationSize][problemDimension]; for (int i = 0; i < populationSize; i++) { population[i] = new double[problemDimension]; for (int l = 0; l < problemDimension; l++) { population[i][l] = Math.random() * (bounds[l][1] - bounds[l][0]) + bounds[l][0]; } population[i] = MiscMethods.saturate(population[i], bounds); //apply saturation correction to particles } //run selection, crossover, mutation and replacement while (j < maxEvaluations) //while on budget { //run tournament int matingPoolSize = populationSize*2; double matingPool[][] = new double[matingPoolSize][problemDimension]; double tournamentMember1fitness; double tournamentMember2fitness; for (int i = 0; i < matingPoolSize; i++) { //1st tournament member int random1 = random.nextInt(populationSize); tournamentMember1fitness = MiscMethods.f(population[random1]); j++; //2nd tournament member int random2 = random.nextInt(populationSize); tournamentMember2fitness = MiscMethods.f(population[random2]); j++; if (tournamentMember1fitness <= tournamentMember2fitness) { matingPool[i] = population[random1]; } else{ matingPool[i] = population[random2]; } } //run box crossover whereby 2 parents create 1 off-spring int l = 0; int newPopulationSize = populationSize; double newPopulation[][] = new double[populationSize][problemDimension]; while (l < matingPoolSize/2) { for (int i = 0; i < matingPoolSize; i+=2) { for (int k = 0; k < problemDimension; k++) { newPopulation[l][k] = Math.min(matingPool[i][k], matingPool[i+1][k]) + (random.nextDouble() * Math.abs(matingPool[i][k] - matingPool[i+1][k])); } l++; } } //run mutation of new population for (int i = 0; i < newPopulationSize; i++) { for (int k = 0; k < problemDimension; k++) { newPopulation[i][k] = newPopulation[i][k] + ((mutationVariance * (bounds[k][1]-bounds[k][0])) * random.nextGaussian()); } newPopulation[i] = MiscMethods.saturate(newPopulation[i], bounds); //apply saturation correction to particles } //update population with new generation for next iteration (maintaining random order) for (int i = 0; i < populationSize; i++) { population[i] = newPopulation[i]; } //save best particle if fitness has improved upon best found //sort new population in order of fitness double[] temp; for (int i = 0; i < newPopulationSize; i++) { for (int k = i + 1; k < newPopulationSize; k++) { if (MiscMethods.f(newPopulation[i]) > MiscMethods.f(newPopulation[k])) { j++; j++; temp = newPopulation[i]; newPopulation[i] = newPopulation[k]; newPopulation[k] = temp; } } } // save best double iterationBestFitness = MiscMethods.f(newPopulation[0]); if (iterationBestFitness < fBest) { fBest = iterationBestFitness; for (int n = 0; n < problemDimension; n++) best = newPopulation[0]; } // end while on budget } finalBest = best; //save the final best System.out.println("GA final fitness: " + fBest); } }
Henry-Lidgley/OptimizationAlgorithms
GA.java
1,409
//update population with new generation for next iteration (maintaining random order)
line_comment
en
false
1,275
15
1,409
15
1,461
15
1,409
15
2,047
16
false
false
false
false
false
true
5018_7
import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; import javax.imageio.ImageIO; public class Run { public static void main(String[] args) { final long startTime = System.currentTimeMillis(); Scanner scan = new Scanner(System.in); int numDuplicates = 0; String filePath; ArrayList<String> fileNames = new ArrayList<String>(); ArrayList<String> fileLocations = new ArrayList<String>(); ArrayList<Dimension> fileDimensions = new ArrayList<Dimension>(); //Get the file path (Already hardcoded in for testing) System.out.println("Please enter the exact file path for the pictures: "); //filePath = scan.nextLine(); filePath = "C:/Users/Mitch Desktop/Desktop/Test"; File folder = new File(filePath); ReadFilesFromFolder reader = new ReadFilesFromFolder(); System.out.println("Reading files under the folder "+ folder.getAbsolutePath()); //Fill the Name array and BufferedImage array reader.getImages(filePath); fileNames = reader.getFileList(); fileLocations = reader.getImageArray(); fileDimensions = reader.getDimensionArray(); //Setting up variables to compare 2 images BufferedImage originalImage = null; BufferedImage compareToImage = null; boolean isSame = true; System.out.println("Images loaded. Begin comparing images."); //Loop through the array of images for(int i=0; i<fileLocations.size(); i++) { //System.out.println("Comparing: "+i+" out of: "+fileLocations.size()); //Assign the original image to the current position try { originalImage = ImageIO.read(new File(fileLocations.get(i))); } catch (IOException e1) { e1.printStackTrace(); } //Begin looping through the rest of the images and comparing each for(int j=i+1; j<fileLocations.size(); j++) { /* //Skip if comparing the same location if(fileLocations.get(i).equalsIgnoreCase(fileLocations.get(j))) { continue; } */ //If images aren't the same size, skip to next image. Already know they are different images if((fileDimensions.get(i).getHeight() != fileDimensions.get(j).getHeight()) || (fileDimensions.get(i).getWidth() != fileDimensions.get(j).getWidth())) { continue; } //Else, they are the same size so begin comparing pixel by pixel else { try { compareToImage = ImageIO.read(new File(fileLocations.get(j))); } catch (IOException e) { e.printStackTrace(); } //Assume the pixels in the images are the same isSame = true; //Loop through all pixels in both images and compare them. for(int m=0; m<originalImage.getHeight(); m++) { for(int n=0; n<originalImage.getWidth(); n++) { //If we find a pixel that differs between them, we know they aren't the same picture. Break loop. if(compareToImage.getRGB(n, m) != originalImage.getRGB(n, m)) { isSame = false; break; } } //If after comparing each pixel isSame is still true after 10 rows of pixels, they are assumed to be the same image. Break the loop if(isSame == true && m > 9) { numDuplicates++; System.out.println("Image: "+ fileNames.get(i) +" and: " + fileNames.get(j) + " ARE THE SAME IMAGE."); System.out.println("Locations for each: "+fileLocations.get(i) + " and: "+ fileLocations.get(j)); break; } } } } } final long endTime = System.currentTimeMillis(); System.out.println("Total execution time: " + (double)(endTime - startTime)/1000 + " seconds for: " + fileNames.size() + " images."); System.out.println("Number of duplicates: "+numDuplicates); } //End main } //End class
ricemitc/ImageCompare
Run.java
1,066
//Begin looping through the rest of the images and comparing each
line_comment
en
false
923
12
1,066
12
1,107
12
1,066
12
1,489
12
false
false
false
false
false
true
5048_5
/** * To find k nearest neighbors of a new instance * Please watch my explanation of how KNN works: xxx * - For classification it uses majority vote * - For regression it finds the mean (average) * * Copyright (C) 2014 * @author Dr Noureddin Sadawi * * This program is free software: you can redistribute it and/or modify * it as you wish ONLY for legal and ethical purposes * * I ask you only, as a professional courtesy, to cite my name, web page * and my YouTube Channel! * */ import java.util.*; class KNN { // the data static double[][] instances = { {0.35,0.91,0.86,0.42,0.71}, {0.21,0.12,0.76,0.22,0.92}, {0.41,0.58,0.73,0.21,0.09}, {0.71,0.34,0.55,0.19,0.80}, {0.79,0.45,0.79,0.21,0.44}, {0.61,0.37,0.34,0.81,0.42}, {0.78,0.12,0.31,0.83,0.87}, {0.52,0.23,0.73,0.45,0.78}, {0.53,0.17,0.63,0.29,0.72}, }; /** * Returns the majority value in an array of strings * majority value is the most frequent value (the mode) * handles multiple majority values (ties broken at random) * * @param array an array of strings * @return the most frequent string in the array */ private static String findMajorityClass(String[] array) { //add the String array to a HashSet to get unique String values Set<String> h = new HashSet<String>(Arrays.asList(array)); //convert the HashSet back to array String[] uniqueValues = h.toArray(new String[0]); //counts for unique strings int[] counts = new int[uniqueValues.length]; // loop thru unique strings and count how many times they appear in origianl array for (int i = 0; i < uniqueValues.length; i++) { for (int j = 0; j < array.length; j++) { if(array[j].equals(uniqueValues[i])){ counts[i]++; } } } for (int i = 0; i < uniqueValues.length; i++) System.out.println(uniqueValues[i]); for (int i = 0; i < counts.length; i++) System.out.println(counts[i]); int max = counts[0]; for (int counter = 1; counter < counts.length; counter++) { if (counts[counter] > max) { max = counts[counter]; } } System.out.println("max # of occurences: "+max); // how many times max appears //we know that max will appear at least once in counts //so the value of freq will be 1 at minimum after this loop int freq = 0; for (int counter = 0; counter < counts.length; counter++) { if (counts[counter] == max) { freq++; } } //index of most freq value if we have only one mode int index = -1; if(freq==1){ for (int counter = 0; counter < counts.length; counter++) { if (counts[counter] == max) { index = counter; break; } } //System.out.println("one majority class, index is: "+index); return uniqueValues[index]; } else{//we have multiple modes int[] ix = new int[freq];//array of indices of modes System.out.println("multiple majority classes: "+freq+" classes"); int ixi = 0; for (int counter = 0; counter < counts.length; counter++) { if (counts[counter] == max) { ix[ixi] = counter;//save index of each max count value ixi++; // increase index of ix array } } for (int counter = 0; counter < ix.length; counter++) System.out.println("class index: "+ix[counter]); //now choose one at random Random generator = new Random(); //get random number 0 <= rIndex < size of ix int rIndex = generator.nextInt(ix.length); System.out.println("random index: "+rIndex); int nIndex = ix[rIndex]; //return unique value at that index return uniqueValues[nIndex]; } } /** * Returns the mean (average) of values in an array of doubless * sums elements and then divides the sum by num of elements * * @param array an array of doubles * @return the mean */ private static double meanOfArray(double[] m) { double sum = 0.0; for (int j = 0; j < m.length; j++){ sum += m[j]; } return sum/m.length; } public static void main(String args[]){ int k = 6;// # of neighbours //list to save city data List<City> cityList = new ArrayList<City>(); //list to save distance result List<Result> resultList = new ArrayList<Result>(); // add city data to cityList cityList.add(new City(instances[0],"London")); cityList.add(new City(instances[1],"Leeds")); cityList.add(new City(instances[2],"Liverpool")); cityList.add(new City(instances[3],"London")); cityList.add(new City(instances[4],"Liverpool")); cityList.add(new City(instances[5],"Leeds")); cityList.add(new City(instances[6],"London")); cityList.add(new City(instances[7],"Liverpool")); cityList.add(new City(instances[8],"Leeds")); //data about unknown city double[] query = {0.65,0.78,0.21,0.29,0.58}; //find disnaces for(City city : cityList){ double dist = 0.0; for(int j = 0; j < city.cityAttributes.length; j++){ dist += Math.pow(city.cityAttributes[j] - query[j], 2) ; //System.out.print(city.cityAttributes[j]+" "); } double distance = Math.sqrt( dist ); resultList.add(new Result(distance,city.cityName)); //System.out.println(distance); } //System.out.println(resultList); Collections.sort(resultList, new DistanceComparator()); String[] ss = new String[k]; for(int x = 0; x < k; x++){ System.out.println(resultList.get(x).cityName+ " .... " + resultList.get(x).distance); //get classes of k nearest instances (city names) from the list into an array ss[x] = resultList.get(x).cityName; } String majClass = findMajorityClass(ss); System.out.println("Class of new instance is: "+majClass); }//end main //simple class to model instances (features + class) static class City { double[] cityAttributes; String cityName; public City(double[] cityAttributes, String cityName){ this.cityName = cityName; this.cityAttributes = cityAttributes; } } //simple class to model results (distance + class) static class Result { double distance; String cityName; public Result(double distance, String cityName){ this.cityName = cityName; this.distance = distance; } } //simple comparator class used to compare results via distances static class DistanceComparator implements Comparator<Result> { @Override public int compare(Result a, Result b) { return a.distance < b.distance ? -1 : a.distance == b.distance ? 0 : 1; } } }
nsadawi/KNN
KNN.java
2,171
//counts for unique strings
line_comment
en
false
1,932
5
2,171
5
2,158
5
2,171
5
2,500
6
false
false
false
false
false
true
6255_2
import java.util.ArrayList; public class ban { public static boolean check(String user) { // check bans for user - either nickname or host name, then return true if it's there return false; } public static void set(String user) { // append user nickname or hostname to end of bans list } public static void remove(String user) { // find "user" string in bans list and remove it } public static ArrayList<String> list(String sender) { // read all bans into list and PM requester return null; } }
cs0x7f/taeng-bot
ban.java
149
// find "user" string in bans list and remove it
line_comment
en
false
123
12
149
13
145
12
149
13
159
13
false
false
false
false
false
true
6440_0
/* Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B. */ class Solution { public boolean buddyStrings(String A, String B) { if (A.length() != B.length()) return false; int[] counter = new int[26]; boolean swapped = false; int firstIndex = -1; for (int i = 0; i < A.length(); i++) { char charA = A.charAt(i); char charB = B.charAt(i); counter[charA - 'a']++; if (charA == charB) continue; // charA != charB if (swapped) return false; if (firstIndex == -1) firstIndex = i; else { swapped = true; if (charA == B.charAt(firstIndex) && charB == A.charAt(firstIndex)) continue; return false; } } if (swapped) return true; for (int i = 0; i < 26; i++) if (counter[i] >= 2) return true; return false; } }
wxping715/LeetCode
859.java
280
/* Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B. */
block_comment
en
false
261
32
280
34
310
34
280
34
320
36
false
false
false
false
false
true
6795_4
import sofia.micro.*; //------------------------------------------------------------------------- /** * this class houses all the subclasses of ants * * @author Mykayla Fernandes (mkaykay1) * @version 2015.10.22 */ public class Ant extends Timer { //~ Fields ................................................................ /** * @param health equals health */ public int health; /** * @param cost equals cost to add ant to world */ public int cost; /** * @param sting equals 40 * turns passed before bee stings */ public int sting = 40; //~ Constructor ........................................................... // ---------------------------------------------------------- /** * Creates a new Ant object. */ public Ant() { super(); } //~ Methods ............................................................... /** * @return equals the ant's current health */ public int getHealth() { return health; } /** * reduces the ant's health by the provided amount. * when the ant's health reaches zero, * it should remove itself from the colony * @param n equals amount it gets injured */ public void injure(int n) { if (health == 0) { this.remove(); } else { health = health - n; } } /** * gets injured when a bee makes contact with it * waits 40 turns before stinging begins */ public void beeSting() { if (this.getIntersectingObjects(Bee.class).size() > 0) { if (sting == 0) { this.injure(1); } else { sting = sting - 1; } } } /** * indicates how many food units are necessary to * be added to the colony * @return the food cost */ public int getFoodCost() { return cost; } /** * executes methods which * give this actor it's unique behavior */ public void act() { this.beeSting(); this.getFoodCost(); this.getHealth(); } }
mfcecilia/cs1114_program04-ants-vs-somebees
Ant.java
510
/** * @param cost equals cost to add ant to world */
block_comment
en
false
487
16
510
15
580
17
510
15
632
17
false
false
false
false
false
true
8257_5
import java.util.*; class Fn { // Method to allocate memory to // blocks as per First fit algorithm static void firstFit(int blockSize[], int m,int processSize[], int n) { // Stores block id of the // block allocated to a process int allocation[] = new int[n]; // Initially no block is assigned to any process for (int i = 0; i < allocation.length; i++){ allocation[i] = -1; } // pick each process and find suitable blocks // according to its size ad assign to it for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (blockSize[j] >= processSize[i]) { // allocate block j to p[i] process allocation[i] = j; // Reduce available memory in this block. blockSize[j] -= processSize[i]; break; } } } System.out.println("\nProcess No.\tProcess Size\tBlock no."); for (int i = 0; i < n; i++) { System.out.print(" " + (i+1) + "\t\t" +processSize[i] + "\t\t"); if (allocation[i] != -1){ System.out.print(allocation[i] + 1); }else{ System.out.print("Not Allocated"); } System.out.println(); } } static void NextFit(int blockSize1[], int m1, int processSize1[], int n1) { // Stores block id of the block allocated to a // process int allocation[] = new int[n1], j = 0; // Initially no block is assigned to any process Arrays.fill(allocation, -1); // pick each process and find suitable blocks // according to its size ad assign to it for (int i = 0; i < n1; i++) { // Do not start from beginning int count =0; while (j < m1) { count++; //makes sure that for every process we traverse through entire //array maximum once only.This avoids the problem of going into infinite loop if memory is //not available if (blockSize1[j] >= processSize1[i]) { // allocate block j to p[i] process allocation[i] = j; // Reduce available memory in this block. blockSize1[j] -= processSize1[i]; break; } // mod m will help in traversing the blocks from // starting block after we reach the end. j = (j + 1) % m1; } } System.out.print("\nProcess No.\tProcess Size\tBlock no.\n"); for (int i = 0; i < n1; i++) { System.out.print( i + 1 + "\t\t" + processSize1[i]+ "\t\t"); if (allocation[i] != -1) { System.out.print(allocation[i] + 1); } else { System.out.print("Not Allocated"); } System.out.println(""); } } public static void main(String[] args) { System.out.println("....First Fit...."); int blockSize[] = {100, 500, 200, 300, 600}; int processSize[] = {212, 417, 112, 426}; int m = blockSize.length; int n = processSize.length; firstFit(blockSize, m, processSize, n); System.out.println("....Next Fit...."); int blockSize1[] = {5, 10, 20}; int processSize1[] = {10, 20, 5}; int m1 = blockSize1.length; int n1 = processSize1.length; NextFit(blockSize1, m1, processSize1, n1); } }
Shivansh7a8/Lp1
Fn.java
948
// pick each process and find suitable blocks
line_comment
en
false
802
8
948
8
937
8
948
8
979
8
false
false
false
false
false
true
8380_1
/** * Write a description of class d here. * * @author (your name) * @version (a version number or a date) */ public class d { // instance variables - replace the example below with your own private int x; /** * Constructor for objects of class d */ public d() { } /** * An example of a method - replace this comment with your own * * @param y a sample parameter for a method * @return the sum of x and y */ public int sampleMethod(int y) { // put your code here return x + y; } }
yrdsb-peths/final-greenfoot-project-Ryand2226894
d.java
151
// instance variables - replace the example below with your own
line_comment
en
false
150
11
151
11
174
11
151
11
177
11
false
false
false
false
false
true
8745_10
//Question:05 Calculate The CGPA Of A Student Using The Marks Given By The User Using Java. //https://www.linkedin.com/in/syedtalhamian/ import java.util.Scanner;//Importing The Java Scanner Class //make sure that the class name matches the name of the file public class cgpa { public static void main(String[] args) { Scanner sc = new Scanner(System.in); //this will create the Scanner object, it is neccessary to create one //here we are using marks of three subjects to calculate cgpa System.out.println("enter marks in physics"); //asking the user to input the marks for the given subject float s1 = sc.nextFloat(); //storing the marks in float because the cgpa could be in decimal. /*it is necessary to use float data type otherwise we would get only the integer part of the cgpa as answer*/ System.out.println("enter marks in chemistry"); float s2 = sc.nextFloat(); System.out.println("enter marks in maths"); float s3 = sc.nextFloat(); float cgpa = (s1+s2+s3)/30; /*calculating the cgpa, here we will divide by 30, because cgpa is given out of 10 and the marks were out of 100 each*/ System.out.println("your cgpa is :"); System.out.println(cgpa); //printing the cgpa } }
syedtalhamian/learning-java
cgpa.java
347
//printing the cgpa
line_comment
en
false
320
5
347
5
362
5
347
5
396
7
false
false
false
false
false
true
10413_8
package Project02; /** * Used to store, set, and get various values for individual player characters. * * It is also used to change each characters life point value, and determine whether or not a player is still alive. * * getDescription = player type (healer, warrior, or wizard) */ public abstract class People { private String personName; private String myNation; private String myTribe; private PeopleType me; protected String myDescription; private int myLifePoints; private boolean dead; public final int MAX_LIFEPOINTS = 100; /** * @param nation * Stores the String name of a nation * @param tribe * Stores the String name of a player's tribe * @param person * Reference to PeopleType, used to check player type (healer, warrior, wizard) * @param lifePoints * Stores life point value of a player */ public People(String nation, String tribe, PeopleType person, int lifePoints) { myNation = nation; myTribe = tribe; me = person; myDescription = me.getDescription(); myLifePoints = lifePoints; dead = false; } /** * Once life points hits 0, sets player as dead */ public void setDead() { dead = true; } /** * @return * Returns current dead value for player (True or False) */ public boolean getDead() { return dead; } /** * @return * Gets player type */ public PeopleType getType() { return me; } /** * @return * Gets player tribe */ public String getTribe() { return myTribe; } /** * @return * Gets player nation */ public String getNation() { return myNation; } /** * @return * Check if player life point value is greater then 0 */ public Boolean isPersonAlive() { return (myLifePoints > 0); } /** * @return * Get current life point value */ public int getLifePoints() { return myLifePoints; } /** * @param points * If current life point value exceeds max life points, set it back to the max. */ public void modifyLifePoints(int points) { myLifePoints += points; if(myLifePoints > MAX_LIFEPOINTS){ myLifePoints = MAX_LIFEPOINTS; } } /** * @param otherPerson * Reference to opponent * @return * abstract for PlayerType (ex: PerezHealer) classes */ public abstract int encounterStrategy(People otherPerson); /** * @return * returns a String profile of the player (nation, tribe, player name, player type, and their remaining life points. */ public String toString() { String result = new String( myNation + "\t" + myTribe + "\t" + me + "\t" + myDescription + "\t" + myLifePoints + " "); return result; } }
evan-toyberg/Project02
People.java
731
/** * @return * Get current life point value */
block_comment
en
false
717
16
731
14
809
17
731
14
865
17
false
false
false
false
false
true
10958_7
import java.lang.reflect.InvocationTargetException; import java.util.EnumMap; import java.util.Map.Entry; import java.util.function.Consumer; import java.util.function.Supplier; /** A user interface for running, displaying, and interacting with a Connect Four game. */ public abstract class UI { // the players of the game protected EnumMap<Turn,Player> players= new EnumMap<Turn,Player>(Turn.class); private Board board= new Board(); // the current board for the game // the logger for the game - initially one that does nothing private Logger logger= new Logger() { public @Override void start(Board board) { } public @Override void observeMove(Board board, Turn player, Move move) { } public @Override void gameOver(Player winner) { } public @Override void registerPlayer(Turn turn, Player player) { } }; /** Look up a class implementing Player with name player. * Construct an instance of that class * by providing turn and argument as the arguments to its constructor. */ public Player createPlayer(Turn turn, String player, String argument) throws ClassNotFoundException, ClassCastException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { Class<? extends Player> playerClass = Class.forName(player).asSubclass(Player.class); return playerClass.getConstructor(Turn.class, String.class).newInstance(turn, argument); } /** Set which player has which turn. * This is only called once for each turn. */ public void setPlayer(Turn turn, Player player) { players.put(turn, player); } /** Set the logger for this game to logger. */ public final void setLogger(Logger logger) { this.logger= logger; } /** Run the Connect Four game. */ public final void runGame() { for (Entry<Turn,Player> entry : players.entrySet()) logger.registerPlayer(entry.getKey(), entry.getValue()); logger.start(board); start(board); players.get(Turn.FIRST).getAsyncMove(board).async(new Consumer<Move>() { Turn turn = Turn.FIRST; public @Override void accept(Move move) { final Consumer<Move> driver= this; board = makeMove(board, turn, move); UI.this.<Void>doLongTask(() -> { for (Player player : players.values()) player.observeMove(board, turn, move); logger.observeMove(board, turn, move); return null; }).async((Void v) -> { turn= turn.getNext(); if (board.isFull()) { gameOver(null); return; } Turn winner= board.hasConnectFour(); if (winner != null) { logger.gameOver(players.get(winner)); gameOver(players.get(winner)); return; } doLongTask(() -> { return players.get(turn).getAsyncMove(board); }).async((Async<Move> async) -> { async.async(driver); }); }); return; } }); } /** Do a long task. If appropriate, do it on a separate thread. */ protected abstract <T> Async<T> doLongTask(Supplier<T> task); /** Display the start of the game. */ protected abstract void start(Board board); /** Display the move made on board by player. * board is the state of the board before the move was made. */ protected abstract Board makeMove(Board board, Turn player, Move move); /** Display the end of the game, with winner as the victor. * If winner is null, then the game ended in a tie. */ protected abstract void gameOver(Player winner); }
rkoren/connect4
UI.java
857
/** Run the Connect Four game. */
block_comment
en
false
782
8
857
8
926
8
857
8
1,002
8
false
false
false
false
false
true
11291_1
class BinarySearch { // Returns index of x if it is present in arr[l.. // r], else return -1 int binarySearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2; // If the element is present at the // middle itself if (arr[mid] == x) return mid; // If element is smaller than mid, then // it can only be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); // Else the element can only be present // in right subarray return binarySearch(arr, mid + 1, r, x); } // We reach here when element is not present // in array return -1; } // Driver method to test above public static void main(String args[]) { BinarySearch ob = new BinarySearch(); int arr[] = { 2, 3, 4, 10, 40 }; int n = arr.length; int x = 10; int result = ob.binarySearch(arr, 0, n - 1, x); if (result == -1) System.out.println("Element not present"); else System.out.println("Element found at index " + result); } }
Ayushi7452/100daysofcodechallenge
Day 22
329
// r], else return -1
line_comment
en
false
326
7
329
7
372
7
329
7
374
7
false
false
false
false
false
true
11389_3
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * The Orb class which is added into the world and used as an attack move by * the player */ public class Orb extends Actor { //An array to hold onto the frames of the orb GreenfootImage[] orbFrames = new GreenfootImage [16]; //Used as a counter for setting the image private int currImg; //An int used to determine how long the fire orb stays in the world for private int lifeSpan; public Orb() { //Adds in the images of the orbs to the array list of images for (int i = 0; i < orbFrames.length; i++) { orbFrames[i] = new GreenfootImage ("fireAttack (" + i + ").png"); orbFrames[i].scale (40, 40); orbFrames[i].rotate (270); } //Sets the lifespan of the orb to a constant lifeSpan = GameConstants.ORB_LIFESPAN; } public void act() { currImg++; animateMove(); checkGround(); checkLifeSpan(); lifeSpan--; } /** * Animates the fire orb * */ private void animateMove() { move (GameConstants.PLAYER_ATTACK_SPEED); //Modulus helps slow down the orb frames setImage (orbFrames [currImg/GameConstants.PLAYER_ATTACK_SPEED % orbFrames.length]); } /** * A method that checks if the fire orb has touched the ground * If it touched the ground, it gets removed from the world * */ private void checkGround() { if (isTouching (Ground.class)) { ((Game)getWorld()).removeObject (this); } } /** * A method to check the life span of the fire orb * If the lifespan is less than or equal to 0, the orb gets removed * */ private void checkLifeSpan() { if (lifeSpan <= 0) { ((Game)getWorld()).removeObject (this); } } }
yurkuul/flaming_fire_survivor
Orb.java
506
//Used as a counter for setting the image
line_comment
en
false
473
9
506
9
529
9
506
9
578
10
false
false
false
false
false
true
11629_7
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Orc here. * * @author (your name) * @version (a version number or a date) */ public class Orc extends Enemy { // image arrays for animation GreenfootImage[] orcRight = new GreenfootImage[8]; GreenfootImage[] orcLeft = new GreenfootImage[8]; GreenfootImage[] orcDefeat = new GreenfootImage[8]; //timers SimpleTimer animationTimer = new SimpleTimer(); SimpleTimer bufferTimer = new SimpleTimer(); SimpleTimer defeatTimer = new SimpleTimer(); //determines which way Orc faces String facing = "right"; //integers int health; int moveLength = 0; int imageIndex = 0; int orcIndex = 0; //runs this code every time a new Orc is created public Orc() { //fills out array of orc walking right animation for(int i = 0; i < orcRight.length; i++) { orcRight[i] = new GreenfootImage("images/orc spritesheet/sprite_0" + (i + 88) + ".png"); orcRight[i].mirrorHorizontally(); orcRight[i].scale(80, 80); } //fills out array of orc walking left animation for(int i = 0; i < orcLeft.length; i++) { orcLeft[i] = new GreenfootImage("images/orc spritesheet/sprite_0" + (i + 88) + ".png"); orcLeft[i].scale(80, 80); } //fills out array of orc defeat animation for(int i = 0; i < orcDefeat.length; i++) { orcDefeat[i] = new GreenfootImage("images/orc spritesheet/sprite_" + (i + 172) + ".png"); orcDefeat[i].scale(80, 80); } animationTimer.mark(); setImage(orcRight[0]); // sets health to 5 hp this.health = 5; } public void act() { MyWorld world = (MyWorld) getWorld(); if(health != 0) { animateOrc(); orcAction(); world.setOrcHealth(health); } else if(health == 0) { removeOrc(); defeatAnimate(); } } //cycles through frames of orc walking animation every 100 milliseconds public void animateOrc() { if(animationTimer.millisElapsed() < 100) { return; } animationTimer.mark(); if(facing.equals("right")) { setImage(orcRight[imageIndex]); imageIndex = (imageIndex + 1) % orcRight.length; } else if(facing.equals("left")) { setImage(orcLeft[imageIndex]); imageIndex = (imageIndex + 1) % orcLeft.length; } else { return; } } // when orc is defeated, the frames of the orc dying are cycled through once public void defeatAnimate() { if(defeatTimer.millisElapsed() < 100) { return; } defeatTimer.mark(); setImage(orcDefeat[orcIndex]); orcIndex = (orcIndex + 1) % orcDefeat.length; } /*if orc touches fireball, a timer starts to make time for the orc defeat animation to run * before removing the orc */ public void hitFireball() { //reset bufferTimer bufferTimer.mark(); //decreases health by 1 health--; if(health == 0){ MyWorld world = (MyWorld) getWorld(); world.setOrcHealth(0); GreenfootSound orcDeath = new GreenfootSound("sounds/Lego yoda death sound.mp3"); orcDeath.play(); } } // after the timer reachers 800 milliseconds, remove the orc public void removeOrc() { if(bufferTimer.millisElapsed() > 800) { facing = "null"; getWorld().removeObject(this); } } // call the getKnightPos() and the enemyHealth() methods in the MyWorld class public void orcAction() { MyWorld world = (MyWorld) getWorld(); world.getKnightPos(); world.enemyHealth(); } // gets the direction orc is facing from the MyWorld class public void orcDirection(String direction) { facing = direction; } }
yrdsb-peths/final-greenfoot-project-IvanMak626
Orc.java
1,135
//fills out array of orc walking right animation
line_comment
en
false
1,073
9
1,135
11
1,242
9
1,135
11
1,359
11
false
false
false
false
false
true
11647_0
public class Item { public static final int SWORD = 1; public static final int LOST_WALLET = 2; public static final int MONSTER_DUNGEON_TWO_KEY = 3; public static final int MONSTER_DUNGEON_THREE_KEY = 3; public static final int BOSS_DUNGEON_ONE_KEY = 4; public static final int BOSS_DUNGEON_TWO_KEY = 5; public static final int BOSS_DUNGEON_THREE_KEY = 6; // SMALL +5, MEDIUM +10, LARGE +15 public static final int SMALL_HEALTH_EMBLEM = 7; public static final int MEDIUM_HEALTH_EMBLEM = 8; public static final int LARGE_HEALTH_EMBLEM = 9; public static final int SMALL_ATTACK_EMBLEM = 10; public static final int MEDIUM_ATTACK_EMBLEM = 11; public static final int LARGE_ATTACK_EMBLEM = 12; public static final int SMALL_MAGIC_EMBLEM = 13; public static final int MEDIUM_MAGIC_EMBLEM = 14; public static final int LARGE_MAGIC_EMBLEM = 15; public static final int SMALL_SPEED_EMBLEM = 16; public static final int MEDIUM_SPEED_EMBLEM = 17; public static final int LARGE_SPEED_EMBLEM = 18; String name; String description; int id; int damage; int price; public Item(int id) { this.id = id; } public String toString() { return String.format("%s", name); } }
phichayut-pak/java-text-rpg
Item.java
408
// SMALL +5, MEDIUM +10, LARGE +15
line_comment
en
false
367
15
408
16
412
14
408
16
525
21
false
false
false
false
false
true
12453_11
//import Scanner import java.util.Scanner; public class WorkerBioData{ String FirstName; String LastName; String NextOfKin; String YearOfBirth; String ResidentialAddress; private int GrossPay=100000; //Caculate Percent private calculcatePercent(int percent){ return (percent/10); } //calculate Tax private int calculcateTax(){ int percent=calculcatePercent(25); return(percent/100 * this.GrossPay); } //Caculate Pension Contribution private int CalculatePensionContribution(){ int percent calculcatePercent(75); return (percent/100 * this.GrossPay); } //Caculate Health INsurance private int CalculateHealthInsurance(){ int percent=calculcatePercent(5); return (percent*this.GrossPay); } //Caculate Housing Contribution private int CalculateHousingContribution(){ int percent=calculcatePercent(5); return (percent*this.GrossPay); } //Caculate Net PAy public int CaculateNetPay(){ int tax=calculcateTax(); int HousingContribution=CalculateHousingContribution(); int PensionDistribution=CalculatePensionContribution(); int HealthInsurance=CalculateHealthInsurance(); int netpay=GrossPay-(tax+HousingContribution+HealthInsurance+PensionDistribution); return netpay; } //CaCulate Retirement Year public int CaculateYearOfRetirement(){ //convert string in date to integer by extracting the year only String[] parts = YearOfBirth.split("/"); int foo = Integer.parseInt(parts[2]); return(65+foo) ; } } public class GetUserData{ public static void main(String[] args) { //instantiate Class by creating new Object WorkerBioData NewEmployee=new WorkerBioData(); // Create scanner object/variable Scanner sc = new Scanner(System.in); //get First Name System.out.println("Enter First Name: "); NewEmployee.FirstName = sc.nextString(); //get Last Name System.out.println("Enter Last Name: "); NewEmployee.LastName = sc.nextString(); //get DOB System.out.println("Enter year of Birth (dd/mm/yy): "); NewEmployee.LastName = sc.nextString(); //get next of Kin System.out.println("Enter Next Of Kin: "); NewEmployee.NextOfKin = sc.nextString(); //get Residential Address System.out.println("Enter Residential Address "); NewEmployee.ResidentialAddress = sc.nextString(); //print Out Save Data System.out.println("FullName:"+ NewEmployee.FirstName+" " NewEmployee.LastName); System.out.println("DOB:"+ NewEmployee.YearOfBirth); System.out.println("NextOfkin:"+ NewEmployee.NextOfKin); System.out.println("Residential Address:"+ NewEmployee.ResidentialAddress); System.out.println("YOur Retirement Age:"+ NewEmployee.CaculateYearOfRetirement()); System.out.println("Your Net Pay is:"+ NewEmployee.CaculateNetPay()); } }
Danijel-Enoch/Java-TQ-code
one.java
747
//get First Name
line_comment
en
false
681
4
747
4
776
4
747
4
901
4
false
false
false
false
false
true
12611_1
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { int choice = 0; while (true) { System.out.println(" 1- Most repeated value"); System.out.println(" 2- Sort"); System.out.println(" 3- Shuffle"); System.out.println(" 4- Find the largest prime"); System.out.println(" 5- Find the smallest prime"); System.out.println(" 6- Check palindrome"); System.out.println(" 7- Check sorted"); System.out.println(" 8- Count primes"); System.out.println(" 9- Reverse array"); System.out.println("10- Shift array"); System.out.println("11- Distinct array"); System.out.println("12- Get the maximum 3 numbers"); System.out.println("13- Get the minimum 3 numbers"); System.out.println("14- Get average"); System.out.println("15- Get median"); System.out.println("16- Return only primes"); System.out.println("17- Zero if less than zero"); System.out.println("18- Execute all functions"); System.out.println("19- Exit"); System.out.println("Please enter your choice ... "); try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); choice = Integer.parseInt(br.readLine()); } catch (Exception e) { System.out.println(e); } if (choice == 1) { most_rep(); } else if (choice == 2) { sort(); } else if (choice == 3) { // Shuffle shuffle(); } else if (choice == 4) { // Find the largest prime } else if (choice == 5) { smallest_prime(); } else if (choice == 6) { // Check palindrome } else if (choice == 7) { // Check sorted } else if (choice == 8) { // Count primes Count_Prime(); } else if (choice == 9) { // Reverse array } else if (choice == 10) { // Shift array System.out.println("The sifted array is : " + shift_array()); } else if (choice == 11) { // Distinct array } else if (choice == 12) { Maxthreenumber(); } else if (choice == 13) { // Get the minimum 3 numbers getThreeMinNums (); } else if (choice == 14) { // Get average } else if (choice == 15) { // Get median } else if (choice == 16) { // Return only primes } else if (choice == 17) { // Zero if less than zero } else if (choice == 18) { // Execute all functions execute_all(); } else break; // exit System.out.println("==========================================="); } } public static void execute_all() { System.out.println(" --Shift array Function-- "); System.out.println("The sifted array is : " + shift_array()); System.out.println(" --Sort array Function-- "); System.out.print("The Sorted array is : "); sort(); System.out.println(""); System.out.println(" --Get Three Minimum numbers-- "); getThreeMinNums (); System.out.println("The maxmam 3 number in array "); Maxthreenumber(); System.out.println(""); System.out.println("The Smallest Prime in array "); smallest_prime(); System.out.println(""); Maxthreenumber(); System.out.println("Most_repeated func"); most_rep(); System.out.println("--shuffle array function--"); shuffle(); } public static void sort() { ArrayList<Integer> arr = new ArrayList<Integer>(); int num = 0; System.out.print("Enter no. of elements you want in array:"); Scanner s = new Scanner(System.in); num = s.nextInt(); System.out.println("Enter all the elements:"); for (int i = 0; i < num; i++) { arr.add(s.nextInt()); } Collections.sort(arr); for (int counter : arr) { System.out.print(counter + " "); } System.out.println(); } public static String shift_array() { String s = ""; try { System.out.println("Please enter the array ... "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); s = br.readLine(); } catch (Exception e) { System.out.println(e); } char[] input = s.toCharArray(); ArrayList<String> arr = new ArrayList<>(); for (int i = 0; i < input.length; i++) arr.add(input[i] + ""); String shifted_arr = ""; shifted_arr += arr.get(arr.size() - 1); for (int i = 0; i < arr.size() - 1; i++) shifted_arr += arr.get(i); return shifted_arr; } //--------------------------------------------count prime number public static void Count_Prime () { int size=0,counter=0,max=0; Scanner input = new Scanner (System.in); System.out.println("Please enter array size : "); size = input.nextInt(); int Array[]= new int[size]; System.out.println("Please enter array "+size+" elements : "); for(int i=0;i<size;i++) { Array[i]=input.nextInt(); } for(int i=0;i<Array.length;i++) { if(max<Array[i]) max=Array[i]; } for(int i=0;i<Array.length;i++) { for(int j=2;j<max;j++) { if(Array[i]==1) break; else if(Array[i]%j==0 && Array[i]!=j) break; else if(j==max-1) { counter++; } } } System.out.println("Prime number = "+counter); } /*Get Three Minimum Numbers */ public static void getThreeMinNums () { ArrayList<Integer> array = new ArrayList<>(); int size =0; Scanner sc = new Scanner(System.in); System.out.println("Enter The size of the array ! "); size=sc.nextInt(); System.out.println("Enter your Array ! "); for(int i=0 ; i<size ; i++) array.add(sc.nextInt()); Collections.sort(array); for(int j=0 ; j<3 && j<size ; j++) System.out.print(array.get(j)+" "); System.out.println(); } //-------------------------------------------maxmam 3 number public static void Maxthreenumber(){ ArrayList<Integer> numbers = new ArrayList<Integer>(); int num = 0; System.out.print("Enter numbers of elements you want in array:"); Scanner input= new Scanner(System.in); num = input.nextInt(); while(num<3) { System.out.println("Numbers should be atleat 3 number "); System.out.println("Enter how many number you will Enter ?"); num= input.nextInt(); } System.out.println("Enter all the elements:"); for (int i = 0; i < num; i++) { numbers.add(input.nextInt()); } Collections.sort(numbers); System.out.println("The lasrgest 3 number in arr are "+ numbers.get(numbers.size()-1) +" "+ numbers.get(numbers.size()-2) +" "+ numbers.get(numbers.size()-3)); } //------------------------------------------------------ Smallest prime public static void smallest_prime () { ArrayList<Integer> Arr = new ArrayList(); ArrayList<Integer> Prim_Arr = new ArrayList(); Scanner input = new Scanner(System.in); int x; int temp; boolean prime; System.out.println("Enter Your Array : "); for (int i = 0; i < 5; i++) { x = input.nextInt(); Arr.add(x); } for (int i = 0; i < Arr.size(); i++) { prime = true ; if (Arr.get(i) == 2) { Prim_Arr.add(Arr.get(i)); continue ;} for (int j = 2; j < Arr.get(i); j++) { if (Arr.get(i) % j == 0) { prime = false ; break;} } if(prime) Prim_Arr.add(Arr.get(i)); } int min; min = Prim_Arr.get(0); for (int i = 0; i < Prim_Arr.size(); i++) { if (min > Prim_Arr.get(i) ) min = Prim_Arr.get(i); } System.out.println("Mini Prime: " +min); } public static class char_data { String symbol=""; int counter=0; } public static int search (String c , Vector<char_data> V) { for (int j=0 ; j<V.size(); j++) { if(c.equals(V.get(j).symbol)) return j; } return -1; } public static void most_rep() { Vector <char_data> Vec=new Vector<char_data>(); Scanner read= new Scanner ( System.in); System.out.println("Enter your text"); String input=read.nextLine(); for(int i=0 ; i<input.length() ; i++) { //System.out.println(i); String temp=""; temp=""+input.charAt(i); int s=search(temp , Vec); if(s==-1) { char_data n= new char_data(); n.symbol=""+input.charAt(i); n.counter=1; Vec.addElement(n); } else { Vec.get(s).counter=(Vec.get(s).counter+1); } } char_data most=new char_data(); if(Vec.size()!=0) {most.symbol=Vec.get(0).symbol;most.counter=Vec.get(0).counter;} for (int t=0 ; t<Vec.size();t++) { if(Vec.get(t).counter>most.counter) {most.symbol=Vec.get(t).symbol;most.counter=Vec.get(t).counter;} } if(Vec.size()!=0) System.out.println("most repeated value: "+ most.symbol); } /** shuffle*/ public static void shuffle() { Scanner sc=new Scanner(System.in); String s=sc.nextLine(); String[] integerStrings = s.split(" "); int[] array= new int[integerStrings.length]; for (int i = 0; i < array.length; i++) array[i] = Integer.parseInt(integerStrings[i]); List<Integer>list = new ArrayList<>(); for(int i:array) list.add(i); Collections.shuffle(list); //print shuffled array System.out.print("shuffled array: "); for(int i=0 ; i<list.size() ; i++) { array[i] = list.get(i); System.out.print(array[i]+" "); } System.out.println(); }//end of shuffle }//end of class main
kenawey/Team-21
Main.java
2,996
// Find the largest prime
line_comment
en
false
2,478
5
2,996
5
3,082
5
2,996
5
3,534
5
false
false
false
false
false
true
12655_0
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map.Entry; import java.util.Set; class RepeatedWordInFile { public static void main(String[] args) { HashMap<String, Integer> wordCountMap = new HashMap<String, Integer>(); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader("sample.txt")); String currentLine = reader.readLine(); while (currentLine != null) { String[] words = currentLine.toLowerCase().split(" "); for (String word : words) { if(wordCountMap.containsKey(word)) { wordCountMap.put(word, wordCountMap.get(word)+1); } else { wordCountMap.put(word, 1); } } currentLine = reader.readLine(); } String mostRepeatedWord = null; int count = 0; Set<Entry<String, Integer>> entrySet = wordCountMap.entrySet(); for (Entry<String, Integer> entry : entrySet) { if(entry.getValue() > count) { mostRepeatedWord = entry.getKey(); count = entry.getValue(); } } System.out.println("The most repeated word in input file is : "+mostRepeatedWord); System.out.println("Number Of Occurrences : "+count); } catch (IOException e) { e.printStackTrace(); } finally { try { reader.close(); //Closing the reader } catch (IOException e) { e.printStackTrace(); } } } }
RITESHMOHAPATRA/JAVA-LAB
part1/p69.java
402
//Closing the reader
line_comment
en
false
360
4
402
4
467
4
402
4
502
6
false
false
false
false
false
true
12738_1
//Day 53 //Given an integer array of size N. Write Program to find maximum product subarray in a given array. import java.util.*; public class ProductSubarray { static int maximumsubarray(int[]arr,int n){ int ans=arr[0]; for(int i=0;i<n;i++){ int product=arr[i]; for(int j=i+1;j<n;j++){ ans=Math.max(ans,product); product=product*arr[j]; } ans=Math.max(ans,product); } return ans; } public static void main(String args[]){ Scanner sc=new Scanner(System.in); System.out.println("enter the size of array"); int n=sc.nextInt(); int[] arr=new int[n]; System.out.println("enter array elements"); for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); } int result=maximumsubarray(arr,n); System.out.println(result); } }
Promodini15/100-Days-Challenge
Day-53.java
257
//Given an integer array of size N. Write Program to find maximum product subarray in a given array.
line_comment
en
false
209
22
257
22
281
22
257
22
286
23
false
false
false
false
false
true
14121_29
/** * Utilities for the algorithm: * e.g.: constants, public methods, variables used for the program */ class Util { // Compute population statistics (diversity) final static boolean COMPUTE_STATS = false; // Dimension of the functions; 10 dimensions final static int DIMENSION = 10; // The minimum value that the variables (phenotypes) can take final static double MIN_VALUE = -5.0; // The maximum value that the variables (phenotypes) can take final static double MAX_VALUE = 5.0; // The step size of the mutation / standard deviation used for nextGaussian final static double MUTATION_STEP_SIZE = 0.05; // Rate of the mutation final static double MUTATION_RATE = 0.1; // The parameter s used in linear parent selection (P. 82) final static double PARENT_LINEAR_S = 2.0; // The number of parents used for recombination final static int N_PARENTS = 2; // Sigma share used in fitness sharing (value should be between 5 and 10) final static double SIGMA_SHARE = 5.0; // Tournament selection k final static int TOURNAMENT_K = 2; // tauSimple double tauSimple; // local tauSimple double tauPrime; // epsilon double epsilon; Mutation mutation = Mutation.UNCORRELATED_N_STEP; ParentSelection parentSelection = ParentSelection.TOURNAMENT; Recombination recombination = Recombination.WHOLE_ARITHMETIC; SurvivorSelection survivorSelection = SurvivorSelection.MU_PLUS_LAMBDA; Topology topology = Topology.RING; Policy policy = Policy.BEST_WORST; // use fitness sharing or not boolean FITNESS_SHARING; // use deterministic crowding or not boolean DETERMINISTIC_CROWDING; // use island model boolean ISLAND_MODEL; // mutation options for an individual enum Mutation { UNIFORM, NON_UNIFORM, UNCORRELATED_ONE_STEP, UNCORRELATED_N_STEP, CORRELATED } // parent selection options for a population enum ParentSelection { UNIFORM, LINEAR_RANK, EXPONENTIAL_RANK, FPS, TOURNAMENT } // recombination options for parents enum Recombination { SIMPLE_ARITHMETIC, SINGLE_ARITHMETIC, WHOLE_ARITHMETIC, BLEND } // survivor selection options enum SurvivorSelection { GENERATIONAL, MU_PLUS_LAMBDA, TOURNAMENT } // topologies enum Topology { RING, TORUS, RANDOM } // migration policy enum Policy { RANDOM_RANDOM, BEST_WORST } // The ratio of offspring to population size final static double OFFSPRING_RATIO = 1.0; // The number of individuals in the population int POPULATION_SIZE; // depends // Number of populations in island model int N_POPULATIONS; // epoch (for exchange) int EPOCH; // kinda 50 ish // number of exchanged individuals final static int N_EXCHANGED = 8; // between 2-5 // torus n and m final static int TORUS_N = 2; final static int TORUS_M = 5; Util() { this.DETERMINISTIC_CROWDING = false; this.FITNESS_SHARING = false; this.ISLAND_MODEL = false; this.POPULATION_SIZE = 100; this.N_POPULATIONS = 1; this.EPOCH = 0; tauSimple = 1 / Math.sqrt(2 * DIMENSION); tauPrime = 1 / Math.sqrt(2 * Math.sqrt(DIMENSION)); epsilon = 0.01; } // Constructor using another Util Util(Util util) { this.POPULATION_SIZE = util.POPULATION_SIZE; this.N_POPULATIONS = util.N_POPULATIONS; this.EPOCH = util.EPOCH; this.DETERMINISTIC_CROWDING = util.DETERMINISTIC_CROWDING; this.FITNESS_SHARING = util.FITNESS_SHARING; this.ISLAND_MODEL = util.ISLAND_MODEL; } void changeIslandUtils(int nPopulations, int epoch) { this.N_POPULATIONS = nPopulations; this.EPOCH = epoch; this.ISLAND_MODEL = true; } void changeMutationParameters(double tauSimple, double tauPrime, double epsilon) { this.tauSimple = tauSimple; this.tauPrime = tauPrime; this.epsilon = epsilon; } }
BogdanFloris/evolutionary-algo-func-optimizer
Util.java
1,142
// number of exchanged individuals
line_comment
en
false
1,055
5
1,142
6
1,183
5
1,142
6
1,439
6
false
false
false
false
false
true
14654_8
/* Alloy Analyzer 4 -- Copyright (c) 2006-2009, Felix Chang * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import org.alloytools.alloy.core.AlloyCore; import edu.mit.csail.sdg.alloy4.Err; import edu.mit.csail.sdg.alloy4.ErrorType; import edu.mit.csail.sdg.alloy4.ErrorFatal; import edu.mit.csail.sdg.alloy4.A4Reporter; import edu.mit.csail.sdg.alloy4.Computer; import edu.mit.csail.sdg.alloy4.Version; import edu.mit.csail.sdg.alloy4.XMLNode; import edu.mit.csail.sdg.alloy4viz.VizGUI; import edu.mit.csail.sdg.ast.Expr; import edu.mit.csail.sdg.ast.ExprConstant; import edu.mit.csail.sdg.ast.ExprVar; import edu.mit.csail.sdg.ast.Module; import edu.mit.csail.sdg.ast.Sig; import edu.mit.csail.sdg.ast.Sig.Field; import edu.mit.csail.sdg.parser.CompUtil; import edu.mit.csail.sdg.sim.SimInstance; import edu.mit.csail.sdg.sim.SimTuple; import edu.mit.csail.sdg.sim.SimTupleset; import edu.mit.csail.sdg.translator.A4Solution; import edu.mit.csail.sdg.translator.A4SolutionReader; import edu.mit.csail.sdg.translator.A4Tuple; import edu.mit.csail.sdg.translator.A4TupleSet; import static edu.mit.csail.sdg.alloy4.A4Preferences.ImplicitThis; import edu.mit.csail.sdg.alloy4.A4Preferences.Verbosity; import static edu.mit.csail.sdg.alloy4.A4Preferences.VerbosityPref; import kodkod.engine.fol2sat.HigherOrderDeclException; import java.io.File; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class Viz { private static final String main_model_name = "model2.als"; public static void main(String[] args) throws Err { VizGUI viz = null; // Computer evaluator = new Computer(); if (args.length != 1) { System.out.println("Error: please provide exactly one argument"); } else { // viz = new VizGUI(false, args[0], null); viz = new VizGUI(true, args[0], null, null, evaluator, 1); } } // the rest of these methods are copied with minor modifications from Alloy's SimpleGUI.java file // they are private there, but we need them in order to run the evaluator on arbitrary XMLs. // exported XMLs don't include the path to the main model file, which is necessary for creating the // evaluator, but we always know where it is, so we skip the lookup that the Alloy implementation does // and just set the mainname directly. private static Computer evaluator = new Computer() { private String filename = null; @Override public final Object compute(final Object input) throws Exception { if (input instanceof File) { filename = ((File) input).getAbsolutePath(); return ""; } if (!(input instanceof String[])) return ""; // [electrum] evaluator takes two arguments, the second is the focused state final String[] strs = (String[]) input; if (strs[0].trim().length() == 0) return ""; // Empty line Module root = null; A4Solution ans = null; try { Map<String,String> fc = new LinkedHashMap<String,String>(); XMLNode x = new XMLNode(new File(filename)); if (!x.is("alloy")) throw new Exception(); String mainname = System.getProperty("user.dir") + "/" + main_model_name; for (XMLNode sub : x) if (sub.is("source")) { String name = sub.getAttribute("filename"); String content = sub.getAttribute("content"); fc.put(name, content); } root = CompUtil.parseEverything_fromFile(A4Reporter.NOP, fc, mainname, (Version.experimental && ImplicitThis.get()) ? 2 : 1); ans = A4SolutionReader.read(root.getAllReachableSigs(), x); for (ExprVar a : ans.getAllAtoms()) { root.addGlobal(a.label, a); } for (ExprVar a : ans.getAllSkolems()) { root.addGlobal(a.label, a); } } catch (Throwable ex) { throw new ErrorFatal("Failed to read or parse the XML file."); } try { Expr e = CompUtil.parseOneExpression_fromString(root, strs[0]); if (AlloyCore.isDebug() && VerbosityPref.get() == Verbosity.FULLDEBUG) { SimInstance simInst = convert(root, ans); if (simInst.wasOverflow()) return simInst.visitThis(e).toString() + " (OF)"; } return ans.eval(e, Integer.valueOf(strs[1])).toString(); } catch (HigherOrderDeclException ex) { throw new ErrorType("Higher-order quantification is not allowed in the evaluator."); } } }; /** Converts an A4TupleSet into a SimTupleset object. */ private static SimTupleset convert(Object object) throws Err { if (!(object instanceof A4TupleSet)) throw new ErrorFatal("Unexpected type error: expecting an A4TupleSet."); A4TupleSet s = (A4TupleSet) object; if (s.size() == 0) return SimTupleset.EMPTY; List<SimTuple> list = new ArrayList<SimTuple>(s.size()); int arity = s.arity(); for (A4Tuple t : s) { String[] array = new String[arity]; for (int i = 0; i < t.arity(); i++) array[i] = t.atom(i); list.add(SimTuple.make(array)); } return SimTupleset.make(list); } /** Converts an A4Solution into a SimInstance object. */ private static SimInstance convert(Module root, A4Solution ans) throws Err { SimInstance ct = new SimInstance(root, ans.getBitwidth(), ans.getMaxSeq()); for (Sig s : ans.getAllReachableSigs()) { if (!s.builtin) ct.init(s, convert(ans.eval(s))); for (Field f : s.getFields()) if (!f.defined) ct.init(f, convert(ans.eval(f))); } for (ExprVar a : ans.getAllAtoms()) ct.init(a, convert(ans.eval(a))); for (ExprVar a : ans.getAllSkolems()) ct.init(a, convert(ans.eval(a))); return ct; } }
utsaslab/squirrelfs
model_checking/Viz.java
1,933
// [electrum] evaluator takes two arguments, the second is the focused state
line_comment
en
false
1,667
16
1,933
16
2,015
17
1,933
16
2,321
17
false
false
false
false
false
true
14896_6
/** * Journal program 17 * Write a program to display a message as a combination of phone keys and * diplay the frequeny of every key. */ import java.util.*; public class SMS { // instance variables String message; char []letter={' ','a','b','c','d','e','f','g','h','i','j','k','l','m','n' ,'o','p','q','r','s','t','u','v','w','x','y','z'}; int []num={0,2,22,222,3,33,333,4,44,444,5,55,555,6,66,666,7,77,777,7777, 8,88,888,9,99,999,9999}; String key=""; int []freq; char []ch= key.toCharArray(); /** * Constructor for objects of class SMS */ public SMS() { // initialise instance variables message=""; } void getData() { Scanner sc = new Scanner(System.in); System.out.print("Enter a message: ");//accept message from user message = sc.nextLine(); } void getKeys() { for(int i=0; i<message.length(); i++) { for(int j=0; j<letter.length; j++) if(message.charAt(i)==letter[j]){// finds combination of phone keys key+=num[j]; } } } void frequency() { freq=new int[key.length()]; ch= key.toCharArray(); //convert string to char array for(int i = 0; i <key.length(); i++) { freq[i] = 1; for(int j = i+1; j <key.length(); j++) { if(ch[i] == ch[j]) { freq[i]++; //count frequency of each char ch[j] = ' '; //replaces already counted char with space } } } } void display() { System.out.print("Key combination: "); System.out.print(key);// display key combination System.out.println(); System.out.println("Number Frequency "); for(int i = 0; i <freq.length; i++) { if(ch[i]!=' ') //char condition System.out.println( ch[i] + " " + freq[i]); } } public static void main () //main method { SMS obj=new SMS(); obj.getData(); obj.getKeys(); obj.frequency(); obj.display(); } }
belhyto/Java-school
SMS.java
649
//convert string to char array
line_comment
en
false
599
7
649
7
723
7
649
7
764
7
false
false
false
false
false
true
16481_9
package org.telkom.university.code.smell; import org.apache.commons.lang3.StringUtils; import java.time.Year; import java.util.UUID; import java.util.regex.Pattern; // Signature: DHF public class User { // This is user's ID index private final String userID; private SchoolIdentifier schoolIdentifier; private SchoolAccount schoolAccount; private GeneralInformation generalInformation; // This is class's constructor public User() { // This is initiate the unique ID this.userID = UUID.randomUUID().toString(); } private void validateProgramStudy(String programStudy) throws Exception { if (programStudy == null || programStudy.trim().isEmpty()) { throw new Exception("Program study should not be null, empty, or blank."); } } private void validateFaculty(String faculty) throws Exception { if (faculty == null || faculty.trim().isEmpty()) { throw new Exception("Faculty should not be null, empty, or blank."); } } private void validateEnrollmentYear(int enrollmentYear) throws Exception { if (enrollmentYear <= 0 || enrollmentYear >= Integer.MAX_VALUE) { throw new Exception("Enrollment year should be a positive integer."); } } // This method is setting up the user's school identifier public void setSchoolIdentifier(SchoolIdentifier schoolIdentifier) throws Exception { String programStudy = schoolIdentifier.getProgramStudy(); String faculty = schoolIdentifier.getFaculty(); int enrollmentYear = schoolIdentifier.getEnrollmentYear(); // Check if the inputs are empty or blank validateProgramStudy(programStudy); validateFaculty(faculty); validateEnrollmentYear(enrollmentYear); } private void validateEmail(String email) throws Exception { if (email == null || email.trim().isEmpty()) { throw new Exception("Email should not be null, empty, or blank."); } } private void validatePassword(String password) throws Exception { if (password == null || password.trim().isEmpty()) { throw new Exception("Password should not be null, empty, or blank."); } } private void validateUserName(String userName) throws Exception { if (userName == null || userName.trim().isEmpty()) { throw new Exception("User name should not be null, empty, or blank."); } } // This method is setting up the user's school account public void setSchoolAccount(SchoolAccount schoolAccount) throws Exception { String email = schoolAccount.getEmail(); String password = schoolAccount.getPassword(); String userName = schoolAccount.getUserName(); // Check if the inputs are empty or blank validateEmail(email); validatePassword(password); validateUserName(userName); } private void validateFirstName(String firstName) throws Exception { if (firstName == null || firstName.trim().isEmpty()) { throw new Exception("First name should not be null, empty, or blank."); } } private void validateLastName(String lastName) throws Exception { if (lastName == null || lastName.trim().isEmpty()) { throw new Exception("Last name should not be null, empty, or blank."); } } private void validateGender(String gender) throws Exception { if (gender == null || gender.trim().isEmpty()) { throw new Exception("Gender should not be null, empty, or blank."); } } private void validateStudentIdentifierNumber(String studentIdentifierNumber) throws Exception { if (studentIdentifierNumber == null || studentIdentifierNumber.trim().isEmpty()) { throw new Exception("Student identifier number should not be null, empty, or blank."); } } // This method is setting up the user's general information public void setGeneralInformation(GeneralInformation generalInformation ) throws Exception { String firstName = generalInformation.getFirstName(); String lastName = generalInformation.getLastName(); String gender = generalInformation.getGender(); String studentIdentifierNumber = generalInformation.getStudentIdentifierNumber(); validateFirstName(firstName); validateLastName(lastName); validateGender(gender); validateStudentIdentifierNumber(studentIdentifierNumber); } // This method is used to calculate the year of the user based on the enrollment year public int calculateEnrollmentYear() { // This is the user's age calculation int currentYears = Year.now().getValue(); return currentYears - schoolIdentifier.getEnrollmentYear(); } // This method is used to validate user's email address public boolean isValidEmail(String email) { String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\."+ "[a-zA-Z0-9_+&*-]+)*@" + "(?:[a-zA-Z0-9-]+\\.)+[a-z" + "A-Z]{2,7}$"; Pattern pat = Pattern.compile(emailRegex); if (email == null) return false; return pat.matcher(email).matches(); } // This method is used to check if the user's password is strong enough public boolean isStrongPassword(String password) { String passwordRegex = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,}$"; Pattern pat = Pattern.compile(passwordRegex); if (password == null) return false; return pat.matcher(password).matches(); } // This method is used to update user's profile public void updateProfile(SchoolIdentifier schoolIdentifier, SchoolAccount schoolAccount, GeneralInformation generalInfomration) throws Exception { if(generalInformation.getStudentIdentifierNumber().length() != 10 || !StringUtils.isNumeric(generalInformation.getStudentIdentifierNumber().length())){ throw new Exception("Input is not valid."); } boolean isValidEmail = isValidEmail(schoolAccount.getEmail()); boolean isStrongPassword = isStrongPassword(schoolAccount.getPassword()); this.setSchoolIdentifier(schoolIdentifier); this.setSchoolAccount(schoolAccount); this.setGeneralInformation(generalInformation); int calculateYear = this.calculateEnrollmentYear(); String emailStatus = "", passwordStatus = ""; emailStatus = isValidEmail ? "VALID" : "INVALID"; passwordStatus = isStrongPassword ? "STRONG" : "WEAK"; if (emailStatus.equals("VALID")) { if (passwordStatus.equals("STRONG")) { System.out.println("UPDATE COMPLETE!"); } else if (passwordStatus.equals("WEAK")) { System.out.println("PLEASE USE BETTER PASSWORD"); } }else if (emailStatus.equals("INVALID")) { if (passwordStatus.equals("STRONG")) { System.out.println("PLEASE CHECK YOUR EMAIL"); } else if (passwordStatus.equals("WEAK")) { System.out.println("THIS IS JOKE RIGHT? PLEASE USE VALID EMAIL AND STRONG PASSWORD"); } } } }
kfebrian/1302204081-UTS-MKPL
User.java
1,549
// This method is used to calculate the year of the user based on the enrollment year
line_comment
en
false
1,441
17
1,549
17
1,670
17
1,549
17
1,865
19
false
false
false
false
false
true
16795_1
// https://www.hackerrank.com/challenges/java-1d-array-introduction/problem import java.util.*; public class Solution { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[] a = new int[n]; for(int j=0;j<n;j++) { a[j] = scan.nextInt(); } scan.close(); // Prints each sequential element in array a for (int i = 0; i < a.length; i++) { System.out.println(a[i]); } } }
haytastan/Hackerrank_Java
19.java
154
// Prints each sequential element in array a
line_comment
en
false
128
8
154
8
165
8
154
8
177
10
false
false
false
false
false
true
17273_4
abstract class Shape { protected ColorInterface color; protected Shape (ColorInterface c) { this.color = c; } abstract void drawShape(int border); abstract void modifyBorder(int border, int increment); } class Triangle extends Shape { protected Triangle(ColorInterface c) { super(c); } // Implementer-specific method @Override void drawShape(int border) { System.out.print("This Triangle is colored with "); color.fillWithColor(border); } // abstraction-specific method @Override void modifyBorder(int border, int increment) { System.out.println("\nNow we are changing the border length " + increment + " times"); border = border * increment; drawShape(border); } } class Rectangle extends Shape { protected Rectangle(ColorInterface c) { super(c); } // Implementer-specific method @Override void drawShape(int border) { System.out.print("This Rectangle is colored with "); color.fillWithColor(border); } // abstraction-specific method @Override void modifyBorder(int border, int increment) { System.out.println("\nNow we are changing the border length " + increment + " times"); border = border * increment; drawShape(border); } } ---------------------------------------------------------- public interface ColorInterface { void fillWithColor(int border); } class RedColor implements ColorInterface { @Override public void fillWithColor(int border) { System.out.print("Red color with " + border + " inch border"); } } class GreenColor implements ColorInterface { @Override public void fillWithColor(int border) { System.out.print("Green color with " + border + " inch border"); } } ----------------------------------------------------------- import java.awt.*; public class Client { public static void main(String[] args) { System.out.println("*****BRIDGE PATTERN*****"); //Coloring Green to Triangle System.out.println("\nColoring Triangle:"); ColorInterface green = new GreenColor(); Shape triangleShape = new Triangle(green); triangleShape.drawShape(20); triangleShape.modifyBorder(20, 3); //Coloring Red to Rectangle System.out.println("\n\nColoring Rectangle :"); ColorInterface red = new RedColor(); Shape rectangleShape = new Rectangle(red); rectangleShape.drawShape(50); rectangleShape.modifyBorder(50, 2); } }
sijoonlee/java-design-patterns
39.java
589
//Coloring Green to Triangle
line_comment
en
false
523
6
589
6
640
6
589
6
697
7
false
false
false
false
false
true
17296_16
public class BST<T extends Comparable<T>> { private Node<T> root; public BST() { root = null; } public Node<T> getRoot() { return root; } /** * Insert a new node into the tree. * If the tree is empty, create a new node and set it as the root. * Otherwise, find the right place to insert the new node. * If the data is less than the root, go to the left subtree. * If the data is greater than the root, go to the right subtree. * Repeat the process until we find the right place to insert the new node. * If the data is already in the tree, do nothing. * * @param data the data to be inserted */ public void insert(T data) { root = insert(root, data); } /** * This is an internal method to insert a new node into the tree. * Used in insert() * * @param node the root node of the tree * @param data the data to be inserted * @return the new node */ Node<T> insert(Node<T> node, T data) { if (node == null) { node = new Node<T>(data); } // We use compareTo() to compare two generic objects if (data.compareTo(node.getData()) < 0) { node.setLeft(insert(node.getLeft(), data)); } else if (data.compareTo(node.getData()) > 0) { node.setRight(insert(node.getRight(), data)); } return node; } /** * Delete a node from the tree with the given data. * If the tree is empty, do nothing. * Otherwise, find the node with the given data. * If the data is less than the root, go to the left subtree. * If the data is greater than the root, go to the right subtree. * Repeat the process until we find the node with the given data. * If the node is found, delete it. * If the node is not found, do nothing. * * @param data the data to be deleted */ public void delete(T data) { root = delete(root, data); } /** * This is an internal method to delete a node from the tree. * Used in delete() * * @param node the root node of the tree * @param data the data to be deleted * @return the new node */ Node<T> delete(Node<T> node, T data) { if (node == null) { return node; } if (data.compareTo(node.getData()) < 0) { node.setLeft(delete(node.getLeft(), data)); } else if (data.compareTo(node.getData()) > 0) { node.setRight(delete(node.getRight(), data)); } else { // else is triggered when we find the node with the given data // node with only one child or no child if (node.getLeft() == null) { return node.getRight(); } else if (node.getRight() == null) { return node.getLeft(); } // node with two children: Get the inorder successor (smallest // in the right subtree) node.setData(minValue(node.getRight())); // Delete the inorder successor node.setRight(delete(node.getRight(), node.getData())); } return node; } /** * This is an internal method to calculate the minimum value of the tree. * Used in delete() * * @param node * @return the minimum value of the tree */ private T minValue(Node<T> node) { T minv = node.getData(); while (node.getLeft() != null) { minv = node.getLeft().getData(); node = node.getLeft(); } return minv; } /** * Calculate the depth of the tree. * The depth of the tree is the number of nodes along the longest path * * @return the depth of the tree */ public int depth() { return depth(root); } /** * This is an internal method to calculate the depth of the tree. * Used in depth() * * @param node the root node of the tree * @return the depth of the tree */ private int depth(Node<T> node) { if (node == null) { return 0; } return 1 + Math.max(depth(node.getLeft()), depth(node.getRight())); } /** * Traverse the tree in order. Print the data of each node. */ void inorder() { inorder(root); } /** * This is an internal method to traverse the tree in order. * Used in inorder() * * @param node the root node of the tree */ void inorder(Node<T> node) { if (node != null) { inorder(node.getLeft()); System.out.print(node.getData() + " "); inorder(node.getRight()); } } public static void main(String[] args) { // Several test cases for the BST class BST<Integer> bst = new BST<Integer>(); bst.insert(5); bst.insert(3); bst.insert(7); bst.insert(2); bst.insert(4); bst.insert(6); bst.insert(8); bst.insert(1); bst.insert(9); bst.insert(10); bst.insert(11); System.out.println("Inorder traversal of the given tree"); bst.inorder(); System.out.println("\nThis should be 1 2 3 4 5 6 7 8 9 10 11"); System.out.println("\nDelete 10"); bst.delete(10); System.out.println("Inorder traversal of the modified tree"); bst.inorder(); System.out.println("\nDelete 7"); bst.delete(7); System.out.println("Inorder traversal of the modified tree"); bst.inorder(); System.out.println("\nDelete 5"); bst.delete(5); System.out.println("Inorder traversal of the modified tree"); System.out.println("=".repeat(10)); System.out.println("\nSTRING TREE TEST\n"); System.out.println("=".repeat(10)); BST<String> bst2 = new BST<String>(); bst2.insert("E"); bst2.insert("B"); bst2.insert("G"); bst2.insert("A"); bst2.insert("C"); bst2.insert("F"); bst2.insert("H"); bst2.insert("D"); bst2.insert("I"); bst2.insert("J"); bst2.insert("K"); System.out.println("Inorder traversal of the given tree"); bst2.inorder(); System.out.println("\nDelete E"); bst2.delete("E"); System.out.println("Inorder traversal of the modified tree"); bst2.inorder(); System.out.println("\nDelete G"); bst2.delete("G"); System.out.println("Inorder traversal of the modified tree"); bst2.inorder(); // 1) Implement a method to calculate the depth of a given binary search tree. // 2) Generate a large number of binary search trees with random values. // 3) Calculate and display statistics (e.g., average depth, minimum depth, // maximum depth) for the trees. int numTrees = 1000; // The number of trees you want to generate int maxDepth = Integer.MIN_VALUE; int minDepth = Integer.MAX_VALUE; int sumDepth = 0; int range = 100; // Range of the random numbers for (int i = 0; i < numTrees; i++) { BST<Integer> randBst = new BST<>(); for (int j = 0; j < 20; j++) { // Inserting 20 random numbers into each tree int randomNum = (int) (Math.random() * range); randBst.insert(randomNum); } int currentDepth = randBst.depth(); maxDepth = Math.max(maxDepth, currentDepth); minDepth = Math.min(minDepth, currentDepth); sumDepth += currentDepth; } double averageDepth = (double) sumDepth / numTrees; System.out.println("Maximum Depth: " + maxDepth); System.out.println("Minimum Depth: " + minDepth); System.out.println("Average Depth: " + averageDepth); } }
CoopTRUE/AlgoClass
BST.java
2,089
// 1) Implement a method to calculate the depth of a given binary search tree.
line_comment
en
false
1,863
18
2,089
18
2,222
18
2,089
18
2,400
19
false
false
false
false
false
true
18781_3
import java.util.Iterator; /** * A collection that implements set behavior. * * @author Dean Hendrix (dh@auburn.edu) * @version 2016-03-01 * */ public interface Set<T> extends Iterable<T> { /** * Ensures the collection contains the specified element. * No specific order can be assumed. Neither duplicate nor null * values are allowed. * * @param element The element whose presence is to be ensured. * @return true if collection is changed, false otherwise. */ boolean add(T element); /** * Ensures the collection does not contain the specified element. * If the specified element is present, this method removes it * from the collection. * * @param element The element to be removed. * @return true if collection is changed, false otherwise. */ boolean remove(T element); /** * Searches for specified element in this collection. * * @param element The element whose presence in this collection is to be tested. * @return true if this collection contains the specified element, false otherwise. */ boolean contains(T element); /** * Returns the current size of this collection. * * @return the number of elements in this collection. */ int size(); /** * Tests to see if this collection is empty. * * @return true if this collection contains no elements, false otherwise. */ boolean isEmpty(); /** * Tests for equality between this set and the parameter set. * Returns true if this set contains exactly the same elements * as the parameter set, regardless of order. * * @return true if this set contains exactly the same elements as * the parameter set, false otherwise */ boolean equals(Set<T> s); /** * Returns a set that is the union of this set and the parameter set. * * @return a set that contains all the elements of this set and the parameter set */ Set<T> union(Set<T> s); /** * Returns a set that is the intersection of this set and the parameter set. * * @return a set that contains elements that are in both this set and the parameter set */ Set<T> intersection(Set<T> s); /** * Returns a set that is the complement of this set and the parameter set. * * @return a set that contains elements that are in this set but not the parameter set */ Set<T> complement(Set<T> s); /** * Returns an iterator over the elements in this collection. * No specific order can be assumed. * * @return an iterator over the elements in this collection */ Iterator<T> iterator(); }
matcoggins/COMP-2210
Set.java
643
/** * Searches for specified element in this collection. * * @param element The element whose presence in this collection is to be tested. * @return true if this collection contains the specified element, false otherwise. */
block_comment
en
false
614
51
643
53
704
56
643
53
736
57
false
false
false
false
false
true
19237_24
/************************************************************************************** * bias_tree * Copyright (c) 2014-2017 National University of Colombia, https://github.com/remixlab * @author Jean Pierre Charalambos, http://otrolado.info/ * * All rights reserved. Library that eases the creation of interactive * scenes, released under the terms of the GNU Public License v3.0 * which is available at http://www.gnu.org/licenses/gpl.html **************************************************************************************/ package remixlab.bias; import remixlab.bias.event.MotionEvent; import java.util.ArrayList; import java.util.List; /** * Agents gather data from different sources --mostly from input devices such touch * surfaces or simple mice-- and reduce them into a rather simple but quite 'useful' set * of interface events ({@link BogusEvent} ) for third party objects ( * {@link Grabber} objects) to consume them ( * {@link #handle(BogusEvent)}). Agents thus effectively open up a channel between all * kinds of input data sources and user-space objects. To add/remove a grabber to/from the * {@link #grabbers()} collection issue {@link #addGrabber(Grabber)} / * {@link #removeGrabber(Grabber)} calls. Derive from this agent and either call * {@link #handle(BogusEvent)} or override {@link #handleFeed()} . * <p> * The agent may send bogus-events to its {@link #inputGrabber()} which may be regarded as * the agent's grabber target. The {@link #inputGrabber()} may be set by querying each * grabber object in {@link #grabbers()} to check if its * {@link Grabber#checkIfGrabsInput(BogusEvent)}) condition is met (see * {@link #updateTrackedGrabber(BogusEvent)}, {@link #updateTrackedGrabberFeed()}). The * first grabber meeting the condition, namely the {@link #trackedGrabber()}), will then * be set as the {@link #inputGrabber()}. When no grabber meets the condition, the * {@link #trackedGrabber()} is then set to null. In this case, a non-null * {@link #inputGrabber()} may still be set with {@link #setDefaultGrabber(Grabber)} (see * also {@link #defaultGrabber()}). */ public abstract class Agent { protected List<Grabber> grabberList; protected Grabber trackedGrabber, defaultGrabber; protected boolean agentTrckn; protected InputHandler handler; /** * Constructs an Agent and registers is at the given inputHandler. */ public Agent(InputHandler inputHandler) { grabberList = new ArrayList<Grabber>(); setTracking(true); handler = inputHandler; handler.registerAgent(this); } // 1. Grabbers /** * Removes the grabber from the {@link #grabbers()} list. * * @see #removeGrabbers() * @see #addGrabber(Grabber) * @see #hasGrabber(Grabber) * @see #grabbers() */ public boolean removeGrabber(Grabber grabber) { if (defaultGrabber() == grabber) setDefaultGrabber(null); if (trackedGrabber() == grabber) resetTrackedGrabber(); return grabberList.remove(grabber); } /** * Clears the {@link #grabbers()} list. * * @see #removeGrabber(Grabber) * @see #addGrabber(Grabber) * @see #hasGrabber(Grabber) * @see #grabbers() */ public void removeGrabbers() { setDefaultGrabber(null); trackedGrabber = null; grabberList.clear(); } /** * Returns the list of grabber (and interactive-grabber) objects handled by this agent. * * @see #removeGrabber(Grabber) * @see #addGrabber(Grabber) * @see #hasGrabber(Grabber) * @see #removeGrabbers() */ public List<Grabber> grabbers() { return grabberList; } /** * Returns true if the grabber is currently in the agents {@link #grabbers()} list. * * @see #removeGrabber(Grabber) * @see #addGrabber(Grabber) * @see #grabbers() * @see #removeGrabbers() */ public boolean hasGrabber(Grabber grabber) { for (Grabber g : grabbers()) if (g == grabber) return true; return false; } /** * Adds the grabber in {@link #grabbers()}. * * @see #removeGrabber(Grabber) * @see #hasGrabber(Grabber) * @see #grabbers() * @see #removeGrabbers() */ public boolean addGrabber(Grabber grabber) { if (grabber == null) return false; if (hasGrabber(grabber)) return false; return grabberList.add(grabber); } /** * Feeds {@link #updateTrackedGrabber(BogusEvent)} and {@link #handle(BogusEvent)} with * the returned event. Returns null by default. Use it in place of * {@link #updateTrackedGrabberFeed()} and/or {@link #handleFeed()} which take * higher-precedence. * <p> * Automatically call by the main event loop ( * {@link InputHandler#handle()}). See ProScene's Space-Navigator * example. * * @see InputHandler#handle() * @see #handleFeed() * @see #updateTrackedGrabberFeed() * @see #handle(BogusEvent) * @see #updateTrackedGrabber(BogusEvent) */ protected BogusEvent feed() { return null; } /** * Feeds {@link #handle(BogusEvent)} with the returned event. Returns null by default. * Use it in place of {@link #feed()} which takes lower-precedence. * <p> * Automatically call by the main event loop ( * {@link InputHandler#handle()}). See ProScene's Space-Navigator * example. * * @see InputHandler#handle() * @see #feed() * @see #updateTrackedGrabberFeed() * @see #handle(BogusEvent) * @see #updateTrackedGrabber(BogusEvent) */ protected BogusEvent handleFeed() { return null; } /** * Feeds {@link #updateTrackedGrabber(BogusEvent)} with the returned event. Returns null * by default. Use it in place of {@link #feed()} which takes lower-precedence. * <p> * Automatically call by the main event loop ( * {@link InputHandler#handle()}). * * @see InputHandler#handle() * @see #feed() * @see #handleFeed() * @see #handle(BogusEvent) * @see #updateTrackedGrabber(BogusEvent) */ protected BogusEvent updateTrackedGrabberFeed() { return null; } /** * Returns the {@link InputHandler} this agent is registered to. */ public InputHandler inputHandler() { return handler; } /** * If {@link #isTracking()} and the agent is registered at the {@link #inputHandler()} * then queries each object in the {@link #grabbers()} to check if the * {@link Grabber#checkIfGrabsInput(BogusEvent)}) condition is met. * The first object meeting the condition will be set as the {@link #inputGrabber()} and * returned. Note that a null grabber means that no object in the {@link #grabbers()} * met the condition. A {@link #inputGrabber()} may also be enforced simply with * {@link #setDefaultGrabber(Grabber)}. * * @param event to query the {@link #grabbers()} * @return the new grabber which may be null. * @see #setDefaultGrabber(Grabber) * @see #isTracking() * @see #handle(BogusEvent) * @see #trackedGrabber() * @see #defaultGrabber() * @see #inputGrabber() */ protected Grabber updateTrackedGrabber(BogusEvent event) { if (event == null || !inputHandler().isAgentRegistered(this) || !isTracking()) return trackedGrabber(); // We first check if default grabber is tracked, // i.e., default grabber has the highest priority (which is good for // keyboards and doesn't hurt motion grabbers: Grabber dG = defaultGrabber(); if (dG != null) if (dG.checkIfGrabsInput(event)) { trackedGrabber = dG; return trackedGrabber(); } // then if tracked grabber remains the same: Grabber tG = trackedGrabber(); if (tG != null) if (tG.checkIfGrabsInput(event)) return trackedGrabber(); // pick the first otherwise trackedGrabber = null; for (Grabber grabber : grabberList) if (grabber != dG && grabber != tG) if (grabber.checkIfGrabsInput(event)) { trackedGrabber = grabber; return trackedGrabber(); } return trackedGrabber(); } /** * Returns the sensitivities used in {@link #handle(BogusEvent)} to * {@link remixlab.bias.event.MotionEvent#modulate(float[])}. */ public float[] sensitivities(MotionEvent event) { return new float[]{1f, 1f, 1f, 1f, 1f, 1f}; } /** * Enqueues an EventGrabberTuple(event, inputGrabber()) on the * {@link InputHandler#eventTupleQueue()}, thus enabling a call on * the {@link #inputGrabber()} * {@link Grabber#performInteraction(BogusEvent)} method (which is * scheduled for execution till the end of this main event loop iteration, see * {@link InputHandler#enqueueEventTuple(EventGrabberTuple)} for * details). * * @see #inputGrabber() * @see #updateTrackedGrabber(BogusEvent) */ protected boolean handle(BogusEvent event) { if (event == null || !handler.isAgentRegistered(this) || inputHandler() == null) return false; if (event instanceof MotionEvent) if (((MotionEvent) event).isAbsolute()) if (event.isNull() && !event.flushed()) return false; if (event instanceof MotionEvent) ((MotionEvent) event).modulate(sensitivities((MotionEvent) event)); Grabber inputGrabber = inputGrabber(); if (inputGrabber != null) return inputHandler().enqueueEventTuple(new EventGrabberTuple(event, inputGrabber)); return false; } /** * If {@link #trackedGrabber()} is non null, returns it. Otherwise returns the * {@link #defaultGrabber()}. * * @see #trackedGrabber() */ public Grabber inputGrabber() { return trackedGrabber() != null ? trackedGrabber() : defaultGrabber(); } /** * Returns true if {@code g} is the agent's {@link #inputGrabber()} and false otherwise. */ public boolean isInputGrabber(Grabber g) { return inputGrabber() == g; } /** * Returns {@code true} if this agent is tracking its grabbers. * <p> * You may need to {@link #enableTracking()} first. */ public boolean isTracking() { return agentTrckn; } /** * Enables tracking so that the {@link #inputGrabber()} may be updated when calling * {@link #updateTrackedGrabber(BogusEvent)}. * * @see #disableTracking() */ public void enableTracking() { setTracking(true); } /** * Disables tracking. * * @see #enableTracking() */ public void disableTracking() { setTracking(false); } /** * Sets the {@link #isTracking()} value. */ public void setTracking(boolean enable) { agentTrckn = enable; if (!isTracking()) trackedGrabber = null; } /** * Calls {@link #setTracking(boolean)} to toggle the {@link #isTracking()} value. */ public void toggleTracking() { setTracking(!isTracking()); } /** * Returns the grabber set after {@link #updateTrackedGrabber(BogusEvent)} is called. It * may be null. */ public Grabber trackedGrabber() { return trackedGrabber; } /** * Default {@link #inputGrabber()} returned when {@link #trackedGrabber()} is null and * set with {@link #setDefaultGrabber(Grabber)}. * * @see #inputGrabber() * @see #trackedGrabber() */ public Grabber defaultGrabber() { return defaultGrabber; } /** * Same as * {@code defaultGrabber() != g1 ? setDefaultGrabber(g1) ? true : setDefaultGrabber(g2) : setDefaultGrabber(g2)} * which is ubiquitous among the examples. */ public boolean shiftDefaultGrabber(Grabber g1, Grabber g2) { return defaultGrabber() != g1 ? setDefaultGrabber(g1) ? true : setDefaultGrabber(g2) : setDefaultGrabber(g2); // return defaultGrabber() == g1 ? setDefaultGrabber(g2) ? true : false : // defaultGrabber() == g2 ? setDefaultGrabber(g1) : false; } /** * Sets the {@link #defaultGrabber()} * <p> * {@link #inputGrabber()} */ public boolean setDefaultGrabber(Grabber grabber) { if (grabber == null) { this.defaultGrabber = null; return true; } if (!hasGrabber(grabber)) { System.out.println( "To set a " + getClass().getSimpleName() + " default grabber the " + grabber.getClass().getSimpleName() + " should be added into agent first. Use one of the agent addGrabber() methods"); return false; } defaultGrabber = grabber; return true; } /** * Sets the {@link #trackedGrabber()} to {@code null}. */ public void resetTrackedGrabber() { trackedGrabber = null; } }
remixlab/proscene
src/remixlab/bias/Agent.java
3,439
/** * Enables tracking so that the {@link #inputGrabber()} may be updated when calling * {@link #updateTrackedGrabber(BogusEvent)}. * * @see #disableTracking() */
block_comment
en
false
3,350
49
3,439
47
3,710
51
3,439
47
4,123
57
false
false
false
false
false
true
19624_0
import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.*; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Map extends Pane { //Extends the Pane class private int unit = 30; //size of one cell (in pixels) private int size; //size of map (number of columns/rows) private int[][] map; // Keeps the data in a two-dimensional array private Position start; //starting point for the player (ball) //Constructs a map from a given text file; public Map(String textFile) throws FileNotFoundException { File source = new File(textFile); if (!source.exists()){ System.out.println("Source file "+ textFile + " does not exits"); System.exit(1); } try ( Scanner input = new Scanner(source); ){ size = input.nextInt(); map = new int[size][size]; input.nextLine(); int currentRow = 0; while (input.hasNext()){ String row = input.nextLine(); String[] content = row.split(" "); for (int column =0; column < content.length; column++){ int number = Integer.parseInt(content[column]); if (number == 2){ //2 - for the starting point of the player start = new Position(column, currentRow); } map[currentRow][column] = number; } currentRow++; } } this.constructMap(); } //Fills the map //Draws the border lines //Draws the walls // 0 - for empty cell, 1 - for wall, and 2 - for the starting point of the player public void constructMap(){ int x =0; int y= 0; for (int row = 0; row < map.length ; row++ ){ for (int column = 0; column < map[0].length; column++){ Rectangle rectangle = new Rectangle(x ,y , unit, unit); if (map[row][column] == 1){ rectangle.setFill(Color.BLACK); }else{ rectangle.setFill(Color.WHITE); rectangle.setStroke(Color.BLACK); } this.getChildren().add(rectangle); x += unit; } x = 0; y += unit; } } //getter methods public int getUnit(){ return unit; } public int getSize(){ return size; } public int[][] getMap(){ return map; } public Position getStartPosition(){ return start; } }
AdilBolatkhanov/myPackman
Map.java
618
//Extends the Pane class
line_comment
en
false
561
6
618
7
679
6
618
7
735
7
false
false
false
false
false
true
19683_27
import java.awt.Color; import java.awt.Dimension; import java.awt.Toolkit; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.StringTokenizer; import javax.swing.JFrame; import javax.swing.JPanel; public class Map extends JFrame { private MapCell startCell; private int numNeighbours = 4; public Map (String mapFile) throws InvalidMapException, FileNotFoundException, IOException { super("The Floor Is Lava!"); super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel p = new JPanel(); Color back = new Color(102, 107, 114); p.setBackground(back); // Get monitor resolution Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int screenHeight = screenSize.height; // set up the file reader and skip the first line BufferedReader in; String line = ""; in = new BufferedReader(new FileReader(mapFile)); line = in.readLine(); // Ignore first line line = in.readLine(); // Tokenize the first line to get the row and column StringTokenizer lineTokens = new StringTokenizer(line); // First line is the number of rows then the number of columns int row = Integer.parseInt(lineTokens.nextToken()); int col = Integer.parseInt(lineTokens.nextToken()); int cellSize = screenHeight / (row + 2); if (lineTokens.hasMoreTokens()) { if (lineTokens.hasMoreTokens()) { cellSize = Integer.parseInt(lineTokens.nextToken()); if (cellSize > (screenHeight / (row + 2))) cellSize = screenHeight / (row + 2); } } // To build the Map we will make temporary use of a 2D array // Once built, the hexagons themselves know all of their neighbors, so // we do not need the 2D array anymore. // Add a row and col of nulls around the "edges" of the builder matrix // (+2's) // This will greatly simplify the neighbor building process below MapCell[][] mapBuilder = new MapCell[row + 2][col + 2]; // HexLayout will arrange the Hexagons in the window p.setLayout(new CellLayout(row, col, 2)); int i = 0; for (int r = 1; r < row + 1; r++) { line = in.readLine(); lineTokens = new StringTokenizer(line); // for each token on the line (col in the Map) for (int c = 1; c < col + 1; c++) { // Read the token and generate the cell type char token = lineTokens.nextToken().charAt(0); //System.out.println(token); switch (token) { case 'F': // ground mapBuilder[r][c] = new MapCell(i,MapCell.CellType.FLOOR); break; case 'W': // wall mapBuilder[r][c] = new MapCell(i,MapCell.CellType.WALL); break; case 'S': // start mapBuilder[r][c] = new MapCell(i,MapCell.CellType.START); startCell = mapBuilder[r][c]; break; case 'E': // exit mapBuilder[r][c] = new MapCell(i,MapCell.CellType.EXIT); break; case 'L': // lava mapBuilder[r][c] = new MapCell(i,MapCell.CellType.LAVA); break; case '$': // gold mapBuilder[r][c] = new MapCell(i,MapCell.CellType.GOLD); break; case 'R': // red lock mapBuilder[r][c] = new MapCell(i,MapCell.CellType.LOCKRED); break; case 'r': // red key mapBuilder[r][c] = new MapCell(i,MapCell.CellType.KEYRED); break; case 'G': // green lock mapBuilder[r][c] = new MapCell(i,MapCell.CellType.LOCKGREEN); break; case 'g': // green key mapBuilder[r][c] = new MapCell(i,MapCell.CellType.KEYGREEN); break; case 'B': // blue lock mapBuilder[r][c] = new MapCell(i,MapCell.CellType.LOCKBLUE); break; case 'b': // blue key mapBuilder[r][c] = new MapCell(i,MapCell.CellType.KEYBLUE); break; default: throw new InvalidMapException(token); } // add to the GUI layout p.add(mapBuilder[r][c]); i++; } // end for cols } // end for rows // go through the 2D matrix again and build the neighbors int offset = 0; for (int r = 1; r < row + 1; r++) { for (int c = 1; c < col + 1; c++) { if (numNeighbours == 6) { // on even rows(insert from left side) need to add one to the // upper and lower neighbors // on odd, do not add anything (offset should be 0) offset = 1 - r % 2; // set the neighbors for this hexagon in the builder mapBuilder[r][c].setNeighbour(mapBuilder[r - 1][c + offset], 0); mapBuilder[r][c].setNeighbour(mapBuilder[r][c + 1], 1); mapBuilder[r][c].setNeighbour(mapBuilder[r + 1][c + offset], 2); mapBuilder[r][c].setNeighbour(mapBuilder[r + 1][c - 1 + offset], 3); mapBuilder[r][c].setNeighbour(mapBuilder[r][c - 1], 4); mapBuilder[r][c].setNeighbour(mapBuilder[r - 1][c - 1 + offset], 5); } else if (numNeighbours == 4) { // set the neighbors for this square in the builder offset = 0; mapBuilder[r][c].setNeighbour(mapBuilder[r - 1][c + offset], 0); mapBuilder[r][c].setNeighbour(mapBuilder[r][c + 1], 1); mapBuilder[r][c].setNeighbour(mapBuilder[r + 1][c + offset], 2); mapBuilder[r][c].setNeighbour(mapBuilder[r][c - 1 + offset], 3); } } // end for cols } // end for rows // close the file in.close(); // set up the GUI window this.add(p); this.pack(); this.setSize(cellSize * row, cellSize * col); this.setVisible(true); } public MapCell getStart() { return startCell; } }
mdzdmr/Floor-is-Lava
Map.java
1,783
// add to the GUI layout
line_comment
en
false
1,548
6
1,783
6
1,772
6
1,783
6
2,244
6
false
false
false
false
false
true