file_id
stringlengths 4
9
| content
stringlengths 41
35k
| repo
stringlengths 7
113
| path
stringlengths 5
90
| token_length
int64 15
4.07k
| original_comment
stringlengths 3
9.88k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | excluded
bool 2
classes |
---|---|---|---|---|---|---|---|---|
160716_0 | /*
Problem: https://open.kattis.com/problems/okviri
Author: Adrian Reithaug
Submitted: June 28th, 2017
Time: 0.09s / 1.00s
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Okviri {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String word = reader.readLine();
String outer = "..#..";
String inner = ".#.#.";
String middle = "#." + word.charAt(0) + ".#";
int count = 1;
for (int i = 1; i < word.length(); i++) {
count++;
if (count % 3 == 0) {
outer += ".*..";
inner += "*.*.";
middle += "." + word.charAt(i) + ".*";
} else {
outer += ".#..";
inner += "#.#.";
middle += "." + word.charAt(i) + ".";
if ((count + 1) % 3 == 0 && i != word.length() - 1) {
middle += "*";
} else {
middle += "#";
}
}
}
System.out.println(outer + "\n" + inner + "\n" + middle + "\n" + inner + "\n" + outer);
}
}
| Adrrei/Kattis-Challenges | Okviri.java | 345 | /*
Problem: https://open.kattis.com/problems/okviri
Author: Adrian Reithaug
Submitted: June 28th, 2017
Time: 0.09s / 1.00s
*/ | block_comment | en | true |
160873_0 | package bot.modules;
import java.util.Arrays;
import java.util.HashSet;
public class TagList {
/**
* The list of tags that are the highest severity.
* These will always be warned about / excluded from searches.
*/
private static final HashSet<String> badTags = new HashSet<>(
Arrays.asList(
"netorare", "netori", "scat", "bestiality", "gigantic", "drugs", "blackmail", "horse",
"vore", "guro", "nose hook", "blood", "cheating", "dog", "pig", "corruption", "mind control",
"vomit", "bbm", "cannibalism", "tentacles", "rape", "snuff", "moral degeneration", "mind break", "humiliation",
"chikan", "ryona", "cum bath", "infantilism", "unbirth", "abortion",
"eye penetration", "urethra insertion", "chloroform", "parasite", "public use", "petrification", "necrophilia",
"brain fuck", "daughter", "torture", "birth", "minigirl", "menstruation", "anorexic", "age regression",
"shrinking", "giantess", "navel fuck", "possession", "miniguy", "nipple fuck", "cbt", "low scat", "dicknipples",
"nipple birth", "monkey", "nazi", "triple anal", "triple vaginal", "diaper", "aunt", "mother", "father",
"niece", "uncle", "grandfather", "grandmother", "granddaughter", "insect", "anal birth", "skinsuit", "vacbed",
"sleeping", "worm"
)
);
/**
* The list of unwholesome tags.
* These are slightly lower severity than the bad tags.
*/
private static final HashSet<String> unwholesomeTags = new HashSet<>(
Arrays.asList(
"amputee", "futanari", "gender bender", "human on furry", "group", "lactation", "femdom",
"ffm threesome", "double penetration", "gag", "harem", "strap-on", "inflation", "mmf threesome", "enema",
"bukkake", "bbw", "dick growth", "huge breasts", "slave", "gaping", "pegging", "smegma",
"triple penetration", "prolapse", "human pet", "foot licking", "milking", "bondage", "multiple penises",
"asphyxiation", "stuck in wall", "human cattle", "clit growth", "ttf threesome", "phimosis", "glory hole",
"eggs", "incest", "urination", "prostitution", "fisting", "piss drinking", "inseki", "feminization",
"old lady", "old man", "mmm threesome", "fff threesome", "all the way through", "farting", "tickling"
)
);
/**
* The highest severity of tags.
* A doujin having any of these tags forbids the bot from saying anything about it.
* These tags probably violate the Discord ToS.
*/
private static final HashSet<String> illegalTags = new HashSet<>(
Arrays.asList(
"lolicon", "shotacon", "oppai loli", "low shotacon", "low lolicon"
)
);
/**
* Returns a copy of the illegal tags.
*
* @return The illegal tags.
*/
public static HashSet<String> getIllegalTags() {
return new HashSet<>(illegalTags);
}
/**
* Returns a copy of the bad tags.
*
* @return The bad tags.
*/
public static HashSet<String> getBadTags() {
return new HashSet<>(badTags);
}
/**
* Returns a copy of the unwholesome tags.
*
* @return The unwholesome tags.
*/
public static HashSet<String> getUnwholesomeTags() {
return new HashSet<>(unwholesomeTags);
}
/**
* Returns a copy of the unwholesome tags, WITHOUT any tags contained
* within the query.
*
* @param query The query to be excluded from the tag list.
* @return The tag list without tags contained in the query.
*/
public static HashSet<String> nonWholesomeTagsWithoutQuery(String query) {
HashSet<String> nonWT = getUnwholesomeTags();
// Remove tag if query contains that tag
nonWT.removeIf(query::contains);
return nonWT;
}
}
| WholesomeGodList/h-bot | src/main/java/bot/modules/TagList.java | 1,162 | /**
* The list of tags that are the highest severity.
* These will always be warned about / excluded from searches.
*/ | block_comment | en | false |
160936_4 | /* This code is part of Freenet. It is distributed under the GNU General
* Public License, version 2 (or at your option any later version). See
* http://www.gnu.org/ for further details of the GPL. */
package freenet.node;
import java.util.Map;
import freenet.clients.http.DarknetConnectionsToadlet;
import freenet.io.comm.Peer;
import freenet.io.xfer.PacketThrottle;
import freenet.node.NodeStats.PeerLoadStats;
import freenet.node.PeerNode.IncomingLoadSummaryStats;
/**
* Contains various status information for a {@link PeerNode}. Used e.g. in
* {@link DarknetConnectionsToadlet} to reduce race-conditions while creating
* the page.
*
* @author David 'Bombe' Roden <[email protected]>
* @version $Id$
*/
public class PeerNodeStatus {
private final String peerAddress;
private final int peerPort;
private final int statusValue;
private final String statusName;
private final String statusCSSName;
private final double location;
private final double[] peersLocation;
private final String version;
private final int simpleVersion;
private final int routingBackoffLength;
private final long routingBackedOffUntil;
private final boolean connected;
private final boolean routable;
private final boolean isFetchingARK;
private final boolean isOpennet;
private final double averagePingTime;
private final boolean publicInvalidVersion;
private final boolean publicReverseInvalidVersion;
private final double backedOffPercent;
private String lastBackoffReason;
private long timeLastRoutable;
private long timeLastConnectionCompleted;
private long peerAddedTime;
private Map<String,Long> localMessagesReceived;
private Map<String,Long> localMessagesSent;
private final int hashCode;
private final double pReject;
private long totalBytesIn;
private long totalBytesOut;
private long totalBytesInSinceStartup;
private long totalBytesOutSinceStartup;
private double percentTimeRoutableConnection;
private PacketThrottle throttle;
private long clockDelta;
private final boolean recordStatus;
private final boolean isSeedServer;
private final boolean isSeedClient;
private final boolean isSearchable;
private final long resendBytesSent;
private final int reportedUptimePercentage;
private final double selectionRate;
private final long messageQueueLengthBytes;
private final long messageQueueLengthTime;
// int's because that's what they are transferred as
public final IncomingLoadSummaryStats incomingLoadStats;
PeerNodeStatus(PeerNode peerNode, boolean noHeavy) {
Peer p = peerNode.getPeer();
if(p == null) {
peerAddress = null;
peerPort = -1;
} else {
peerAddress = p.getFreenetAddress().toString();
peerPort = p.getPort();
}
this.selectionRate = peerNode.selectionRate();
this.statusValue = peerNode.getPeerNodeStatus();
this.statusName = peerNode.getPeerNodeStatusString();
this.statusCSSName = peerNode.getPeerNodeStatusCSSClassName();
this.location = peerNode.getLocation();
this.peersLocation = peerNode.getPeersLocation();
this.version = peerNode.getVersion();
this.simpleVersion = peerNode.getSimpleVersion();
this.routingBackoffLength = peerNode.getRoutingBackoffLength();
this.routingBackedOffUntil = peerNode.getRoutingBackedOffUntil();
this.connected = peerNode.isConnected();
this.routable = peerNode.isRoutable();
this.isFetchingARK = peerNode.isFetchingARK();
this.isOpennet = peerNode.isOpennet();
this.averagePingTime = peerNode.averagePingTime();
this.publicInvalidVersion = peerNode.publicInvalidVersion();
this.publicReverseInvalidVersion = peerNode.publicReverseInvalidVersion();
this.backedOffPercent = peerNode.backedOffPercent.currentValue();
this.lastBackoffReason = peerNode.getLastBackoffReason();
this.timeLastRoutable = peerNode.timeLastRoutable();
this.timeLastConnectionCompleted = peerNode.timeLastConnectionCompleted();
this.peerAddedTime = peerNode.getPeerAddedTime();
if(!noHeavy) {
this.localMessagesReceived = peerNode.getLocalNodeReceivedMessagesFromStatistic();
this.localMessagesSent = peerNode.getLocalNodeSentMessagesToStatistic();
} else {
this.localMessagesReceived = null;
this.localMessagesSent = null;
}
this.hashCode = peerNode.hashCode;
this.pReject = peerNode.getPRejected();
this.totalBytesIn = peerNode.getTotalInputBytes();
this.totalBytesOut = peerNode.getTotalOutputBytes();
this.totalBytesInSinceStartup = peerNode.getTotalInputSinceStartup();
this.totalBytesOutSinceStartup = peerNode.getTotalOutputSinceStartup();
this.percentTimeRoutableConnection = peerNode.getPercentTimeRoutableConnection();
this.throttle = peerNode.getThrottle();
this.clockDelta = peerNode.getClockDelta();
this.recordStatus = peerNode.recordStatus();
this.isSeedClient = peerNode instanceof SeedClientPeerNode;
this.isSeedServer = peerNode instanceof SeedServerPeerNode;
this.isSearchable = peerNode.isRealConnection();
this.resendBytesSent = peerNode.getResendBytesSent();
this.reportedUptimePercentage = peerNode.getUptime();
messageQueueLengthBytes = peerNode.getMessageQueueLengthBytes();
messageQueueLengthTime = peerNode.getProbableSendQueueTime();
incomingLoadStats = peerNode.outputLoadTracker().getIncomingLoadStats();
}
public long getMessageQueueLengthBytes() {
return messageQueueLengthBytes;
}
public long getMessageQueueLengthTime() {
return messageQueueLengthTime;
}
/**
* @return the localMessagesReceived
*/
public Map<String, Long> getLocalMessagesReceived() {
return localMessagesReceived;
}
/**
* @return the localMessagesSent
*/
public Map<String, Long> getLocalMessagesSent() {
return localMessagesSent;
}
/**
* @return the peerAddedTime
*/
public long getPeerAddedTime() {
return peerAddedTime;
}
/**
* Counts the peers in <code>peerNodes</code> that have the specified
* status.
* @param peerNodeStatuses The peer nodes' statuses
* @param status The status to count
* @return The number of peers that have the specified status.
*/
public static int getPeerStatusCount(PeerNodeStatus[] peerNodeStatuses, int status) {
int count = 0;
for (int peerIndex = 0, peerCount = peerNodeStatuses.length; peerIndex < peerCount; peerIndex++) {
if (peerNodeStatuses[peerIndex].getStatusValue() == status) {
count++;
}
}
return count;
}
/**
* @return the timeLastConnectionCompleted
*/
public long getTimeLastConnectionCompleted() {
return timeLastConnectionCompleted;
}
/**
* @return the backedOffPercent
*/
public double getBackedOffPercent() {
return backedOffPercent;
}
/**
* @return the lastBackoffReason
*/
public String getLastBackoffReason() {
return lastBackoffReason;
}
/**
* @return the timeLastRoutable
*/
public long getTimeLastRoutable() {
return timeLastRoutable;
}
/**
* @return the publicInvalidVersion
*/
public boolean isPublicInvalidVersion() {
return publicInvalidVersion;
}
/**
* @return the publicReverseInvalidVersion
*/
public boolean isPublicReverseInvalidVersion() {
return publicReverseInvalidVersion;
}
/**
* @return the averagePingTime
*/
public double getAveragePingTime() {
return averagePingTime;
}
/**
* @return the getRoutingBackedOffUntil
*/
public long getRoutingBackedOffUntil() {
return routingBackedOffUntil;
}
/**
* @return the location
*/
public double getLocation() {
return location;
}
public double[] getPeersLocation() {
return peersLocation;
}
/**
* @return the peerAddress
*/
public String getPeerAddress() {
return peerAddress;
}
/**
* @return the peerPort
*/
public int getPeerPort() {
return peerPort;
}
/**
* @return the routingBackoffLength
*/
public int getRoutingBackoffLength() {
return routingBackoffLength;
}
/**
* @return the statusCSSName
*/
public String getStatusCSSName() {
return statusCSSName;
}
/**
* @return the statusName
*/
public String getStatusName() {
return statusName;
}
/**
* @return the statusValue
*/
public int getStatusValue() {
return statusValue;
}
/**
* @return the version
*/
public String getVersion() {
return version;
}
/**
* @return the connected
*/
public boolean isConnected() {
return connected;
}
/**
* @return the routable
*/
public boolean isRoutable() {
return routable;
}
/**
* @return the isFetchingARK
*/
public boolean isFetchingARK() {
return isFetchingARK;
}
/**
* @return the isOpennet
*/
public boolean isOpennet() {
return isOpennet;
}
/**
* @return the simpleVersion
*/
public int getSimpleVersion() {
return simpleVersion;
}
@Override
public String toString() {
return statusName + ' ' + peerAddress + ':' + peerPort + ' ' + location + ' ' + version + " backoff: " + routingBackoffLength + " (" + (Math.max(routingBackedOffUntil - System.currentTimeMillis(), 0)) + ')';
}
@Override
public int hashCode() {
return hashCode;
}
public double getPReject() {
return pReject;
}
public long getTotalInputBytes() {
return totalBytesIn;
}
public long getTotalOutputBytes() {
return totalBytesOut;
}
public long getTotalInputSinceStartup() {
return totalBytesInSinceStartup;
}
public long getTotalOutputSinceStartup() {
return totalBytesOutSinceStartup;
}
public double getPercentTimeRoutableConnection() {
return percentTimeRoutableConnection;
}
public PacketThrottle getThrottle() {
return throttle;
}
public long getClockDelta() {
return clockDelta;
}
public boolean recordStatus() {
return recordStatus;
}
public boolean isSeedServer() {
return isSeedServer;
}
public boolean isSeedClient() {
return isSeedClient;
}
public boolean isSearchable() {
return isSearchable;
}
public long getResendBytesSent() {
return resendBytesSent;
}
public int getReportedUptimePercentage() {
return reportedUptimePercentage;
}
public double getSelectionRate() {
return selectionRate;
}
}
| blueyed/fred-staging | src/freenet/node/PeerNodeStatus.java | 2,792 | /**
* @return the localMessagesSent
*/ | block_comment | en | true |
160949_14 | package tools;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* This class describes the debt in library system.
*
* @author Lenar Gumerov
* @author Anastasia Minakova
* @author Madina Gafarova
*/
public class Debt {
/**
* tools.Debt ID.
*/
private int debtId;
/**
* Associated patron's ID.
*/
private int patronId;
/**
* Associated document ID.
*/
private int documentId;
/**
* Booking date.
*/
private Date bookingDate;
/**
* Expire date.
*/
private Date expireDate;
/**
* Fee applied to this debt.
*/
private double fee;
/**
* Renew status. Is associated document can be renewed.
*/
private boolean canRenew;
/**
* Initialize new debt.
*
* @param patronId Associated patron ID.
* @param documentId Associated document ID.
* @param bookingDate Booking date.
* @param expireDate Expire date.
* @param fee Fee applied to this debt.
* @param canRenew Renew status.
*/
public Debt(int patronId, int documentId, Date bookingDate, Date expireDate, double fee, boolean canRenew) {
this.patronId = patronId;
this.documentId = documentId;
this.bookingDate = bookingDate;
this.expireDate = expireDate;
this.fee = fee;
this.canRenew = canRenew;
}
/**
* Get this debt in string notation.
*
* @return String with debt description.
*/
public String toString() {
return patronId + " " + documentId + " (" + (new SimpleDateFormat("dd-MMM-yyyy")).format(bookingDate) + ") (" + (new SimpleDateFormat("dd-MMM-yyyy")).format(expireDate) + ") " + fee + " " + canRenew + " ";
}
/**
* Get the associated patron ID.
*
* @return users.Patron ID.
*/
public int getPatronId() {
return patronId;
}
/**
* Set the new associated patron ID.
*
* @param patronId New patron ID.
*/
public void setPatronId(int patronId) {
this.patronId = patronId;
}
/**
* Get the associated document ID.
*
* @return documents.Document ID.
*/
public int getDocumentId() {
return documentId;
}
/**
* Set the new associated document ID.
*
* @param documentId New document ID.
*/
public void setDocumentId(int documentId) {
this.documentId = documentId;
}
/**
* Get the booking date.
*
* @return Booking date.
* @see Date
*/
public Date getBookingDate() {
return bookingDate;
}
/**
* Set the new booking date.
*
* @param bookingDate New booking date.
* @see Date
*/
public void setBookingDate(Date bookingDate) {
this.bookingDate = bookingDate;
}
/**
* Get the expire date.
*
* @return Expire date.
* @see Date
*/
public Date getExpireDate() {
return expireDate;
}
/**
* Set the new expire date.
*
* @param date New expire date.
* @see Date
*/
public void setExpireDate(Date date) {
this.expireDate = date;
}
/**
* Get the fee applied to this debt.
*
* @return Fee.
*/
public double getFee() {
return fee;
}
/**
* Apply the new fee to this debt.
*
* @param fee New fee.
*/
public void setFee(double fee) {
this.fee = fee;
}
/**
* Get the info about ability to renew associated document.
*
* @return Renew status.
*/
public boolean canRenew() {
return canRenew;
}
/**
* Set the new renew status. Info about ability to renew associated document.
*
* @param canRenew New renew status.
*/
public void setCanRenew(boolean canRenew) {
this.canRenew = canRenew;
}
/**
* Get the remaining time to expire date in days.
*
* @return Days remain.
*/
public int daysLeft() {
return (int) ((expireDate.getTime() - System.currentTimeMillis()) / (60 * 60 * 24 * 1000));
}
/**
* Get this debt ID.
*
* @return tools.Debt ID.
*/
public int getDebtId() {
return debtId;
}
/**
* Set the new debt ID.
*
* @param debtId New debt ID.
*/
public void setDebtId(int debtId) {
this.debtId = debtId;
}
/**
* Apply fee for this debt.
*
* @param database tools.Database that stores the documents information.
*/
public void countFee(Database database) {
if (daysLeft() < 0) {
setFee(min(daysLeft() * (-100), database.getDocument(documentId).getPrice()));
}
}
/**
* For internal use.
* Returns the minimal number.
*/
private double min(double a, double b) {
return a < b ? a : b;
}
}
| lenargum/libraryProject | src/tools/Debt.java | 1,401 | /**
* Get the booking date.
*
* @return Booking date.
* @see Date
*/ | block_comment | en | false |
161039_28 | package prr.core;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;
import prr.core.exception.*;
abstract public class Terminal implements Serializable {
private static final long serialVersionUID = 202208091753L;
// Terminal Attributes.
private String _id;
private double _debt;
private double _payments;
private TerminalState _stateBefore;
private TerminalState _state;
private Client _associate;
protected Set<String> _friends;
private Map<Integer,Communication> _madeCommunications;
private Map<Integer,Communication> _receivedCommunications;
protected InteractiveCommunication _ongoingCommunication;
private Notifier _notifier;
protected Network _network;
/**
* Terminal class constructor.
* @param id ID of the created terminal.
* @param associate ID of the owner of the created terminal.
*/
public Terminal(String id, Client associate, Network network) {
_id = id;
_debt = 0.0;
_payments = 0.0;
_state = new IdleState(this);
_associate = associate;
_friends = new TreeSet<>();
_madeCommunications = new TreeMap<>();
_receivedCommunications = new TreeMap<>();
_ongoingCommunication = null;
_stateBefore = null;
_notifier = new NotificationSender(this);
_network = network;
}
// Returns.
/** @return terminal id. */
public String getID() { return this._id; }
/** @return terminal debt amount. */
protected double getDebt() { return this._debt; }
/** @return terminal payments amount. */
protected double getPayments() { return this._payments; }
/** @return previous terminal state. */
protected TerminalState getOriginalState() { return _stateBefore; }
/** @return this terminal state. */
protected TerminalState getState() { return this._state; }
/** @return associated client id. */
protected Client getAssociate() { return this._associate; }
/** @return this terminal notifier. */
protected Notifier getNotifier() { return _notifier; }
protected Network getNetwork() { return _network; }
// More Complex Functions
/** @return this terminal balance. */
protected double getBalance() { return getPayments()-getDebt(); }
/** @return a Set with terminal made communications. */
protected Map<Integer, Communication> getMadeComms() { return Collections.unmodifiableMap(_madeCommunications); }
/**
* adds a received Communication.
* @param c Communication to add.
* @return this terminal.
*/
protected Terminal addReceived(Communication c) {
_associate.addReceivedComm(c);
_receivedCommunications.put(c.getID(), c);
return this;
}
/**
* adds a made Communication.
* @param c Communication to add.
* @return this terminal.
*/
protected Terminal addMade(Communication c) {
c.changeID(_network.getAllComms().size()+1);
_associate.addMadeComm(c);
_network.addCommunication(c);
_madeCommunications.put(c.getID(), c);
return this;
}
/** @param cost to add to debt. */
protected void addDebt(double cost) {
_debt += cost;
_associate.addDebt(cost);
}
/** @return a String with all terminal friends IDs. */
public String getFriendsIDs() {
return _friends.isEmpty() ? "" : "|" + _friends.stream().map(String::toString).collect(Collectors.joining(","));
}
/** @return a String with the format terminalType|terminalId|ClientId|TerminalStatus. */
public String getReadyToWrite() { return this.getClass().getSimpleName().toUpperCase()+ "|" + this.getID() + "|" + this.getAssociate().getID()
+ "|" + _state.toString(); }
/** @return a String with the format terminalType|terminalId|ClientId|TerminalStatus|balance-paid|balance-debts|friend1,...,friend. */
public String getReadyToDisplay() { return getReadyToWrite() +"|"+ Math.round(getPayments())
+"|" + Math.round(getDebt()) + getFriendsIDs() ; }
/**
* 3.5.1, 3.5.2, 3.5.3 -> turns the terminals to On/Off/Silence/Busy modes.
* @return true if the terminal state changes, false if it's already the requested state
*/
public boolean turnOn() { return _state.turnOn(); }
public boolean turnOff() { return _state.turnOff(); }
public boolean setOnSilent() { return _state.setOnSilent(); }
public boolean setOnBusy() { return _state.setOnBusy(); }
/** @param newState change terminal to given state. */
public void changeState(TerminalState newState) {
_stateBefore = _state;
_state = newState;
}
/**
* 3.5.4 -> adds a new friend terminal to this terminal friends.
* @param id id of terminal to add as friend.
*/
public void addFriend(String id) { _friends.add(id); }
/**
* 3.5.5 -> removes a friend terminal from this terminal friends.
* @param id id of terminal to remove as friend.
*/
public void removeFriend(String id) { _friends.remove(id); }
/**
* 3.5.6 -> pays a communication.
* @param id communication to pay.
* @throws InvalidCommunicationException communication does not exist.
*/
public void payCommunication(int id) throws InvalidCommunicationException {
if (this._madeCommunications.containsKey(id)) {
var communication = _madeCommunications.get(id);
var cost = communication.getCost();
if(!communication.isPaid() && !communication._isOngoing) {
_debt -= cost;
_payments += cost;
_associate.pay(cost);
communication.setPaidTrue();
return;
}
throw new InvalidCommunicationException();
}
throw new InvalidCommunicationException();
}
/**
* 3.5.7 -> gets payments/debts of this terminal
* @return the payments/debts of this terminal
*/
public long showPayments() { return Math.round(_payments); }
public long showDebts() { return Math.round(_debt); }
public boolean notUsed() { return _madeCommunications.isEmpty() && _receivedCommunications.isEmpty(); }
/**
* 3.5.8 -> send a text communication.
* @param destinationID ID of the destination terminal.
* @param message to send in the communication.
* @throws UnknownIdentifierException given terminal does not exist.
* @throws DestinationIsOffException destination terminal is turned off.
*/
public void sendTextCommunication(String destinationID, String message) throws UnknownIdentifierException, DestinationIsOffException {
Terminal destination = this._network.getTerminal(destinationID);
destination.getState().sendTextCommunication(destination, this, message);
_associate.getState().update(_associate.getBalance(),_ongoingCommunication);
}
public boolean hasPositiveBalance() { return (_payments - _debt) > 0; }
protected void unsubscribe(Client client) { _notifier.unsubscribe(client); }
protected abstract boolean receiveVideo();
/**
* 3.5.9 -> send a interactive communication.
* @param destinationID ID of the destination terminal.
* @param type of the interactive communication (VIDEO, VOICE).
* @throws UnknownIdentifierException given terminal does not exist.
* @throws DestinationIsOffException destination terminal is turned off.
* @throws DestinationIsBusyException destination terminal is busy.
* @throws DestinationIsSilencedException destination terminal is silenced.
* @throws UnsupportedAtOriginException this terminal doesn't support video.
* @throws UnsupportedAtDestinationException destination terminal doesn't support video.
*/
public abstract void sendInteractiveCommunication(String destinationID, String type) throws UnknownIdentifierException, DestinationIsOffException,
DestinationIsBusyException, DestinationIsSilencedException,
UnsupportedAtOriginException, UnsupportedAtDestinationException;
/**
* 3.5.10 -> ends current interactive communication.
* @param duration of the communication.
* @return cost of the communication.
*/
public long endInteractiveCommunication(int duration) {
long cost = _ongoingCommunication.endCommunication(duration);
_ongoingCommunication.freeTerminals();
_associate.getState().update(_associate.getBalance(),_ongoingCommunication);
_associate.getState().update(_associate.getBalance(),_madeCommunications.values());
_ongoingCommunication=null;
return cost;
}
/**
* 3.5.11 -> shows current interactive communication.
* @return the current interactive communication with the requested format.
*/
public String showOngoingCommunication() {
return (_ongoingCommunication!=null) ? _ongoingCommunication.getReadyToDisplay() : null;
}
/**
* Checks if this terminal can end the current interactive communication.
* @return true if this terminal is busy (i.e., it has an active interactive communication) and
* it was the originator of this communication.
**/
public boolean canEndCurrentCommunication() {
return _ongoingCommunication != null && _ongoingCommunication._isOngoing;
}
/**
* Checks if this terminal can start a new communication.
* @return true if this terminal is neither off neither busy, false otherwise.
**/
public boolean canStartCommunication() {
return (!canEndCurrentCommunication() && (_state.isOn()) || _state.isOnSilent());
}
}
| Dacops/UniProjects | PO/prr/core/Terminal.java | 2,200 | /**
* 3.5.11 -> shows current interactive communication.
* @return the current interactive communication with the requested format.
*/ | block_comment | en | true |
162153_0 |
/**
* Write a description of class Msn here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Msn
{
// instance variables - replace the example below with your own
private String mensaje;
public Msn( String mens )
{
mensaje = mens;
}
public String getMsn()
{
return mensaje;
}
}
| ImCrisam/Bluej_POO_UIS | Interface/Msn.java | 101 | /**
* Write a description of class Msn here.
*
* @author (your name)
* @version (a version number or a date)
*/ | block_comment | en | true |
162202_0 | public final class akf$a
extends aji.a<a>
{
oh mSnapbryoAnalytics;
public final akf c()
{
super.a();
if (mSnapbryoAnalytics == null) {
mSnapbryoAnalytics = new oh();
}
return new akf(this);
}
}
/* Location:
* Qualified Name: akf.a
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | reverseengineeringer/com.snapchat.android | src/akf$a.java | 122 | /* Location:
* Qualified Name: akf.a
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | block_comment | en | true |
162469_0 | package b1780;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int minus = 0;
static int zero = 0;
static int plus = 0;
static int N;
static int[][] papers;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
papers = new int[N][N];
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < N; j++) {
papers[i][j] = Integer.parseInt(st.nextToken());
}
}
divide(0, 0, N);
System.out.println(minus + "\n" + zero + "\n" + plus);
}
private static void divide(int x, int y, int index) {
// ๋จผ์ ํด๋น ๊ตฌ๊ฐ์ด ๊ฐ์ ์ซ์๋ก ์ด๋ฃจ์ด์ ธ์๋์ง ํ์ธ
int target = papers[x][y];
boolean allSame = true;
for (int i = 0; i < index; i++) {
for (int j = 0; j < index; j++) {
if (target != papers[x + i][y + j]) {
allSame = false;
}
}
}
// ๋ค ๊ฐ์ง ์์ผ๋ฉด ๋ถํ ์ ๋ณต
if (!allSame) {
divide(x, y, index / 3);
divide(x + index / 3, y, index / 3);
divide(x + (index / 3) * 2, y, index / 3);
divide(x, y + index / 3, index / 3);
divide(x + index / 3, y + index / 3, index / 3);
divide(x + (index / 3) * 2, y + index / 3, index / 3);
divide(x, y + (index / 3) * 2, index / 3);
divide(x + index / 3, y + (index / 3) * 2, index / 3);
divide(x + (index / 3) * 2, y + (index / 3) * 2, index / 3);
}
// ๊ฐ๋ค๋ฉด ์๋ง์ ๋ณ์ ์ฆ๊ฐ
else {
if (target == -1) {
minus++;
} else if (target == 0) {
zero++;
} else {
plus++;
}
}
}
}
| HurDong/Algorithm | BOJ/b1780/Main.java | 636 | // ๋จผ์ ํด๋น ๊ตฌ๊ฐ์ด ๊ฐ์ ์ซ์๋ก ์ด๋ฃจ์ด์ ธ์๋์ง ํ์ธ | line_comment | en | true |
163047_1 | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
/**
* Simple I/O operations.
*
* You do not need to change this class.
*/
public class IO {
/**
*
* @param fileName a maze file name. File should not contain any extra white
* space.
* @return the Maze data structure of the maze represented by the file.
*/
public static Maze readInputFile(String fileName) {
char[][] mazeMatrix = null;
Square playerSquare = null;
Square goalSquare = null;
int noOfRows;
int noOfCols;
try {
ArrayList<String> lines = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
while ((line = reader.readLine()) != null)
if (!line.equals(""))
lines.add(line);
noOfRows = lines.size();
noOfCols = lines.get(0).length();
mazeMatrix = new char[noOfRows][noOfCols];
for (int i = 0; i < noOfRows; ++i) {
line = lines.get(i);
for (int j = 0; j < noOfCols; ++j) {
mazeMatrix[i][j] = line.charAt(j);
if (mazeMatrix[i][j] == 'H')
playerSquare = new Square(i, j);
if (mazeMatrix[i][j] == 'C')
goalSquare = new Square(i, j);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return new Maze(mazeMatrix, playerSquare, goalSquare);
}
/**
* Output the necessary information. You do not need to write any
* System.out.println() anywhere.
*
* @param maze
* the maze with each square that is part of the
* solution path
* @param cost
* the cost of the solution path
* @param noOfNodesExpanded
* the number of nodes expanded
* @param maxDepth
* the maximum depth searched
* @param maxFrontierSize
* the maximum size of the frontier list at any point during the
* search
*/
public static void printOutput(Maze maze, int cost, int noOfNodesExpanded) {
char[][] mazeMatrix = maze.getMazeMatrix();
for (int i = 0; i < mazeMatrix.length; ++i) {
for (int j = 0; j < mazeMatrix[0].length; ++j) {
System.out.print(mazeMatrix[i][j]);
}
System.out.println();
}
System.out.println("Total solution cost: " + cost);
System.out.println("Number of nodes expanded: " + noOfNodesExpanded);
}
}
| belostoky/cs540 | hw1/prob3/IO.java | 743 | /**
*
* @param fileName a maze file name. File should not contain any extra white
* space.
* @return the Maze data structure of the maze represented by the file.
*/ | block_comment | en | false |
163409_18 | import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.*;
/**
* @author Nikola Nikolov
* @version 5 May 2021
*/
public class Bank {
private ArrayList<FillTypeQuestion>[] questions;
private ArrayList<Integer> shuffledPosition;
private ArrayList<String> givenAnswers;
private Map<String,Integer> studentResults;
private String id;
private static final int maxAnswersToGive = 10;
Bank() {
this("");
}
Bank(String id) {
this.id = id;
questions = new ArrayList[2];
questions[0] = new ArrayList<FillTypeQuestion>();
questions[1] = new ArrayList<FillTypeQuestion>();
givenAnswers = new ArrayList<String>();
shuffledPosition = new ArrayList<Integer>();
studentResults = new HashMap<>();
}
/**
* Get identifier
* @return id
*/
public String getId() {
return id;
}
/**
* This method sets the value for id
*
* @param id becomes the value
*/
public void setId(String id) {
this.id = id;
}
/**
* This method returns all the Questions
* @param lang the choosed language
* @return ret
*/
public String printAllQuestions(int lang) {
StringBuilder ret = new StringBuilder();
for (int i = 0; i < questions[0].size(); i++) {
ret.append(i + 1);
ret.append(". ");
ret.append(questions[lang].get(i).toString());
}
return ret.toString();
}
/**
* This method add a question (two languages) in the question ArrayList
*
* @param firstLang becomes the value of the fist language
* @param secLang becomes the value of the second language
*/
public void setQuestions(FillTypeQuestion firstLang, FillTypeQuestion secLang) {
questions[0].add(firstLang);
questions[1].add(secLang);
}
/**
* This method adds a new Question in the Quiz
*/
public void addQuestion() {
FillTypeQuestion newQuestion;
FillTypeQuestion newQuestionSecLang;
String response;
System.out.println("What kind of question do you want to create");
System.out.println(" F - Fill-type question");
System.out.println(" C - Choose-type question");
System.out.println(" M - Match-type question");
loop:
while (true) {
Scanner scan = new Scanner(System.in);
response = scan.nextLine().toUpperCase();
switch (response) { //checking what type of question and initialising it
case "F":
newQuestion = new FillTypeQuestion();
newQuestionSecLang = new FillTypeQuestion();
break loop;
case "C":
newQuestion = new ChooseTypeQuestion();
newQuestionSecLang = new ChooseTypeQuestion();
break loop;
case "M":
newQuestion = new MatchTypeQuestion();
newQuestionSecLang = new MatchTypeQuestion();
break loop;
default:
System.out.println("Try Again!");
}
}
newQuestion.createQuestion(); // calls the right method to create the question
System.out.println("Please type the SAME question in Bulgarian");
newQuestionSecLang.createQuestion();
questions[0].add(newQuestion); // store the English version
questions[1].add(newQuestionSecLang); // store the Bulgarian version
//System.out.println(questions[0].size() - 1);
shuffledPosition.add(questions[0].size() - 1);
}
/**
* This methid prints the collected information about the results of the quiz and returns the average result for the Quiz
* @return average result
*/
public int printCollectedResults(){
int average = 0;
for(Map.Entry m:studentResults.entrySet()){
System.out.println(" " + m.getKey() + " - " + m.getValue());
average += (int)(m.getValue());
}
return average/studentResults.size();
}
/**
* Prints the menu that is user can use throughout the quiz
*/
private void printQuizMenu() {
System.out.println("Before you start the quiz you have to know that you can use this commands through the quiz:");
System.out.println(" N - next question (automatically safes the answer)");
System.out.println(" P - previous question (automatically safes the answer)");
System.out.println(" S - Submit & Exit)");
}
/**
* By this method the user can do a quiz
* @param language
* @param username of the user
*/
public void doTheQuiz(int language, String username) {
LocalDateTime now = LocalDateTime.now();
givenAnswers = new ArrayList<String>(); // we store the answers that have been given
for (int i = 0; i < maxAnswersToGive; i++) givenAnswers.add(" "); // making sure that we have added enough elements
int currentQues = 1; // and using " " just so we can check if the user have got and answer
String response;
Scanner scan = new Scanner(System.in);
Collections.shuffle(shuffledPosition); // use shuffeledPosition so we can print them in random order without moving themselves
int maxQtoAnswer = setQNumToDoInQuiz(); // maxQtoAnswer is the nummber of q that user wants to answer from the Quiz
printQuizMenu();
long start = System.currentTimeMillis(); //saving the time so we know when quiz have been started
do {
System.out.println(currentQues + "/" + maxQtoAnswer);
System.out.print(currentQues + ". ");
questions[language].get(shuffledPosition.get(currentQues-1)).printQues();
response = scan.nextLine().toUpperCase();
switch (response) {
case "N":
if (currentQues == maxQtoAnswer) {
System.out.println("That is the last question. You can submit your work by typing 'S'");
break;
}
currentQues++;
break;
case "P":
if (currentQues-1 == 0) {
System.out.println("That is the first question. There is no previous.");
break;
}
currentQues--;
break;
case "S":
break;
default:
givenAnswers.set(shuffledPosition.get(currentQues-1), response);
if (currentQues == maxQtoAnswer) {
System.out.println("That is the last question. You can submit your work by typing 'S'");
break;
}
currentQues++;
}
} while (!(response.equals("S")));
long end = System.currentTimeMillis(); // saving that time when the quiz have been ended
float time = (end - start) / 1000;
int hour = (int) (time/120); time = time -hour*120;
int min = (int) (time/60); time = time-min*60;
System.out.println("You do the quiz for " + hour + ":"+ min + ":"+ (int)time);
int result = calculateQuizResults(maxQtoAnswer);
System.out.println("Your Result is " + result + "% !");
studentResults.put(username, result); //saving the Quiz results
}
/**
* This method asks the user how many questions he wants to answer
* @return num the max number of questions to answer
*/
public int setQNumToDoInQuiz(){
String response;
Scanner scan = new Scanner(System.in);
Integer num = null;
do {
System.out.println("How many questions from the quiz you want to do");
response = scan.nextLine();
try {
// Parse the input if it is successful, it will set a non null value to i
num = Integer.parseInt(response);
} catch (NumberFormatException e) {
// The input value was not an integer so i remains null
System.out.println("That's not a number!");
}
} while (num == null && num >0);
if(num > questions[0].size()){
return questions[0].size();
}else{
return num;
}
}
/**
* Get the num of questions
* @return the num of questions
*/
public int getQuestionsNum(){
return questions[0].size();
}
/**
* This method returns the result of the quiz in %
*
* @param maxQ max questions to answer from the quiz
* @return result - the result of the quiz in %
*/
private int calculateQuizResults(int maxQ) {
float result = 0;
int notAnswered = 0;
for (int i = 0; i < maxAnswersToGive; i++) {
if (givenAnswers.get(i) ==" "){
notAnswered++;
}
else if(questions[0].get(i).isTheRightAnswer(givenAnswers.get(i))) {
result++;
}
}
result = result / maxQ * 100;
System.out.println( (notAnswered-(maxAnswersToGive -maxQ)) + " not answered questions");
return Math.round(result);
}
/**
* This method remove a question
* @param index of the question
*/
public void deleteQuestion(int index) {
questions[0].remove(index);
questions[1].remove(index);
for (int i = 0; i < shuffledPosition.size(); i++) {
if (shuffledPosition.get(i) == index) {
shuffledPosition.remove(i);
break;
}
}
}
/**
* Write information about the bank in the file
*/
public void save(PrintWriter pw) {
pw.println(id);
pw.println(questions[0].size());
for (int i = 0; i < questions[0].size(); i++) {
questions[0].get(i).save(pw);
questions[1].get(i).save(pw);
}
pw.println(studentResults.size());
for(Map.Entry m:studentResults.entrySet()){
pw.println(m.getKey());
pw.println(m.getValue());
}
}
/**
* Reads in information about the Bank from the file
* @param infile
*/
public void load(Scanner infile) {
id = infile.next();
int num = infile.nextInt();
shuffledPosition = new ArrayList<Integer>();
questions = new ArrayList[2];
givenAnswers = new ArrayList<String>();
questions[0] = new ArrayList<FillTypeQuestion>();
questions[1] = new ArrayList<FillTypeQuestion>();
studentResults = new HashMap<>();
for (int oCount = 0; oCount < num; oCount++) {
FillTypeQuestion q = null;
String s = infile.next();
if (s.equals("FILL-TYPE")) {
q = new FillTypeQuestion();
} else if(s.equals("CHOOSE-TYPE")){
q = new ChooseTypeQuestion();
} else {
q = new MatchTypeQuestion();
}
q.load(infile);
questions[0].add(q);
s = infile.next();
if (s.equals("FILL-TYPE")) { //we are doing that second time because otherwise both languages will be the same
q = new FillTypeQuestion();
} else if(s.equals("CHOOSE-TYPE")){
q = new ChooseTypeQuestion();
} else {
q = new MatchTypeQuestion();
}
q.load(infile);
questions[1].add(q);
shuffledPosition.add(questions[0].size() - 1);
}
num = infile.nextInt();
for (int i=0; i<num; i++){
studentResults.put(infile.next(), infile.nextInt());
}
}
}
| nikkola01/Questionnaire-Software | src/Bank.java | 2,735 | // maxQtoAnswer is the nummber of q that user wants to answer from the Quiz | line_comment | en | false |
164055_2 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package com.mycompany.lab7;
/**
*
* @author prabin
*/
/*Create a base class fruit which has name,taste and size as tis attributes.Amethod called eat() is created which describes
the name of the fruit and its taste .Inherit the same in 2 other class Apple and orange and override the eat() method to represent each
fruit taste.*/
class fruit{
String name;
String taste;
String size;
public fruit(String name,String taste, String size){
this.name=name;
this.taste=taste;
this.size=size;
}
void eat(){
System.out.println(name+" Taste "+taste+".It is "+size+" in size.");
}
}
class apple extends fruit{
public apple(String name,String taste,String size){
super(name,taste,size);
}
void displayapple(){
eat();
}
}
class orange extends fruit{
public orange(String name,String taste,String size){
super(name,taste,size);
}
void displayorange(){
eat();
}
}
public class QN1 {
public static void main(String[] args){
apple a=new apple("Apple","Sweet","Small");
a.displayapple();
orange o=new orange("Orange","Sour and Sweet","Medium");
o.displayorange();
}
}
| Prabinpoudel192/java-lab7 | QN1.java | 382 | /*Create a base class fruit which has name,taste and size as tis attributes.Amethod called eat() is created which describes
the name of the fruit and its taste .Inherit the same in 2 other class Apple and orange and override the eat() method to represent each
fruit taste.*/ | block_comment | en | false |
164185_0 | /**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null)
return null;
ListNode slow = head;
ListNode fast = head;
while(fast!=null && fast.next!=null){
slow = slow.next;
fast = fast.next.next;
if(slow==fast){
ListNode slow1 = head;
while(slow1!=slow){
slow = slow.next;
slow1 = slow1.next;
}
return slow;
}
}
return null;
}
}
| goswamishipra15/Code-by-Shipra | 7.java | 190 | /**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/ | block_comment | en | true |
164305_0 | //Note: I accessed the original template code from a helpful Github repository regarding the mooc.fi course.
package Part4;
import java.util.Scanner;
import java.util.ArrayList;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Items {
public static void main(String args[]){
ArrayList<Item> items = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while(true){
System.out.print("Name: ");
String name = scanner.nextLine();
if(name.equals("")){
break;
}
items.add(new Item(name));
}
for(Item item: items){
System.out.println(item.toString());
}
scanner.close();
}
static class Item {
private String name;
private LocalDateTime createdAt;
public Item(String name) {
this.name = name;
this.createdAt = LocalDateTime.now();
}
public String getName() {
return name;
}
@Override
public String toString() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss");
return this.name + " (created at: " + formatter.format(this.createdAt) + ")";
}
}
} | Lilacc777/JavaProgrammingExercises | Part4/Items.java | 290 | //Note: I accessed the original template code from a helpful Github repository regarding the mooc.fi course. | line_comment | en | true |
164717_0 | /**
@file
@author Benny Bobaganoosh <[email protected]>
@section LICENSE
Copyright (c) 2014, Benny Bobaganoosh
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.io.IOException;
/**
* The sole purpose of this class is to hold the main method.
*
* Any other use should be placed in a separate class
*/
public class Main
{
// Lazy exception handling here. You can do something more interesting
// depending on what you're doing
public static void main(String[] args) throws IOException
{
Display display = new Display(800, 600, "Software Rendering");
RenderContext target = display.GetFrameBuffer();
Bitmap texture = new Bitmap("./res/bricks.jpg");
Bitmap texture2 = new Bitmap("./res/bricks2.jpg");
Mesh monkeyMesh = new Mesh("./res/smoothMonkey0.obj");
Transform monkeyTransform = new Transform(new Vector4f(0,0.0f,3.0f));
Mesh terrainMesh = new Mesh("./res/terrain2.obj");
Transform terrainTransform = new Transform(new Vector4f(0,-1.0f,0.0f));
Camera camera = new Camera(new Matrix4f().InitPerspective((float)Math.toRadians(70.0f),
(float)target.GetWidth()/(float)target.GetHeight(), 0.1f, 1000.0f));
float rotCounter = 0.0f;
long previousTime = System.nanoTime();
while(true)
{
long currentTime = System.nanoTime();
float delta = (float)((currentTime - previousTime)/1000000000.0);
previousTime = currentTime;
camera.Update(display.GetInput(), delta);
Matrix4f vp = camera.GetViewProjection();
monkeyTransform = monkeyTransform.Rotate(new Quaternion(new Vector4f(0,1,0), delta));
target.Clear((byte)0x00);
target.ClearDepthBuffer();
monkeyMesh.Draw(target, vp, monkeyTransform.GetTransformation(), texture2);
terrainMesh.Draw(target, vp, terrainTransform.GetTransformation(), texture);
display.SwapBuffers();
}
}
}
| errmalt/3DSoftwareRenderer | src/Main.java | 804 | /**
@file
@author Benny Bobaganoosh <[email protected]>
@section LICENSE
Copyright (c) 2014, Benny Bobaganoosh
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ | block_comment | en | true |
164827_0 | /*
* Q. Create a Book class for a library system.๐
* โข Instance variables: title, author, isbn.
* โข Static variable: totalBooks, a counter for the total number of book instances.
* โข Instance methods: borrowBook(), returnBook().
* โข Static method: getTotalBooks(), to get the total number of books in the library.
*
*/
public class Book {
static int totalNoOfBooks;
String title;
String author;
String isbn;
boolean isBorrowed;
static {
totalNoOfBooks = 0;
}
{
totalNoOfBooks++;
}
Book(String isbn, String title, String author) {
this.isbn = isbn;
this.title = title;
this.author = author;
}
Book(String isbn) {
this(isbn, "Unknown", "Unknown");
}
static int getTotalNoOfBooks() {
return totalNoOfBooks;
}
void borrowBook() {
if (isBorrowed) {
System.out.println("This book has already been borrowed.");
} else {
this.isBorrowed = true;
System.out.println("Enjoy " + this.title);
}
}
void returnBook() {
if (isBorrowed) {
this.isBorrowed = false;
System.out.println("Hope you enjoyed, Please leave a review");
} else {
System.out.println("This book is already in the library");
}
}
public static void main(String[] args) {
Book designOfWebsite = new Book("1", "Design", "aashu");
Book javaProgramming = new Book("2");
System.out.println("Total number of books in the library: " + Book.getTotalNoOfBooks());
designOfWebsite.borrowBook();
javaProgramming.borrowBook();
designOfWebsite.borrowBook();
designOfWebsite.returnBook();
designOfWebsite.returnBook();
}
} | codeaashu/Book-Library-System | Book.java | 456 | /*
* Q. Create a Book class for a library system.๐
* โข Instance variables: title, author, isbn.
* โข Static variable: totalBooks, a counter for the total number of book instances.
* โข Instance methods: borrowBook(), returnBook().
* โข Static method: getTotalBooks(), to get the total number of books in the library.
*
*/ | block_comment | en | true |
165224_3 | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Day2 {
/*Part 1*/
static final int MAX_BLUES = 14;
static final int MAX_REDS = 12;
static final int MAX_GREENS = 13;
public boolean isGamePossible(String line) {
String[] games = line.split(";");
boolean isGamePossible = true;
for(String game : games) {
int blueSum = 0;
int redSum = 0;
int greenSum = 0;
String[] sets = game.split(",");
for(String set : sets) {
if(set.contains("blue")) {
String num = set.replace("blue", "");
blueSum += Integer.parseInt(num.trim());
}
if(set.contains("red")) {
String num = set.replace("red", "");
redSum += Integer.parseInt(num.trim());
}
if(set.contains("green")) {
String num = set.replace("green", "");
greenSum += Integer.parseInt(num.trim());
}
}
isGamePossible = isGamePossible && blueSum <= MAX_BLUES &&
redSum <= MAX_REDS &&
greenSum <= MAX_GREENS;
}
return isGamePossible;
}
/*Part 2*/
public record Triple (int blue, int red, int green) {}
public Triple minimumCubes(String line) {
String[] games = line.split(";");
int maxBlue = -1;
int maxRed = -1;
int maxGreen = -1;
for(String game : games) {
String[] sets = game.split(",");
for(String set : sets) {
if(set.contains("blue")) {
String num = set.replace("blue", "");
maxBlue = Math.max(maxBlue, Integer.parseInt(num.trim()));
}
if(set.contains("red")) {
String num = set.replace("red", "");
maxRed = Math.max(maxRed, Integer.parseInt(num.trim()));
}
if(set.contains("green")) {
String num = set.replace("green", "");
maxGreen = Math.max(maxGreen, Integer.parseInt(num.trim()));
}
}
}
return new Triple(maxBlue, maxRed, maxGreen);
}
public static void main(String[] args) throws IOException {
Day2 day2 = new Day2();
FileReader fileReader = new FileReader("input2.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line = null;
int res = 0;
try {
while ((line = bufferedReader.readLine()) != null) {
String[] gameSplit = line.split(":");
/* Part 1*/
/*int gameNum = Integer.parseInt(gameSplit[0].replace("Game ", ""));
boolean isGamePossible = day2.IsGamePossible(gameSplit[1]);
if(isGamePossible) {
res += gameNum;
}*/
/* Part 2 */
int gameNum = Integer.parseInt(gameSplit[0].replace("Game ", ""));
var triple = day2.minimumCubes(gameSplit[1]);
res += (triple.blue * triple.red * triple.green);
}
} catch (IOException e) {
e.printStackTrace();
}
bufferedReader.close();
System.out.println(res);
}
}
| lara-luis/adventOfCode2023 | Day2.java | 870 | /*int gameNum = Integer.parseInt(gameSplit[0].replace("Game ", ""));
boolean isGamePossible = day2.IsGamePossible(gameSplit[1]);
if(isGamePossible) {
res += gameNum;
}*/ | block_comment | en | true |
165560_0 | //Create 15 classes of your choice in each class declare 2 static methods and invoke the method
public class Collegehsn{
public static void students (){
System.out.println("maland college");
}
public static void teachers (){
System.out.println("maland college");
}
}
| jhenkar01/java | Collegehsn.java | 76 | //Create 15 classes of your choice in each class declare 2 static methods and invoke the method | line_comment | en | false |
165585_19 | import java.util.*;
class Combination {
private int n;
private int r;
private int[] now; // ํ์ฌ ์กฐํฉ
private ArrayList<ArrayList<Position>> result; // ๋ชจ๋ ์กฐํฉ
public ArrayList<ArrayList<Position>> getResult() {
return result;
}
public Combination(int n, int r) {
this.n = n;
this.r = r;
this.now = new int[r];
this.result = new ArrayList<ArrayList<Position>>();
}
public void combination(ArrayList<Position> arr, int depth, int index, int target) {
if (depth == r) {
ArrayList<Position> temp = new ArrayList<>();
for (int i = 0; i < now.length; i++) {
temp.add(arr.get(now[i]));
}
result.add(temp);
return;
}
if (target == n) return;
now[index] = target;
combination(arr, depth + 1, index + 1, target + 1);
combination(arr, depth, index, target + 1);
}
}
class Position {
private int x;
private int y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
}
public class Main {
public static int n; // ๋ณต๋์ ํฌ๊ธฐ
public static char[][] board = new char[6][6]; // ๋ณต๋ ์ ๋ณด (N x N)
public static ArrayList<Position> teachers = new ArrayList<>(); // ๋ชจ๋ ์ ์๋ ์์น ์ ๋ณด
public static ArrayList<Position> spaces = new ArrayList<>(); // ๋ชจ๋ ๋น ๊ณต๊ฐ ์์น ์ ๋ณด
// ํน์ ๋ฐฉํฅ์ผ๋ก ๊ฐ์๋ฅผ ์งํ (ํ์ ๋ฐ๊ฒฌ: true, ํ์ ๋ฏธ๋ฐ๊ฒฌ: false)
public static boolean watch(int x, int y, int direction) {
// ์ผ์ชฝ ๋ฐฉํฅ์ผ๋ก ๊ฐ์
if (direction == 0) {
while (y >= 0) {
if (board[x][y] == 'S') { // ํ์์ด ์๋ ๊ฒฝ์ฐ
return true;
}
if (board[x][y] == 'O') { // ์ฅ์ ๋ฌผ์ด ์๋ ๊ฒฝ์ฐ
return false;
}
y -= 1;
}
}
// ์ค๋ฅธ์ชฝ ๋ฐฉํฅ์ผ๋ก ๊ฐ์
if (direction == 1) {
while (y < n) {
if (board[x][y] == 'S') { // ํ์์ด ์๋ ๊ฒฝ์ฐ
return true;
}
if (board[x][y] == 'O') { // ์ฅ์ ๋ฌผ์ด ์๋ ๊ฒฝ์ฐ
return false;
}
y += 1;
}
}
// ์์ชฝ ๋ฐฉํฅ์ผ๋ก ๊ฐ์
if (direction == 2) {
while (x >= 0) {
if (board[x][y] == 'S') { // ํ์์ด ์๋ ๊ฒฝ์ฐ
return true;
}
if (board[x][y] == 'O') { // ์ฅ์ ๋ฌผ์ด ์๋ ๊ฒฝ์ฐ
return false;
}
x -= 1;
}
}
// ์๋์ชฝ ๋ฐฉํฅ์ผ๋ก ๊ฐ์
if (direction == 3) {
while (x < n) {
if (board[x][y] == 'S') { // ํ์์ด ์๋ ๊ฒฝ์ฐ
return true;
}
if (board[x][y] == 'O') { // ์ฅ์ ๋ฌผ์ด ์๋ ๊ฒฝ์ฐ
return false;
}
x += 1;
}
}
return false;
}
// ์ฅ์ ๋ฌผ ์ค์น ์ดํ์, ํ ๋ช
์ด๋ผ๋ ํ์์ด ๊ฐ์ง๋๋์ง ๊ฒ์ฌ
public static boolean process() {
// ๋ชจ๋ ์ ์์ ์์น๋ฅผ ํ๋์ฉ ํ์ธ
for (int i = 0; i < teachers.size(); i++) {
int x = teachers.get(i).getX();
int y = teachers.get(i).getY();
// 4๊ฐ์ง ๋ฐฉํฅ์ผ๋ก ํ์์ ๊ฐ์งํ ์ ์๋์ง ํ์ธ
for (int j = 0; j < 4; j++) {
if (watch(x, y, j)) {
return true;
}
}
}
return false;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
board[i][j] = sc.next().charAt(0);
// ์ ์๋์ด ์กด์ฌํ๋ ์์น ์ ์ฅ
if (board[i][j] == 'T') {
teachers.add(new Position(i, j));
}
// ์ฅ์ ๋ฌผ์ ์ค์นํ ์ ์๋ (๋น ๊ณต๊ฐ) ์์น ์ ์ฅ
if (board[i][j] == 'X') {
spaces.add(new Position(i, j));
}
}
}
// ๋น ๊ณต๊ฐ์์ 3๊ฐ๋ฅผ ๋ฝ๋ ๋ชจ๋ ์กฐํฉ์ ํ์ธ
Combination comb = new Combination(spaces.size(), 3);
comb.combination(spaces, 0, 0, 0);
ArrayList<ArrayList<Position>> spaceList = comb.getResult();
// ํ์์ด ํ ๋ช
๋ ๊ฐ์ง๋์ง ์๋๋ก ์ค์นํ ์ ์๋์ง์ ์ฌ๋ถ
boolean found = false;
for (int i = 0; i < spaceList.size(); i++) {
// ์ฅ์ ๋ฌผ๋ค์ ์ค์นํด๋ณด๊ธฐ
for (int j = 0; j < spaceList.get(i).size(); j++) {
int x = spaceList.get(i).get(j).getX();
int y = spaceList.get(i).get(j).getY();
board[x][y] = 'O';
}
// ํ์์ด ํ ๋ช
๋ ๊ฐ์ง๋์ง ์๋ ๊ฒฝ์ฐ
if (!process()) {
// ์ํ๋ ๊ฒฝ์ฐ๋ฅผ ๋ฐ๊ฒฌํ ๊ฒ์
found = true;
break;
}
// ์ค์น๋ ์ฅ์ ๋ฌผ์ ๋ค์ ์์ ๊ธฐ
for (int j = 0; j < spaceList.get(i).size(); j++) {
int x = spaceList.get(i).get(j).getX();
int y = spaceList.get(i).get(j).getY();
board[x][y] = 'X';
}
}
if (found) System.out.println("YES");
else System.out.println("NO");
}
}
| movingone/algorithm_study | 13/6.java | 1,547 | // ์ฅ์ ๋ฌผ ์ค์น ์ดํ์, ํ ๋ช
์ด๋ผ๋ ํ์์ด ๊ฐ์ง๋๋์ง ๊ฒ์ฌ | line_comment | en | true |
165738_5 | /*
* Brandon Gerber
* 2/2/2024
* COP3804
* Books.java
*/
public class Books {
public String title;
public String author;
public int publicationYear;
public String ISBN;
public boolean available;
public double price;
private static int totalAvailableBooks = 0;
public int daysOverdue;
public double lateFee;
// constructor
public Books(String t, String a, int py, String num, boolean avail, double p) {
title = t;
author = a;
publicationYear = py;
ISBN = num;
available = avail;
price = p;
totalAvailableBooks++;
}
// setters
public void setTitle(String t) {
t = title;
}
public void setAuthor(String a) {
a = author;
}
public void setYear(int py) {
py = publicationYear;
}
public void setISBN(String num) {
num = ISBN;
}
public void setAvailable(boolean avail) {
avail = available;
}
public void setPrice(double p) {
p = price;
}
// getters
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public int getYear() {
return publicationYear;
}
public String getISBN() {
return ISBN;
}
public boolean getAvailable() {
return available;
}
public double getPrice() {
return price;
}
// display all info
public void displayInfo() {
System.out.println("Title: " + title + "\nAuthor: " + author + "\nPublication Year: " + publicationYear + "\nISBN: " + ISBN + "\nAvailable: " + available + "\nPrice: " + price);
}
// borrowing book, if its available decrement available books
public void borrowBook() {
if(available == true) {
System.out.println("The book is available to be borrowed, Total books available: " +totalAvailableBooks--);
available = false;
} else System.out.println("Sorry, this book is already borrowed");
}
// return book, increment book when book is put back into totalavailablebooks
public void returnBook() {
if(available == false) {
System.out.println("The book is not available, Total books available: " +totalAvailableBooks++);
available = true;
} else System.out.println("Sorry, this book is already in the library");
}
public void calculateLateFee(int daysOverdue) {
lateFee = (.5*daysOverdue);
System.out.println("Your late fee for this book is $" +lateFee);
} // method to return totalavailablebooks
public int totalAvailableBooks() {
return totalAvailableBooks;
}
}
| brandongerber/UMLHomework | Books.java | 726 | // borrowing book, if its available decrement available books
| line_comment | en | true |
165796_1 | /**
* LayerSort
* Interface to sorting layers
*
* @author Lee Byron
* @author Martin Wattenberg
*/
public abstract class LayerSort {
abstract String getName();
abstract Layer[] sort(Layer[] layers);
/**
* Creates a 'top' and 'bottom' collection.
* Iterating through the previously sorted list of layers, place each layer
* in whichever collection has less total mass, arriving at an evenly
* weighted graph. Reassemble such that the layers that appeared earliest
* end up in the 'center' of the graph.
*/
protected Layer[] orderToOutside(Layer[] layers) {
int j = 0;
int n = layers.length;
Layer[] newLayers = new Layer[n];
int topCount = 0;
float topSum = 0;
int[] topList = new int[n];
int botCount = 0;
float botSum = 0;
int[] botList = new int[n];
// partition to top or bottom containers
for (int i=0; i<n; i++) {
if (topSum < botSum) {
topList[topCount++] = i;
topSum += layers[i].sum;
} else {
botList[botCount++] = i;
botSum += layers[i].sum;
}
}
// reassemble into single array
for (int i = botCount - 1; i >= 0; i--) {
newLayers[j++] = layers[botList[i]];
}
for (int i = 0; i < topCount; i++) {
newLayers[j++] = layers[topList[i]];
}
return newLayers;
}
}
| silky/streamgraph | LayerSort.java | 400 | /**
* Creates a 'top' and 'bottom' collection.
* Iterating through the previously sorted list of layers, place each layer
* in whichever collection has less total mass, arriving at an evenly
* weighted graph. Reassemble such that the layers that appeared earliest
* end up in the 'center' of the graph.
*/ | block_comment | en | true |
165835_0 | /**
* @author Caleb Martin of CCMJ
*/
import java.util.ArrayList;
public class Activity
{
private Type type;
private String name;
private String time;
private String description;
private ArrayList<String> packingList;
/**
* Creates an instance of an activity
* @param type The type of activity
* @param name The name of the activity
* @param time The time the activity is held
*/
public Activity(Type type, String name, String time)
{
this.type = type;
this.name = name;
this.time = time;
}
/**
* Sets the description of the activity
* @param description The description to add
*/
public void setDescription(String description)
{
this.description = description;
}
/**
* Adds an item to the activity's packing list
* @param item The item to add
*/
public void addToPackingList(String item)
{
this.packingList.add(item);
}
/**
* Sets the entire packing list to a new list
* @param items The list to set
*/
public void setPackingList(ArrayList<String> packingList)
{
this.packingList = packingList;
}
public Type getType()
{
return this.type;
}
public String getName()
{
return this.name;
}
public String getTime()
{
return this.time;
}
public String getDescription()
{
return this.description;
}
public ArrayList<String> getPackingList()
{
return this.packingList;
}
/**
* Returns the Activity object as a human-readable string
* @return Returns the name, time, and description of the activity on separate lines
*/
public String toString()
{
return this.name + "\n" + this.time + "\n" + this.description + "\n";
}
}
| Jackson-Williams-15/CampSystem | Activity.java | 439 | /**
* @author Caleb Martin of CCMJ
*/ | block_comment | en | true |
166321_6 | /*=============================================
class Warrior -- protagonist of Ye Olde RPG
(_)
__ ____ _ _ __ _ __ _ ___ _ __
\ \ /\ / / _` | '__| '__| |/ _ \| '__|
\ V V / (_| | | | | | | (_) | |
\_/\_/ \__,_|_| |_| |_|\___/|_|
=============================================*/
public class Warrior extends Character {
// ~~~~~~~~~~~ INSTANCE VARIABLES ~~~~~~~~~~~
// inherited from superclass
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/*=============================================
default constructor
pre: instance vars are declared
post: initializes instance vars.
=============================================*/
public Warrior() {
super();
_hitPts = 125;
_strength = 100;
_defense = 40;
_attack = .4;
}
/*=============================================
overloaded constructor
pre: instance vars are declared
post: initializes instance vars. _name is set to input String.
=============================================*/
public Warrior( String name ) {
this();
if (!name.equals("")) {
_name = name;
}
}
/*=============================================
void specialize() -- prepares character for special attack
pre:
post: Attack of character is increased, defense is decreased
=============================================*/
public void specialize() {
_attack = .75;
_defense = 20;
}
/*=============================================
void normalize() -- revert stats back to normal
pre:
post: Attack and defense of character is de-specialized
=============================================*/
public void normalize() {
_attack = .45;
_defense = 40;
}
/*=============================================
String about() -- returns descriptions character type
pre:
post: Info is returned
=============================================*/
public String about() {
return "Warriors are fierce and strong fighters, but are slow.";
}
/*==========================
String heroSpecial()
pre:
post: executes a character's special move, for example, a priest would heal itself, and
returns a string summarizing what happened.
========================*/
public String heroSpecial(){
if (((int) (Math.random()*99)) >= 50){
this._strength+=20;
return "your warrior summons a magical steroid and eats it, your warrior's strength has increased to " + this._strength;
}
else {
this._hitPts-=10;
this._defense -=10;
return "your warrior accidentally summons a bad magic steroid, lowering HP and defence by 10" ;
}
}
}//end class Warrior
| siuryan-cs-stuy/YoRPG_FileNotFound | Warrior.java | 646 | /*=============================================
void specialize() -- prepares character for special attack
pre:
post: Attack of character is increased, defense is decreased
=============================================*/ | block_comment | en | false |
166502_0 |
/*
* @author: Abhinaya Ramachandran
* Completely fair scheduler
*
*/
public class Process {
public int processId;
public long execTime;
public long timeInCPU;
public long waitTime;
public long arrivalTime;
public RedBlackTree rbt;
public long unfairness;
public long startTime;
public HeapImpl heap;
public long turnAroundTime;
public Process(HeapImpl hp,int newId,long newArrivalTime, long newExecTime){
timeInCPU=0;
turnAroundTime=0;
processId=newId;
execTime=newExecTime;
arrivalTime=newArrivalTime;
waitTime=arrivalTime;
unfairness=arrivalTime;
heap=hp;
heap.insert(this);
}
public Process(RedBlackTree rbtree,int newId,long newArrivalTime, long newExecTime){
timeInCPU=0;
processId=newId;
execTime=newExecTime;
arrivalTime=newArrivalTime;
waitTime=arrivalTime;
unfairness=arrivalTime;
rbt=rbtree;
rbt.insert(this);
}
}
| abhinayaramachandran/TaskScheduler | Process.java | 311 | /*
* @author: Abhinaya Ramachandran
* Completely fair scheduler
*
*/ | block_comment | en | true |
166654_0 | public class RecycledSteel {
static private int steel_id;
static private String steel_type;
static private String steel_name;
static private float steel_weight;
static private float steel_price;
static String dataRecylSteel[][] = {{"0","Hot rolled steel","Solid square steel","1","12"}};
RecycledSteel(int id){
String[] array = dataRecylSteel[id];
this.steel_id = Integer.parseInt(array[0]);
this.steel_type = array[1];
this.steel_name = array[2];
this.steel_weight = Float.parseFloat(array[3]);
this.steel_price = Float.parseFloat(array[4]);
}
public static void addSteel(String[] newRecord){
int nextId = 1;
if (newRecord.length != 5) {
System.out.println("Invalid data format. Please provide an array with 5 elements.");
return;
}
String[] formattedRecord = new String[5];
formattedRecord[0] = String.valueOf(nextId++);
for (int i = 1; i < 5; i++) {
formattedRecord[i] = newRecord[i - 1];
}
// Create a new array to accommodate the additional record
String[][] newData = new String[dataRecylSteel.length + 1][];
for (int i = 0; i < dataRecylSteel.length; i++) {
newData[i] = dataRecylSteel[i];
}
newData[dataRecylSteel.length] = formattedRecord;
dataRecylSteel = newData;
}
public static void displayInfoSteel(){
for (int i = 0; i < dataRecylSteel.length; i++) {
System.out.println("ID :"+dataRecylSteel[i][0]+" , Steel Type :"+dataRecylSteel[i][1]+" , Weight :"+dataRecylSteel[i][2]+" , Price :"+dataRecylSteel[i][2]);
}
}
}
| TERPHK/java | RecycledSteel.java | 511 | // Create a new array to accommodate the additional record | line_comment | en | true |
167099_0 | /**
* Class representing the TodoApp application.
* It is the main entry point for this program.
*/
import java.util.Scanner;
import java.util.InputMismatchException;
import java.lang.IndexOutOfBoundsException;
public class App{
private static TodoList tasksList = new TodoList();
public static void main(String[] args)
{
while(true)
{
try
{
printMenu();
handleMainMenu();
}
catch(InputMismatchException e)
{
System.out.println("Wrong choose");
}
}
}
public static void printMenu()
{
System.out.println("\nChoose option:");
System.out.println("(1) Show all tasks");
System.out.println("(2) Add new task");
System.out.println("(3) Archive tasks");
System.out.println("(0) Exit\n");
}
public static int handleOption() throws InputMismatchException
{
InputMismatchException wrongInput = new InputMismatchException();
Scanner choose = new Scanner(System.in);
int choice = 0;
if(choose.hasNextInt()) choice = choose.nextInt();
else throw wrongInput;
return choice;
}
public static void handleMainMenu()
{
int choice;
do {
choice = handleOption();
if(choice == 1) handleTaskOption();
else if(choice == 2) addNewItem();
else if(choice == 3) tasksList.archiveTasks();
else if(choice == 0) System.exit(0);
else System.out.println("Wrong choice!");
} while (true);
}
public static void handleTaskOption()
{
int option;
do
{
tasksList.listTasks();
System.out.println();
printItemMenu();
option = handleOption();
if(option == 1) markItem();
else if(option == 2) unmarkItem();
else if(option == 0) break;
else System.out.println("Wrong choice");;
} while (true);
}
public static void markItem()
{
int option;
do {
System.out.println("Choose item to mark");
option = handleOption();
if(option >0 && option <= tasksList.getListSize())
{
tasksList.getItem(option-1).mark();
}
if(option == 0) break;
else System.out.println("Wrong choice");;
} while (true);
}
public static void unmarkItem()
{
int option;
do {
System.out.println("Choose item to unmark");
option = handleOption();
if(option > 0 && option <= tasksList.getListSize())
{
tasksList.getItem(option-1).unmark();
}
if(option == 0) break;
else System.out.println("Wrong choice");;
} while (true);
}
public static void printItemMenu()
{
System.out.println("\n(1) Mark item");
System.out.println("(2) Unmark item");
System.out.println("(0) Back\n");
}
public static void addNewItem()
{
Scanner newDescr = new Scanner(System.in);
System.out.println("Type description to new item:");
TodoItem newItem = new TodoItem(newDescr.nextLine());
tasksList.addItem(newItem);
}
}
| CodecoolKRK20171/java-todo-app-smoczis | App.java | 774 | /**
* Class representing the TodoApp application.
* It is the main entry point for this program.
*/ | block_comment | en | true |
167812_1 | //Create file using (file handling)
import java.io.File;
import java.io.IOException;
public class CreateFileExample1
{
public static void main(String[] args)
{
File file = new File("C:\\Users\\91989\\Desktop\\Filedemo1.txt"); //initialize File object and passing path as argument
boolean result;
try
{
result = file.createNewFile(); //creates a new file
if(result) // test if successfully created a new file
{
System.out.println("file created "+file.getCanonicalPath()); //returns the path string
}
else
{
System.out.println("File already exist at location: "+file.getCanonicalPath());
}
}
catch (IOException e)
{
e.printStackTrace(); //prints exception if any
}
}
}
| shivanshunigam01/100days_of_code | Day78/.java | 216 | //initialize File object and passing path as argument | line_comment | en | true |
168087_0 | /*
* Timer.java - part of the GATOR project
*
* Copyright (c) 2018 The Ohio State University
*
* This file is distributed under the terms described in LICENSE in the
* root directory.
*/
package utils;
public class Timer {
private static long start;
public static void reset() {
start = System.currentTimeMillis();
}
public static long duration() {
return System.currentTimeMillis() - start;
}
}
| droidxp/droidfax-fork | src/utils/Timer.java | 108 | /*
* Timer.java - part of the GATOR project
*
* Copyright (c) 2018 The Ohio State University
*
* This file is distributed under the terms described in LICENSE in the
* root directory.
*/ | block_comment | en | true |
168839_0 | import java.io.*;
import java.util.*;
class Edge implements Comparable{
int start,end;
int cost;
public int compareTo(Object temp){
Edge cnt = (Edge) temp;
if(cnt.cost<this.cost) return 1;
return -1;
}
}
class Set{
final int N = 100;
int father[] = new int[N],num[] = new int[N];
void init(){
for(int i=0;i<N;++i){
father[i] = -1;
num[i] = 0;
}
}
int find(int who){
int u,v = who;
while(this.father[who]!=-1){
who = this.father[who];
}
while(v!=who){
u = this.father[v];
this.father[v] = who;
v = u;
}
return who;
}
void set(int a,int b){
a = this.find(a);
b = this.find(b);
if(a==b)
return ;
if(this.num[a]>this.num[b]){
this.father[b] = a;
this.num[a]+=this.num[b];
}else{
this.father[a] = b;
this.num[b]+=this.num[a];
}
}
}
public class Main {
static final int N = 100000;
static int n,m;
static Set set = new Set();
static Edge edge[] = new Edge[N];
static void start(){
for(int i=0;i<N;++i)
edge[i] = new Edge();
}
static int solve(){
int ans=0;
int i;
Arrays.sort(edge,0,m);
for(i=0;i<m;++i){
if(set.find(edge[i].start)!=set.find(edge[i].end))
ans+=edge[i].cost;
set.set(edge[i].start, edge[i].end);
}
return ans;
}
public static void main(String[]args) throws Exception{
int i,j;
start();
StreamTokenizer cin = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
//StreamTokenizer cin = new StreamTokenizer(new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))));
while(true){
n = Get_Num(cin);
if(n==0) break;
m = Get_Num(cin);
set.init();
for(i=0;i<m;++i){
edge[i].start = Get_Num(cin);
edge[i].end = Get_Num(cin);
edge[i].cost = Get_Num(cin);
}
System.out.println(solve());
}
}
static int Get_Num(StreamTokenizer cin)throws Exception{
cin.nextToken();
return (int)cin.nval;
}
}
| Hangjun/pku-online-judge | 1287.java | 792 | //StreamTokenizer cin = new StreamTokenizer(new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))));
| line_comment | en | true |
168971_0 | /* Write a Java program to show inheritance. Make classes grandfather, father and son and then inherit the properties from other classes. */
class grandfather {
String gprop = "House";
void disp1() {
System.out.println("Grandfather has house");
}
}
class Father extends grandfather {
String fprop = "Car";
void disp2() {
System.out.println("Father has car");
}
}
class Son extends Father {
String sprop = "Bike";
void disp3() {
System.out.println("Son has bike");
}
}
public class Family {
public static void main(String args[]) {
Son s = new Son();
System.out.println("Son has " + s.gprop);
System.out.println("Son has " + s.fprop);
System.out.println("Son has " + s.sprop);
System.out.println("Father has " + s.gprop);
s.disp1();
s.disp2();
s.disp3();
}}
| anshikasrivastava17/Java-DSA-Programs | Family.java | 249 | /* Write a Java program to show inheritance. Make classes grandfather, father and son and then inherit the properties from other classes. */ | block_comment | en | true |
169208_7 | import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
public class SubFasta {
private static final NumberFormat nf = new DecimalFormat("############.#");
private static final String[] fastaEnds = {"bases", "qv", "qual", "fna", "contig", "fa", "fasta"};
private static final String[] fastqEnds = {"fq", "fastq", "txt"};
private static class Position {
public int start;
public int end;
public String name = null;
public Position() {
}
public Position(int s, int e, String n) {
start = s;
end = e;
name = n;
}
}
private static final int MAX_READ = 10000;
private HashMap<Integer, ArrayList<Double>> positionQual = new HashMap<Integer, ArrayList<Double>>(MAX_READ);
private HashMap<String, ArrayList<Position>> fastaToOutput = new HashMap<String, ArrayList<Position>>();
private HashMap<String, Integer> outputToPosition = new HashMap<String, Integer>();
private HashMap<String, Boolean> outputIDs = new HashMap<String, Boolean>();
private int minValue = Integer.MAX_VALUE;
private int maxValue = Integer.MIN_VALUE;
private boolean splitByTab = false;
private boolean reorder = false;
private ArrayList<String> toOutput = new ArrayList<String>();
public SubFasta() {
}
public void inputIDs(String file) throws Exception {
if (file == null || file.equalsIgnoreCase("null")) {
return;
}
String line = null;
BufferedReader bf = new BufferedReader(new InputStreamReader(
new FileInputStream(file)));
int position = 0;
while ((line = bf.readLine()) != null) {
String[] split = null;
if (splitByTab == true) {
split=line.trim().split("\\t+");
} else {
split=line.trim().split("\\s+");
}
try {
if (split.length < 3) {
throw new Exception("Insufficient number of arguments");
}
Position p = new Position();
p.start = Integer.parseInt(split[1])-1;
p.end = Integer.parseInt(split[2])-1;
if (split.length > 3) {
p.name = split[3];
}
if (fastaToOutput.get(split[0]) == null) {
fastaToOutput.put(split[0], new ArrayList<Position>());
}
fastaToOutput.get(split[0]).add(p);
outputToPosition.put(split[0], position);
position++;
} catch (Exception e) {
System.err.println("Invalid line " + e.getLocalizedMessage() + " for line " + line);
}
}
bf.close();
}
public void outputFasta(String fastaSeq, String ID) {
boolean isInN = true;
int lastPos = fastaSeq.length();
for (int i = 0; i < fastaSeq.length(); i++) {
if (fastaSeq.charAt(i) == 'N') {
if (isInN == false) { lastPos = i; }
isInN = true;
} else {
isInN = false;
}
}
if (isInN == true) {
System.err.println("Trimming sequence " + ID + " to be " + lastPos + " instead of " + fastaSeq.length());
} else {
lastPos = fastaSeq.length();
}
outputFasta(fastaSeq.substring(0, lastPos).toUpperCase(), null, ID, ">", null, true);
}
public void outputFasta(String fastaSeq, String qualSeq, String ID, String fastaSeparator, String qualSeparator, boolean convert) {
if (fastaSeq.length() == 0) {
return;
}
if (qualSeq != null && qualSeq.length() != fastaSeq.length()) {
System.err.println("Error length of sequences and fasta for id " + ID + " aren't equal fasta: " + fastaSeq.length() + " qual: " + qualSeq.length());
qualSeq = qualSeq.substring(0, Math.min(qualSeq.length(), fastaSeq.length()));
//System.exit(1);
}
String IDtoCheck=(splitByTab == true ? ID : ID.split("\\s+")[0]);
if (fastaToOutput.size() == 0 || fastaToOutput.get(IDtoCheck) != null) {
if (outputIDs.get(ID) != null && outputIDs.get(ID) == true) {
return;
}
StringBuilder str = new StringBuilder();
boolean rc = false;
String origID = IDtoCheck;
outputIDs.put(ID, true);
ArrayList<Position> ps = fastaToOutput.get(IDtoCheck);
for (Position p : ps) {
if (p == null) { p = new Position(0, 0, ID); }
if (p.start > p.end) { rc = true; int tmp = p.start; p.start = p.end; p.end = tmp; }
if (p.start < 0) { p.start = 0; }
if (p.end == 0 || p.end > fastaSeq.length()) { System.err.println("FOR ID " + ID + " ADJUSTED END to " + fastaSeq.length()); p.end = fastaSeq.length(); }
if (ID.indexOf(",") != -1) { ID = ID.split(",")[0]; }
if (p.name != null && p.name.indexOf(",") != -1) { p.name = p.name.split(",")[0]; }
if (reorder) {
str.append(fastaSeparator + (p.name == null ? ID : p.name) + "\n");
} else {
System.out.println(fastaSeparator + (p.name == null ? ID : p.name));
}
String toPrint = fastaSeq.substring(p.start, (Math.min(p.end+1, fastaSeq.length()))).toUpperCase();
if (rc) {
toPrint = Utils.rc(toPrint);
}
if (reorder) {
str.append(convert == true ? Utils.convertToFasta(toPrint) : toPrint + "\n");
} else {
System.out.println(convert == true ? Utils.convertToFasta(toPrint) : toPrint);
}
if (qualSeq != null) {
if (reorder) {
str.append(qualSeparator + (p.name == null ? ID : p.name) + "\n");
str.append((convert == true ? Utils.convertToFasta(qualSeq.substring(p.start, Math.min(p.end+1, qualSeq.length()))) : qualSeq.substring(p.start, Math.min(p.end+1, qualSeq.length()))) + "\n");
} else {
System.out.println(qualSeparator + (p.name == null ? ID : p.name));
System.out.println((convert == true ? Utils.convertToFasta(qualSeq.substring(p.start, Math.min(p.end+1, qualSeq.length()))) : qualSeq.substring(p.start, Math.min(p.end+1, qualSeq.length()))));
}
}
/*
System.err.println(">" + ID);
for (int i = 0; i < qualSeq.length(); i++) {
int value = (int) qualSeq.charAt(i);
if (value < minValue) {
minValue = value;
}
if (value > maxValue) {
maxValue = value;
}
double qv = (double)value;
qv -= (int)'!';
System.err.print(qv + " ");
// store the list of values
if (positionQual.get(i) == null) {
positionQual.put(i, new ArrayList<Double>());
}
positionQual.get(i).add(qv);
}
System.err.println();
*/
}
while (toOutput.size() <= outputToPosition.get(origID)) {
toOutput.add("");
}
toOutput.set(outputToPosition.get(origID), str.toString());
}
}
public void processFasta(String inputFile) throws Exception {
BufferedReader bf = Utils.getFile(inputFile, fastaEnds);
String line = null;
StringBuffer fastaSeq = new StringBuffer();
String header = "";
StringBuffer qualSeq = new StringBuffer();
while ((line = bf.readLine()) != null) {
if (line.startsWith(">")) {
outputFasta(fastaSeq.toString(), header);
/*
for (int i = 0; i < fastaSeq.length(); i++) {
qualSeq.append("I");
} outputFasta(fastaSeq.toString(), qualSeq.toString(), header, "@", "+", false);
*/
header = line.trim().split("\\s+")[0].substring(1);
//if (header.indexOf(",") != -1) { header = header.split(",")[0]; }
fastaSeq = new StringBuffer();
qualSeq = new StringBuffer();
}
else {
if (inputFile.contains("qual") || line.trim().split("\\s+").length > 1) { fastaSeq.append(" "); }
fastaSeq.append(line);
}
}
outputFasta(fastaSeq.toString(), header);
/*
for (int i = 0; i < fastaSeq.length(); i++) {
qualSeq.append("I");
}
outputFasta(fastaSeq.toString(), qualSeq.toString(), header, "@", "+", false);
*/
bf.close();
}
public void processFastq(String inputFile) throws Exception {
BufferedReader bf = Utils.getFile(inputFile, fastqEnds);
String line = null;
String header = "";
while ((line = bf.readLine()) != null) {
// read four lines at a time for fasta, qual, and headers
String ID = line.substring(1);
String fasta = bf.readLine();
String qualID = bf.readLine().split("\\s+")[0].substring(1);
if (qualID.length() != 0 && !qualID.equals(ID)) {
System.err.println("Error ID " + ID + " DOES not match quality ID " + qualID);
System.exit(1);
}
String qualSeq = bf.readLine();
//outputFasta(fasta, ID);
outputFasta(fasta, qualSeq, ID, "@", "+", false);
}
bf.close();
}
public void finish() throws Exception {
if (reorder == true) {
for (String out : toOutput) {
System.out.print(out);
}
}
}
public static void printUsage() {
System.err.println("This program subsets a fasta or fastq file by a specified list. The default sequence is N. Multiple fasta files can be supplied by using a comma-separated list.");
System.err.println("Example usage: SubFasta subsetFile fasta1.fasta,fasta2.fasta");
}
public static void main(String[] args) throws Exception {
if (args.length < 1) { printUsage(); System.exit(1);}
SubFasta f = new SubFasta();
if (args.length < 2) {
printUsage();
System.exit(1);
}
int argOffset = 0;
if (args[0].equalsIgnoreCase("true") || args[0].equalsIgnoreCase("false")) {
f.splitByTab = Boolean.parseBoolean(args[0]);
System.err.println ("Splitting using boolean is " + f.splitByTab);
argOffset++;
}
if (args[0].equalsIgnoreCase("-r")) {
f.reorder = Boolean.parseBoolean(args[1]);
argOffset++;
argOffset++;
}
f.inputIDs(args[argOffset++]);
for (int i = argOffset; i < args.length; i++) {
String[] splitLine = args[i].trim().split(",");
for (int j = 0; j < splitLine.length; j++) {
System.err.println("Processing file " + splitLine[j]);
if ((splitLine[j].contains("qual") || splitLine[j].contains("qv") || splitLine[j].contains("fasta") || splitLine[j].contains("fna") || splitLine[j].contains("fa") || splitLine[j].contains("contig") || splitLine[j].contains("txt")) && !(splitLine[j].contains("fastq"))) {
f.processFasta(splitLine[j]);
} else if (splitLine[j].contains("fastq") || splitLine[j].contains("txt") || splitLine[j].contains("fq")) {
f.processFastq(splitLine[j]);
} else {
System.err.println("Unknown file type " + splitLine[j]);
}
}
}
f.finish();
/*
if (f.minValue != Integer.MAX_VALUE) {
System.err.println("Processed files and min value for quality I saw is " + f.minValue + " aka " + (char)f.minValue + " and max is " + f.maxValue + " AKA " + (char)f.maxValue);
}
for (int i = 0; i < MAX_READ; i++) {
if (f.positionQual.get(i) == null) {
System.err.println(i + " 0");
} else {
double total = 0;
for (Double val : f.positionQual.get(i)) {
total+=val;
}
total /= f.positionQual.get(i).size();
System.err.println(i + " " + total);
}
}
*/
}
}
| skoren/triobinningScripts | SubFasta.java | 3,258 | /*
if (f.minValue != Integer.MAX_VALUE) {
System.err.println("Processed files and min value for quality I saw is " + f.minValue + " aka " + (char)f.minValue + " and max is " + f.maxValue + " AKA " + (char)f.maxValue);
}
for (int i = 0; i < MAX_READ; i++) {
if (f.positionQual.get(i) == null) {
System.err.println(i + " 0");
} else {
double total = 0;
for (Double val : f.positionQual.get(i)) {
total+=val;
}
total /= f.positionQual.get(i).size();
System.err.println(i + " " + total);
}
}
*/ | block_comment | en | true |
169490_0 | /***************************************************************************************************
* File : employee.java
* Description : to print employee details
* Author : Kevin Biju Kulangara
* Version : 1.0
* Date : 17/10/2023
*************************************************************************************************/
package sample;
import java.util.Scanner;
class Employee{
String name;
int age;
String phonenumber;
float salary;
String address;
Scanner sc=new Scanner(System.in);
void getdetails() {
System.out.println("Enter your name");
name=sc.next();
System.out.println("Enter your age");
age=sc.nextInt();
System.out.println("Enter your phone number");
phonenumber=sc.next();
System.out.println("Enter your Salary");
salary=sc.nextInt();
sc.nextLine();
System.out.println("Enter your address");
address=sc.nextLine();
}
void printdetails(){
System.out.println("Name is:"+name);
System.out.println("age is:"+age);
System.out.println("Phonenumber:"+phonenumber);
System.out.println("Address:"+address);
System.out.println("Salary:"+salary);
}
}
class Officer extends Employee{
String specialization;
public void specialization()
{
System.out.println("Enter Specialization:");
specialization=sc.nextLine();
}
public void printSpecialization()
{
System.out.println("Specialization:"+specialization);
}
}
class Manager extends Employee
{
String department;
public void department()
{
System.out.println("Enter Department:");
department=sc.next();
}
public void printdepartment()
{
System.out.println("Department is:"+department);
}
}
public class Employeedetails {
public static void main(String[]args) {
Officer officer=new Officer();
officer.getdetails();
officer.specialization();
System.out.println("Details of Officer:");
officer.printdetails();
officer.printSpecialization();
Manager manager=new Manager();
manager.getdetails();
manager.department();
System.out.println("Details of Manager:");
manager.printdetails();
manager.printdepartment();
}
}
| Kevin1077/JAVA-LAB-S3 | Employeedetails.java | 582 | /***************************************************************************************************
* File : employee.java
* Description : to print employee details
* Author : Kevin Biju Kulangara
* Version : 1.0
* Date : 17/10/2023
*************************************************************************************************/ | block_comment | en | true |
170170_0 | class FoodItem {
private String name;
private double price;
private String description;
private boolean is_available;
private int restaurant_id;
public FoodItem(String name, double price, String description, boolean is_available, int restaurant_id) {
this.name = name;
this.price = price;
this.description = description;
this.is_available = is_available;
this.restaurant_id = restaurant_id;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public double getPrice() {
return price;
}
public boolean isAvailable() {
return is_available;
}
public int getRestaurantId() {
return restaurant_id;
}
public void setPrice(double price) {
this.price = price;
}
public void setDescription(String description) {
this.description = description;
}
public void setAvailability(boolean is_available) {
this.is_available = is_available;
}
public void setName(String name) {
this.name = name;
}
/**
* @return String
*
* This method returns the information about the food item
*/
public String getFoodInfo() {
Restaurant restaurant = CSVOperations.getRestaurantById(this.restaurant_id);
return "\nName: " + this.name + "; Price: " + this.price + "; Description: " + this.description + "; Available: " + this.is_available + "; Restaurant: " + restaurant.getName() + "; Address: " + restaurant.getAddress() + "\n";
}
} | xelilovkamran/food_delivery_system | src/FoodItem.java | 369 | /**
* @return String
*
* This method returns the information about the food item
*/ | block_comment | en | false |
170302_8 | import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* PixGrid Class
* Holds Pix objects and handles movement
* @author Nic Manoogian <[email protected]>
* @author Mike Lyons
*/
public class PixGrid
{
private BufferedImage canvas;
private Pix[][] grid;
/**
* Constructs a PixGrid with size 640x480
*/
public PixGrid()
{
// Defaults to 640x480
grid = new Pix[640][480];
}
/**
* Constructs a PixGrid with size and 10 Pix objects
* @param xsize width
* @param ysize height
*/
public PixGrid(int xsize, int ysize)
{
grid = new Pix[xsize][ysize];
generate_blank_world();
}
/**
* Constructs a PixGrid with size and n Pix objects
* @param xsize width
* @param ysize height
* @param n number of Pix objects to add
*/
public PixGrid(int xsize, int ysize, int n)
{
grid = new Pix[xsize][ysize];
generate_blank_world();
}
/**
* Fills grid with white Pix of a certain type
*/
public void generate_blank_world()
{
for( int i = 0; i < grid.length; i++ )
{
for( int j = 0; j < grid[0].length; j ++ )
{
grid[i][j] = new Pix(255,255,255);
}
}
}
/**
* Returns the grid
* @return grid
*/
public Pix[][] getGrid()
{
return grid;
}
/**
* Loops through all non-white Pix and transitions them in a random direction (N S E W)
*/
public void update()
{
for( int i = 0; i < grid.length; i++ )
{
for( int j = 0; j < grid[0].length; j ++ )
{
if( !grid[i][j].isWhite() )
{
grid[i][j].update( i , j );
}
}
}
}
/**
* Returns a String representation of a PixGrid
* @return PixGrid String representation
*/
public String toString()
{
String new_string = "";
for( int i = 0; i < grid.length; i++ )
{
for( int j = 0; j < grid[0].length; j ++ )
{
new_string += "(" + grid[i][j] + ") ";
}
new_string += "\n";
}
return new_string;
}
} | nmanoogian/PixelifeJava | PixGrid.java | 772 | /**
* Returns a String representation of a PixGrid
* @return PixGrid String representation
*/ | block_comment | en | false |
170411_7 | /*
* Course: SE 2030 - 041
* Fall 22-23
* GTFS Project
* Created by: Christian Basso, Ian Czerkis, Matt Wehman, Patrick McDonald.
* Created on: 09/10/22
* Copyright 2022 Ian Czerkis, Matthew Wehman, Patrick McDonald, Christian Basso
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.
*/
import java.util.ArrayList;
import java.util.HashMap;
/**
* This is the Route class and it is the path which a bus will take
* @author czerkisi
* @version 1.0
* @created 05-Oct-2022 12:59:52 PM
*/
public class Route {
private String agencyID;
private String routeColor;
private String routeDesc;
private String routeID;
private String routeLongName;
private String routeShortName;
private String routeTextColor;
private String routeType;
private String routeURL;
private HashMap<String, Stop> stops = new HashMap<>();
private HashMap<String, Trip> trips = new HashMap<>();
//Testing
private HashMap<String, ArrayList<Stop>> allStopsList = new HashMap<>();
private HashMap<String, ArrayList<Trip>> tripsList = new HashMap<>();
/**
* Creates an instance of a Route
* @param routeID
* @param agencyID
* @param routeShortName
* @param routeLongName
* @param routeDesc
* @param routeType
* @param routeURL
* @param routeColor
* @param routeTextColor
*/
public Route(String routeID, String agencyID, String routeShortName, String routeLongName, String routeDesc, String routeType, String routeURL, String routeColor, String routeTextColor) {
try {
this.agencyID = agencyID;
this.routeColor = routeColor;
this.routeDesc = routeDesc;
this.routeID = routeID;
this.routeLongName = routeLongName;
this.routeShortName = routeShortName;
this.routeTextColor = routeTextColor;
this.routeType = routeType;
this.routeURL = routeURL;
} catch (NumberFormatException e){
throw new RuntimeException("File is not formatted correctly");
}
}
public void setAgencyID(String agencyID) {
this.agencyID = agencyID;
}
public void setRouteColor(String routeColor) {
this.routeColor = routeColor;
}
public void setRouteDesc(String routeDesc) {
this.routeDesc = routeDesc;
}
public void setRouteID(String routeID) {
this.routeID = routeID;
}
public void setRouteLongName(String routeLongName) {
this.routeLongName = routeLongName;
}
public void setRouteShortName(String routeShortName) {
this.routeShortName = routeShortName;
}
public void setRouteTextColor(String routeTextColor) {
this.routeTextColor = routeTextColor;
}
public void setRouteType(String routeType) {
this.routeType = routeType;
}
public void setRouteURL(String routeURL) {
this.routeURL = routeURL;
}
public String getAgencyID() {
return agencyID;
}
public String getRouteColor() {
return routeColor;
}
public String getRouteDesc() {
return routeDesc;
}
public String getRouteID() {
return routeID;
}
public String getRouteLongName() {
return routeLongName;
}
public String getRouteShortName() {
return routeShortName;
}
public String getRouteTextColor() {
return routeTextColor;
}
public String getRouteType() {
return routeType;
}
public String getRouteURL() {
return routeURL;
}
public HashMap<String, Stop> getStops() {
return stops;
}
public HashMap<String, Trip> getTrips() {
return trips;
}
public HashMap<String, ArrayList<Stop>> getStopsList() {
return allStopsList;
}
public HashMap<String, ArrayList<Trip>> getTripsList() {
return tripsList;
}
private int displayDist() {
return 0;
}
public void addStop(Stop stop){
ArrayList<Stop> stops1 = new ArrayList<>();
stops1.add(stop);
allStopsList.put(stop.getStopID(), stops1);
}
/**
* This takes in a new Route in place of the old one
* This method has not been implemented yet
* @param newRoute
* @return boolean
*/
public boolean update(Route newRoute) {
return false;
}
/**
* This adds Trips to an arrayList. This method will handle the chaining for the
* Trips in tripList
* @param key
* @param val
* @author Patrick
*/
public void addTrip(String key, Trip val){
if (tripsList.containsKey(key)){
tripsList.get(key).add(val);
} else {
tripsList.put(key, new ArrayList<>());
tripsList.get(key).add(val);
}
}
/**
* This adds Stops to an arrayList. This method will handle the chaining for the
* stops in allStopsList
* @param key
* @param val
* @author Patrick
*/
public void addStops(String key, Stop val){
if (allStopsList.containsKey(key)){
allStopsList.get(key).add(val);
} else {
allStopsList.put(key, new ArrayList<>());
allStopsList.get(key).add(val);
}
}
/**
* checks that all required fields are filled in
* @throws CSVReader.MissingRequiredFieldException if a required field is empty
*/
public void checkRequired() throws CSVReader.MissingRequiredFieldException {
if (routeID.isEmpty() | routeColor.isEmpty()){
throw new CSVReader.MissingRequiredFieldException("A required field is missing");
}
}
public boolean equals(Route r) {
return
this.routeID.equals(r.routeID) &&
this.routeColor.equals(r.routeColor) &&
this.routeDesc.equals((r.routeDesc)) &&
this.agencyID.equals(r.agencyID) &&
this.routeLongName.equals(r.routeLongName) &&
this.routeShortName.equals(r.routeShortName) &&
this.routeURL.equals(r.routeURL) &&
this.routeType.equals(r.routeType);
}
@Override
public String toString() {
return routeID + ","
+agencyID + ","
+routeShortName + ","
+routeLongName + ","
+routeDesc + ","
+routeType + ","
+routeURL + ","
+routeColor + ","
+routeTextColor;
}
} | cjbass02/milwaukee-google-transit-feed | Route.java | 1,704 | /**
* checks that all required fields are filled in
* @throws CSVReader.MissingRequiredFieldException if a required field is empty
*/ | block_comment | en | true |
170564_4 | /**
* This class is used to create objects that represent prizes in the
* Lucky Vending Machine. It is used by the PrizeList and Player classes.
*
* @author Bai Chan Kheo 22262407
* @version 1.3 27 May 2015
*/
public class Prize
{
private String name;
private int worth;
private int cost;
/**
* Constructor that takes no arguments.
*/
public Prize()
{
name = "";
worth = 0;
cost = 0;
}
/**
* Constructor that takes arguments for all attributes.
*
* @param newName The name of the prize.
* @param newWorth The prize's worth.
* @param newCost The prize's cost.
*/
public Prize(String newName, int newWorth, int newCost)
{
name = newName;
worth = newWorth;
cost = newCost;
}
/**
* Method that displays the details of the Prize object.
*/
public void displayPrize()
{
System.out.println(name + ", Worth: $" + worth +
", Cost: $" + cost);
}
/**
* Accessor method for cost attribute.
*
* @return The cost of the Prize.
*/
public int getCost()
{
return cost;
}
/**
* Accessor method for name attribute.
*
* @return The name of the Prize.
*/
public String getName()
{
return name;
}
/**
* Accessor method for worth attribute.
*
* @return The prize's worth.
*/
public int getWorth()
{
return worth;
}
/**
* Mutator method for cost attribute.
*
* @param newCost The cost of the prize.
* @return True if the cost is valid.
*/
public boolean setCost(int newCost)
{
boolean valid = false;
if (newCost > 0)
{
cost = newCost;
valid = true;
}
return valid;
}
/**
* Mutator method for name attribute.
*
* @param newName The name of the prize.
* @return True if the name is valid.
*/
public boolean setName(String newName)
{
boolean valid = false;
if (newName.trim().length() > 0 && Character.isLetter(newName.charAt(0)))
{
name = newName;
valid = true;
}
return valid;
}
/**
* Mutator method for worth attribute.
*
* @param newWorth The prize's worth.
* @return True if the worth is valid.
*/
public boolean setWorth(int newWorth)
{
boolean valid = false;
if (newWorth > 0)
{
worth = newWorth;
valid = true;
}
return valid;
}
} | kheob/F9IT131-Assignment-2 | Prize.java | 694 | /**
* Accessor method for cost attribute.
*
* @return The cost of the Prize.
*/ | block_comment | en | false |
170606_7 | package Maps;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import javax.imageio.ImageIO;
import Geom.Point3D;
/**
*
* @author Netanel Ben-Isahar
* @author daniel abergel
* this class represent a map with objects that represent the edges of the map.
* it also support some conversion functions.
*
*/
public class Map
{
private Point3D StartPoint ;
private Point3D EndPoint ;
private Pixel FrameSize ;
public BufferedImage myImage;
/**
* this constructor build the map with the appropriate values.
*/
public Map()
{
StartPoint = new Point3D(35.20234,32.10584,0);
EndPoint = new Point3D(35.21237,32.10193,0);
FrameSize = new Pixel(1433, 642);
StartPoint.GPS2Meter();
EndPoint.GPS2Meter();
try {
myImage = ImageIO.read(new File("Ariel1.PNG"));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* this function calculate the gps location after adding pixels distance
* @param PixelXMove represent the move on the x axis
* @param PixelYMove represent the move on the y axis
* @return the new gps point after the move
*/
public Point3D Pixel2GPSPoint( double PixelXMove , double PixelYMove )
{
Pixel p = Pixel2Meter(FrameSize.get_PixelX(), FrameSize.get_PixelY());
PixelXMove = PixelXMove * p.get_PixelX();
PixelYMove = PixelYMove * p.get_PixelY();
Point3D result = new Point3D(PixelXMove + StartPoint.x(),PixelYMove + StartPoint.y(),0);
result.Meter2GPS();
return result ;
}
/**
* this function calculate the pixel location after adding pixels distance
* @param PixelXMove represent the move on the x axis
* @param PixelYMove represent the move on the y axis
* @return the new pixel point after the move
*/
private Pixel Pixel2Meter(double PixelXSize , double PixelYSize )
{
double disX = EndPoint.x() - StartPoint.x() ;
double disY = EndPoint.y() - StartPoint.y();
double PixelAsMeterX = disX / PixelXSize ;
double PixelAsMeterY = disY / PixelYSize ;
Pixel _Pixel = new Pixel(PixelAsMeterX, PixelAsMeterY);
return _Pixel ;
}
/**
* this function convert between gps point to pixels
* @param Point represent the 3D point
* @return the pixel location
*/
public Pixel GPSPoint2Pixel(Point3D Point)
{
Point.GPS2Meter();
Pixel Worth = Pixel2Meter(FrameSize.get_PixelX(), FrameSize.get_PixelY());
double disX = Point.x() - StartPoint.x() ;
double disY = Point.y() - StartPoint.y();
double dx = disX / Worth.get_PixelX() ;
double dy = disY / Worth.get_PixelY() ;
Point.Meter2GPS();
Pixel Pix = new Pixel(dx, dy);
if(isVaildPixel(Pix))
return Pix ;
else
{
// throw new RuntimeException("The Pixel is out of bounds");
}
return Pix ;
}
/**
* this function is checking if the point is in our area
* @param p represent the pixel point
* @return true if the point is in our area
*/
private boolean isVaildPixel(Pixel p)
{
Pixel PSubtract = FrameSize.Subtract(p) ;
return PSubtract.get_PixelX() > 0 && PSubtract.get_PixelY() > 0;
}
/**
* this function calculate the correct pixels position after rescaling the picture
* @param p represent the new end point
* @param PackArr arraylist of packmans
* @param FruitArr arraylist of fruits
*/
public void ChangeFrameSize(Pixel p)
{
FrameSize.set_PixelX(p.get_PixelX());
FrameSize.set_PixelY(p.get_PixelY());
}
}
| DanielAbergel/PackmanGame | src/Maps/Map.java | 1,122 | /**
* this function calculate the correct pixels position after rescaling the picture
* @param p represent the new end point
* @param PackArr arraylist of packmans
* @param FruitArr arraylist of fruits
*/ | block_comment | en | false |
170900_5 | import java.util.ArrayList;
public class Operators_strs {
public static void main(String[] args) {
System.out.println('a'+'b'); //char is converted to it's int value (ASCII value)
//after printing garbage collection will come and take "ab" as it's no longer of any use because you've not stored it anywhere.
System.out.println("a"+"b");
System.out.println('a'+3); //97(ASCII value of 'a') + 3 = 100
System.out.println((char)('a'+3));
System.out.println("a"+1); //int will be converted to the Integer wrapper class which will call .toString()
System.out.println("Shruti" + new ArrayList<>());
System.out.println("a" + new Integer(56));
//**operator + is only defined, in Java, for primitives and if any 1 of the operand is string.
//It means you can use + with any of the complex objects but the condition is that atleast 1 object should be of type string.
//Hence, new Integer(56) + new ArrayList<>() will give error
System.out.println(new (56) + "" + new ArrayList<>()); //now it'll work //not suitable to write new Integer(56) nowadays
//Java doesn't allow you to do operator overloading like we can do in C++ & Python.
//Java avoids it because it results in poor code and it has only overloaded the + operator for strings(exception) to support concatenation.
}
}
// Output :
// 195
// ab
// 100
// d
// a1
// Shruti[]
// a56
// 56[]
| ShrutiSharma-27/STRINGS | Operators_strs.java | 408 | //It means you can use + with any of the complex objects but the condition is that atleast 1 object should be of type string. | line_comment | en | true |
170907_8 | /**
Battleship!
KU EECS 448 project 2
TeamName: BigSegFaultEnergy
* \Author: Chance Penner
* \Author: Markus Becerra
* \Author: Sarah Scott
* \Author: Thomas Gardner
* \Author: Haonan Hu
* \File: Ship.java
* \Date: 10/14/2019
* \Brief: This class serves as a the executive class of
Battleship
KU EECS 448 project 1
TeamName: Poor Yorick
* \Author: Max Goad
* \Author: Jace Bayless
* \Author: Tri Pham
* \Author: Apurva Rai
* \Author: Meet Kapadia
* \File: Ship.java
* \Brief: This class serves as a the executive class of
Battleship
*/
//Here are erternal classes that need to be imported
import java.awt.Point;
import java.util.ArrayList;
public class Ship
{
//Declare variables for the ship coordinates, ship size
private ArrayList<Point> shipCoordinates = new ArrayList<Point>();
private int shipSize;
private int shipPieces;
/*
* @ pre none
* @ param Ships' size
* @ post constuctor
* @ return none
*/
public Ship(int size)
{
this.shipSize = size;
this.shipPieces = size;
}
/*
* @ pre none
* @ param none
* @ post gets ship's size
* @ return returns ships size
*/
public int getSize()
{
return shipSize;
}
/*
* @ pre none
* @ param none
* @ post gets ships coordinates
* @ return returns ship's coordinates
*/
public ArrayList<Point> getShipCoordinates() {
return shipCoordinates;
}
/*
* @ pre none
* @ param x and y values of the grid
* @ post adds new coordinates of the ship
* @ return none
*/
public void addCoordinates(int x, int y)
{
shipCoordinates.add(new Point(x, y));
}
/*
* @ pre none
* @ param new x and y values of the grid
* @ post none
* @ return returns true or false on whether or not the ships are in line
*/
public boolean inline(int newX, int newY)
{
if (shipCoordinates.size() == 0)
{
return true;
}
for (Point shipPiece : shipCoordinates)
{
int x = (int) shipPiece.getX();
int y = (int) shipPiece.getY();
if (newX == x && (newY == y + 1 || newY == y - 1))
{
return true;
}
else if (newY == y && (newX == x + 1 || newX == x - 1))
{
return true;
}
}
return false;
}
/*
* @ pre the coordinate an opponenet entered to fire at
* @ param x and y values of the grid
* @ post decreases the number of ships because it was "attacked"
* @ return none
*/
public void hit(int x, int y)
{
shipPieces--;
}
/*
* @ pre none
* @ param x and y values of the grid
* @ post none
* @ return returns true or false on whether or not a specific coordinate exists or not
*/
public boolean containsCoordinate(int x, int y)
{
if (shipCoordinates.size() == 0)
{
return false;
}
if (x >= 0 && x <= 7 && y >= 0 && y <= 7)
{
for (int i = 0; i < shipCoordinates.size(); i++)
{
int cordX = (int) shipCoordinates.get(i).getX();
int cordY = (int) shipCoordinates.get(i).getY();
if (cordX == x && cordY == y)
{
return true;
}
}
}
return false;
}
/*
* @ pre the coordinate an opponenet entered to fire at a specific ship
* @ param none
* @ post none
* @ return returns true or false on whether or not the ship is destroyed or not
*/
public boolean isDestroyed()
{
if (shipPieces <= 0)
{
return true;
}
return false;
}
}
| ChancePenner/Battleship-Java | Ship.java | 1,031 | /*
* @ pre the coordinate an opponenet entered to fire at
* @ param x and y values of the grid
* @ post decreases the number of ships because it was "attacked"
* @ return none
*/ | block_comment | en | false |
171408_8 | import java.util.LinkedList;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* A simple work queue implementation based on the IBM developerWorks article by
* Brian Goetz. It is up to the user of this class to keep track of whether
* there is any pending work remaining.
*
* @see <a href="https://www.ibm.com/developerworks/library/j-jtp0730/">Java
* Theory and Practice: Thread Pools and Work Queues</a>
*/
public class WorkQueue {
/**
* Pool of worker threads that will wait in the background until work is
* available.
*/
private final PoolWorker[] workers;
/** Queue of pending work requests. */
private final LinkedList<Runnable> queue;
/** Used to signal the queue should be shutdown. */
private volatile boolean shutdown;
/** The default number of threads to use when not specified. */
public static final int DEFAULT = 5;
/**
* logger to see what is going on
*/
private Logger log = LogManager.getLogger(); // TODO Use keywords
/**
* variable to keep track of pending work
*/
private int pending;
/**
* Starts a work queue with the default number of threads.
*
* @see #WorkQueue(int)
*/
public WorkQueue() {
this(DEFAULT);
}
/**
* Starts a work queue with the specified number of threads.
*
* @param threads
* number of worker threads; should be greater than 1
*/
public WorkQueue(int threads) {
this.queue = new LinkedList<>();
this.workers = new PoolWorker[threads];
shutdown = false;
pending = 0;
// start the threads so they are waiting in the background
for (int i = 0; i < threads; i++) {
workers[i] = new PoolWorker();
workers[i].start();
}
}
/**
* Adds a work request to the queue. A thread will process this request when
* available.
*
* @param r work request (in the form of a {@link Runnable} object)
*/
public void execute(Runnable r) {
incrementPending();
synchronized (queue) {
queue.addLast(r);
queue.notifyAll();
log.debug("{} being added to work queue ... {} pending jobs", Thread.currentThread().getName(), pending);
}
}
/**
* Asks the queue to shutdown. Any unprocessed work will not be finished,
* but threads in-progress will not be interrupted.
*/
public void shutdown() {
// safe to do unsynchronized due to volatile keyword
shutdown = true;
synchronized (queue) {
queue.notifyAll();
}
}
/**
* Returns the number of worker threads being used by the work queue.
*
* @return number of worker threads
*/
public int size() {
return workers.length;
}
/**
* Signifies the end of work
*/
public synchronized void finish() {
while(pending > 0) {
try {
this.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
/**
* Adds to the total amount of jobs for workers to execute
*/
private synchronized void incrementPending() {
pending++;
}
/**
* Subtracts the total amount of jobs for workers to execute
*/
private synchronized void decrementPending() {
assert pending > 0;
pending--;
if (pending == 0) {
this.notifyAll();
}
}
/**
* Waits until work is available in the work queue. When work is found, will
* remove the work from the queue and run it. If a shutdown is detected, will
* exit instead of grabbing new work from the queue. These threads will
* continue running in the background until a shutdown is requested.
*/
private class PoolWorker extends Thread {
@Override
public void run() {
Runnable r = null;
while (true) {
synchronized (queue) {
while (queue.isEmpty() && !shutdown) {
try {
queue.wait();
}
catch (InterruptedException ex) {
System.err.println("Warning: Work queue interrupted while waiting.");
Thread.currentThread().interrupt();
}
}
// exit while for one of two reasons:
// (a) queue has work, or (b) shutdown has been called
if (shutdown) {
break;
}
else {
r = queue.removeFirst();
}
}
try {
log.debug("{} starting ... {} pending jobs", Thread.currentThread().getName(), pending);
r.run();
}
catch (RuntimeException ex) {
// catch runtime exceptions to avoid leaking threads
System.err.println("Warning: Work queue encountered an exception while running.");
}
finally {
decrementPending();
log.debug("{} finished ... {} pending jobs", Thread.currentThread().getName(), pending);
}
}
}
}
} | arcSoftworks/search_engine | WorkQueue.java | 1,238 | /**
* Starts a work queue with the default number of threads.
*
* @see #WorkQueue(int)
*/ | block_comment | en | false |
171629_0 | package codewars;
/**
* Created by qiank on 1/27/2016.
*/
public class GpsSpeed {
public static int gps(int s, double[] x) {
int speed = 0;
for(int i = 0; i+1 < x.length; i++)
{
double t = (x[i+1]-x[i])*3600/s; // FUCKING ANNOYING: *s/3600 is wrong
int t2 = (int)Math.floor(t);
if(t2>speed) speed = t2;
}
return speed;
}
public static void main(String args[]){
double []x = new double[] {0.0, 0.18, 0.36, 0.54, 0.72, 1.05, 1.26, 1.47, 1.92, 2.16, 2.4, 2.64, 2.88, 3.12, 3.36, 3.6, 3.84};
System.out.println(gps(20, x));
}
}
| qiankanglai/practice | src/codewars/GpsSpeed.java | 291 | /**
* Created by qiank on 1/27/2016.
*/ | block_comment | en | true |
171824_0 | package Ch8;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
/*
Measure the difference when counting long words with a parallelStream
instead of a stream . Call System.currentTimeMillis before and after the call and
print the difference. Switch to a larger document (such as War and Peace)
if you have a fast computer.
*/
public class Ex2 {
public static void main(String[] args) throws Throwable {
String contents = new String(Files.readAllBytes(Paths.get("war and peace.txt")));
List<String> words = Arrays.asList(contents.split("\\PL+"));
long start = System.currentTimeMillis();
long n = words.stream()
.filter(w -> w.length() > 12)
.count();
long end = System.currentTimeMillis();
System.out.println(end - start + "ms");
start = System.currentTimeMillis();
n = words.parallelStream()
.filter(w -> w.length() > 12)
.count();
end = System.currentTimeMillis();
System.out.println(end - start + "ms");
}
}
| siegler/CoreJavaForTheImpatient | src/Ch8/Ex2.java | 301 | /*
Measure the difference when counting long words with a parallelStream
instead of a stream . Call System.currentTimeMillis before and after the call and
print the difference. Switch to a larger document (such as War and Peace)
if you have a fast computer.
*/ | block_comment | en | false |
171981_2 | package hw8;
import java.util.*;
import hw5.DirectedLabeledEdge;
/**
* CampusPath represented an immutable path on map from location A to location B
* A campusPath is a collection of Edge of PathNode which represent the path from
* A to B if A and B is directly connected by a single road.
*
* Assume an edge from A to B is represent as [A, distance, B]:
* A path from A to D is represented as:
* [A, 0.0, A] [A, distance, B] [B, distance, C] [C, distance, D]
*
* Specification field:
* @specfield path : List of the passed-by location's coordinate and distance between them
* @specfield totalDistance: Double // Distance of a path
* @specfield totalTurns : Double // Number of turns this path has
*
* Abstract Invariant:
* A path must have at least 0 turn and at least 0 distance
*/
public class CampusPath {
/* Abstraction Function:
* AF(r) = CampusPath p such that:
* p.path = r.path
* p.totalDistance = r.totalCost
* p.totalTurns = r.size
*
* Representation Invariant:
* CampusPath != null || path != null || totalCost != null ||
* size >= 0 || totalCost >=0
*/
/**
* Checks that the representation invariant holds (if any).
*/
private void checkRep() {
assert(this != null);
assert(this.path != null);
assert(this.totalCost != null);
assert(this.size >= 0);
assert(this.totalCost >= 0);
}
private final List<DirectedLabeledEdge<PathNode, Double>> path;
private final Double totalCost;
private final int size;
/**
* @requires passed in list of pass is not null
* @param path the collection of edges that represent the location a Campus path passed by and distance between locations
* @effects Construct a new CampusPath with passed-in path
* @modifies this
* @throws IllegalArgumentException if passed in list is null
*/
public CampusPath(List<DirectedLabeledEdge<PathNode, Double>> path) {
if (path == null) {
throw new IllegalArgumentException("Campus path can not build on a null path");
}
this.path = path;
Double cost = 0.0;
for (DirectedLabeledEdge<PathNode, Double> edge : path) {
cost += edge.getLabel();
}
totalCost = cost;
size = path.size();
checkRep();
}
/**
* @return the total turns a campus path has
*/
public int getTotalTurns() {
if (size == 1) {
return 0;
} else {
return this.size - 2;
}
}
/**
* @requires n >= 0 && n < this.size
* @param turn, the number of turns at the target location
* @return the distance from location after n turns to location after n+1 turns, Double
* if path's start location and destination is the same, return 0.0 regardless the parameter
* @throws IllegalArgumentException when n < 0 || n >= this.size
*/
public Double getDistance(int n) {
if (n < 0 || n >= this.size) {
throw new IllegalArgumentException("The number of turns has to be in the range of total path turns");
}
if (this.size == 1) {
return path.get(0).getLabel();
} else {
return path.get(n+1).getLabel();
}
}
/**
* @requires n >= 0 && n < this.size
* @param turn, the number of turns at the target location
* @return the x coordinate of current start position after n turns, Double
* if path's start location and destination is the same, return start location regardless the parameter
* @throws IllegalArgumentException when n < 0 || n >= this.size
*/
public Double getStartLocationX(int n) {
if (n < 0 || n >= this.size) {
throw new IllegalArgumentException("The number of turns has to be in the range of total path turns");
}
if (this.size == 1) {
return path.get(0).getParentNode().getX();
} else {
return path.get(n+1).getParentNode().getX();
}
}
/**
* @requires n >= 0 && n < this.size
* @param turn, int the number of turns already made
* @return the y coordinate of current start position after n turns, Double
* if path's start location and destination is the same, return start location regardless the parameter
* @throws IllegalArgumentException when n < 0 || n >= this.size
*/
public Double getStartLocationY(int n) {
if (n < 0 || n >= this.size) {
throw new IllegalArgumentException("The number of turns has to be in the range of total path turns");
}
if (this.size == 1) {
return path.get(0).getParentNode().getY();
} else {
return path.get(n+1).getParentNode().getY();
}
}
/**
* @requires n >= 0 && n < this.size
* @param turn, int the number of turns already made
* @return the x coordinate of current destination position after n turns, Double
* if path's start location and destination is the same, return dest location regardless the parameter
* @throws IllegalArgumentException when n < 0 || n >= this.size
*/
public Double getDestLocationX(int n) {
if (n < 0 || n >= this.size) {
throw new IllegalArgumentException("The number of turns has to be in the range of total path turns");
}
if (this.size == 1) {
return path.get(0).getChildrenNode().getX();
} else {
return path.get(n+1).getChildrenNode().getX();
}
}
/**
* @requires n >= 0 && n < this.size
* @param turn, int the number of turns already made
* @return the y coordinate of current destination position after n turns, Double
* if path's start location and destination is the same, return dest location regardless the parameter
* @throws IllegalArgumentException when n < 0 || n >= this.size
*/
public Double getDestLocationY(int n) {
if (n < 0 || n >= this.size) {
throw new IllegalArgumentException("The number of turns has to be in the range of total path turns");
}
if (this.size == 1) {
return path.get(0).getChildrenNode().getY();
} else {
return path.get(n+1).getChildrenNode().getY();
}
}
}
| hanyax/CampusMap | hw8/CampusPath.java | 1,724 | /**
* Checks that the representation invariant holds (if any).
*/ | block_comment | en | false |
172477_2 | package spam2;
import battlecode.common.*;
import java.util.Arrays;
import java.util.Random;
public class Util {
static final Direction[] directions = {
Direction.NORTH,
Direction.NORTHEAST,
Direction.EAST,
Direction.SOUTHEAST,
Direction.SOUTH,
Direction.SOUTHWEST,
Direction.WEST,
Direction.NORTHWEST,
};
static RobotController rc;
static Robot robot;
static int getExpectedSlandererBenefit(int spawnInfluence, int spawnRound, int round1, int round2){
int perRound = slandBenefitPerRound(spawnInfluence);
int diff1 = round1 - spawnRound; int diff2 = round2 - spawnRound;
if(diff1 > 50){
return 0;
}
diff2 = Math.min(diff2, 50);
return (diff2 - diff1) * perRound;
}
static int slandBenefitPerRound(int spawnInfluence){
return (int)Math.floor(((1/50) + 0.03 * Math.exp(-0.001 * spawnInfluence)) * spawnInfluence);
}
static MapLocation copyLoc(MapLocation loc){ return loc.add(Direction.CENTER); }
// Finds the EC that spawned you
static MapLocation findAdjacentEC() throws GameActionException{
MapLocation myLoc = rc.getLocation();
for(Direction dir : directions){
MapLocation adjLoc = myLoc.add(dir);
if(!rc.canSenseLocation(adjLoc)){
continue;
}
RobotInfo info = rc.senseRobotAtLocation(adjLoc);
if(info == null){
continue;
}
if(info.team == robot.myTeam && info.type == RobotType.ENLIGHTENMENT_CENTER){
return info.location;
}
}
Log.log("Could not find adjacent EC!");
return null;
}
static boolean tryBuild(RobotType type, Direction dir, int influence) throws GameActionException {
if (rc.canBuildRobot(type, dir, influence)) {
Log.debug("Built robot of type: " + type.toString() + ", with influence: " + influence);
rc.buildRobot(type, dir, influence);
return true;
}
Log.debug("Failed to build robot of type: " + type.toString() + ", with influence: " + influence + ", in direction: " + dir.toString());
return false;
}
static DetectedInfo getClosestEnemyEC(){
int min_dist = Integer.MAX_VALUE;
DetectedInfo closest = null;
for(int i = 0; i < robot.robotLocationsIdx; i++){
// Find the closest enemy EC
DetectedInfo detected = robot.robotLocations[i];
if(detected.team != robot.myTeam.opponent() || detected.type != RobotType.ENLIGHTENMENT_CENTER){
continue;
}
int distance = robot.myLoc.distanceSquaredTo(detected.loc);
if(distance < min_dist){
closest = detected;
}
}
return closest;
}
static DetectedInfo[] getCorrespondingRobots(Team team, RobotType type, MapLocation loc){
DetectedInfo[] copy = new DetectedInfo[robot.robotLocationsIdx];
int count = 0;
for(int i = 0; i < robot.robotLocationsIdx; i++){
DetectedInfo info = robot.robotLocations[i];
if(team != null && info.team != team){
continue;
}
if(type != null && info.type != type){
continue;
}
if(loc != null && !info.loc.equals(loc)){
continue;
}
copy[count] = info;
count++;
}
DetectedInfo[] copy2 = Arrays.copyOfRange(copy, 0, count);
return copy2;
}
static boolean isGridSquare(MapLocation loc, MapLocation ECLoc){
if(getGridSquareDist(loc, ECLoc) == 1){
return false;
}
int xdiff = Math.abs(loc.x - ECLoc.x);
int ydiff = Math.abs(loc.y - ECLoc.y);
return xdiff % 2 == ydiff % 2;
}
// returns true if loc2 is CCW to loc1
static boolean isCCW(MapLocation loc1, MapLocation loc2, MapLocation center){
// https://gamedev.stackexchange.com/questions/22133/how-to-detect-if-object-is-moving-in-clockwise-or-counterclockwise-direction
return ((loc1.x - center.x)*(loc2.y - center.y) - (loc1.y - center.y)*(loc2.x - center.x)) > 0;
}
static int getGridSquareDist(MapLocation loc, MapLocation ECLoc){
int diffX = loc.x - ECLoc.x;
int diffY = loc.y - ECLoc.y;
return Math.max(Math.abs(diffX), Math.abs(diffY));
}
static Direction[] shuffleArr(Direction[] arr){
Random rand = new Random();
Direction[] copy = new Direction[arr.length];
for(int i = 0; i < arr.length; i++){
copy[i] = arr[i];
}
for (int i = 0; i < copy.length; i++) {
int randomIndexToSwap = rand.nextInt(copy.length);
Direction temp = copy[randomIndexToSwap];
copy[randomIndexToSwap] = copy[i];
copy[i] = temp;
}
return copy;
}
static boolean isSlanderer(int id) throws GameActionException {
robot.typeInQuestion = null;
Comms.checkFlag(id);
return robot.typeInQuestion == RobotType.SLANDERER;
}
}
| Aryan34/battlecode21 | src/spam2/Util.java | 1,489 | // returns true if loc2 is CCW to loc1 | line_comment | en | true |
172642_0 | public class User {
private int rank;
private int progress;
public User(){
this.rank = -8;
this.progress = 0;
}
public int getRank(){
return this.rank;
}
public int getProgress(){
return this.progress;
}
public void incProgress(int lvl){
if(lvl<-8 || lvl==0 || lvl>8){
throw new IllegalArgumentException("The rank of an activity cannot be less than 8, 0, or greater than 8!");
}
int dif;
if(lvl<this.rank){
if(lvl<0 && this.rank>0){
dif=this.rank-lvl-1;
}else{
dif=this.rank-lvl;
}
if(dif==1){
this.progress++;
}
}else{
int inc;
if(lvl>0 && this.rank<0){
inc = lvl-this.rank-1;
}else{
inc = lvl-this.rank;
}
// System.out.println(inc);
if(inc==0){
this.progress+=3;
}else{
this.progress+=10*inc*inc;
}
}
if(this.progress>=100){
// System.out.println(this.progress);
int rankInc = this.progress/100;
this.progress = this.progress%100;
while(rankInc>0){
this.rank++;
if(this.rank==0) this.rank=1;
rankInc--;
}
}
}
public String toString(){
return "User{" + "rank=" + this.rank + ", progress=" + this.progress + "}";
}
}
| wsw2025/RankingSystem | User.java | 396 | // System.out.println(inc); | line_comment | en | true |
172736_0 | /*******************************************************************************
* 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;
import polyglot.util.CodeWriter;
import polyglot.util.Position;
import polyglot.util.SerialVersionUID;
import polyglot.visit.PrettyPrinter;
/**
* A {@code Block} represents a Java block statement -- an immutable
* sequence of statements.
*/
public class Block_c extends AbstractBlock_c {
private static final long serialVersionUID = SerialVersionUID.generate();
// @Deprecated
public Block_c(Position pos, List<Stmt> statements) {
this(pos, statements, null);
}
public Block_c(Position pos, List<Stmt> statements, Ext ext) {
super(pos, statements, ext);
}
@Override
public void prettyPrint(CodeWriter w, PrettyPrinter tr) {
w.write("{");
w.unifiedBreak(4, 1, " ", 1);
w.begin(0);
super.prettyPrint(w, tr);
w.end();
w.unifiedBreak(0, 1, " ", 1);
w.write("}");
}
@Override
public Node copy(NodeFactory nf) {
return nf.Block(this.position, this.statements);
}
}
| polyglot-compiler/polyglot | src/polyglot/ast/Block_c.java | 660 | /*******************************************************************************
* 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.
******************************************************************************/ | block_comment | en | true |
173023_11 | package whatsapp;
import okhttp3.*;
import org.json.*;
import java.io.IOException;
import java.util.Base64;
public class Mpesa {
private String appKey;
private String appSecret;
public String JSONSTK="";
public Mpesa(String app_key, String app_secret){
appKey=app_key;
appSecret=app_secret;
}
public String getAppKey() {
return appKey;
}
public void setAppKey(String appKey) {
this.appKey = appKey;
}
public void setJsonKey(String jsonKey) {
this.JSONSTK = jsonKey;
}
public String getJsonKey() {
return JSONSTK;
}
public String getAppSecret() {
return appSecret;
}
public void setAppSecret(String appSecret) {
this.appSecret = appSecret;
}
public String authenticate() throws IOException {
String appKeySecret = appKey + ":" + appSecret;
byte[] bytes = appKeySecret.getBytes("ISO-8859-1");
String encoded = Base64.getEncoder().encodeToString(bytes);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials")
.get()
.addHeader("authorization", "Basic "+encoded)
.addHeader("cache-control", "no-cache")
.build();
Response response = client.newCall(request).execute();
JSONObject jsonObject=new JSONObject(response.body().string());
System.out.println(""
+ "\n First Authenticate String to print Acess Token"
+ "\n"+jsonObject.getString("access_token"));
return jsonObject.getString("access_token");
}
public String C2BSimulation( String shortCode, String commandID, String amount, String MSISDN, String billRefNumber) throws IOException {
JSONArray jsonArray=new JSONArray();
JSONObject jsonObject=new JSONObject();
jsonObject.put("ShortCode", shortCode);
jsonObject.put("CommandID", commandID);
jsonObject.put("Amount", amount);
jsonObject.put("Msisdn", MSISDN);
jsonObject.put("BillRefNumber", billRefNumber);
jsonArray.put(jsonObject);
String requestJson=jsonArray.toString().replaceAll("[\\[\\]]","");
System.out.println(requestJson);//Print JSON request
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, requestJson);
Request request = new Request.Builder()
.url("https://sandbox.safaricom.co.ke/mpesa/c2b/v1/simulate")
.post(body)
.addHeader("content-type", "application/json")
.addHeader("authorization", "Bearer "+authenticate())
.addHeader("cache-control", "no-cache")
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
return response.body().toString(); //Print Response
}
public String B2CRequest( String initiatorName, String securityCredential,String commandID, String amount, String partyA,String partyB, String remarks, String queueTimeOutURL, String resultURL, String occassion) throws IOException {
JSONArray jsonArray=new JSONArray();
JSONObject jsonObject=new JSONObject();
jsonObject.put("InitiatorName", initiatorName);
jsonObject.put("SecurityCredential", securityCredential);
jsonObject.put("CommandID", commandID);
jsonObject.put("Amount", amount);
jsonObject.put("PartyA", partyA);
jsonObject.put("PartyB", partyB);
jsonObject.put("Remarks", remarks);
jsonObject.put("QueueTimeOutURL", queueTimeOutURL);
jsonObject.put("ResultURL", resultURL);
jsonObject.put("Occassion", occassion);
jsonArray.put(jsonObject);
String requestJson=jsonArray.toString().replaceAll("[\\[\\]]","");
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, requestJson);
Request request = new Request.Builder()
.url( "https://sandbox.safaricom.co.ke/mpesa/reversal/v1/request")
.post(body)
.addHeader("content-type", "application/json")
.addHeader("authorization", "Bearer "+authenticate())
.addHeader("cache-control", "no-cache")
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
return response.body().toString();
}
public String B2BRequest( String initiatorName, String accountReference,String securityCredential,String commandID, String senderIdentifierType,String receiverIdentifierType,float amount, String partyA,String partyB, String remarks, String queueTimeOutURL, String resultURL, String occassion) throws IOException {
JSONArray jsonArray=new JSONArray();
JSONObject jsonObject=new JSONObject();
jsonObject.put("Initiator", initiatorName);
jsonObject.put("SecurityCredential", securityCredential);
jsonObject.put("CommandID", commandID);
jsonObject.put("SenderIdentifierType", senderIdentifierType);
jsonObject.put("RecieverIdentifierType",receiverIdentifierType);
jsonObject.put("Amount", amount);
jsonObject.put("PartyA", partyA);
jsonObject.put("PartyB", partyB);
jsonObject.put("Remarks", remarks);
jsonObject.put("AccountReference", accountReference);
jsonObject.put("QueueTimeOutURL", queueTimeOutURL);
jsonObject.put("ResultURL", resultURL);
jsonArray.put(jsonObject);
String requestJson=jsonArray.toString().replaceAll("[\\[\\]]","");
System.out.println(requestJson);
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, requestJson);
Request request = new Request.Builder()
.url("https://sandbox.safaricom.co.ke/safaricom/b2b/v1/paymentrequest")
.post(body)
.addHeader("content-type", "application/json")
.addHeader("authorization", "Bearer "+authenticate())
.addHeader("cache-control", "no-cache")
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
public String STKPushSimulation(String businessShortCode, String password, String timestamp,String transactionType, String amount, String phoneNumber, String partyA, String partyB, String callBackURL,String accountReference, String transactionDesc) throws IOException {
JSONArray jsonArray=new JSONArray();
JSONObject jsonObject=new JSONObject();
jsonObject.put("BusinessShortCode", businessShortCode);
jsonObject.put("Password", password);
jsonObject.put("Timestamp", timestamp);
jsonObject.put("TransactionType", transactionType);
jsonObject.put("Amount",amount);
jsonObject.put("PartyA", partyA);
jsonObject.put("PartyB", partyB);
jsonObject.put("PhoneNumber", phoneNumber);
jsonObject.put("CallBackURL", callBackURL);
jsonObject.put("AccountReference", accountReference);
jsonObject.put("TransactionDesc", transactionDesc);
jsonArray.put(jsonObject);
String requestJson=jsonArray.toString().replaceAll("[\\[\\]]","");
System.out.println(requestJson);//Print JSON request
setJsonKey(requestJson);
System.out.println("");
OkHttpClient client = new OkHttpClient();
String url="https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest";
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, requestJson);
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("content-type", "application/json")
.addHeader("authorization", "Bearer "+authenticate())
.addHeader("cache-control", "no-cache")
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
//return response.body().toString();
System.out.println(response.toString());
return response.toString();
}
public String STKPushTransactionStatus( String businessShortCode, String password, String timestamp, String checkoutRequestID) throws IOException {
JSONArray jsonArray=new JSONArray();
JSONObject jsonObject=new JSONObject();
jsonObject.put("BusinessShortCode", businessShortCode);
jsonObject.put("Password", password);
jsonObject.put("Timestamp", timestamp);
jsonObject.put("CheckoutRequestID", checkoutRequestID);
jsonArray.put(jsonObject);
String requestJson=jsonArray.toString().replaceAll("[\\[\\]]","");
System.out.println(requestJson);//Print JSON request
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, requestJson);
Request request = new Request.Builder()
.url("https://sandbox.safaricom.co.ke/mpesa/stkpushquery/v1/query")
.post(body)
.addHeader("authorization", "Bearer "+authenticate())
.addHeader("content-type", "application/json")
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
return response.body().toString();
}
public String reversal(String initiator, String securityCredential, String commandID, String transactionID, String amount, String receiverParty, String recieverIdentifierType, String resultURL,String queueTimeOutURL, String remarks, String ocassion) throws IOException {
JSONArray jsonArray=new JSONArray();
JSONObject jsonObject=new JSONObject();
jsonObject.put("Initiator", initiator);
jsonObject.put("SecurityCredential", securityCredential);
jsonObject.put("CommandID", commandID);
jsonObject.put("TransactionID", transactionID);
jsonObject.put("Amount",amount);
jsonObject.put("ReceiverParty", receiverParty);
jsonObject.put("RecieverIdentifierType", recieverIdentifierType);
jsonObject.put("QueueTimeOutURL", queueTimeOutURL);
jsonObject.put("ResultURL", resultURL);
jsonObject.put("Remarks", remarks);
jsonObject.put("Occasion", ocassion);
jsonArray.put(jsonObject);
String requestJson=jsonArray.toString().replaceAll("[\\[\\]]","");
System.out.println(requestJson);
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, requestJson);
Request request = new Request.Builder()
.url("https://sandbox.safaricom.co.ke/safaricom/reversal/v1/request")
.post(body)
.addHeader("content-type", "application/json")
.addHeader("authorization", "Bearer xNA3e9KhKQ8qkdTxJJo7IDGkpFNV")
.addHeader("cache-control", "no-cache")
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
return response.body().string();
}
public String balanceInquiry(String initiator, String commandID, String securityCredential, String partyA, String identifierType, String remarks, String queueTimeOutURL, String resultURL) throws IOException {
JSONArray jsonArray=new JSONArray();
JSONObject jsonObject=new JSONObject();
jsonObject.put("Initiator", initiator);
jsonObject.put("SecurityCredential", securityCredential);
jsonObject.put("CommandID", commandID);
jsonObject.put("PartyA", partyA);
jsonObject.put("IdentifierType",identifierType);
jsonObject.put("Remarks", remarks);
jsonObject.put("QueueTimeOutURL", queueTimeOutURL);
jsonObject.put("ResultURL", resultURL);
jsonArray.put(jsonObject);
String requestJson=jsonArray.toString().replaceAll("[\\[\\]]","");
System.out.println(requestJson);
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, requestJson);
Request request = new Request.Builder()
.url("https://sandbox.safaricom.co.ke/safaricom/accountbalance/v1/query")
.post(body)
.addHeader("content-type", "application/json")
.addHeader("authorization", "Bearer fwu89P2Jf6MB1A2VJoouPg0BFHFM")
.addHeader("cache-control", "no-cache")
.addHeader("postman-token", "2aa448be-7d56-a796-065f-b378ede8b136")
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
public String registerURL(String shortCode, String responseType, String confirmationURL, String validationURL) throws IOException {
JSONArray jsonArray=new JSONArray();
JSONObject jsonObject=new JSONObject();
jsonObject.put("ShortCode", shortCode);
jsonObject.put("ResponseType", responseType);
jsonObject.put("ConfirmationURL", confirmationURL);
jsonObject.put("ValidationURL", validationURL);
jsonArray.put(jsonObject);
String requestJson=jsonArray.toString().replaceAll("[\\[\\]]","");
System.out.println(requestJson);
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, requestJson);
Request request = new Request.Builder()
.url("https://sandbox.safaricom.co.ke/mpesa/c2b/v1/registerurl")
.post(body)
.addHeader("content-type", "application/json")
.addHeader("authorization", "Bearer "+authenticate())
.addHeader("cache-control", "no-cache")
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
return response.body().string();
}
}
| Mtemi/Whatsapp-Business-Bot-with-MPESA-Integration- | Mpesa.java | 3,306 | //sandbox.safaricom.co.ke/safaricom/reversal/v1/request") | line_comment | en | true |
173642_0 | /**
* Copyright (c) Rich Hickey. All rights reserved.
* The use and distribution terms for this software are covered by the
* Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
* which can be found in the file epl-v10.html at the root of this distribution.
* By using this software in any fashion, you are agreeing to be bound by
* the terms of this license.
* You must not remove this notice, or any other, from this software.
**/
/* rich Jan 1, 2009 */
package clojure.lang;
import java.util.Map;
public abstract class ARef extends AReference implements IRef{
protected volatile IFn validator = null;
private volatile IPersistentMap watches = PersistentHashMap.EMPTY;
public ARef(){
super();
}
public ARef(IPersistentMap meta){
super(meta);
}
protected void validate(IFn vf, Object val){
try
{
if(vf != null && !RT.booleanCast(vf.invoke(val)))
throw new IllegalStateException("Invalid reference state");
}
catch(RuntimeException re)
{
throw re;
}
catch(Exception e)
{
throw new IllegalStateException("Invalid reference state", e);
}
}
protected void validate(Object val){
validate(validator, val);
}
public void setValidator(IFn vf){
validate(vf, deref());
validator = vf;
}
public IFn getValidator(){
return validator;
}
public IPersistentMap getWatches(){
return watches;
}
synchronized public IRef addWatch(Object key, IFn callback){
watches = watches.assoc(key, callback);
return this;
}
synchronized public IRef removeWatch(Object key){
watches = watches.without(key);
return this;
}
public void notifyWatches(Object oldval, Object newval){
IPersistentMap ws = watches;
if(ws.count() > 0)
{
for(ISeq s = ws.seq(); s != null; s = s.next())
{
Map.Entry e = (Map.Entry) s.first();
IFn fn = (IFn) e.getValue();
if(fn != null)
fn.invoke(e.getKey(), this, oldval, newval);
}
}
}
}
| aaronc/clojure | src/jvm/clojure/lang/ARef.java | 611 | /**
* Copyright (c) Rich Hickey. All rights reserved.
* The use and distribution terms for this software are covered by the
* Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
* which can be found in the file epl-v10.html at the root of this distribution.
* By using this software in any fashion, you are agreeing to be bound by
* the terms of this license.
* You must not remove this notice, or any other, from this software.
**/ | block_comment | en | true |
173737_0 | package com.roy;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.StringTokenizer;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import Util.*;
import javax.servlet.http.HttpServletResponse;
public class CareerServlet extends HttpServlet {
FileInputStream fis = null;
PreparedStatement ps = null;
Connection con = null;
String name;
String email;
String position;
String phone;
String resume;
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("txt/html");
PrintWriter out = resp.getWriter();
name = req.getParameter("name");
email = req.getParameter("email");
phone = req.getParameter("mno");
position = req.getParameter("psapplied");
resume = req.getParameter("fileupload");
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/roydb","root","FgYuy*(oiTR");
String sql = "insert into career_form values(?,?,?,?,?)";
ps = con.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, phone);
ps.setString(4, position);
fis = new FileInputStream(new File(resume));
System.out.println("*************************" + fis.available());
ps.setBinaryStream(5,fis,(int)resume.length());
ps.executeUpdate();
//out.write("Thank You ," +name+ "we will response you soon !"+"<a href='index.html'>Home</a>");
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtil.cleanup(ps, con);
}
}
}
| nksharma1994/RE_Web | WEB-INF/classes/com/roy/CareerServlet.java | 579 | //localhost:3306/roydb","root","FgYuy*(oiTR"); | line_comment | en | true |
173906_1 | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0){
int n=sc.nextInt();
if(n>98){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}
}
| danu20002/code_chef_solutions | fever.java | 164 | /* Name of the class has to be "Main" only if the class is public. */ | block_comment | en | false |
174129_0 | /*
* Decompiled with CFR 0.152.
*/
public class dH {
private String a;
private String b;
public dH(String string, String string2) {
this.a = string.replaceAll("&", "\u00a7");
this.b = string2.replaceAll("&", "\u00a7");
}
public String a() {
return this.b;
}
public String b() {
return this.a;
}
}
| n3xtbyte/deadcode-source | dH.java | 114 | /*
* Decompiled with CFR 0.152.
*/ | block_comment | en | true |
174266_13 | package polygon;
//import polygon.Point3D;
import java.awt.*;
public class BezierCurve {
public static final int START_POINT = 0x01;
public static final int END_POINT = 0x02;
public static final int START_HELP_POINT = 0x04;
public static final int END_HELP_POINT = 0x08;
// p0: start of the curve
// p3: end of the curve
// p1: help-point of p0
// p2: help-point of p3
private Point3D
p0,
p1,
p2,
p3;
private int
CurveIntervalls = 20,
width,
height;
private Color
CurveColor = Color.black,
HelplineColor = Color.green;
private int visiblePointSize = 5;
public BezierCurve(int width, int height) {
this( new Point3D( width/8, 5*height/8, 0), // p0
new Point3D( 7*width/8, 5*height/8, 0), // p3
new Point3D( 3*width/8, height/4, 0), // p1
new Point3D( 5*width/8, height/4, 0), // p2
width,
height
);
}
public BezierCurve( Point3D startPoint,
Point3D endPoint,
Point3D startHelpPoint,
Point3D endHelpPoint,
int width,
int height ) {
this.width = width;
this.height = height;
this.p0 = startPoint;
this.p3 = endPoint;
this.p1 = startHelpPoint;
this.p2 = endHelpPoint;
}
public BezierCurve( Rectangle bounds ) {
//this.width = width;
//this.height = height;
this.p0 = new Point3D( bounds.getX(),
bounds.getY() + bounds.getHeight(),
0.0 );
this.p3 = new Point3D( bounds.getX() + bounds.getWidth(),
bounds.getY() + bounds.getHeight(),
0.0 );
this.p1 = new Point3D( p0.getX() + bounds.getWidth()*0.25,
p0.getY() - bounds.getHeight(),
0.0 );
this.p2 = new Point3D( p3.getX() - bounds.getWidth()*0.25,
p3.getY() - bounds.getHeight(),
0.0 );
}
public BezierCurve( Point3D startPoint,
Point3D endPoint,
Point3D startHelpPoint,
Point3D endHelpPoint ) {
this( startPoint,
endPoint,
startHelpPoint,
endHelpPoint,
(int)(endPoint.getX()-startPoint.getX()),
(int)(endPoint.getY()-startPoint.getY())
);
}
public Point3D getStartPoint() {
return this.p0;
}
public Point3D getEndPoint() {
return this.p3;
}
public Point3D getStartHelpPoint() {
return this.p1;
}
public Point3D getEndHelpPoint() {
return this.p2;
}
public void setVisiblePointSize( int size ) {
this.visiblePointSize = size;
}
private void drawRelativePoint( Graphics g,
Point3D p,
int size,
Point3D origin,
Point3D scaling ) {
g.fillRect( (int)(p.getX()*scaling.getX()-size/2.0 + origin.getX()),
(int)(p.getY()*scaling.getY()-size/2.0 + origin.getY()),
size, size );
}
private void drawRelativeLine( Graphics g,
Point3D a,
Point3D b,
Point3D origin,
Point3D scaling ) {
g.drawLine( (int)(a.getX()*scaling.getX() + origin.getX()),
(int)(a.getY()*scaling.getY() + origin.getY()),
(int)(b.getX()*scaling.getX() + origin.getX()),
(int)(b.getY()*scaling.getY() + origin.getY())
);
}
public void update(Graphics g, Point3D origin, Point3D scaling ) {
double
x1 = p0.getX(), // p0.getXMiddlePosition(),
y1 = p0.getY(), // p0.getYMiddlePosition(),
x2, y2,
CurveStep = 1.0/(double)CurveIntervalls,
u= CurveStep;
//u=(CurveStep * (scaling.getX()+scaling.getY())/2.0); // use average scaling
g.setColor(HelplineColor);
// draw the helpline between the start and the end of the Curve
// WHY?
//drawRelativeLine( g, p0, p3, origin );
// draw the helplines between the startpoint and the first helppoint and
// between the endpoint an the secound helppoint
drawRelativeLine( g, p0, p1, origin, scaling );
drawRelativeLine( g, p3, p2, origin, scaling );
// Draw the points themselves
drawRelativePoint( g, p0, this.visiblePointSize, origin, scaling );
drawRelativePoint( g, p1, this.visiblePointSize, origin, scaling );
drawRelativePoint( g, p2, this.visiblePointSize, origin, scaling );
drawRelativePoint( g, p3, this.visiblePointSize, origin, scaling );
g.setColor(CurveColor);
// draw the Bezier Curve in CurveIntervall Steps
for (int i=0; i<CurveIntervalls; i++) {
x2 = p0.getX()*Math.pow(1.0-u,3)+p1.getX()*3*u*Math.pow(1.0-u,2)
+ p2.getX()*3*Math.pow(u,2)*(1.0-u)+p3.getX()*Math.pow(u,3);
y2 = p0.getY()*Math.pow(1.0-u,3)+p1.getY()*3*u*Math.pow(1.0-u,2)
+p2.getY()*3*Math.pow(u,2)*(1.0-u)+p3.getY()*Math.pow(u,3);
//g.drawLine((int)x1, (int)y1, (int)x2, (int)y2);
drawRelativeLine( g,
new Point3D(x1,y1,0),
new Point3D(x2,y2,0),
origin,
scaling );
x1=x2;
y1=y2;
u+=CurveStep;
}
//paintComponents(g);
}
public void paint(Graphics g) {
paint( g, new Point3D(), new Point3D(1.0,1.0,0.0) );
}
public void paint( Graphics g, Point3D origin, Point3D scaling ) {
update(g, origin, scaling);
}
}
| IkarosKappler/extrusiongen | BezierCurve.java | 1,704 | //u=(CurveStep * (scaling.getX()+scaling.getY())/2.0); // use average scaling | line_comment | en | true |
174402_0 | import java.util.ArrayList;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.util.ArrayList;
import java.util.Scanner;
enum Color {
RED, GREEN
}
abstract class Tree {
private int value;
private Color color;
private int depth;
public Tree(int value, Color color, int depth) {
this.value = value;
this.color = color;
this.depth = depth;
}
public int getValue() {
return value;
}
public Color getColor() {
return color;
}
public int getDepth() {
return depth;
}
public abstract void accept(TreeVis visitor);
}
class TreeNode extends Tree {
private ArrayList<Tree> children = new ArrayList<>();
public TreeNode(int value, Color color, int depth) {
super(value, color, depth);
}
public void accept(TreeVis visitor) {
visitor.visitNode(this);
for (Tree child : children) {
child.accept(visitor);
}
}
public void addChild(Tree child) {
children.add(child);
}
}
class TreeLeaf extends Tree {
public TreeLeaf(int value, Color color, int depth) {
super(value, color, depth);
}
public void accept(TreeVis visitor) {
visitor.visitLeaf(this);
}
}
abstract class TreeVis
{
public abstract int getResult();
public abstract void visitNode(TreeNode node);
public abstract void visitLeaf(TreeLeaf leaf);
}
class SumInLeavesVisitor extends TreeVis { int result=0;
public int getResult() {
return result;
}
public void visitNode(TreeNode node) {
}
public void visitLeaf(TreeLeaf leaf) {
result+=leaf.getValue();
}
}
class ProductOfRedNodesVisitor extends TreeVis { long result=1L;
public int getResult() {
return (int)result;
}
public void visitNode(TreeNode node) {
if(node.getColor()==Color.RED){
result= (result * node.getValue()) % (1000000007);
}
}
public void visitLeaf(TreeLeaf leaf) {
if(leaf.getColor()==Color.RED){
result= (result * leaf.getValue()) % (1000000007);
}
}
}
class FancyVisitor extends TreeVis { int sumOfNode=0; int sumOfLeaf=0; public int getResult() { return Math.abs(sumOfNode-sumOfLeaf); }
public void visitNode(TreeNode node) {
if(node.getDepth()%2==0){
sumOfNode+=node.getValue();
}
}
public void visitLeaf(TreeLeaf leaf) {
if(leaf.getColor()==Color.GREEN){
sumOfLeaf+=leaf.getValue();
}
}
}
public class Solution {
public static Tree solve() {
//read the tree from STDIN and return its root as a return value of this function
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] vals = new int[n];
for(int i=0; i<n; i++){
vals[i]= sc.nextInt();
}
Color[] colors = new Color[n];
for(int i=0; i<n; i++){
colors[i]= sc.nextInt()==1? Color.GREEN:Color.RED;
}
Map<Integer, Set<Integer>> nodeEdges = new HashMap<>();
for(int i=0; i<n-1; i++){
int u = sc.nextInt();
int v = sc.nextInt();
if(!nodeEdges.containsKey(u)){
nodeEdges.put(u,new HashSet<Integer>());
}
if(!nodeEdges.containsKey(v)){
nodeEdges.put(v,new HashSet<Integer>());
}
nodeEdges.get(u).add(v);
nodeEdges.get(v).add(u);
}
Map<TreeNode, Integer> nodeIndexMap = new HashMap<>();
List<TreeNode> parents = new ArrayList<>();
TreeNode root = new TreeNode(vals[0],colors[0],0);
nodeIndexMap.put(root,1);
parents.add(root);
while(!parents.isEmpty()){
List<TreeNode> nextLevelParents = new ArrayList<>();
for(TreeNode node : parents){
int depth = node.getDepth();
int parentIndex = nodeIndexMap.get(node);
for(int childIndex: nodeEdges.get(parentIndex)){
nodeEdges.get(childIndex).remove(parentIndex);
if(!nodeEdges.get(childIndex).isEmpty()){
TreeNode child = new TreeNode(vals[childIndex-1], colors[childIndex-1],depth+1);
nextLevelParents.add(child);
nodeIndexMap.put(child, childIndex);
node.addChild(child);
}else{
TreeLeaf leaf = new TreeLeaf(vals[childIndex-1], colors[childIndex-1],depth+1);
node.addChild(leaf);
}
}
}
parents = nextLevelParents;
}
sc.close();
return root;
}
public static void main(String[] args) {
Tree root = solve();
SumInLeavesVisitor vis1 = new SumInLeavesVisitor();
ProductOfRedNodesVisitor vis2 = new ProductOfRedNodesVisitor();
FancyVisitor vis3 = new FancyVisitor();
root.accept(vis1);
root.accept(vis2);
root.accept(vis3);
int res1 = vis1.getResult();
int res2 = vis2.getResult();
int res3 = vis3.getResult();
System.out.println(res1);
System.out.println(res2);
System.out.println(res3);
}
}
| AnujPawaadia/HackerRank | day74.java | 1,397 | //read the tree from STDIN and return its root as a return value of this function | line_comment | en | false |
174553_6 | __________________________________________________________________________________________________
sample 0 ms submission
class Solution {
public int kthSmallest(int[][] matrix, int k) {
// use binaru search
// the array is not fully sorted
// but when we know lo and hi, we could always know how many entries
// are smaller than mid (in an efficient way), and redefine the search range
int row = matrix.length, col = matrix[0].length;
int lo = matrix[0][0], hi = matrix[row-1][col-1];
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
// now count how many entries are smaller than mid
// you may count row by row, or another way
int count = getLessOrEqual(matrix, mid);
if (count < k) lo = mid + 1;
else hi = mid;
}
// how can you make sure that lo is one of the elements in the matrix?
return lo;
}
private int getLessOrEqual(int[][] matrix, int target) {
// this function is very interesting!
// think about how it works!
int i = matrix.length - 1, j = 0;
int res = 0;
while (i >= 0 && j < matrix[0].length) {
if (matrix[i][j] > target) {
i --;
} else {
res += i + 1;
j++;
}
}
return res;
}
}
__________________________________________________________________________________________________
sample 38732 kb submission
class Solution {
public int kthSmallest(int[][] M, int k) {
int n = M.length;
PriorityQueue<Tuple> Q = new PriorityQueue<>(10000, (a, b) -> M[a.r][a.c] - M[b.r][b.c]);
Tuple t = new Tuple(0, 0);
Q.add(t);
while (k-- > 0) {
t = Q.remove();
if (t.r + 1 < n)
Q.add(new Tuple(t.r + 1, t.c));
if (t.r == 0 && t.c + 1 < n)
Q.add(new Tuple(t.r, t.c + 1));
}
return M[t.r][t.c];
}
class Tuple {
int r;
int c;
Tuple(int r, int c) {
this.r = r;
this.c = c;
}
}
}
__________________________________________________________________________________________________
| strengthen/LeetCode | Java/378.java | 590 | // how can you make sure that lo is one of the elements in the matrix? | line_comment | en | false |
174555_0 | /*
* Solution to Project Euler problem 106
* Copyright (c) Project Nayuki. All rights reserved.
*
* https://www.nayuki.io/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/
import java.math.BigInteger;
public final class p106 implements EulerSolution {
public static void main(String[] args) {
System.out.println(new p106().run());
}
/*
* Lemma to confirm denominator:
* For each natural number n >= 2, any set of size n has exactly
* (3^n + 1) / 2 - 2^n unordered pairs of non-empty disjoint subsets.
* Proof:
* 0. Let A be an arbitrary set of size n. We want to count its subset pairs.
* 1. Suppose we can label each element of A with a letter from the set {B, C, N}.
* A label is defined as an n-tuple of letters from the set {B, C, N}.
* For example, the set {a,b,c,d} can be labeled as (B,B,C,N) or (N,C,N,N).
* 2. Let L be the set of all possible labels on A. We know that |L| = 3^n.
* 3. If a label doesn't contain any B's, then it is equivalent to saying that the
* label is composed of any number of C's and N's, so there are 2^n of them.
* 4. If a label doesn't contain any C's, then it is equivalent to saying that the
* label is composed of any number of B's and N's, so there are 2^n of them.
* 5. If a label doesn't contain any B's or C's, then it is the singleton of all N's.
* 6. How many labels contain at least one B and at least one C?
* Using the inclusion-exclusion principle, we have:
* |Have B and Have C| = |All labels| - |Lacks B or Lacks C|
* = |All labels| - (|Lacks B| + |Lacks C| - |Lacks B and Lacks C|)
* = |All labels| - |Lacks B| - |Lacks C| + |Lacks B and Lacks C|
* = 3^n - 2^n - 2^n + 1.
* 7. For an arbitrary label that has at least one B and at least one C,
* what actually matters is which elements of A are put into one subset
* and which elements of A are put into the other disjoint subset, but
* the names of these subsets as B and C are interchangeable. Hence we
* divide by 2 to remove this degree of freedom, giving us a final count
* of (3^n - 2^n - 2^n + 1) / 2 = (3^n + 1) / 2 - 2^n.
* Corollary:
* This confirms some values mentioned in the problem statement:
* - Set size n = 7 has 966 subset pairs.
* - Set size n = 12 has 261625 subset pairs.
*
*
* Main theorem:
* Let A be an arbitrary set such that all of the following hold:
* - Its size is n.
* - It consists only of positive integers.
* - It satisfies the property (ii) given in the problem statement.
* - a0 < a1 < ... < a_{n-1} are all the elements of A listed in ascending order.
* To verify property (i), we would need to test some number of unordered pairs
* of non-empty disjoint subsets of A to see that the subsets have unequal sums
* Then we claim that exactly this many pairs need to be tested for equality:
* The summation of (n choose 2k) * [(2k choose k) / 2 - (2k choose k) / (k + 1)]
* for k from 2 to floor(n / 2) (inclusive).
*
* Proof:
* We begin by arguing about what subset pairs don't need to be tested,
* then progress to counting which subset pairs do and don't need to be tested.
*
* Let B and C be an arbitrary pair of non-empty disjoint subsets of A.
* Furthermore, restrict the pair (and prevent duplicate counting) so that
* the smallest element of B is smaller than the smallest element of C.
* Assume that for each element of B and C, we know what index of A
* it comes from, but we don't look at the actual element's value.
*
* If sets B and C have different sizes, then property (ii) implies that
* either S(B) < S(C) or S(B) > S(C), which in both cases imply S(B) != S(C).
* Hence we only care about the cases where |B| = |C|.
*
* If |B| = |C| = 1, then we know by disjointness that S(B) != S(C).
* (Namely because each set has a different singleton element.)
*
* For the interesting case, we have |B| = |C| >= 2. If we can match each
* element of B to a unique larger element in C, then we know for sure that
* S(B) < S(C), which further implies that S(B) != S(C). When we find such
* a matching, the ordering of the elements of A already implies inequality,
* without the need to examine the actual element values.
*
* To illustrate with a concrete example, suppose B = {a0,a1} and C = {a2,a3}
* are subsets of some set A. For each element of the set B or C, we are
* assumed to know what index of A the element came from. Because we know
* a0 < a2 and a1 < a3, we add these inequalities to get S(B) = a0 + a1
* < a2 + a3 = S(C), implying S(B) != S(C). Similarly, with B = {a0,a2} and
* C = {a1,a3}, we have a0 < a1 and a2 < a3, leading to a0 + a2 < a1 + a3.
* But in the case of B = {a0,a3} and C = {a1,a2}, we cannot conclude
* whether S(B) equals S(C) without examining the actual element values.
*
* Let's imagine scanning the elements of A in ascending order. When we
* encounter an element a_i that is:
* - In B, then we push it onto a stack, remembering that we need to
* pair it with a later (and thus larger) element that is in C.
* - In C, then we consult the stack. If the stack is empty, then this
* element cannot be paired with an earlier (and thus smaller) element that
* is in B, so no match exists. Otherwise we pop one element from the stack.
* - Not in B or C, then we ignore it because it plays no role in the sums.
*
* Suppose we lay out the elements of A as a sequence, and label each element
* according to the subsets B and C in a particular way. If element a_i is in B,
* then label it as ( (left parenthesis). If element a_i is in C, then label it
* as ) (right parenthesis). Otherwise label it as nothing/space.
*
* To illustrate, suppose A has size 5, B = {a0,a1}, and C = {a2,a3}.
* Then this pair of subsets corresponds with the label "(( ))" on A.
*
* We can see that a pair of subsets doesn't need to be tested if
* its label corresponds to a string of balanced parentheses. This is
* a well-known combinatorics problem (which I won't try to prove):
* The Catalan number C_k = (2k choose k) / (k + 1) represents the
* number of ways that k pairs of parentheses can be arranged in a
* sequence to produce a proper expression (i.e. no prefix contains
* more right parentheses than left parentheses).
*
* There are (n choose 2k) ways to choose elements from A that will
* then be split among the subsets B and C. Focus on one arbitrary choice.
*
* Subsequently, there are (2k choose k) / 2 ways to put k of those
* elements into B and k of those elements into C, but without
* regards to the ordering of B and C.
*
* However, C_k = (2k choose k) / (k + 1) of those choices of subset
* pairs will necessarily have unequal sums due to the ordering of
* elements, hence they don't need to be tested.
*
* This means that for a given k >= 2, we need to test (n choose 2k)
* * ((2k choose k) / 2 - (2k choose k) / (k + 1)) subset pairs.
*
* Finally, we sum this term for k = 2, 3, 4, ... as long as 2k <= n,
* so that we consider all the sizes of k where we can take a pair
* of k-sized disjoint subsets of A.
*
* Corollary:
* Although the derivation/justification is long, the amount of
* arithmetic is small enough to be doable by hand calculation.
*/
private static final int SET_SIZE = 12;
public String run() {
BigInteger ans = BigInteger.ZERO;
for (int i = 2; i * 2 <= SET_SIZE; i++) {
BigInteger x = Library.binomial(SET_SIZE, i * 2);
BigInteger y = Library.binomial(i * 2, i).shiftRight(1);
BigInteger z = Library.binomial(i * 2, i).divide(BigInteger.valueOf(i + 1)); // Catalan number
ans = ans.add(x.multiply(y.subtract(z)));
}
return ans.toString();
}
}
| nayuki/Project-Euler-solutions | java/p106.java | 2,541 | /*
* Solution to Project Euler problem 106
* Copyright (c) Project Nayuki. All rights reserved.
*
* https://www.nayuki.io/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/ | block_comment | en | true |
174593_0 | /*
Below we will define an n-interesting polygon. Your task is to find the area of a polygon for a given n.
A 1-interesting polygon is just a square with a side of length 1. An n-interesting polygon is obtained by taking the n - 1-interesting polygon and appending 1-interesting polygons to its rim, side by side. You can see the 1-, 2-, 3- and 4-interesting polygons in the picture below.
Example
For n = 2, the output should be
shapeArea(n) = 5;
For n = 3, the output should be
shapeArea(n) = 13.
*/
int shapeArea(int n) {
int num = 1;
for(int i = 1; i <= n; i++){
num = num + (4 * (i-1));
}
return num;
}
| AntDuPar/Codesignal-Leetcode-Questions | shapeArea.java | 218 | /*
Below we will define an n-interesting polygon. Your task is to find the area of a polygon for a given n.
A 1-interesting polygon is just a square with a side of length 1. An n-interesting polygon is obtained by taking the n - 1-interesting polygon and appending 1-interesting polygons to its rim, side by side. You can see the 1-, 2-, 3- and 4-interesting polygons in the picture below.
Example
For n = 2, the output should be
shapeArea(n) = 5;
For n = 3, the output should be
shapeArea(n) = 13.
*/ | block_comment | en | true |
176358_1 | /*
* FlatFS -- flat file system
*
* You must follow the coding standards distributed
* on the class web page.
*
* (C) 2007 Mike Dahlin
*
*/
import java.io.IOException;
import java.io.EOFException;
public class FlatFS{
public static final int ASK_MAX_FILE = 2423;
public static final int ASK_FREE_SPACE_BLOCKS = 29542;
public static final int ASK_FREE_FILES = 29545;
public static final int ASK_FILE_METADATA_SIZE = 3502;
public static final byte EOF = (byte)28;
private PTree ptree;
public FlatFS(boolean doFormat)
throws IOException
{
this.ptree = new PTree(doFormat);
}
public TransID beginTrans()
{
return ptree.beginTrans();
}
public void commitTrans(TransID xid)
throws IOException, IllegalArgumentException
{
ptree.commitTrans(xid);
}
public void abortTrans(TransID xid)
throws IOException, IllegalArgumentException
{
ptree.abortTrans(xid);
}
public int createFile(TransID xid)
throws IOException, IllegalArgumentException
{
return ptree.createTree(xid); //tnum and inumber will be the same.
}
public void deleteFile(TransID xid, int inumber)
throws IOException, IllegalArgumentException
{
ptree.deleteTree(xid, inumber);
}
public int read(TransID xid, int inumber, int offset, int count, byte buffer[])
throws IOException, IllegalArgumentException, EOFException
{
int startBlock = Helper.paddedDiv(offset, PTree.BLOCK_SIZE_BYTES);
byte[][] blocks = new byte[Helper.paddedDiv(count, PTree.BLOCK_SIZE_BYTES)][PTree.BLOCK_SIZE_BYTES];
if (startBlock > ptree.getMaxDataBlockId(xid, inumber))
throw new EOFException();
for(int i = 0; i < blocks.length; i++)
ptree.readData(xid, inumber, startBlock+i, blocks[i]);
for (int i = 0; i < count; i++) {
buffer[i] = blocks[i/PTree.BLOCK_SIZE_BYTES][i%PTree.BLOCK_SIZE_BYTES];
if (buffer[i] == EOF)
return i+1;
}
return count;
}
public void write(TransID xid, int inumber, int offset, int count, byte buffer[])
throws IOException, IllegalArgumentException
{
int startBlock = Helper.paddedDiv(offset, PTree.BLOCK_SIZE_BYTES);
byte[][] blocks = new byte[Helper.paddedDiv(count, PTree.BLOCK_SIZE_BYTES)][PTree.BLOCK_SIZE_BYTES];
for (int i =0; i < buffer.length; i++) {
blocks[i/PTree.BLOCK_SIZE_BYTES][i%PTree.BLOCK_SIZE_BYTES] = buffer[i];
}
for (int i = 0; i < blocks.length; i++)
ptree.writeData(xid, inumber, startBlock + i, blocks[i]);
}
public void readFileMetadata(TransID xid, int inumber, byte buffer[])
throws IOException, IllegalArgumentException
{
ptree.readTreeMetadata(xid, inumber, buffer);
}
public void writeFileMetadata(TransID xid, int inumber, byte buffer[])
throws IOException, IllegalArgumentException
{
ptree.writeTreeMetadata(xid, inumber, buffer);
}
public int getParam(int param)
throws IOException, IllegalArgumentException
{
if (param == ASK_MAX_FILE)
return ptree.getParam(PTree.ASK_FREE_TREES);
else if (param == ASK_FILE_METADATA_SIZE)
return ptree.METADATA_SIZE;
else if (param == ASK_FREE_FILES)
return ptree.getParam(PTree.ASK_FREE_TREES);
else if (param == ASK_FREE_SPACE_BLOCKS)
return ptree.getParam(PTree.ASK_FREE_SPACE);
else
throw new IllegalArgumentException();
}
}
| ProCynic/lab-FS | FlatFS.java | 999 | //tnum and inumber will be the same.
| line_comment | en | true |
176496_0 | /**
* Author Jack
*
* The purpose of this class is control the program flow, change panels and call
* to save/load program data on close/open.
*/
//Project Package
package cse_360_project;
//Necessary Imports
import javax.swing.JFrame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Main {
public static void main(String[] args) {
RecordManager.getInstanceOf().load("WorkoutRecord.ser","MetricRecord.ser");
//Build the central JFrame and fill with WindowListeners and closing procedures
final JFrame frame = new JFrame("Wicket Health Tracker");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
RecordManager.getInstanceOf().save("WorkoutRecord.ser","MetricRecord.ser");
frame.dispose();
System.exit(0);
}
});
//Display the program
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setSize(1440, 850);
frame.setVisible(true);
}
}
| wickethealthtracker/team8 | Main.java | 267 | /**
* Author Jack
*
* The purpose of this class is control the program flow, change panels and call
* to save/load program data on close/open.
*/ | block_comment | en | true |
177086_0 | /****************************
* This file is part of the MobiPerf project (http://mobiperf.com).
* We make it open source to help the research community share our efforts.
* If you want to use all or part of this project, please give us credit and cite MobiPerf's official website (mobiperf.com).
* The package is distributed under license GPLv3.
* If you have any feedbacks or suggestions, don't hesitate to send us emails ([email protected]).
* The server suite source code is not included in this package, if you have specific questions related with servers, please also send us emails
*
* Contact: [email protected]
* Development Team: Junxian Huang, Birjodh Tiwana, Zhaoguang Wang, Zhiyun Qian, Cheng Chen, Yutong Pei, Feng Qian, Qiang Xu
* Copyright: RobustNet Research Group led by Professor Z. Morley Mao, (Department of EECS, University of Michigan, Ann Arbor) and Microsoft Research
*
****************************/
package com.mobiperf.ui;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import com.mobiperf.R;
public class Thanks extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thanks);
findViewById(R.id.tpa_btn_stop).setOnClickListener(
new View.OnClickListener() {
// @Override
public void onClick(View v) {
SharedPreferences settings = getSharedPreferences("pref", 0);
SharedPreferences.Editor spe = settings.edit();
spe.putBoolean("canUpload", false);
spe.commit();
Intent intent = new Intent(getActivity(), com.mobiperf.service.TcpdumpService.class);
stopService(intent);
finish();
}
});
}
protected Activity getActivity() {
return this;
}
/******************** Menu ends here ********************/
}
| quietbamboo/MobiPerfUmich | client/src/com/mobiperf/ui/Thanks.java | 507 | /****************************
* This file is part of the MobiPerf project (http://mobiperf.com).
* We make it open source to help the research community share our efforts.
* If you want to use all or part of this project, please give us credit and cite MobiPerf's official website (mobiperf.com).
* The package is distributed under license GPLv3.
* If you have any feedbacks or suggestions, don't hesitate to send us emails ([email protected]).
* The server suite source code is not included in this package, if you have specific questions related with servers, please also send us emails
*
* Contact: [email protected]
* Development Team: Junxian Huang, Birjodh Tiwana, Zhaoguang Wang, Zhiyun Qian, Cheng Chen, Yutong Pei, Feng Qian, Qiang Xu
* Copyright: RobustNet Research Group led by Professor Z. Morley Mao, (Department of EECS, University of Michigan, Ann Arbor) and Microsoft Research
*
****************************/ | block_comment | en | true |
177866_5 | package selenium;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Methods {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\Files\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
//Methods
System.out.println(driver.getTitle()); //Get title of current webpage
System.out.println(driver.getCurrentUrl()); //Get Current Url of webpage for validation
System.out.println(driver.getPageSource()); //Get Page Source *(it helpful in some situation, where right click on webpage is disable)
driver.close();
}
}
| katejay/Selenium-Exercise | Basics/Methods.java | 204 | //Get Page Source *(it helpful in some situation, where right click on webpage is disable)
| line_comment | en | false |
177883_1 | /*
"In computing, End Of File (commonly abbreviated EOF) is a condition in a computer operating system where no more data can be read from a data source." โ (Wikipedia: End-of-file)
The challenge here is to read n lines of input until you reach EOF, then number and print all n lines of content.
Hint: Java's Scanner.hasNext() method is helpful for this problem.
Input Format
Read some unknown n lines of input from stdin(System.in) until you reach EOF; each line of input contains a non-empty String.
Output Format
For each line, print the line number, followed by a single space, and then the line content received as input:
k This is the line read as input for line number 'k'.
Sample Input
Hello world
I am a file
Read me until end-of-file.
Sample Output
1 Hello world
2 I am a file
3 Read me until end-of-file.
*/
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc=new Scanner(System.in);
int i = 1;
while(sc.hasNext())
{
System.out.println(i+" "+sc.nextLine());
i++;
}
}
} | HevaWu/Leetcode | Java_End_Of_File.java | 360 | /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ | block_comment | en | true |
178089_5 | import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* Created by Lee-or on 02/10/2017.
*/
public class Map {
private BufferedImage mapBuffImg;
private byte[][] binaryMap;
private List<Point> criticalPoints;
public Map(BufferedImage givenMap){
this.mapBuffImg = givenMap;
this.criticalPoints = null;
}
/*TODO maybe "pixels" should be a given argument..*/
private byte[][] fromImageToBinaryArray(BufferedImage image){
//BufferedImage image = ImageIO.read(new File("/some.jpg"));
int width = image.getWidth();
int height = image.getHeight();
byte[][] pixels = new byte[width][];
for (int x = 0; x < width; ++x) {
pixels[x] = new byte[height];
for (int y = 0; y < height; ++y) {
pixels[x][y] = (byte) (image.getRGB(x, y) == 0xFFFFFFFF ? 0 : 1);
}
}
return pixels;
}
// "All BufferedImage objects have an upper left corner coordinate of (0, 0)." (javadoc)
// x- row, y- col => x- width, y- height.
/**
* firstPixelOfAnObstacle
* @param map
* @param x x coordinate of the pixel the user wishes to check.
* @param y y coordinate of the pixel the user wishes to check.
* @param width width of the map.
* @param height the height of the map.
* @return true if the given pixel is a critical point. Otherwise, false.
*/
/*TODO --PROBLEM-- this algorithm returns false if there are more than 1 pixel in row in the same column */
/*TODO this algorithm doesn't verify that there are no 2 critical points in the same vertical line*/
private boolean firstPixelOfAnObstacle(byte[][] map, int x, int y, int width, int height){
//if()
}
/**
* findCriticalPointsInMap.
* @return array which holds the coordinates of all critical points in this Map.
*/
private void findCriticalPointsInMap(){
int height = this.mapBuffImg.getHeight();
int width= this.mapBuffImg.getWidth();
for(int i=0; i<height; ++i){
for (int j=0; j<width; ++j){
}
}
}
public List<Point> getCriticalPoints(){
if(this.criticalPoints == null){
this.criticalPoints = new LinkedList<Point>();
this.findCriticalPointsInMap();
}
return getCopyOfCriticalPointsList();
}
/**
* getCopyOfCriticalPointsList.
* @return the copy of the 'criticalPoints' list.
*/
private List<Point> getCopyOfCriticalPointsList(){
List<Point> cloneList = new ArrayList<Point>();
for(Point point : this.criticalPoints) {
cloneList.add(point.clone());
}
return cloneList;
}
}
| Lee-or/find_critical_points | src/Map.java | 726 | /**
* firstPixelOfAnObstacle
* @param map
* @param x x coordinate of the pixel the user wishes to check.
* @param y y coordinate of the pixel the user wishes to check.
* @param width width of the map.
* @param height the height of the map.
* @return true if the given pixel is a critical point. Otherwise, false.
*/ | block_comment | en | false |
178294_0 | import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* https://open.kattis.com/problems/musicalchairs/
*
* @author brunovolpato
*/
public class MusicalChairs {
public static int solve(InputStream is) {
Scanner sc = new Scanner(is);
int n = sc.nextInt();
List<Professor> professors = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
Professor professor = new Professor();
professor.id = i + 1;
professor.opus = sc.nextInt();
professors.add(professor);
}
int pos = 0;
while (professors.size() > 1) {
Professor current = professors.get(pos % professors.size());
int opus = current.opus;
pos = (pos + opus - 1) % professors.size();
professors.remove(pos);
}
return professors.get(0).id;
}
public static void main(String[] args) {
System.out.println(solve(System.in));
}
}
class Professor {
int id;
int opus;
}
| bvolpato/kattis | java/MusicalChairs.java | 323 | /**
* https://open.kattis.com/problems/musicalchairs/
*
* @author brunovolpato
*/ | block_comment | en | true |
178308_9 | /*
* 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 edu.ufp.inf.aed2.project1;
/**
*
* @author Bruno Silva
*/
public class Artista {
String username;
String nome;
String generomusical;
private RedBlackBST_Projecto<String, Musica> artistMusicSt = new RedBlackBST_Projecto<>();//Musica deste artista
/**
*
* @param username
* @param nome
* @param generomusical
*/
public Artista(String username, String nome, String generomusical) {
this.username = username;
this.nome = nome;
this.generomusical = generomusical;
}
/**
*
* @return
*/
public String getUsername() {
return username;
}
/**
*
* @param username
*/
public void setUsername(String username) {
this.username = username;
}
/**
*
* @return
*/
public String getNome() {
return nome;
}
/**
*
* @param nome
*/
public void setNome(String nome) {
this.nome = nome;
}
/**
*
* @return
*/
public String getGeneromusical() {
return generomusical;
}
/**
*
* @param generomusical
*/
public void setGeneromusical(String generomusical) {
this.generomusical = generomusical;
}
/**
*
* @return
*/
public RedBlackBST_Projecto<String, Musica> getArtistMusicSt() {
return artistMusicSt;
}
/**
*
* @param artistMusicSt
*/
public void setArtistMusicSt(RedBlackBST_Projecto<String, Musica> artistMusicSt) {
this.artistMusicSt = artistMusicSt;
}
}
| brunosilv/music-streaming | Artista.java | 479 | /**
*
* @param generomusical
*/ | block_comment | en | true |
178378_0 | 1. Pascal's Triangle
class Solution {
public List<Integer> generator(int r){
long a=1;
List<Integer> ar=new ArrayList<>();
ar.add(1);
for(int c=1;c<r;c++){
a=a*(r-c);
a=a/c;
ar.add((int)a);
}
return ar;
}
public List<List<Integer>> generate(int n){
List<List<Integer>> a=new ArrayList<>();
for(int r=1;r<=n;r++){
a.add(generator(r));
}
return a;
}
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2. Pascal's Triangle 2
public class Solution{
public List<Integer> getRow(int R){
List<Integer> r=new ArrayList<>();
r.add(1);
long p=1;
for(int k=1;k<=R;k++){
long n=p*(R-k+1)/k;
r.add((int)n);
p=n;
}
return r;
}
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
3. Same Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null && q==null){
return true;
}
if(p==null || q==null || p.val!=q.val){
return false;
}
return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
}
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
4. Symmetric Tree
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
public boolean isSymmetric(TreeNode root){
if(root==null){
return true;
}
return isMirror(root.left,root.right);
}
public boolean isMirror(TreeNode node1,TreeNode node2){
if(node1==null && node2==null){
return true;
}
if(node1==null || node2==null){
return false;
}
return node1.val==node2.val && isMirror(node1.left,node2.right) && isMirror(node1.right,node2.left);
}
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
5. Climbing Stairs
class Solution{
public int climbStairs(int n){
if(n==0 || n==1){
return 1;
}
int p=1,c=1;
for(int i=2;i<=n;i++){
int t=c;
c=c+p;
p=t;
}
return c;
}
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| ShaqilShaheen10/LeetCodePractice | Day4.java | 783 | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/ | block_comment | en | true |
178396_0 | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private boolean areTreeEqual(TreeNode root, TreeNode subRoot) {
if (root == null && subRoot == null) return true;
if (root == null || subRoot == null || root.val != subRoot.val) return false;
boolean left = true;
boolean right = true;
if (root.left != null || subRoot.left != null) {
left = areTreeEqual(root.left, subRoot.left);
}
if (root.right != null || subRoot.right != null) {
right = areTreeEqual(root.right, subRoot.right);
}
return left && right;
}
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
if (root == null && subRoot == null) return true;
if (root == null || subRoot == null) return false;
if (areTreeEqual(root, subRoot)) {
return true;
}
return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
}
} | jdolphin5/leetcode | 572.java | 348 | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/ | block_comment | en | true |
178638_0 | package ch_04;
import java.util.Scanner;
/**
* *4.24 (Order three cities) Write a program that prompts the user to enter three cities and
* displays them in ascending order.
* <p>
* Here is a sample run:
* Enter the first city: Chicago
* Enter the second city: Los Angeles
* Enter the third city: Atlanta
* The three cities in alphabetical order are Atlanta Chicago Los Angeles
*/
public class Exercise04_24 {
public static void main(String[] args) {
String tempCity = "";
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of city 1: ");
String cityOne = input.next();
System.out.print("Enter the name of city 2: ");
String cityTwo = input.next();
System.out.print("Enter the name of city 3: ");
String cityThree = input.next();
if (cityOne.charAt(0) > cityTwo.charAt(0)) {
tempCity = cityTwo;
cityTwo = cityOne;
cityOne = tempCity;
if (cityTwo.charAt(0) > cityThree.charAt(0)) {
tempCity = cityThree;
cityThree = cityTwo;
cityTwo = tempCity;
}
}
System.out.println("The cities in alphabetical order are: "
+ cityOne + " " + cityTwo + " " + cityThree + ".");
}
}
| Taabannn/intro-to-java-programming | ch_04/Exercise04_24.java | 351 | /**
* *4.24 (Order three cities) Write a program that prompts the user to enter three cities and
* displays them in ascending order.
* <p>
* Here is a sample run:
* Enter the first city: Chicago
* Enter the second city: Los Angeles
* Enter the third city: Atlanta
* The three cities in alphabetical order are Atlanta Chicago Los Angeles
*/ | block_comment | en | false |
178926_8 | /**
* Copyright 2009 The Australian National University (ANU)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ands.rifcs.base;
import org.w3c.dom.Node;
/**
* Class representing a RIF-CS Subject object.
*
* @author Scott Yeadon
*
*/
public class Subject extends RIFCSElement {
/**
* Construct a Subject object.
*
* @param n
* A w3c Node, typically an Element
*
* @throws RIFCSException A RIFCSException
*/
protected Subject(final Node n) throws RIFCSException {
super(n, Constants.ELEMENT_SUBJECT);
}
/**
* Set the type.
*
* @param type
* The type of subject
*/
public final void setType(final String type) {
super.setAttributeValue(Constants.ATTRIBUTE_TYPE, type);
}
/**
* return the type.
*
* @return
* The type attribute value or empty string if attribute
* is empty or not present
*/
public final String getType() {
return super.getAttributeValue(Constants.ATTRIBUTE_TYPE);
}
/**
* Set the termIdentifier.
*
* @param termIdentifier
* The termIdentifier of subject
*/
public final void setTermIdentifier(final String termIdentifier) {
super.setAttributeValue(Constants.ATTRIBUTE_TERM_IDENTIFIER,
termIdentifier);
}
/**
* return the termIdentifier.
*
* @return
* The termIdentifier attribute value or empty string if attribute
* is empty or not present
*/
public final String getTermIdentifier() {
return super.getAttributeValue(Constants.ATTRIBUTE_TERM_IDENTIFIER);
}
/**
* Set the language.
*
* @param lang
* The xml:lang attribute value
*/
public final void setLanguage(final String lang) {
super.setAttributeValueNS(Constants.NS_XML,
Constants.ATTRIBUTE_LANG, lang);
}
/**
* Obtain the language.
*
* @return
* The language or empty string if attribute
* is empty or not present
*/
public final String getLanguage() {
return super.getAttributeValueNS(Constants.NS_XML,
Constants.ATTRIBUTE_LANG);
}
/**
* Set the content.
*
* @param value
* The content of the subject
*/
public final void setValue(final String value) {
super.setTextContent(value);
}
/**
* Obtain the content.
*
* @return
* The subject string
*/
public final String getValue() {
return super.getTextContent();
}
}
| au-research/ANDS-RIFCS-API | src/org/ands/rifcs/base/Subject.java | 739 | /**
* Obtain the language.
*
* @return
* The language or empty string if attribute
* is empty or not present
*/ | block_comment | en | false |
178932_1 | /*
* Copyright 2015 Australian Centre For Plant Functional Genomics
*
* 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 shared;
/**
*
* @author Radoslaw Suchecki [email protected]
*/
public class MerMap {
private boolean OutOfMemory;
public boolean isOutOfMemory() {
return OutOfMemory;
}
public synchronized void setOutOfMemory() {
this.OutOfMemory = true;
}
}
| rsuchecki/yakat | src/shared/MerMap.java | 241 | /**
*
* @author Radoslaw Suchecki [email protected]
*/ | block_comment | en | true |
179071_0 | // Ref: https://iridiumcao.github.io/algorithm/chief/content.html
public class Chief2 {
public static void main(String[] args) {
int[] a = { 0, 1 };// 0่กจ็คบไธๆฏๅฐๅท๏ผ1่กจ็คบๆฏๅฐๅท
int[] b = { 0, 1 };
int[] c = { 0, 1 };
int[] d = { 0, 1 };
for (int i : a) {
for (int j : b) {
for (int k : c) {
for (int m : d) {
int count = 0;
count += (i != 1) ? 1 : 0;
count += (k == 1) ? 1 : 0;
count += (m == 1) ? 1 : 0;
count += (m != 1) ? 1 : 0;
if (count == 3) {
System.out.println("A " + (i == 1 ? "" : "ไธ") + "ๆฏๅฐๅท");
System.out.println("B " + (j == 1 ? "" : "ไธ") + "ๆฏๅฐๅท");
System.out.println("C " + (k == 1 ? "" : "ไธ") + "ๆฏๅฐๅท");
System.out.println("D " + (m == 1 ? "" : "ไธ") + "ๆฏๅฐๅท");
System.out.println("----");
}
}
}
}
}
}
}
| iridiumcao/iridiumcao.github.io | algorithm/chief/Chief2.java | 356 | // Ref: https://iridiumcao.github.io/algorithm/chief/content.html | line_comment | en | true |
179574_2 | /** Global.java
*
* Copyright 2017 President and Fellows of Harvard College
*
* 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.
*/
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import config.ConfigManager;
import dao.WorkflowDao;
import models.db.workflow.Status;
import models.db.workflow.WorkflowRun;
import org.python.util.install.Installation;
import play.Application;
import play.GlobalSettings;
import play.Logger;
import java.io.File;
import java.security.Permission;
import java.util.Date;
import java.util.List;
public class Global extends GlobalSettings {
private WorkflowDao workflowDao = new WorkflowDao();
@Override
public void onStart(Application app) {
Logger.info("Application has started");
// Clean up stalled workflows
List<WorkflowRun> stalled = workflowDao.findWorkflowRunsByStatus(Status.RUNNING);
for (WorkflowRun run : stalled) {
run.setEndTime(new Date());
run.setStatus(Status.ERRORS);
run.save();
}
}
@Override
public void onStop(Application app) {
Logger.info("Application shutdown...");
}
@Override
public void beforeStart(Application app) {
Config config = ConfigFactory.defaultApplication();
System.out.println();
if (config.hasPath("kurator.autoInstall") && config.getBoolean("kurator.autoInstall")) {
//File packagesDir = new File(config.getString("jython.packages"));
File packagesDir = new File("packages").getAbsoluteFile();
if (!packagesDir.exists()) {
System.out.println("Creating packages directory: " + packagesDir.getAbsolutePath());
if (!packagesDir.getParentFile().exists()) {
System.out.println("Error: Parent directory " + packagesDir.getParent() + " does not exist!");
System.exit(-1);
}
if (!packagesDir.getParentFile().canWrite()) {
System.out.println("Error: Current user does not have write permissions for directory " + packagesDir.getParent());
System.exit(-1);
}
packagesDir.mkdir();
}
//File workspaceDir = new File(config.getString("jython.workspace"));
File workspaceDir = new File("workspace").getAbsoluteFile();
if (!workspaceDir.exists()) {
System.out.println("Creating workspace directory: " + workspaceDir.getAbsolutePath());
if (!workspaceDir.getParentFile().exists()) {
System.out.println("Error: Parent directory " + workspaceDir.getParent() + " does not exist!");
System.exit(-1);
}
if (!workspaceDir.getParentFile().canWrite()) {
System.out.println("Error: Current user does not have write permissions in directory " + workspaceDir.getParent());
System.exit(-1);
}
workspaceDir.mkdir();
}
//File jythonDir = new File(config.getString("jython.home"));
File jythonDir = new File("jython").getAbsoluteFile();
if (!jythonDir.exists()) {
System.out.println("Jython not found, running installer now...");
boolean success = jythonDir.mkdir();
System.out.println("Creating jython home directory: " + jythonDir.getAbsolutePath());
if (!jythonDir.getParentFile().exists()) {
System.out.println("Error: Parent directory " + jythonDir.getParent() + " does not exist!");
System.exit(-1);
}
if (!jythonDir.getParentFile().canWrite()) {
System.out.println("Error: Current user does not have write permissions in directory " + jythonDir.getParent());
System.exit(-1);
}
//Before running the external Command
MySecurityManager secManager = new MySecurityManager();
System.setSecurityManager(secManager);
String[] args = {"-s", "-d", jythonDir.getAbsolutePath()};
Installation.driverMain(args, null, null);
}
}
unzipPackages();
}
private void unzipPackages() {
Config config = ConfigFactory.defaultApplication();
File file = new File("packages");
if (file.exists()) {
String[] packages = file.list();
for (String packageName : packages) {
File packageFile = new File(file.getAbsolutePath() + File.separator + packageName);
if (!packageFile.isDirectory() && packageFile.getName().endsWith(".zip")) {
System.out.println("Auto unpacking packages zip file: " + packageFile.getName());
ConfigManager.getInstance().unpack(packageFile);
packageFile.delete();
}
}
}
}
class MySecurityManager extends SecurityManager {
@Override public void checkExit(int status) {
System.out.println("Installation of kurator-web is complete. Deploy package zip files to the packages " +
"directory and rerun the startup script to start the server.");
File pid = new File("RUNNING_PID");
if (pid.exists()) {
pid.deleteOnExit();
}
}
@Override
public void checkPermission(Permission perm) {
}
@Override
public void checkPermission(Permission perm, Object context) {
}
}
} | kurator-org/kurator-web | app/Global.java | 1,306 | //File packagesDir = new File(config.getString("jython.packages")); | line_comment | en | true |
180072_21 | import java.util.*;
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class User extends JFrame implements ActionListener{
// this will be the class that runs when application opens, everything else accessed from here
protected ArrayList<Pet> joshagachi = new ArrayList<Pet>();
protected String ownerName;
protected ArrayList<Item> purchasedFoods = new ArrayList<Item>();
protected Shop foodShop;
protected ArrayList<Item> purchasedSwag = new ArrayList<Item>();
protected Shop accessoryShop;
// cutting time element, not fun
protected Container p = this.getContentPane();
protected JTextField ownerNameField = new JTextField("", 10);
protected JTextField petNameField = new JTextField("", 10);
public User() {
super("Welcome to Joshagachi!");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
p.setLayout(new BorderLayout());
// title
JLabel title = new JLabel(new ImageIcon("TempTitle.png"));
Panel header = new Panel();
header.setLayout(new FlowLayout());
header.add(title);
p.add(header, BorderLayout.NORTH);
load();
this.setVisible(true);
this.setSize(400,300);
}
// this is the main the whole project will run from
public static void main(String[] args) {
new User();
}
// is never used
public void save() {
try{
BufferedWriter out = new BufferedWriter(new FileWriter("pets.txt"));
// works better when in conjunction with string for some reason
for(int i = 0; i<joshagachi.size(); i++) {
Pet j = joshagachi.get(i);
out.write(String.format("%s/%s/%d/%d", j.species, j.name, j.foodLevel, j.energyLevel));
System.out.println("Saved: "+j.name);
}
out.close();
}
catch(FileNotFoundException r){
System.out.println("No file found");
}
catch(IOException r){
System.out.println("Problem reading 'pets.txt'");
}
}
public void load() {
//check if pets.txt exists, if not run through name creation and get Joshagachi
System.out.println("Loading Pets");
try{
FileReader file = new FileReader("pets.txt");
BufferedReader fileStream = new BufferedReader(file);
String line = fileStream.readLine();
int counter = 0;
while(line!=null){
System.out.println(line);
if(line!=null){
if(counter==0)
ownerName = line;
else {
String[] data = line.split("/");
joshagachi.add(new Pet(this, data[0], data[1], Double.parseDouble(data[2]), Double.parseDouble(data[3])));
}
}
System.out.println(line);
line = fileStream.readLine();
counter++;
}
System.out.println("Counter: "+counter);
// file exists, but no Joshagachi's
if(counter<=0)
newUser();
// if there are Joshagachi's, let em in
else
returningUser();
// done with file, close it
fileStream.close();
}
catch(FileNotFoundException e){
// start new user sequence
newUser();
}
catch(IOException e){
System.out.println("Problem reading 'pets.txt'\n"+e);
}
// need to load shop info for food and accessories
System.out.println("Loading Food Shop");
try{
FileReader file = new FileReader("foods.dat");
BufferedReader fileStream = new BufferedReader(file);
String line = fileStream.readLine();
ArrayList<Item> tempFoods = new ArrayList<Item>();
while(line!=null){
System.out.println(line);
if(line!=null){
String[] data = line.split("/");
Food f = new Food(Double.parseDouble(data[0]), data[1], data[2], Integer.parseInt(data[3]), data[4]);
tempFoods.add(f);
}
line = fileStream.readLine();
}
// done with file, close it
fileStream.close();
//create foodShop
foodShop = new Shop(this, "Yummy Yummies", "To feed your hungry Joshagachi", tempFoods, "assets/Yummies.png");
}
catch(FileNotFoundException e){
System.out.println("No foods.dat file found");
}
catch(IOException e){
System.out.println("Problem reading 'foods.dat'\n"+e);
}
System.out.println("Loading Game Shop");
try{
FileReader file = new FileReader("accessories.dat");
BufferedReader fileStream = new BufferedReader(file);
String line = fileStream.readLine();
ArrayList<Item> tempSwag = new ArrayList<Item>();
while(line!=null){
System.out.println(line);
if(line!=null){
String[] data = line.split("/");
Accessory a = new Accessory(Double.parseDouble(data[0]), data[1], data[2], Integer.parseInt(data[3]), data[4]);
tempSwag.add(a);
}
line = fileStream.readLine();
}
// done with file, close it
fileStream.close();
//create foodShop
accessoryShop = new Shop(this, "Fresh Swag", "To keep your Joshagachi Fresh", tempSwag, "assets/Games.png");
}
catch(FileNotFoundException e){
System.out.println("No accessories.dat file found");
}
catch(IOException e){
System.out.println("Problem reading 'accessories.dat'\n"+e);
}
// load purchased inventories
System.out.println("Loading purchasedFood");
try{
FileReader file = new FileReader("foods.txt");
BufferedReader fileStream = new BufferedReader(file);
String line = fileStream.readLine();
ArrayList<Item> tempFoods = new ArrayList<Item>();
while(line!=null){
System.out.println(line);
if(line!=null){
String[] data = line.split("/");
Food f = new Food(Double.parseDouble(data[0]), data[1], data[2], Integer.parseInt(data[3]), data[4]);
tempFoods.add(f);
}
line = fileStream.readLine();
}
// done with file, close it
fileStream.close();
//fill out inventory
purchasedFoods = tempFoods;
}
catch(FileNotFoundException e){
System.out.println("No foods.txt file found");
}
catch(IOException e){
System.out.println("Problem reading 'foods.txt'\n"+e);
}
System.out.println("Loading purchasedSwag");
try{
FileReader file = new FileReader("accessories.txt");
BufferedReader fileStream = new BufferedReader(file);
String line = fileStream.readLine();
ArrayList<Item> tempSwag = new ArrayList<Item>();
while(line!=null){
System.out.println(line);
if(line!=null){
String[] data = line.split("/");
Accessory a = new Accessory(Double.parseDouble(data[0]), data[1], data[2], Integer.parseInt(data[3]), data[4]);
tempSwag.add(a);
}
line = fileStream.readLine();
}
// done with file, close it
fileStream.close();
//fill out inventory
purchasedSwag = tempSwag;
}
catch(FileNotFoundException e){
System.out.println("No accessories.txt file found");
}
catch(IOException e){
System.out.println("Problem reading 'accessories.txt'\n"+e);
}
}
public void createPetMenu() {
new PetMenu(this);
}
public void returningUser() {
JPanel welcomePanel = new JPanel();
welcomePanel.setLayout(new FlowLayout());
JLabel welcome = new JLabel("Welcome back "+ownerName+"! Your Joshagachis missed you!", SwingConstants.CENTER);
JButton ok = new JButton(new AbstractAction("Awesome!") {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
createPetMenu();
//new PetMenu(ownerName, joshagachi);
}
});
//ok.setPreferredSize(new Dimension(70,70));
welcomePanel.add(welcome);
welcomePanel.add(ok);
p.add(welcomePanel, BorderLayout.CENTER);
}
public void newUser() {
JPanel welcomePanel = new JPanel();
welcomePanel.setLayout(new FlowLayout());
JLabel welcome = new JLabel("Welcome to Joshagachi! What's your name?", SwingConstants.CENTER);
JButton ok = new JButton(new AbstractAction("OK gimmie") {
@Override
public void actionPerformed(ActionEvent e) {
// move to picking Joshagachi
dispose();
createPetMenu();
//new PetMenu(ownerName, joshagachi);
}
});
ok.setPreferredSize(new Dimension(0,70));
JButton ownerSubmit = new JButton(new AbstractAction("submitOwnerName") {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(p.getComponents().length);
ownerName = ownerNameField.getText().replace("\\s+", "");
welcome.setText("Let's get you a Joshagachi "+ownerName+"!");
if(p.getComponents().length == 3) {
p.add(ok, BorderLayout.SOUTH);
}
}
});
ownerSubmit.setText("Submit");
p.add(welcome, BorderLayout.NORTH);
welcomePanel.add(ownerNameField);
welcomePanel.add(ownerSubmit);
welcomePanel.add(new JLabel(new ImageIcon("assets/TempTitle.png")));
p.add(welcomePanel, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e) {
System.out.println(e);
dispose();
}
} | LegoGuy32109/Joshagachi | User.java | 2,573 | //new PetMenu(ownerName, joshagachi); | line_comment | en | true |
180153_5 | package prj5;
import java.util.Comparator;
/**
* Class for Major Percent
*
* @author group48
* @version 04.27.2017
*/
public class MajorPercent implements Comparator<String> {
// ~ Fields
private int[][] like;
private int[][] heard;
// ~ Constructor
/**
* new a majorCount
*/
public MajorPercent() {
like = new int[4][2];
heard = new int[4][2];
}
// ~ Methods
/**
* Increment the results
*
* @param major
* represent the major of a student
* @param answerHeard
* whether that student has heard this song or not
* @param answerLike
* whether that student likes that song or not
*/
public void increment(String major, String answerHeard, String answerLike) {
heard(major, answerHeard);
like(major, answerLike);
}
/**
* increase the heard part
*
* @param major
* represents the major of the student
* @param answer
* answer to like or not
*/
private void heard(String major, String answer) {
if (compare(major, "Computer Science") == 0) {
if (compare(answer, "Yes") == 0) {
heard[0][1]++;
}
else if (compare(answer, "No") == 0) {
heard[0][0]++;
}
}
else if (compare(major, "Other Engineering") == 0) {
if (compare(answer, "Yes") == 0) {
heard[1][1]++;
}
else if (compare(answer, "No") == 0) {
heard[1][0]++;
}
}
else if (compare(major, "Math or CMDA") == 0) {
if (compare(answer, "Yes") == 0) {
heard[2][1]++;
}
else if (compare(answer, "No") == 0) {
heard[2][0]++;
}
}
else if (compare(major, "Other") == 0) {
if (compare(answer, "Yes") == 0) {
heard[3][1]++;
}
else if (compare(answer, "No") == 0) {
heard[3][0]++;
}
}
}
/**
* Increase the like part.
*
* @param major
* the student's major
* @param answer
* answer to like or not
*/
private void like(String major, String answer) {
if (compare(major, "Computer Science") == 0) {
if (compare(answer, "Yes") == 0) {
like[0][1]++;
}
else if (compare(answer, "No") == 0) {
like[0][0]++;
}
}
else if (compare(major, "Other Engineering") == 0) {
if (compare(answer, "Yes") == 0) {
like[1][1]++;
}
else if (compare(answer, "No") == 0) {
like[1][0]++;
}
}
else if (compare(major, "Math or CMDA") == 0) {
if (compare(answer, "Yes") == 0) {
like[2][1]++;
}
else if (compare(answer, "No") == 0) {
like[2][0]++;
}
}
else if (compare(major, "Other") == 0) {
if (compare(answer, "Yes") == 0) {
like[3][1]++;
}
else if (compare(answer, "No") == 0) {
like[3][0]++;
}
}
}
/**
* get the heard or not results in percentages
*
* @return the heard or not results
*/
public int[] getHeard() {
int[] result = new int[4];
result[0] = (int)((1.0 * heard[0][1] / (heard[0][0] + heard[0][1]))
* 100);
result[1] = (int)((1.0 * heard[1][1] / (heard[1][0] + heard[1][1]))
* 100);
result[2] = (int)((1.0 * heard[2][1] / (heard[2][0] + heard[2][1]))
* 100);
result[3] = (int)((1.0 * heard[3][1] / (heard[3][0] + heard[3][1]))
* 100);
return result;
}
/**
* get the like or not results
*
* @return the like or not results
*/
public int[] getLike() {
int[] result = new int[4];
result[0] = (int)((1.0 * like[0][1] / (like[0][0] + like[0][1])) * 100);
result[1] = (int)((1.0 * like[1][1] / (like[1][0] + like[1][1])) * 100);
result[2] = (int)((1.0 * like[2][1] / (like[2][0] + like[2][1])) * 100);
result[3] = (int)((1.0 * like[3][1] / (like[3][0] + like[3][1])) * 100);
return result;
}
/**
* Compare two strings together
*
* @return 0 if equal, neg if major is less than answer, and pos if greater
*/
@Override
public int compare(String major, String answer) {
return major.compareTo(answer);
}
}
| bharathc346-zz/Project5 | src/prj5/MajorPercent.java | 1,356 | /**
* Increment the results
*
* @param major
* represent the major of a student
* @param answerHeard
* whether that student has heard this song or not
* @param answerLike
* whether that student likes that song or not
*/ | block_comment | en | false |
180490_1 | /*
* 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 lab.pkg3;
/**
*
* @author Dolan
*/
public class RoofRack extends ColoradoDecorator
{
public RoofRack(Colorado inColorado)
{
super(inColorado);
System.out.println("Adding roof rack");
}
public String getDescription()
{
return tempColorado.getDescription() + ", roof rack";
}
public double getCost()
{
return tempColorado.getCost() + 250.00;
}
}
| ClaytonBrezinski/ENSE-470---Lab-3 | src/lab/pkg3/RoofRack.java | 163 | /**
*
* @author Dolan
*/ | block_comment | en | true |
180608_1 | /**
* The JoylessToilets class represents a specific type of room, namely Joyless Toilets, which is a subclass of the Room class.
* It inherits properties such as description, name, and icon path from the Room class and may have additional
* instance variables or behaviors specific to Joyless Toilets.
*
* The authors of this class are: ABBE Tristan, ANET Janelle, DELPIROU Corentin,
* MAZURIE Jules, PERSONNE Germain, RIVIERE Jade.
*
* @author ABBE Tristan, ANET Janelle, DELPIROU Corentin, MAZURIE Jules, PERSONNE Germain, RIVIERE Jade
* @version 1.0
*/
public class JoylessToilets extends Room
{ private int countFlushRoyal = 0 ;
/**
* Constructor for objects of the JoylessToilets class.
* Initializes the JoylessToilets with a specific description, name, and icon path.
*/
public JoylessToilets()
{
super("Magnificent toilets but with a slightly worn color making the atmosphere heavy and oppressive."
+" The brush is missing.", "Joyless Toilets","ImagesAliceRedimmensionnรฉes/Joyless_toilets.png",20);
}
public void setCountFlushRoyal(){
this.countFlushRoyal++;
}
public int getCountFlushRoyal(){
return countFlushRoyal;
}
}
| TristanAbbe/World-OF-Zhuul- | JoylessToilets.java | 360 | /**
* Constructor for objects of the JoylessToilets class.
* Initializes the JoylessToilets with a specific description, name, and icon path.
*/ | block_comment | en | true |
180684_2 | package java8features;
interface vechicle{
public void start();
//public void clean();-->>> error because it will give me an because it is an abstract method for this in java 8 one method called default and static method that has method body
public default void clean()
{
System.out.println("cleaning is process");
}
//with this my excitng class is not failing as we alreday know when ever we implements any
// interface compulsory we should override their abstract method here we are not overide with default method
public static void coll()
{
System.out.println("collection of new cars are added");
}
// another new method are introduce in java * main difference is static method is not overide and default method can be override
}
public class inter implements vechicle {
@Override
public void clean() {
System.out.println("overide cleaning");
}
@Override
/*public static void coll()
{
System.out.println("collection of new cars are added");
}
here we are trying to override the static method that we can not override
*/
public void start()
{
System.out.println("car is started");
}
public static void main(String[]args)
{
inter i=new inter();
i.start();
i.clean();
vechicle.coll();
}
}
| 7654878448/java-programming | inter.java | 350 | // interface compulsory we should override their abstract method here we are not overide with default method
| line_comment | en | true |
181503_0 | package com.view;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
/**
* The Roboto font.
*
* @see <a href="https://www.google.com/design/spec/resources/roboto-noto-fonts.html">Roboto & Noto fonts (Google design guidelines)</a>
*/
public class Roboto {
public static final Font BLACK = loadFont("Roboto-Black.ttf").deriveFont(Font.BOLD);
public static final Font BLACK_ITALIC = loadFont("Roboto-BlackItalic.ttf").deriveFont(Font.BOLD | Font.ITALIC);
public static final Font BOLD = loadFont("Roboto-Bold.ttf").deriveFont(Font.BOLD);
public static final Font BOLD_ITALIC = loadFont("Roboto-BoldItalic.ttf").deriveFont(Font.BOLD | Font.ITALIC);
public static final Font ITALIC = loadFont("Roboto-Italic.ttf").deriveFont(Font.ITALIC);
public static final Font LIGHT = loadFont("Roboto-Light.ttf").deriveFont(Font.PLAIN);
public static final Font LIGHT_ITALIC = loadFont("Roboto-LightItalic.ttf").deriveFont(Font.ITALIC);
public static final Font MEDIUM = loadFont("Roboto-Medium.ttf").deriveFont(Font.PLAIN);
public static final Font MEDIUM_ITALIC = loadFont("Roboto-MediumItalic.ttf").deriveFont(Font.ITALIC);
public static final Font REGULAR = loadFont("Roboto-Regular.ttf").deriveFont(Font.PLAIN);
public static final Font THIN = loadFont("Roboto-Thin.ttf").deriveFont(Font.PLAIN);
public static final Font THIN_ITALIC = loadFont("Roboto-ThinItalic.ttf").deriveFont(Font.ITALIC);
private static Font loadFont(String resourceName) {
try (InputStream inputStream = MainUI.class.getResourceAsStream("/lib/Fonts/" + resourceName)) {
return Font.createFont(Font.TRUETYPE_FONT, inputStream);
} catch (IOException | FontFormatException e) {
throw new RuntimeException("Could not load " + resourceName, e);
}
}
} | rsangeethk/uibot | src/com/view/Roboto.java | 499 | /**
* The Roboto font.
*
* @see <a href="https://www.google.com/design/spec/resources/roboto-noto-fonts.html">Roboto & Noto fonts (Google design guidelines)</a>
*/ | block_comment | en | false |
181525_0 | /**
* โI acknowledge that I am aware of the academic integrity guidelines of this course, and that I worked
* on this assignment independently without any unauthorized helpโ
*/
import FileHandler.Solver;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
new Solver().solve(args);
}
}
| Gamal-Abd-El-Hameed/HUFFMAN | src/Main.java | 85 | /**
* โI acknowledge that I am aware of the academic integrity guidelines of this course, and that I worked
* on this assignment independently without any unauthorized helpโ
*/ | block_comment | en | true |
181612_6 | package priority;
import person.Patient;
import java.util.ArrayList;
/**
* This is an abstract class that creates a PriorityQueue which controls the order in which Patients are admitted
* to or treated at the hospital.
*
* @author Shysta and Justice
* @version 2.0
* @since 1.0
*/
public abstract class Priority {
ArrayList<Patient> patientList;
/**
* A constructor for the Priority Class.
*/
public Priority() {
this.patientList = new ArrayList<>();
}
/**
* Adds a patient to the Priority Queue patientList. This method makes use of the template design pattern.
* It instantiates an algorithm for dynamically ordering the patient's list in the PriorityQueue.
*/
public void add_patient(Patient patient) {
if (this.patientList.isEmpty()) {
this.patientList.add(patient);
}
int i = 0;
while (!this.patientList.contains(patient)) {
if (higherPriority(this.patientList.get(i), patient)) {
int num;
num = this.patientList.indexOf(this.patientList.get(i));
this.patientList.add(num, patient);
} else if (i == this.patientList.size() - 1) {
this.patientList.add(this.patientList.size(), patient);
} else {
i += 1;
}
}
}
public abstract boolean higherPriority(Patient patient, Patient newPatient);
/**
* Removes a patient from the priority queue of patients by reference to the patient.
*
* @param patient patient to be removed from the priority queue of patients.
* @return the patient that was removed.
*/
public Patient delete_patient(Patient patient) {
patientList.remove(patient);
return patient;
}
/**
* Removes the last patient from the list of patients.
*
* @return the patient that was removed.
*/
public Patient delete_patient() {
Patient patient = patientList.get(0);
patientList.remove(patient);
return patient;
}
/**
* Checks whether the hospital's list of patients is empty.
*
* @return true if the list is empty and false if it is not.
*/
public boolean isEmpty() {
return patientList.isEmpty();
}
/**
* Returns a list containing all the patients in the priority queue in the hospital.
*
* @return a list containing all the patients in the priority queue in the hospital.
*/
public ArrayList<Patient> show_patientList() {
return patientList;
}
}
| CSC207-UofT/course-project-all-stars | src/priority/Priority.java | 596 | /**
* Returns a list containing all the patients in the priority queue in the hospital.
*
* @return a list containing all the patients in the priority queue in the hospital.
*/ | block_comment | en | false |
181662_0 | import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ProductosCRUD {
private Connection connect() {
// URL de la base de datos SQLite (se crea si no existe)
String url = "jdbc:sqlite:productos.db";
Connection conn = null;
try {
conn = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return conn;
}
public void crearProducto(String nombre, double precio) {
String sql = "INSERT INTO productos(nombre, precio) VALUES(?,?)";
try (Connection conn = this.connect();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, nombre);
pstmt.setDouble(2, precio);
pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public void obtenerProductos() {
String sql = "SELECT id, nombre, precio FROM productos";
try (Connection conn = this.connect();
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
System.out.println("ID: " + rs.getInt("id") +
", Nombre: " + rs.getString("nombre") +
", Precio: " + rs.getDouble("precio"));
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public void actualizarProducto(int id, String nuevoNombre, double nuevoPrecio) {
String sql = "UPDATE productos SET nombre = ?, precio = ? WHERE id = ?";
try (Connection conn = this.connect();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, nuevoNombre);
pstmt.setDouble(2, nuevoPrecio);
pstmt.setInt(3, id);
pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public void eliminarProducto(int id) {
String sql = "DELETE FROM productos WHERE id = ?";
try (Connection conn = this.connect();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, id);
pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) {
ProductosCRUD crud = new ProductosCRUD();
// Ejemplos de uso del CRUD
crud.crearProducto("Producto A", 19.99);
crud.crearProducto("Producto B", 29.99);
System.out.println("Productos existentes:");
crud.obtenerProductos();
// Actualizar un producto
crud.actualizarProducto(1, "Producto A Modificado", 24.99);
System.out.println("Productos despuรฉs de la actualizaciรณn:");
crud.obtenerProductos();
// Eliminar un producto
crud.eliminarProducto(2);
System.out.println("Productos despuรฉs de la eliminaciรณn:");
crud.obtenerProductos();
}
}
| Elcuz/2 | sql.java | 783 | // URL de la base de datos SQLite (se crea si no existe)
| line_comment | en | true |
182661_18 | import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.BufferedOutputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
/**
* A supplier may be a manufacturer, distributor, or depot.
* Supplier attributes include:
* name, demand, inventory on hand, maximum storage capacity,
* cost per unit stored, and surplus inventory.
*
* @author CS4050 (design)
* @author Dr. Jody Paul (code)
* @version 20231112
*/
public class Supplier implements java.io.Serializable {
/** Serialization version requirement. */
private static final long serialVersionUID = 405002L;
/** Default file name for serialized object. */
private static final String SERIAL_FILENAME = "supplier.ser";
/** Default maximum capacity. */
public static final int MAX_CAPACITY = Integer.MAX_VALUE;
/** Name of supplier. */
private String name;
/** Cost of storage at supplier's location. */
private int storageCost;
/**
* Direct demand at this supplier's location.
* If direct demand == 0, then is considered a depot.
* If direct demand is less than 0, then is considered a manufacturer.
*/
private int demand;
/** Inventory on hand. */
private int inventory;
/** Maximum amount of inventory that can be held. */
private int maxCapacity;
/**
* Surplus, defined as (inventory - demand).
* If positive, surplus represents the number of
* units subject to storage cost.
* If negative, surplus represents unrealized
* value (units that would otherwise have been sold).
* Storing this value is not necessary because the accessor,
* surplus(), computes this value dynamically.
*/
private int surplus;
/**
* Construct a supplier using default values.
*/
public Supplier() {
this.name = this.toString();
this.storageCost = 0;
this.demand = 0;
this.inventory = 0;
this.maxCapacity = MAX_CAPACITY;
this.surplus = 0;
}
/**
* Fully-parameterized supplier constructor.
* Note that surplus is automatically calculated as the
* difference between inventory and demand.
* @param name the name of this supplier
* @param cost the storage cost per unit stored
* @param demand the expected demand at this distributing supplier
* @param inventory the actual inventory at this supplier
* @param capacity the maximum capacity at this supplier
*/
public Supplier(String name,
int cost,
int demand,
int inventory,
int capacity) {
this.name = name;
this.storageCost = cost;
this.demand = demand;
this.maxCapacity = capacity;
if (inventory > capacity) {
this.inventory = capacity;
} else {
this.inventory = inventory;
}
this.surplus = inventory - demand;
}
/**
* @return this supplier's name
*/
public String name() { return this.name; }
/**
* @return the cost of storage at this supplier's location
*/
public int storageCost() { return this.storageCost; }
/**
* @return the maximum number of units that can be stored
*/
public int maxCapacity() { return this.maxCapacity; }
/**
* @return the demand at this supplier's location.
*/
public int demand() { return this.demand; }
/**
* @return the current inventory at this supplier's location.
*/
public int inventory() { return this.inventory; }
/**
* @return the surplus inventory at this supplier's location.
*/
public int surplus() {
this.surplus = this.inventory - this.demand;
return this.surplus;
}
/**
* Compares this supplier to the specified object.
* The result is <code>true</code> if and only if the argument is
* not <code>null</code> and is a Supplier object with the same
* name, storage cost, demand, and inventory values.
* @param anObject the object to compare with this supplier
* @return <code>true</code> if the given object represents a Supplier
* equivalent to this supplier, <code>false</code> otherwise
*/
@Override
public boolean equals(final Object anObject) {
if ((anObject == null)
|| (this.getClass() != anObject.getClass())) {
return false;
}
Supplier other = ((Supplier) anObject);
return (this.name.equals(other.name)
&& this.storageCost == other.storageCost
&& this.demand == other.demand
&& this.maxCapacity == other.maxCapacity
&& this.inventory == other.inventory);
}
/**
* Returns a hash code value for this supplier.
* @return hash code value for this supplier
*/
@Override
public int hashCode() {
if (name == null) return 43;
return this.name.hashCode();
}
/**
* Save this supplier to a file.
* @param filename the name of the file in which to save this supplier;
* if null, uses default file name
* @return <code>true</code> if successful save;
* <code>false</code> otherwise
* @throws java.io.IOException if unexpected IO error
*/
public final boolean save(final String filename) throws java.io.IOException {
boolean success = true;
String supplierFileName = filename;
if (supplierFileName == null) {
supplierFileName = Supplier.SERIAL_FILENAME;
}
// Serialize the supplier.
try {
OutputStream file = new FileOutputStream(supplierFileName);
OutputStream buffer = new BufferedOutputStream(file);
ObjectOutput output = new ObjectOutputStream(buffer);
try {
output.writeObject(this);
} finally { output.close(); }
} catch (IOException ex) {
System.err.println("Unsuccessful save. " + ex);
throw ex;
}
// Attempt to deserialize the supplier as verification.
try {
InputStream file = new FileInputStream(supplierFileName);
InputStream buffer = new BufferedInputStream(file);
ObjectInput input = new ObjectInputStream(buffer);
try {
@SuppressWarnings("unchecked") // Accommodate type erasure.
Supplier restored = (Supplier) input.readObject();
// Simple check that deserialized data matches original.
if (!this.toString().equals(restored.toString())) {
System.err.println("[1] State restore did not match save!");
success = false;
}
if (!this.equals(restored)) {
System.err.println("[2] State restore did not match save!");
success = false;
}
} finally { input.close(); }
} catch (ClassNotFoundException ex) {
System.err.println(
"Unsuccessful deserialization: Class not found. " + ex);
success = false;
} catch (IOException ex) {
System.err.println("Unsuccessful deserialization: " + ex);
success = false;
}
return success;
}
/**
* Restore this supplier from a file.
* <br /><em>Postconditions:</em>
* <blockquote>If successful, previous contents of this supplier have
* been replaced by the contents of the file.
* If unsuccessful, content of the supplier is unchanged.</blockquote>
* @param filename the name of the file from which to restore this supplier;
* if null, uses default file name
* @return <code>true</code> if successful restore;
* <code>false</code> otherwise
* @throws java.io.IOException if unexpected IO error
*/
public final boolean restore(final String filename) throws
java.io.IOException {
boolean success = false;
String supplierFileName = filename;
if (supplierFileName == null) {
supplierFileName = Supplier.SERIAL_FILENAME;
}
Supplier restored = null;
try {
InputStream file = new FileInputStream(supplierFileName);
InputStream buffer = new BufferedInputStream(file);
ObjectInput input = new ObjectInputStream(buffer);
try {
@SuppressWarnings("unchecked") // Accommodate type erasure.
Supplier retrieved = (Supplier) input.readObject();
restored = retrieved;
} finally {
input.close();
success = true;
}
} catch (ClassNotFoundException ex) {
System.err.println(
"Unsuccessful deserialization: Class not found. " + ex);
success = false;
} catch (IOException ex) {
System.err.println("Unsuccessful deserialization: " + ex);
throw ex;
}
if (restored == null) {
System.err.println(
"Unsuccessful deserialization: restored == null");
success = false;
} else {
this.name = restored.name;
this.storageCost = restored.storageCost;
this.demand = restored.demand;
this.inventory = restored.inventory;
this.maxCapacity = restored.maxCapacity;
this.surplus = restored.surplus;
}
return success;
}
}
| WillMoody27/distribution-project-final-algo-program-4050-ford-fulkerson-and-Dijkstras | src/Supplier.java | 2,091 | /**
* Compares this supplier to the specified object.
* The result is <code>true</code> if and only if the argument is
* not <code>null</code> and is a Supplier object with the same
* name, storage cost, demand, and inventory values.
* @param anObject the object to compare with this supplier
* @return <code>true</code> if the given object represents a Supplier
* equivalent to this supplier, <code>false</code> otherwise
*/ | block_comment | en | false |
182902_2 | /*
* Card class
* TODO: In the constructor of the class, check if the passed arguments are in the
* valid range. If not, throw an java.security.InvalidParameterException
*/
// use import statments to specify the package where class is defined
// now you can just refer to the exception by its name InvalidParameterException
import java.security.InvalidParameterException;
public class Card{
private int value;
private char suite;
/*
* Constructor of the Card class
* @param val - card value in the range [2-14], where 11-Jack, 12-Queen, 13-King, 14-Ace
* @param suite - the suite of the card: D - diamonds, H - hearts, S - Spaces, C - clubs
*/
public Card(int val, char s) throws InvalidParameterException
{
// check the input for being in the valid range
if (val < 2 || val > 14)
{
throw new InvalidParameterException("Value must be in the range [2, 14]");
}
// check if the suite is valid
if (s != 'D' && s != 'H' && s != 'S' && s != 'C')
{
throw new InvalidParameterException("Value must be ether 'D', 'H', 'S' or 'C'");
}
value = val;
suite = s;
}
public int getValue(){
return value;
}
public char getSuite(){
return suite;
}
public String toString()
{
String cardDescription = "";
if (value >=2 && value <=10){
cardDescription+=value + " ";
}
else if (value == 11){
cardDescription+="Jack ";
}
else if (value == 12){
cardDescription+="Queen ";
}
else if (value == 13){
cardDescription+="King ";
}
else if (value == 14){
cardDescription+="Ace ";
}
if (suite == 'S'){
cardDescription+="Spades";
}
else if (suite == 'D'){
cardDescription+="Diamonds";
}
else if (suite == 'C'){
cardDescription+="Clubs";
}
else if (suite == 'H'){
cardDescription+="Hearts";
}
return cardDescription;
}
}
| NabeelSait/NabeelSaitCSCI_2300Coursework | lab6/Card.java | 537 | // now you can just refer to the exception by its name InvalidParameterException | line_comment | en | false |
182981_0 | /*
* Write a method called stripHtmlTags that accepts a Scanner representing
* an input file containing an HTML web page as its parameter, then reads
* that file and prints the file's text with all HTML tags removed. A tag
* is any text between the characters < and > . For example, consider the
* following text:
* <html>
* <head>
* <title>My web page</title>
* </head>
* <body>
* <p>There are many pictures of my cat here,
* as well as my <b>very cool</b> blog page,
* stuff about my trip to Vegas.</p>
*
* Here's my cat now:<img src="cat.jpg">
* </body>
* </html>
*
* If the file contained these lines, your program should output the following text:
*
* My web page
*
*
* There are many pictures of my cat here,
* as well as my very cool blog page,
* which contains awesome
* stuff about my trip to Vegas.
*
* Here's my cat now:
*
* You may assume that the file is a well-formed HTML document and that there
* are no < or > characters inside tags.
*/
public static void stripHtmlTags(Scanner input) {
while (input.hasNextLine()) {
String line = input.nextLine();
while (line.contains("<") || line.contains(">")) {
int index1 = line.indexOf("<");
int index2 = line.indexOf(">");
if (index1 == 0) {
line = line.substring(index2 + 1);
} else {
line = line.substring(0, index1) + line.substring(index2 + 1);
}
}
System.out.println(line);
}
}
| Creede15/practice-it | chapter-6/stripHtmlTags.java | 429 | /*
* Write a method called stripHtmlTags that accepts a Scanner representing
* an input file containing an HTML web page as its parameter, then reads
* that file and prints the file's text with all HTML tags removed. A tag
* is any text between the characters < and > . For example, consider the
* following text:
* <html>
* <head>
* <title>My web page</title>
* </head>
* <body>
* <p>There are many pictures of my cat here,
* as well as my <b>very cool</b> blog page,
* stuff about my trip to Vegas.</p>
*
* Here's my cat now:<img src="cat.jpg">
* </body>
* </html>
*
* If the file contained these lines, your program should output the following text:
*
* My web page
*
*
* There are many pictures of my cat here,
* as well as my very cool blog page,
* which contains awesome
* stuff about my trip to Vegas.
*
* Here's my cat now:
*
* You may assume that the file is a well-formed HTML document and that there
* are no < or > characters inside tags.
*/ | block_comment | en | true |
183517_17 | package plc.project;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.Optional;
/**
* The parser takes the sequence of tokens emitted by the lexer and turns that
* into a structured representation of the program, called the Abstract Syntax
* Tree (AST).
*
* The parser has a similar architecture to the lexer, just with {@link Token}s
* instead of characters. As before, {@link #peek(Object...)} and {@link
* #match(Object...)} are helpers to make the implementation easier.
*
* This type of parser is called <em>recursive descent</em>. Each rule in our
* grammar will have it's own function, and reference to other rules correspond
* to calling that functions.
*/
public final class Parser {
private final TokenStream tokens;
public Parser(List<Token> tokens) {
this.tokens = new TokenStream(tokens);
parseStatement();
}
/**
* Parses the {@code source} rule.
*/
public Ast.Source parseSource() throws ParseException {
throw new UnsupportedOperationException(); //TODO
}
/**
* Parses the {@code field} rule. This method should only be called if the
* next tokens start a global, aka {@code LIST|VAL|VAR}.
*/
public Ast.Global parseGlobal() throws ParseException {
throw new UnsupportedOperationException(); //TODO
}
/**
* Parses the {@code list} rule. This method should only be called if the
* next token declares a list, aka {@code LIST}.
*/
public Ast.Global parseList() throws ParseException {
throw new UnsupportedOperationException(); //TODO
}
/**
* Parses the {@code mutable} rule. This method should only be called if the
* next token declares a mutable global variable, aka {@code VAR}.
*/
public Ast.Global parseMutable() throws ParseException {
throw new UnsupportedOperationException(); //TODO
}
/**
* Parses the {@code immutable} rule. This method should only be called if the
* next token declares an immutable global variable, aka {@code VAL}.
*/
public Ast.Global parseImmutable() throws ParseException {
throw new UnsupportedOperationException(); //TODO
}
/**
* Parses the {@code function} rule. This method should only be called if the
* next tokens start a method, aka {@code FUN}.
*/
public Ast.Function parseFunction() throws ParseException {
throw new UnsupportedOperationException(); //TODO
}
/**
* Parses the {@code block} rule. This method should only be called if the
* preceding token indicates the opening a block.
*/
public List<Ast.Statement> parseBlock() throws ParseException {
throw new UnsupportedOperationException(); //TODO
}
/**
* Parses the {@code statement} rule and delegates to the necessary method.
* If the next tokens do not start a declaration, if, while, or return
* statement, then it is an expression/assignment statement.
*/
public Ast.Statement parseStatement() throws ParseException {
/*Ast.Expression leftStatement = parseExpression();
if(match("=")){
Ast.Expression rightStatement = parseExpression();
if(match(";")){
return new Ast.Statement.Assignment(leftStatement,rightStatement);
}
else{
throw new ParseException("Missing closing statement ;", tokens.get(0).getIndex());
}
}
if(match(";")){
return new Ast.Statement.Expression(leftStatement);
}
else{
throw new ParseException("Missing closing statement ;", tokens.get(0).getIndex());
}
*/
return null;
}
/**
* Parses a declaration statement from the {@code statement} rule. This
* method should only be called if the next tokens start a declaration
* statement, aka {@code LET}.
*/
public Ast.Statement.Declaration parseDeclarationStatement() throws ParseException {
throw new UnsupportedOperationException(); //TODO
}
/**
* Parses an if statement from the {@code statement} rule. This method
* should only be called if the next tokens start an if statement, aka
* {@code IF}.
*/
public Ast.Statement.If parseIfStatement() throws ParseException {
throw new UnsupportedOperationException(); //TODO
}
/**
* Parses a switch statement from the {@code statement} rule. This method
* should only be called if the next tokens start a switch statement, aka
* {@code SWITCH}.
*/
public Ast.Statement.Switch parseSwitchStatement() throws ParseException {
throw new UnsupportedOperationException(); //TODO
}
/**
* Parses a case or default statement block from the {@code switch} rule.
* This method should only be called if the next tokens start the case or
* default block of a switch statement, aka {@code CASE} or {@code DEFAULT}.
*/
public Ast.Statement.Case parseCaseStatement() throws ParseException {
throw new UnsupportedOperationException(); //TODO
}
/**
* Parses a while statement from the {@code statement} rule. This method
* should only be called if the next tokens start a while statement, aka
* {@code WHILE}.
*/
public Ast.Statement.While parseWhileStatement() throws ParseException {
throw new UnsupportedOperationException(); //TODO
}
/**
* Parses a return statement from the {@code statement} rule. This method
* should only be called if the next tokens start a return statement, aka
* {@code RETURN}.
*/
public Ast.Statement.Return parseReturnStatement() throws ParseException {
throw new UnsupportedOperationException();//TODO
}
/**
* Parses the {@code expression} rule.
*/
public Ast.Expression parseExpression() throws ParseException {
return parseLogicalExpression();//TODO
}
/**
* Parses the {@code logical-expression} rule.
*/
public Ast.Expression parseLogicalExpression() throws ParseException {
Ast.Expression leftExpression = parseComparisonExpression();
while(match("&&") || match("||")){
String operator = tokens.get(-1).getLiteral();
Ast.Expression rightExpression = parseComparisonExpression();
leftExpression = new Ast.Expression.Binary(operator,leftExpression,rightExpression);
}
return leftExpression;
}
/**
* Parses the {@code equality-expression} rule.
*/
public Ast.Expression parseComparisonExpression() throws ParseException {
Ast.Expression leftExpression = parseAdditiveExpression();
while(match("<") || match(">") || match("==") || match("!=")){
String operator = tokens.get(-1).getLiteral();
Ast.Expression rightExpression = parseAdditiveExpression();
leftExpression = new Ast.Expression.Binary(operator,leftExpression,rightExpression);
}
return leftExpression;
}
/**
* Parses the {@code additive-expression} rule.
*/
public Ast.Expression parseAdditiveExpression() {
Ast.Expression leftExpression = parseMultiplicativeExpression();
while(match("+") || match("-")){
String operator = tokens.get(-1).getLiteral();
Ast.Expression rightExpression = parseMultiplicativeExpression();
leftExpression = new Ast.Expression.Binary(operator,leftExpression,rightExpression);
}
return leftExpression;
}
/**
* Parses the {@code multiplicative-expression} rule.
*/
public Ast.Expression parseMultiplicativeExpression() {
Ast.Expression leftExpression = parsePrimaryExpression();
while(match("*") || match("/")|| match("^")){
String operator = tokens.get(-1).getLiteral();
Ast.Expression rightExpression = parsePrimaryExpression();
leftExpression = new Ast.Expression.Binary(operator,leftExpression,rightExpression);
}
return leftExpression;
}
/**
* Parses the {@code primary-expression} rule. This is the top-level rule
* for expressions and includes literal values, grouping, variables, and
* functions. It may be helpful to break these up into other methods but is
* not strictly necessary.
*/
public Ast.Expression parsePrimaryExpression() throws ParseException{
if (match("NIL")) {
return new Ast.Expression.Literal(null);
}
else if (match("TRUE")) {
return new Ast.Expression.Literal(true);
}
else if (match("FALSE")) {
return new Ast.Expression.Literal(false);
}
else if (peek(Token.Type.INTEGER)) {
String literal = tokens.get(0).getLiteral();
match(Token.Type.INTEGER);
return new Ast.Expression.Literal(new BigInteger(literal));
}
else if (peek(Token.Type.DECIMAL)) {
String literal = tokens.get(0).getLiteral();
match(Token.Type.DECIMAL);
return new Ast.Expression.Literal(new BigDecimal(literal));
}
//NEEDS WORKS
else if(match(Token.Type.IDENTIFIER)){
String name = tokens.get(-1).getLiteral();
return new Ast.Expression.Access(Optional.empty(), name);
}
else if(match("(")){
Ast.Expression expression = parseExpression();
if(!match(")")){
throw new ParseException("Expected Closing Parenthesis ",-1);
//TODO
}
return new Ast.Expression.Group(expression);
}
else if (peek(Token.Type.CHARACTER)) {
return new Ast.Expression.Literal('N');
}
else if (peek(Token.Type.STRING)) {
if(match("\"")){
String name = tokens.get(0).getLiteral();
match("\"");
return new Ast.Expression.Access(Optional.empty(), name);
}
throw new ParseException("Not valid string", -1);
}
else if (peek(Token.Type.OPERATOR)) {
new Ast.Expression.Literal(Token.Type.INTEGER);
match(Token.Type.OPERATOR);
Ast.Expression expression = parseExpression();
match(Token.Type.OPERATOR);
return expression;
} else {
throw new ParseException("Invalid primary expression", -1);
//TODO
}
return null;
}
/**
* As in the lexer, returns {@code true} if the current sequence of tokens
* matches the given patterns. Unlike the lexer, the pattern is not a regex;
* instead it is either a {@link Token.Type}, which matches if the token's
* type is the same, or a {@link String}, which matches if the token's
* literal is the same.
*
* In other words, {@code Token(IDENTIFIER, "literal")} is matched by both
* {@code peek(Token.Type.IDENTIFIER)} and {@code peek("literal")}.
*/
private boolean peek(Object... patterns) {
for (int i = 0; i < patterns.length; i++) {
if (!tokens.has(i)) {
return false;
}
else if (patterns[i] instanceof Token.Type) {
if (patterns[i] != tokens.get(i).getType()) {
return false;
}
}
else if (patterns[i] instanceof String) {
if (!patterns[i].equals(tokens.get(i).getLiteral())) {
return false;
}
}
else {
throw new AssertionError("Invalid pattern object: " + patterns[i].getClass());
}
}
return true;
}
/**
* As in the lexer, returns {@code true} if {@link #peek(Object...)} is true
* and advances the token stream.
*/
private boolean match(Object... patterns) {
boolean peek = peek(patterns);
if (peek) {
for (int i = 0; i < patterns.length; i++) {
tokens.advance();
}
}
return peek;
}
private static final class TokenStream {
private final List<Token> tokens;
private int index = 0;
private TokenStream(List<Token> tokens) {
this.tokens = tokens;
}
/**
* Returns true if there is a token at index + offset.
*/
public boolean has(int offset) {
return index + offset < tokens.size();
}
/**
* Gets the token at index + offset.
*/
public Token get(int offset) {
return tokens.get(index + offset);
}
/**
* Advances to the next token, incrementing the index.
*/
public void advance() {
index++;
}
}
}
| jsaarela1/PLC_Project | Parser.java | 2,715 | /**
* Parses a declaration statement from the {@code statement} rule. This
* method should only be called if the next tokens start a declaration
* statement, aka {@code LET}.
*/ | block_comment | en | false |
183953_0 | //๋ฐฑ์ค์์ java ๋๋ฆด๋ผ class์ด๋ฆ์ Main์ผ๋ก ๋ฐ๊พธ๊ณ ๋๋ฆฌ๋ฉด ๊ฐ๋ฅ!
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Gear {
public static void main(String[] args) throws IOException {
int[][] gearState = new int[5][8];
String[] gearNumber = new String[8];
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < 4; i++) {
gearNumber = bufferedReader.readLine().split("");
for (int j = 0; j < 8; j++) {
gearState[i][j] = Integer.parseInt(gearNumber[j]);
}
}
int k = Integer.parseInt(bufferedReader.readLine());
while (k-- > 0) {
StringTokenizer stringTokenizer = new StringTokenizer(bufferedReader.readLine());
int wheelNumber = Integer.parseInt(stringTokenizer.nextToken());
int rotate = Integer.parseInt(stringTokenizer.nextToken());
boolean[] checkNumber = new boolean[3];
for (int i = 0; i <3; i++) {
if (gearState[i][2] == gearState[i + 1][6]) {
checkNumber[i] = true;
}
}
if (wheelNumber == 1) {
rotation(wheelNumber, rotate, gearState);
if (!checkNumber[0]) {
rotate = changeRotate(rotate);
rotation(2,rotate,gearState);
if(!checkNumber[1]){
rotate = changeRotate(rotate);
rotation(3, rotate, gearState);
if(!checkNumber[2]){
rotate = changeRotate(rotate);
rotation(4,rotate,gearState);
}
}
}
} else if (wheelNumber == 2) {
rotation(wheelNumber, rotate,gearState);
if(!checkNumber[0]||!checkNumber[1]){
if(!checkNumber[0]){
rotate = changeRotate(rotate);
rotation(1,rotate,gearState);
rotate = changeRotate(rotate);
}
if(!checkNumber[1]){
rotate = changeRotate(rotate);
rotation(3,rotate,gearState);
if(!checkNumber[2]){
rotate = changeRotate(rotate);
rotation(4,rotate,gearState);
}
}
}
} else if (wheelNumber == 3) {
rotation(wheelNumber,rotate,gearState);
if(!checkNumber[1]||!checkNumber[2]){
if(!checkNumber[2]){
rotate = changeRotate(rotate);
rotation(4, rotate,gearState);
rotate = changeRotate(rotate);
}
if(!checkNumber[1]){
rotate = changeRotate(rotate);
rotation(2, rotate,gearState);
if(!checkNumber[0]){
rotate = changeRotate(rotate);
rotation(1,rotate,gearState);
}
}
}
} else if (wheelNumber == 4) {
rotation(4,rotate,gearState);
if(!checkNumber[2]){
rotate = changeRotate(rotate);
rotation(3,rotate,gearState);
if(!checkNumber[1]){
rotate=changeRotate(rotate);
rotation(2,rotate,gearState);
if(!checkNumber[0]){
rotate= changeRotate(rotate);
rotation(1, rotate,gearState);
}
}
}
}
}
int sum=0;
if (gearState[0][0]==1){
sum+=1;
}
if(gearState[1][0]==1){
sum+=2;
}
if(gearState[2][0]==1){
sum+=4;
}
if(gearState[3][0]==1){
sum+=8;
}
System.out.println(sum);
}
private static void rotation(int wheelNumber, int rotate, int[][] gearState) {
if (rotate == 1) {
int lastNumber = gearState[wheelNumber-1][7];
for (int i = 7; i > 0; i--) {
gearState[wheelNumber-1][i] = gearState[wheelNumber-1][i-1];
}
gearState[wheelNumber-1][0] = lastNumber;
} else if (rotate == -1) {
int temp = gearState[wheelNumber-1][0];
for (int i = 0; i < 7; i++) {
gearState[wheelNumber-1][i] = gearState[wheelNumber-1][i+1];
}
gearState[wheelNumber-1][7] = temp;
}
}
private static int changeRotate(int rotate) {
int answer=0;
if (rotate == 1) {
answer = -1;
} else if (rotate == -1) {
answer = 1;
}
return answer;
}
}
| dawn-Wi/algorithm | 14891.java | 1,153 | //๋ฐฑ์ค์์ java ๋๋ฆด๋ผ class์ด๋ฆ์ Main์ผ๋ก ๋ฐ๊พธ๊ณ ๋๋ฆฌ๋ฉด ๊ฐ๋ฅ! | line_comment | en | true |
184992_10 | public class Pawn extends ConcretePiece {
private static int pieceCounter = 0; //0-12 Def pieces player 1, 13-36 Att pieces player 2.
public Pawn(Player player){
//define player field
super.player = player;
//enter unicode of pawn
super.pieceType = "โ"; //2659 = pawn unicode
//naming the piece the way they are created, D1 - D13(NO D7 = KING = K7), A1 - A24.
//toString implement at concretePiece and return the pieceName
super.pieceName = setPieceName(); //unique key, is the piece name.
pieceCounter++; //updating the piece counter
}
//piece counter.
private int countPiecesHelper(){
if(pieceCounter == 37) {pieceCounter = 0;} //when the last piece created, reseat the piece counter for the next game.
else if(pieceCounter == 6) pieceCounter++; //since number 6 that is actually number 7 piece, saved for the king.
return pieceCounter;
}
//naming the piece the way they are created, D1 - D13(NO D7 = KING = K7), A1 - A24.
private String setPieceName(){
String prefixAD = this.player.isPlayerOne() ? "D" : "A";
String name = this.player.isPlayerOne() ? prefixAD + (countPiecesHelper() + 1):
prefixAD + (countPiecesHelper() - 12);
return name;
}
}
| AmitGini/Hnefatafl_Vikings_Chess_Game | Pawn.java | 361 | //since number 6 that is actually number 7 piece, saved for the king.
| line_comment | en | false |
185393_5 | import sun.misc.Unsafe;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.LockSupport;
/**
* @author zhangdididi
*/
public class Aqs {
/**
* ่ฎฐๅฝๅฝๅๅ ้็ๆฌกๆฐ
*/
private volatile int state = 0;
/**
* ๅฝๅๆๆ้็็บฟ็จ
*/
private Thread lockHolder;
public int getState() {
return state;
}
public void setLockHolder(Thread lockHolder) {
this.lockHolder = lockHolder;
}
/**
* ็บฟ็จๅฎๅ
จ็้ๅ---ๅบไบCAS็ฎๆณ
*/
private static ConcurrentLinkedQueue<Thread> waiters = new ConcurrentLinkedQueue<Thread>();
/**
* ๅ็งป้
*/
private static final long STATEOFFSET;
/**
* ้่ฟๅๅฐ่ทๅไธไธชUnsafeๅฎไพๅฏน่ฑก
*/
private static final Unsafe UNSAFE = aqs.UnsafeIntance.reflectGetUnsafe();
static {
try {
//่ทๅๅ็งป้
STATEOFFSET = UNSAFE.objectFieldOffset(Aqs.class.getDeclaredField("state"));
} catch (Exception e) {
throw new Error();
}
}
//CASไฟฎๆน state ๅญๆฎต
public final boolean compareAndSetState(int expect, int updata) {
return UNSAFE.compareAndSwapInt(this, STATEOFFSET, expect, updata);
}
/**
* ๅฐ่ฏ่ทๅ้
*/
public boolean aquire() {
Thread current = Thread.currentThread();
//ๅฝๅๅ ้็็ถๆ
int c = getState();
if (c == 0) {
//ๅฝๅๅๆญฅๅจ่ฟๆฒกๆ่ขซๆๆ
boolean canUse = waiters.isEmpty() || current == waiters.peek();
if (canUse && compareAndSetState(0, 1)) {
//ไฟฎๆนๆๅ็็บฟ็จ๏ผ่ฎพ็ฝฎไธบๆๆ่
setLockHolder(current);
return true;
}
}
return false;
}
/**
* ๅ ้ๅ็ๅค็
*/
public void lock() {
//ๅ ้ๆๅ
if (aquire()) {
return;
}
//ๆฒกๆๅ ้ๆๅ
Thread current = Thread.currentThread();
waiters.add(current);
//่ชๆ๏ผๆญปๅพช็ฏ็กฎไฟๆฒกๆ่ทๅๅฐ้็็บฟ็จไธๅ ๆง่กๅ็ปญไปฃ็ /ๅ ๆCPU
for (;;){
if (aquire()) {
//ๅค้้ๅคด็บฟ็จ็่ฏ๏ผๅฐฑ้่ฆไป้ๅไธญ็งป้ค่ฏฅ็บฟ็จ๏ผ่ฎฉๅ้ข็็บฟ็จๆๅฐ้้ฆ
waiters.poll();
return;
}
LockSupport.park();//้ปๅก--้ๆพCPUไฝฟ็จๆ๏ผ่ขซๅทๅ
ฅๅฐ่ฟ่กๆถ็ถๆๆฎต
}
}
/**
* ้ๆพ้
*/
public void unlock() {
if (lockHolder != Thread.currentThread()) {
//ๆๅบๅผๅธธ
throw new RuntimeException("Lockholder is not current thread");
}
int state = getState();
if (compareAndSetState(state, 0)) {
setLockHolder(null);
Thread first = waiters.peek();
if (first != null) {
//ๅฐฑ้่ฆๅค้้้ฆ็บฟ็จ
LockSupport.unpark(first);
}
}
}
}
| zhangdididi/MyAbstractQueuedSynchronizer | Aqs.java | 706 | /**
* ้่ฟๅๅฐ่ทๅไธไธชUnsafeๅฎไพๅฏน่ฑก
*/ | block_comment | en | true |
185506_0 | /**
A PUP'd array (or singleton) of native types.
Copyright University of Illinois at Urbana-Champaign
Written by Orion Sky Lawlor, [email protected], 2004/1/21
*/
package charm.debug.fmt;
public class PNative extends PAbstract {
private float[] v_float;
private double[] v_double;
private int[] v_int;
private long[] v_long;
private int len;
PNative(int[] v) {v_int=v; v_long=null; v_float=null; v_double=null; len=v.length;}
PNative(long[] v) {v_int=null; v_long=v; v_float=null; v_double=null; len=v.length;}
PNative(float[] v) {v_int=null; v_long=null; v_float=v; v_double=null; len=v.length; }
PNative(double[] v) {v_int=null; v_long=null; v_float=null; v_double=v; len=v.length; }
/// Return the element with this name
public String toString() {
StringBuffer ret=new StringBuffer(super.toString());
if (len>1) ret.append("{");
for (int i=0;i<len;i++) {
if (v_int!=null) ret.append(""+v_int[i]);
if (v_long!=null) ret.append(""+v_long[i]);
if (v_float!=null) ret.append(""+v_float[i]);
if (v_double!=null) ret.append(""+v_double[i]);
if (i+1!=len)
ret.append(", ");
}
if (len>1) ret.append("} ");
return ret.toString();
}
public int length() {return len;}
/// Assuming this is an int, return the i'th value
public int getIntValue(int i) {return v_int[i];}
public long getLongValue(int i) {return v_long[i];}
public float getFloatValue(int i) {return v_float[i];}
public double getDoubleValue(int i) {return v_double[i];}
/// Draw this object to this screen.
public boolean draw(PDisplayStyle p,int drawStyle) {
super.draw(p,drawStyle);
for (int i=0;i<len;i++) {
String v="??";
if (v_int!=null) v=Integer.toString(v_int[i]);
if (v_long!=null) v=Long.toString(v_int[i]);
if (v_float!=null) v=Float.toString(v_float[i]);
if (v_double!=null) v=Double.toString(v_double[i]);
if (!p.drawString(v)) return false; // too far to right
}
return true;
}
};
| UIUC-PPL/ccs_tools | charm/debug/fmt/PNative.java | 733 | /**
A PUP'd array (or singleton) of native types.
Copyright University of Illinois at Urbana-Champaign
Written by Orion Sky Lawlor, [email protected], 2004/1/21
*/ | block_comment | en | true |
185633_0 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package mainPackage;
/**
*
* @author Nayeem Khan
*/
public class RulesAndRegulations {
private String userType;
private String rulesAndRegulations;
public RulesAndRegulations(String userType, String rulesAndRegulations) {
this.userType = userType;
this.rulesAndRegulations = rulesAndRegulations;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public String getRulesAndRegulations() {
return rulesAndRegulations;
}
public void setRulesAndRegulations(String rulesAndRegulations) {
this.rulesAndRegulations = rulesAndRegulations;
}
}
| knayeem401416/metro-rail | src/mainPackage/RulesAndRegulations.java | 228 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/ | block_comment | en | true |
186147_5 |
import java.io.Serializable;
import java.io.File;
import java.text.DecimalFormat;
//A serializeable class that represents the attributes of different solar panels.
public class Module implements Serializable{
/**
*
*/
private static final long serialVersionUID = 2L;
transient private static String homedir = System.getProperty("user.home");
transient private static String delim = System.getProperty("file.separator");
transient final static File productionPath = new File(homedir + delim + "Dropbox" + delim + "Utility and Permiting" + delim + "Application File" + delim + "Modules");
protected double Watts;
protected String Token;
protected String Brand;
protected String Number;
protected String NumberBrandQty;
protected String ArrayTilt;
protected String ArrayAzimuth;
protected String quantity;
protected String DCkiloWatts;
protected String Racking;
protected String ptcRating;
protected double ptcrate;
protected double DCkWatts;
protected int Quantity;
protected String fileName;
protected final String space = " ";
protected static DecimalFormat myFormat = new DecimalFormat("##.####");
//constructor uses values input in ModuleEditor class.
public Module(String Token, String Watts, String Brand, String Number, String ptcRating ) {
this.Watts = Double.parseDouble(Watts);
this.Brand = Brand;
this.Number = Number;
this.ptcRating = ptcRating;
this.ptcrate = Double.parseDouble(ptcRating);
this.Token = Token;
this.fileName = productionPath.getAbsolutePath() + delim + Token + ".data";
}
//sets the racking as obtained from the csv file
public void setRacking(String Racking)
{
this.Racking = Racking;
}
//sets a string and integer version of module quantity as input from user.
public void setQuantity(String Quantity)
{
this.quantity = Quantity;
this.Quantity = Integer.parseInt(Quantity);
}
//sets the azimuth as obtained from the csv file
public void setAzimuth(String Azimuth)
{
ArrayAzimuth = Azimuth;
}
//tilt obtained from csv file
public void setTilt(String Tilt)
{
ArrayTilt = Tilt;
}
//Creates a string used in installation agreements
public void setNumberBrandQty()
{
NumberBrandQty = Brand + " " + Number + " " + "(Qty. " + quantity + ")";
}
//sets a string and double version of DCkilowatts.
public void setDCkiloWatts()
{
DCkWatts = Double.parseDouble(myFormat.format(Watts * Quantity));
DCkiloWatts = myFormat.format(Watts * Quantity);
}
//myriad self explanatory getter methods.
public String getBrand() {
return Brand;
}
public String getNumber() {
return Number;
}
public String getNumberBrandQty() {
return NumberBrandQty;
}
public String getArrayTilt() {
return ArrayTilt;
}
public String getArrayAzimuth() {
return ArrayAzimuth;
}
public String getQuantityString() {
return quantity;
}
public double getDCkWatts()
{
return DCkWatts;
}
public String getDCkiloWatts() {
return DCkiloWatts;
}
public String getRacking() {
return Racking;
}
public String getptcRating() {
return ptcRating;
}
public double getptcrate() {
return ptcrate;
}
public int getQuantityInt() {
return Quantity;
}
public String getFileName() {
return fileName;
}
public String getWatts() {
return Integer.toString((int)(Watts*1000));
}
public String toString(){
return Token;
}
}
| Seth5141/iText-PDF-Preparer | Module.java | 997 | //sets the azimuth as obtained from the csv file | line_comment | en | true |
186457_6 | /*
SMS Pricing
Documentation: https://www.twilio.com/docs/sms/api/pricing
NumberType: mobile, local, shortcode, or toll free
*/
package messaging;
import com.twilio.Twilio;
import com.twilio.rest.pricing.v1.messaging.Country;
import com.twilio.type.InboundSmsPrice;
import com.twilio.type.OutboundSmsPrice;
public class msg_pricing {
private static final String ACCOUNT_SID = System.getenv("ACCOUNT_SID");
private static final String AUTH_TOKEN = System.getenv("AUTH_TOKEN");
public static void main(String[] args) {
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
String countryCode = "GB";
System.out.println("+ Get Twilio Messaging pricing for country code: " + countryCode);
Country messagingCountry = Country.fetcher(countryCode).fetch();
for (InboundSmsPrice price : messagingCountry.getInboundSmsPrices()) {
// For each message pricing category,
// print number type and current (reflecting any discounts your account has) price.
System.out.println("++ from: " + price.getType()
+ " " + price.getCurrentPrice()
+ " " + price.getBasePrice()
);
}
System.out.println("+ End of list.");
System.out.println("");
System.out.println("+ List the country's carriers: MCC MNC Name");
for (OutboundSmsPrice price : messagingCountry.getOutboundSmsPrices()) {
// For each message pricing category,
// print number type and current (reflecting any discounts your account has) price.
System.out.println("+ " + price.getMcc()
+ " " + price.getMnc()
+ " " + price.getCarrier()
// + " " + price.getPrices()
);
}
System.out.println("+ End of list.");
/*
System.out.println("+ list of countries where Twilio Messaging is available.");
ResourceSet<Country> messagingCountries = Country.reader().read();
for (Country country : messagingCountries) {
System.out.println("+ " + country.getIsoCountry());
}
System.out.println("+ End of list.");
*/
}
}
| tigerfarm/JavaTwSamples | messaging/msg_pricing.java | 520 | /*
System.out.println("+ list of countries where Twilio Messaging is available.");
ResourceSet<Country> messagingCountries = Country.reader().read();
for (Country country : messagingCountries) {
System.out.println("+ " + country.getIsoCountry());
}
System.out.println("+ End of list.");
*/ | block_comment | en | true |
186731_0 | package com.itabrek;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class CrptApi {
private final long interval;
private final int requestLimit;
private final Lock lock = new ReentrantLock();
private final AtomicInteger requestCount = new AtomicInteger(0);
private final Condition condition = lock.newCondition();
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private static final String url = "https://ismp.crpt.ru/api/v3/lk/documents/create";
public CrptApi(long interval, int requestsLimit) {
this.interval = interval;
this.requestLimit = requestsLimit;
scheduler.scheduleAtFixedRate(this::resetRequestCount, interval, interval, TimeUnit.MILLISECONDS);
}
private void resetRequestCount() {
lock.lock();
try {
requestCount.set(0);
condition.signalAll();
} finally {
lock.unlock();
}
}
public void shutdownScheduler() {
scheduler.shutdown();
try {
if (!scheduler.awaitTermination(1, TimeUnit.SECONDS)) {
scheduler.shutdownNow();
}
} catch (InterruptedException e) {
scheduler.shutdownNow();
Thread.currentThread().interrupt();
}
}
public String createDocument(Document document, String signature) throws InterruptedException {
lock.lock();
try {
while (requestCount.get() >= requestLimit) {
condition.await();
}
requestCount.incrementAndGet();
} finally {
lock.unlock();
}
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(url);
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(document);
httpPost.setEntity(new StringEntity(json));
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Signature", signature);
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
int statusCode = response.getCode();
String responseString = EntityUtils.toString(response.getEntity());
System.out.println(responseString);
return "Status: " + statusCode + ", Response: " + responseString;
}
} catch (Exception e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
}
}
public static class Document{
public Description description;
public String doc_id;
public String doc_status;
public String doc_type;
public boolean importRequest;
public String owner_inn;
public String participant_inn;
public String producer_inn;
public String production_date;
public String production_type;
public List<Product> products = new ArrayList<>();
public String reg_date;
public String reg_number;
public Document(Description description, String doc_id, String doc_status, String doc_type, boolean importRequest, String owner_inn, String participant_inn, String producer_inn, String production_date, String production_type, List<Product> products, String reg_date, String reg_number) {
this.description = description;
this.doc_id = doc_id;
this.doc_status = doc_status;
this.doc_type = doc_type;
this.importRequest = importRequest;
this.owner_inn = owner_inn;
this.participant_inn = participant_inn;
this.producer_inn = producer_inn;
this.production_date = production_date;
this.production_type = production_type;
this.products = products;
this.reg_date = reg_date;
this.reg_number = reg_number;
}
public Document() {
}
public Description getDescription() {
return description;
}
public void setDescription(Description description) {
this.description = description;
}
public String getDoc_id() {
return doc_id;
}
public void setDoc_id(String doc_id) {
this.doc_id = doc_id;
}
public String getDoc_status() {
return doc_status;
}
public void setDoc_status(String doc_status) {
this.doc_status = doc_status;
}
public String getDoc_type() {
return doc_type;
}
public void setDoc_type(String doc_type) {
this.doc_type = doc_type;
}
public boolean isImportRequest() {
return importRequest;
}
public void setImportRequest(boolean importRequest) {
this.importRequest = importRequest;
}
public String getOwner_inn() {
return owner_inn;
}
public void setOwner_inn(String owner_inn) {
this.owner_inn = owner_inn;
}
public String getParticipant_inn() {
return participant_inn;
}
public void setParticipant_inn(String participant_inn) {
this.participant_inn = participant_inn;
}
public String getProducer_inn() {
return producer_inn;
}
public void setProducer_inn(String producer_inn) {
this.producer_inn = producer_inn;
}
public String getProduction_date() {
return production_date;
}
public void setProduction_date(String production_date) {
this.production_date = production_date;
}
public String getProduction_type() {
return production_type;
}
public void setProduction_type(String production_type) {
this.production_type = production_type;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public String getReg_date() {
return reg_date;
}
public void setReg_date(String reg_date) {
this.reg_date = reg_date;
}
public String getReg_number() {
return reg_number;
}
public void setReg_number(String reg_number) {
this.reg_number = reg_number;
}
}
public static class Description{
public String participantInn;
public Description(String participantInn) {
this.participantInn = participantInn;
}
public String getParticipantInn() {
return participantInn;
}
public void setParticipantInn(String participantInn) {
this.participantInn = participantInn;
}
}
public class Product{
public String certificate_document;
public String certificate_document_date;
public String certificate_document_number;
public String owner_inn;
public String producer_inn;
public String production_date;
public String tnved_code;
public String uit_code;
public String uitu_code;
public Product(String certificate_document, String certificate_document_date, String certificate_document_number, String owner_inn, String producer_inn, String production_date, String tnved_code, String uit_code, String uitu_code) {
this.certificate_document = certificate_document;
this.certificate_document_date = certificate_document_date;
this.certificate_document_number = certificate_document_number;
this.owner_inn = owner_inn;
this.producer_inn = producer_inn;
this.production_date = production_date;
this.tnved_code = tnved_code;
this.uit_code = uit_code;
this.uitu_code = uitu_code;
}
public String getCertificate_document() {
return certificate_document;
}
public void setCertificate_document(String certificate_document) {
this.certificate_document = certificate_document;
}
public String getCertificate_document_date() {
return certificate_document_date;
}
public void setCertificate_document_date(String certificate_document_date) {
this.certificate_document_date = certificate_document_date;
}
public String getCertificate_document_number() {
return certificate_document_number;
}
public void setCertificate_document_number(String certificate_document_number) {
this.certificate_document_number = certificate_document_number;
}
public String getOwner_inn() {
return owner_inn;
}
public void setOwner_inn(String owner_inn) {
this.owner_inn = owner_inn;
}
public String getProducer_inn() {
return producer_inn;
}
public void setProducer_inn(String producer_inn) {
this.producer_inn = producer_inn;
}
public String getProduction_date() {
return production_date;
}
public void setProduction_date(String production_date) {
this.production_date = production_date;
}
public String getTnved_code() {
return tnved_code;
}
public void setTnved_code(String tnved_code) {
this.tnved_code = tnved_code;
}
public String getUit_code() {
return uit_code;
}
public void setUit_code(String uit_code) {
this.uit_code = uit_code;
}
public String getUitu_code() {
return uitu_code;
}
public void setUitu_code(String uitu_code) {
this.uitu_code = uitu_code;
}
}
}
| rozoomcool/exam_thread_safety_requests | CrptApi.java | 2,356 | //ismp.crpt.ru/api/v3/lk/documents/create"; | line_comment | en | true |
186945_0 | /**
* TASK 16: Setting up the paddle class
* add the following fields
* 1. double speed (paddle speed)
* 2. direction (moves only in the x-axis.
* a. value 1: to the right
* b. value -1: to the left
* c. value 0: no motion, initial value.
* d. initialize the class with a constructor
* e. add getters for the field.
*
* TASK 17: Implement the draw, moveRight,
* moveLeft methods.
*/
public class Paddle extends BaseObject{
private double speed;
private double direction;
public Paddle (double x, double y, double radius) {
super(x, y, radius);
}
public Paddle (double x, double y){
this(x, y, 3);
this.speed = 1;
this.direction = 0;
}
@Override
void move() {
//calculates the change in x of the paddle
double dx = this.direction * speed;
//calculate a new value for x
x += dx;
}
public void moveRight(){
this.direction = 1; //to move the paddle right
}
public void moveLeft(){
this.direction = -1; //to move the paddle left
}
@Override
void draw(Canvas canvas) {
}
public double getSpeed() { return speed; }
public double getDirection() { return direction;}
}
| joshua-akuna/arkanoid-clone_java | Paddle.java | 340 | /**
* TASK 16: Setting up the paddle class
* add the following fields
* 1. double speed (paddle speed)
* 2. direction (moves only in the x-axis.
* a. value 1: to the right
* b. value -1: to the left
* c. value 0: no motion, initial value.
* d. initialize the class with a constructor
* e. add getters for the field.
*
* TASK 17: Implement the draw, moveRight,
* moveLeft methods.
*/ | block_comment | en | true |
187002_0 | /*
Topic:- Java Reflection - Attributes
Link:- https://www.hackerrank.com/challenges/java-reflection-attributes/problem?isFullScreen=true
Problem:-
JAVA reflection is a very powerful tool to inspect the attributes of a class in runtime.
For example, we can retrieve the list of public fields of a class using getDeclaredMethods().
You have to print all the methods of another class called Student in alphabetical order.
The Student class looks like this:
class Student{
private String name;
private String id;
private String email;
public String getName() {
return name;
}
public void setId(String id) {
this.id = id;
}
public void setEmail(String email) {
this.email = email;
}
public void anothermethod(){ }
......
......
some more methods
......
}
You have to print all the methods of the student class in alphabetical order like this:
anothermethod
getName
setEmail
setId
......
......
some more methods
......
There is no sample input/output for this problem. If you press "Run Code", it will compile it, but it won't show any outputs.
Hint: See the oracle docs for more details about JAVA Reflection Methods and Fields
Solution:-
*/
public class Solution {
public static void main(String[] args){
Class student = new Student().getClass();
Method[] methods = student.getDeclaredMethods();
ArrayList<String> methodList = new ArrayList<>();
for(Method method:methods){
methodList.add(method.getName());
}
Collections.sort(methodList);
for(String name: methodList){
System.out.println(name);
}
}
}
| Shrey212001/100DaysOfCode | Day59.java | 392 | /*
Topic:- Java Reflection - Attributes
Link:- https://www.hackerrank.com/challenges/java-reflection-attributes/problem?isFullScreen=true
Problem:-
JAVA reflection is a very powerful tool to inspect the attributes of a class in runtime.
For example, we can retrieve the list of public fields of a class using getDeclaredMethods().
You have to print all the methods of another class called Student in alphabetical order.
The Student class looks like this:
class Student{
private String name;
private String id;
private String email;
public String getName() {
return name;
}
public void setId(String id) {
this.id = id;
}
public void setEmail(String email) {
this.email = email;
}
public void anothermethod(){ }
......
......
some more methods
......
}
You have to print all the methods of the student class in alphabetical order like this:
anothermethod
getName
setEmail
setId
......
......
some more methods
......
There is no sample input/output for this problem. If you press "Run Code", it will compile it, but it won't show any outputs.
Hint: See the oracle docs for more details about JAVA Reflection Methods and Fields
Solution:-
*/ | block_comment | en | true |
187094_2 |
// Java implementation of finding length of longest
// Common substring using Dynamic Programming
public
class
LongestCommonSubSequence
{
/*
Returns length of longest common substring
of X[0..m-1] and Y[0..n-1]
*/
static
int
LCSubStr(
char
X[],
char
Y[],
int
m,
int
n)
{
// Create a table to store lengths of longest common suffixes of
// substrings. Note that LCSuff[i][j] contains length of longest
// common suffix of X[0..i-1] and Y[0..j-1]. The first row and
// first column entries have no logical meaning, they are used only
// for simplicity of program
int
LCStuff[][] =
new
int
[m +
1
][n +
1
];
int
result =
0
;
// To store length of the longest common substring
// Following steps build LCSuff[m+1][n+1] in bottom up fashion
for
(
int
i =
0
; i <= m; i++)
{
for
(
int
j =
0
; j <= n; j++)
{
if
(i ==
0
|| j ==
0
)
LCStuff[i][j] =
0
;
else
if
(X[i -
1
] == Y[j -
1
])
{
LCStuff[i][j] = LCStuff[i -
1
][j -
1
] +
1
;
result = Integer.max(result, LCStuff[i][j]);
}
else
LCStuff[i][j] =
0
;
}
}
return
result;
}
// Driver Program to test above function
public
static
void
main(String[] args)
{
String X =
"OldSite:GeeksforGeeks.org"
;
String Y =
"NewSite:GeeksQuiz.com"
;
int
m = X.length();
int
n = Y.length();
System.out.println(
"Length of Longest Common Substring is "
+ LCSubStr(X.toCharArray(), Y.toCharArray(), m, n));
}
}
// This code is contributed by Sumit Ghosh | dhyan/code2vec_code_complexity | Dataset/346.java | 589 | /*
Returns length of longest common substring
of X[0..m-1] and Y[0..n-1]
*/ | block_comment | en | false |
187899_0 | /******************************************************************************
Online Java Compiler.
Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute it.
*******************************************************************************/
public class Main
{
HashMap<Integer, HashMap<Integer>> diffSet;
public static void main(String[] args) {
diffSet = new HashSet<>();
nodeValues = new HashSet<>();
mapForNodeToLevel = new HashMap<>();
inorder(root);
TreeNode x1
TreeNode x2
}
public void inorder(TreeNode root, int level) {
if (root == null)
return;
diffSet.add(x - root.value);
inoder(root.left, level + 1);
inorder(root.right, level + 1);
}
public boolean isPairExist(TreeNode root) {
if(root == null)
return false;
if (diffSet.contains(root.value)) {
return true;
}
return isPairExist(root.left) || isPairExist(root.right);
}
/**
* Tree
* x
* find a if there is any such pair whose sum will be x
*
* {1, 1, 2}
* x = 3
* a + b = x
* a = x - b
*
* sorted array find single element
* 1, 1, 2, 2, 3, 3, 4, 5, 5
*
* 0, 1, 2, 3, 4, 5, 6, 7, 8
*
*
* yes yes yes, no no non o
* start = 0;
* end = 8
* mid = 4;
*
* if (mid is even)
* then check its value is present at next index
*
* 1, 1, 2, 2, 3, 4, 4
*
* 0, 1, 2, 3, 4, 5, 6
* start == 0
* end = 6
*
* start = 4
* end = 6
* mid = 5
*
* start = 4
* end = 5
* mid = 4
*
* start = 4
* end = 4
* mid = 4
* */
public boolean isSingleElementExist(int arr[]) {
int start = 0;
int end = arr.length - 1;
while(start < end) {
int mid = (start + end) / 2;
if (mid % 2 != 0) {
if (arr[mid] != arr[mid - 1])
end = mid - 1;
else
start = mid + 1;
} else {
if (arr[mid] != arr[mid + 1]) {
end = mid;
} else {
start = mid + 2;
}
}
}
}
}
| pradhuman2022/Ds-Algo | MMT-1.java | 705 | /******************************************************************************
Online Java Compiler.
Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute it.
*******************************************************************************/ | block_comment | en | true |
188508_12 | /**
* Models a simple solid sphere.
* This class represents a Ball object. When combined with the GameArena class,
* instances of the Ball class can be displayed on the screen.
*/
public class Ball
{
// The following instance variables define the
// information needed to represent a Ball
// Feel free to declare more instance variables if you think it will support your work.
private double xPosition; // The X coordinate of this Ball
private double yPosition; // The Y coordinate of this Ball
private double size; // The diameter of this Ball
private int layer; // The layer of this ball is on.
private String colour; // The colour of this Ball
// Permissible colours are:
// BLACK, BLUE, CYAN, DARKGREY, GREY,
// GREEN, LIGHTGREY, MAGENTA, ORANGE,
// PINK, RED, WHITE, YELLOW, BROWN
/**
* Constructor for the Ball class. Sets a default layer of 0.
* @param x The x co-ordinate of centre of the Ball (in pixels)
* @param y The y co-ordinate of centre of the Ball (in pixels)
* @param diameter The diameter of the Ball (in pixels)
* @param col The colour of the Ball (Permissible colours are: BLACK, BLUE, CYAN, DARKGREY, GREY, GREEN, LIGHTGREY, MAGENTA, ORANGE, PINK, RED, WHITE, YELLOW or BROWN)
*/
public Ball(double x, double y, double diameter, String col)
{
this.xPosition = x;
this.yPosition = y;
this.size = diameter;
this.colour = col;
this.layer = 0;
}
/**
* Constructor for the Ball class, with a layer specified.
* @param x The x co-ordinate of centre of the Ball (in pixels)
* @param y The y co-ordinate of centre of the Ball (in pixels)
* @param diameter The diameter of the Ball (in pixels)
* @param col The colour of the Ball (Permissible colours are: BLACK, BLUE, CYAN, DARKGREY, GREY, GREEN, LIGHTGREY, MAGENTA, ORANGE, PINK, RED, WHITE, YELLOW or BROWN)
* @param layer The layer this ball is to be drawn on. Objects with a higher layer number are always drawn on top of those with lower layer numbers.
*/
public Ball(double x, double y, double diameter, String col, int layer)
{
this.xPosition = x;
this.yPosition = y;
this.size = diameter;
this.colour = col;
this.layer = layer;
}
/**
* Obtains the current position of this Ball.
* @return the X coordinate of this Ball within the GameArena.
*/
public double getXPosition()
{
return xPosition;
}
/**
* Obtains the current position of this Ball.
* @return the Y coordinate of this Ball within the GameArena.
*/
public double getYPosition()
{
return yPosition;
}
/**
* Moves the current position of this Ball to the given co-ordinates
* @param x the new x co-ordinate of this Ball
*/
public void setXPosition(double x)
{
this.xPosition = x;
}
/**
* Moves the current position of this Ball to the given co-ordinates
* @param y the new y co-ordinate of this Ball
*/
public void setYPosition(double y)
{
this.yPosition = y;
}
/**
* Obtains the size of this Ball.
* @return the diameter of this Ball,in pixels.
*/
public double getSize()
{
return size;
}
/**
* Sets the diameter of this Ball to the given size.
* @param s the new diameter of this Ball, in pixels.
*/
public void setSize(double s)
{
size = s;
}
/**
* Obtains the layer of this Ball.
* @return the layer of this Ball.
*/
public int getLayer()
{
return layer;
}
/**
* Sets the layer of this Ball.
* @param l the new layer of this Ball. Higher layer numbers are drawn on top of low layer numbers.
*/
public void setLayer(int l)
{
layer = l;
}
/**
* Obtains the colour of this Ball.
* @return a textual description of the colour of this Ball.
*/
public String getColour()
{
return colour;
}
/**
* Sets the colour of this Ball.
* @param c the new colour of this Ball, as a String value. Permissable colours are: BLACK, BLUE, CYAN, DARKGREY, GREY, GREEN, LIGHTGREY, MAGENTA, ORANGE, PINK, RED, WHITE, YELLOW or #RRGGBB.
*/
public void setColour(String c)
{
colour = c;
}
/**
* Moves this Ball by the given amount.
*
* @param dx the distance to move on the x axis (in pixels)
* @param dy the distance to move on the y axis (in pixels)
*/
public void move(double dx, double dy)
{
xPosition += dx;
yPosition += dy;
}
/**
* Determines if this Ball is overlapping a given ball.
* If the two balls overlap, they have collided.
*
* @param b the ball to test for collision
* @return true of this ball is overlapping the ball b, false otherwise.
*/
public boolean collides(Ball b)
{
double dx = b.xPosition - xPosition;
double dy = b.yPosition - yPosition;
double distance = Math.sqrt(dx*dx+dy*dy);
return distance < size/2 + b.size/2;
}
} | tade-art/Java-Air-Hockey-Game | Ball.java | 1,485 | // PINK, RED, WHITE, YELLOW, BROWN
| line_comment | en | true |
188844_0 | import java.io.File;
import java.io.FileNotFoundException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Mine {
public static void main(String[] args) {
if (args.length != 3) {
System.err.println(">>> ERROR: Run program with java Mine *candidate_transaction_file* *difficulty* *prev_hash*");
System.exit(1);
}
Transaction[] transactions = readTransactions(args[0]);
assert transactions != null;
// System.out.println("$$$ Transactions read in successfully");
Arrays.sort(transactions);
// System.out.println("$$$ Sorted transactions based on miner reward");
Block block = new Block(transactions, args[2], new BigInteger(args[1]));
mine(block);
// System.out.println("$$$ Successfully mined block");
}
private static Transaction[] readTransactions(String filename) {
try {
ArrayList<Transaction> transactions = new ArrayList<>();
Scanner scanner = new Scanner(new File(filename));
while (scanner.hasNext()) {
String transaction = scanner.nextLine();
String[] transactionParts = transaction.split(";");
String[] inputs = transactionParts[0].split(",");
String[] outputs = transactionParts[1].split(",");
transactions.add(new Transaction(transaction, inputs, outputs));
}
return transactions.toArray(new Transaction[transactions.size()]);
} catch (FileNotFoundException e) {
System.err.println(">>> ERROR: Invalid configuration file provided: " + filename);
System.exit(1);
return null;
}
}
private static void mine(Block block) {
String nonce = "0000";
BigInteger target = new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16)
.divide(block.getDifficulty());
boolean lookingForTarget = true;
BigInteger numHashes = new BigInteger("0");
// Keep looping until we find target...
while (lookingForTarget) {
// Increment number of hashes tried
numHashes = numHashes.add(BigInteger.ONE);
// Concatenate our nonce and our block
// Uncomment to see failed attempts
// System.out.println("Trying: " + concat);
// Calculate the hash. Kept in a BigInteger since we will want to compare it.
block.buildBlock(nonce);
// If our hash is less than the target, we have succeeded
if (block.getHash().compareTo(target) < 0) {
lookingForTarget = false;
System.out.println("\nCANDIDATE BLOCK - Hash: " + block.getHash().toString());
System.out.println("1. Prev hash: " + block.getPrevHash());
System.out.println("2. Block size (< 16): " + block.getSize());
System.out.println("3. Current timestamp: " + block.getTimestamp());
System.out.println("4. Difficulty: " + block.getDifficulty());
System.out.println("5. Nonce: " + nonce);
System.out.println("6. Concat Root: " + block.getConcatRoot());
System.out.println("7. List of Transactions:\n" + block.getTransactionList());
}
else {
// Uncomment to see failed attempts
// System.out.println("Fail, hash "
// + leftPad(hash.toString(16), 64) + " >= "
// + leftPad(target.toString(16), 64));
nonce = incrementStringNonce(nonce);
if (nonce.length() != 4) {
System.out.println(">>> ERROR: Nonce = " + nonce);
System.exit(1);
}
}
}
}
/**
* This increments our String nonce by accepting a String version
* and returning a String version. For example:
* "000A" -> "000B"
* "FFFE" -> "FFFF"
* @param nonce initial nonce
* @return nonce incremented by one in string form
*/
private static String incrementStringNonce(String nonce) {
char[] chars = nonce.toCharArray();
for (int i = chars.length-1; i >= 0; i--) {
if (chars[i] < 126) {
chars[i]++;
return String.valueOf(chars);
} else {
chars[i] = 32;
}
}
return String.valueOf(chars);
}
}
| adamrichman1/BlockchainCrypto_D2 | Mine.java | 1,028 | // System.out.println("$$$ Transactions read in successfully"); | line_comment | en | true |
189010_0 | /*
[ 1, 5, 9],
[ 3, 7, 13],
[ 8, 13, 15]
*/
// binary search solution: https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/301357/Java-0ms-(added-Python-and-C%2B%2B)%3A-Easy-to-understand-solutions-using-Heap-and-Binary-Search
// my binary tree solution
class Solution {
public int kthSmallest(int[][] matrix, int k) {
Queue<int[]> Q = new PriorityQueue<>((n1, n2) -> matrix[n1[0]][n1[1]] - matrix[n2[0]][n2[1]]);
Q.add(new int[] { 0, 0 });
Set<String> visited = new HashSet<>();
visited.add(Integer.toString(0) + "-" + Integer.toString(0));
int res = -1;
while (!Q.isEmpty() && k-- > 0) {
int[] parent = Q.poll();
int[] childR = new int[2];
int[] childL = new int[2];
if (parent[1] + 1 < matrix.length) {
childR[0] = parent[0];
childR[1] = parent[1] + 1;
}
if (parent[0] + 1 < matrix.length) {
childL[0] = parent[0] + 1;
childL[1] = parent[1];
}
if (!visited.contains(Integer.toString(childR[0]) + "-" + Integer.toString(childR[1]))) {
visited.add(Integer.toString(childR[0]) + "-" + Integer.toString(childR[1]));
Q.add(new int[] { childR[0], childR[1] });
}
if (!visited.contains(Integer.toString(childL[0]) + "-" + Integer.toString(childL[1]))) {
visited.add(Integer.toString(childL[0]) + "-" + Integer.toString(childL[1]));
Q.add(new int[] { childL[0], childL[1] });
}
res = matrix[parent[0]][parent[1]];
}
return res;
}
} | HongyuHe/leetcode-new-round | bs/378_bs.java | 553 | /*
[ 1, 5, 9],
[ 3, 7, 13],
[ 8, 13, 15]
*/ | block_comment | en | true |
189096_0 |
package pkg11visitorpattern;
/**
*
* @author Johan Urban s1024726
* @author Paolo Scattolin s1023775
* @assignment 11: visitor pattern
* @date 12/05/2019
*/
public interface Form {
public <R, A> R accept(FormVisitor<R, A> visitor, A a);
public int getPrecedence();
}
| Uni-Projects/OOP-Assignment-11 | Form.java | 114 | /**
*
* @author Johan Urban s1024726
* @author Paolo Scattolin s1023775
* @assignment 11: visitor pattern
* @date 12/05/2019
*/ | block_comment | en | true |
189244_0 | package com.stanleyidesis;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.media.MediaBrowserCompat.MediaItem;
import android.support.v4.media.MediaBrowserServiceCompat;
import android.support.v4.media.session.MediaSessionCompat;
import java.util.ArrayList;
import java.util.List;
/**
* This class provides a MediaBrowser through a service. It exposes the media library to a browsing
* client, through the onGetRoot and onLoadChildren methods. It also creates a MediaSession and
* exposes it through its MediaSession.Token, which allows the client to create a MediaController
* that connects to and send control commands to the MediaSession remotely. This is useful for
* user interfaces that need to interact with your media session, like Android Auto. You can
* (should) also use the same service from your app's UI, which gives a seamless playback
* experience to the user.
* <p>
* To implement a MediaBrowserService, you need to:
*
* <ul>
*
* <li> Extend {@link MediaBrowserServiceCompat}, implementing the media browsing
* related methods {@link MediaBrowserServiceCompat#onGetRoot} and
* {@link MediaBrowserServiceCompat#onLoadChildren};
* <li> In onCreate, start a new {@link MediaSessionCompat} and notify its parent
* with the session's token {@link MediaBrowserServiceCompat#setSessionToken};
*
* <li> Set a callback on the {@link MediaSessionCompat#setCallback(MediaSessionCompat.Callback)}.
* The callback will receive all the user's actions, like play, pause, etc;
*
* <li> Handle all the actual music playing using any method your app prefers (for example,
* {@link android.media.MediaPlayer})
*
* <li> Update playbackState, "now playing" metadata and queue, using MediaSession proper methods
* {@link MediaSessionCompat#setPlaybackState(android.support.v4.media.session.PlaybackStateCompat)}
* {@link MediaSessionCompat#setMetadata(android.support.v4.media.MediaMetadataCompat)} and
* {@link MediaSessionCompat#setQueue(java.util.List)})
*
* <li> Declare and export the service in AndroidManifest with an intent receiver for the action
* android.media.browse.MediaBrowserService
*
* </ul>
* <p>
* To make your app compatible with Android Auto, you also need to:
*
* <ul>
*
* <li> Declare a meta-data tag in AndroidManifest.xml linking to a xml resource
* with a <automotiveApp> root element. For a media app, this must include
* an <uses name="media"/> element as a child.
* For example, in AndroidManifest.xml:
* <meta-data android:name="com.google.android.gms.car.application"
* android:resource="@xml/automotive_app_desc"/>
* And in res/values/automotive_app_desc.xml:
* <automotiveApp>
* <uses name="media"/>
* </automotiveApp>
*
* </ul>
*/
public class MyMusicService extends MediaBrowserServiceCompat {
private MediaSessionCompat mSession;
@Override
public void onCreate() {
super.onCreate();
mSession = new MediaSessionCompat(this, "MyMusicService");
setSessionToken(mSession.getSessionToken());
mSession.setCallback(new MediaSessionCallback());
mSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
}
@Override
public void onDestroy() {
mSession.release();
}
@Override
public BrowserRoot onGetRoot(@NonNull String clientPackageName,
int clientUid,
Bundle rootHints) {
return new BrowserRoot("root", null);
}
@Override
public void onLoadChildren(@NonNull final String parentMediaId,
@NonNull final Result<List<MediaItem>> result) {
result.sendResult(new ArrayList<MediaItem>());
}
private final class MediaSessionCallback extends MediaSessionCompat.Callback {
@Override
public void onPlay() {
}
@Override
public void onSkipToQueueItem(long queueId) {
}
@Override
public void onSeekTo(long position) {
}
@Override
public void onPlayFromMediaId(String mediaId, Bundle extras) {
}
@Override
public void onPause() {
}
@Override
public void onStop() {
}
@Override
public void onSkipToNext() {
}
@Override
public void onSkipToPrevious() {
}
@Override
public void onCustomAction(String action, Bundle extras) {
}
@Override
public void onPlayFromSearch(final String query, final Bundle extras) {
}
}
}
| yoyo770/cordova-carplay-android-auto | src/android/MyMusicService.java | 1,156 | /**
* This class provides a MediaBrowser through a service. It exposes the media library to a browsing
* client, through the onGetRoot and onLoadChildren methods. It also creates a MediaSession and
* exposes it through its MediaSession.Token, which allows the client to create a MediaController
* that connects to and send control commands to the MediaSession remotely. This is useful for
* user interfaces that need to interact with your media session, like Android Auto. You can
* (should) also use the same service from your app's UI, which gives a seamless playback
* experience to the user.
* <p>
* To implement a MediaBrowserService, you need to:
*
* <ul>
*
* <li> Extend {@link MediaBrowserServiceCompat}, implementing the media browsing
* related methods {@link MediaBrowserServiceCompat#onGetRoot} and
* {@link MediaBrowserServiceCompat#onLoadChildren};
* <li> In onCreate, start a new {@link MediaSessionCompat} and notify its parent
* with the session's token {@link MediaBrowserServiceCompat#setSessionToken};
*
* <li> Set a callback on the {@link MediaSessionCompat#setCallback(MediaSessionCompat.Callback)}.
* The callback will receive all the user's actions, like play, pause, etc;
*
* <li> Handle all the actual music playing using any method your app prefers (for example,
* {@link android.media.MediaPlayer})
*
* <li> Update playbackState, "now playing" metadata and queue, using MediaSession proper methods
* {@link MediaSessionCompat#setPlaybackState(android.support.v4.media.session.PlaybackStateCompat)}
* {@link MediaSessionCompat#setMetadata(android.support.v4.media.MediaMetadataCompat)} and
* {@link MediaSessionCompat#setQueue(java.util.List)})
*
* <li> Declare and export the service in AndroidManifest with an intent receiver for the action
* android.media.browse.MediaBrowserService
*
* </ul>
* <p>
* To make your app compatible with Android Auto, you also need to:
*
* <ul>
*
* <li> Declare a meta-data tag in AndroidManifest.xml linking to a xml resource
* with a <automotiveApp> root element. For a media app, this must include
* an <uses name="media"/> element as a child.
* For example, in AndroidManifest.xml:
* <meta-data android:name="com.google.android.gms.car.application"
* android:resource="@xml/automotive_app_desc"/>
* And in res/values/automotive_app_desc.xml:
* <automotiveApp>
* <uses name="media"/>
* </automotiveApp>
*
* </ul>
*/ | block_comment | en | true |