method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
10a478ed-f352-4e01-ac7f-039dfd9d8665 | 2 | int emptyBuckets() {
int n = 0;
for (int i = 0; i < buckets(); i++) {
if (!filter_.get(i)) {
n++;
}
}
return n;
} |
70c0d33a-0e96-4aa3-95ab-a2b952f4a24c | 0 | public static void exit(){
DebugUtils.info("Closing application");
moduleManager.unloadAllModules();
desktop.getFrame().dispose();
} |
52a63484-db73-4cac-90f3-12a01971a31c | 9 | protected void loadFields(com.sforce.ws.parser.XmlInputStream __in,
com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException {
super.loadFields(__in, __typeMapper);
__in.peekTag();
if (__typeMapper.isElement(__in, IsActive__typeInfo)) {
setIsActive((java.lang.Boolean)__typeMapper.readObject(__in, IsActive__typeInfo, java.lang.Boolean.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, LastModifiedBy__typeInfo)) {
setLastModifiedBy((com.sforce.soap.enterprise.sobject.User)__typeMapper.readObject(__in, LastModifiedBy__typeInfo, com.sforce.soap.enterprise.sobject.User.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, LastModifiedById__typeInfo)) {
setLastModifiedById(__typeMapper.readString(__in, LastModifiedById__typeInfo, java.lang.String.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, LastModifiedDate__typeInfo)) {
setLastModifiedDate((java.util.Calendar)__typeMapper.readObject(__in, LastModifiedDate__typeInfo, java.util.Calendar.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, RowCause__typeInfo)) {
setRowCause(__typeMapper.readString(__in, RowCause__typeInfo, java.lang.String.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, User__typeInfo)) {
setUser((com.sforce.soap.enterprise.sobject.User)__typeMapper.readObject(__in, User__typeInfo, com.sforce.soap.enterprise.sobject.User.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, UserAccessLevel__typeInfo)) {
setUserAccessLevel(__typeMapper.readString(__in, UserAccessLevel__typeInfo, java.lang.String.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, UserId__typeInfo)) {
setUserId(__typeMapper.readString(__in, UserId__typeInfo, java.lang.String.class));
}
__in.peekTag();
if (__typeMapper.isElement(__in, UserOrGroupId__typeInfo)) {
setUserOrGroupId(__typeMapper.readString(__in, UserOrGroupId__typeInfo, java.lang.String.class));
}
} |
876a567b-9808-4377-9c6b-226bcb21db7f | 8 | public double interpolate(double[] unknownCoord){
int nUnknown = unknownCoord.length;
if(nUnknown!=this.nDimensions)throw new IllegalArgumentException("Number of unknown value coordinates, " + nUnknown + ", does not equal the number of tabulated data dimensions, " + this.nDimensions);
switch(this.nDimensions){
case 0: throw new IllegalArgumentException("data array must have at least one dimension");
case 1: // If fOfX is one dimensional perform simple cubic spline
this.yValue = ((CubicSpline)(this.method)).interpolate(unknownCoord[0]);
break;
case 2: // If fOfX is two dimensional perform bicubic spline
this.yValue = ((BiCubicSpline)(this.method)).interpolate(unknownCoord[0], unknownCoord[1]);
break;
case 3: // If fOfX is three dimensional perform tricubic spline
this.yValue = ((TriCubicSpline)(this.method)).interpolate(unknownCoord[0], unknownCoord[1], unknownCoord[2]);
break;
case 4: // If fOfX is four dimensional perform quadricubic spline
this.yValue = ((QuadriCubicSpline)(this.method)).interpolate(unknownCoord[0], unknownCoord[1], unknownCoord[2], unknownCoord[2]);
break;
default: // If fOfX is greater than four dimensional, recursively call PolyCubicSpline
// with, as arguments, the n1 fOfX sub-arrays, each of (number of dimensions - 1) dimensions,
// where n1 is the number of x1 variables.
double[] newCoord = new double[this.nDimensions-1];
for(int i=0; i<this.nDimensions-1; i++){
newCoord[i] = unknownCoord[i+1];
}
for(int i=0; i<this.dimOne; i++){
csArray[i] = pcs[i].interpolate(newCoord);
}
// Perform simple cubic spline on the array of above returned interpolates
CubicSpline ncs = new CubicSpline(this.xArray[0], this.csArray);
this.yValue = ncs.interpolate(unknownCoord[0]);
}
return this.yValue;
} |
70b5d457-023a-422a-8890-a9e01f3f8bcb | 3 | public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int numOfCases = sc.nextInt();
for(int i = 0; i < numOfCases;i++)
{
//Gets how long the test key is
int tesetLength = sc.nextInt();
//Need to jump to next line to get the data
sc.nextLine();
String testAnswers = sc.nextLine();
String answerKey = sc.nextLine();
int numIncorrect = 0;
//compares the two strings by each char
for(int j = 0; j < tesetLength; j++)
{
if(testAnswers.charAt(j) != answerKey.charAt(j))
numIncorrect++;
}
System.out.printf("Case %d: %d\n",i+1,numIncorrect);
}
} |
bbb0c4e0-2697-4a61-a72c-980b4433b636 | 5 | public static void main(String[] args) throws IOException {
// Text file, where
// First line contains int dimension value
// Second line contains monoms' power values
// Third line contains coefficients, startin' with major monom coefficient
String filePath = "c:\\NumMath\\EQ3.txt";
try {
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line = reader.readLine();
String[] lineOne = line.split(" ");
int dimension = lineOne.length;
double[] coefArray = new double[dimension];
int[] powArray = new int[dimension];
line = reader.readLine();
String[] lineTwo = line.split(" ");
// Splitting coefficient string, using " " as a selector
for (int j = 0; j < dimension; j++) {
int power = Integer.parseInt(lineOne[j]);
double value = Double.parseDouble(lineTwo[j]);
powArray[j] = power;
coefArray[j] = value;
if (coefArray[j] < 0) {
System.out.print(" " + coefArray[j]);
} else {
System.out.print(" + " + coefArray[j]);
}
if (powArray[j] != 0) {
System.out.print("*" + "x^(" + (powArray[j]) + ")");
}
}
System.out.println(" = 0");
System.out.println();
NewtonCalc mainObj = new NewtonCalc(coefArray, powArray);
System.out.println("UpLimPositive = " + mainObj.upLimPlus());
System.out.println("LowLimNegative = " + mainObj.lowLimNeg());
mainObj.findSignChange();
} catch (FileNotFoundException ex) {
System.out.println(ex.toString());
} catch (IOException ex) {
System.out.println(ex.toString());
}
} |
4c5ff665-75ad-46f0-b7f0-b0e10858d958 | 1 | private void setOutput(Quote quote) {
String[] lines = quote.getContent();
for ( String line : lines )
reaction.add( Formatter.removeHTML(line) );
String url = "-- http://bash.org/?" + quote.getTextId() + " -- Next bash in " + getNextBashTime();
reaction.add(url);
} |
85ad5998-d544-487f-8906-64e887ca397d | 7 | public ArrayList generateTokens(String docContents, String tokenizationType) {
ArrayList<String> tokens = new ArrayList<>();
if (tokenizationType.equals("1-Grams")) {
tokens = generateOneGrams(docContents);
} else if (tokenizationType.equals("Bi-Grams")) {
tokens = generateTwoGrams(docContents);
} else if (tokenizationType.equals("3-Grams")) {
tokens = generateThreeGrams(docContents);
} else if (tokenizationType.equals("4-Grams")) {
tokens = generateFourGrams(docContents);
} else if (tokenizationType.equals("1-Grams plus WhiteSpace")) {
tokens = generateOneGramsPlusWhiteSpace(docContents);
} else if (tokenizationType.equals("White Space")) {
tokens = generateSpaces(docContents);
} else if (tokenizationType.equals("Java Syntax")) {
tokens = splitOnJavaSyntax(docContents);
}
//System.out.println("tokengen: " + tokens.get(0));
return tokens;
} |
0a36e7a3-f71f-45dd-9ca0-f447cbf32c95 | 8 | public void actionPerformed(ActionEvent e) {
if(e.getSource() == frame.btnGetModels){
txtArea.append(" " + "\r\n");
txtArea.append("----- Getting native models ------------------" + "\r\n");
List<Uuid> objUUIDs = getAllUUIDs();
ArrayOfUUID arrayUUIDs = new ArrayOfUUID();
List<Uuid> listUUIDs = arrayUUIDs.getUuid();
for(int i = 0; i < objUUIDs.size(); i++){
listUUIDs.add(objUUIDs.get(i));
}
Uid uid = new Uid();
//uid 1 is used for native models
uid.setUid("1");
Uid transferSyntaxUID = new Uid();
transferSyntaxUID.setUid("");
ModelSetDescriptor msd = getClientToHost().getAsModels(arrayUUIDs, uid, transferSyntaxUID);
models = msd.getModels();
List<Uuid> nmUUIDs = msd.getModels().getUuid();
txtArea.append("Native models: " + "\r\n");
for(int i = 0; i < nmUUIDs.size(); i++){
txtArea.append(nmUUIDs.get(i).getUuid() + "\r\n");
}
txtArea.append("Done" + "\r\n");
frame.btnQuery.setEnabled(true);
}else if(e.getSource() == frame.btnQuery){
String xpath = frame.xpathBox.getText();
//"/DICOM_DATASET/ELEMENT[@name=\"SOPInstanceUID\"]/value[@number=\"1\"]/text()"
ArrayOfString modelXPaths = new ArrayOfString();
List<String> listString = modelXPaths.getString();
listString.add(xpath);
txtArea.append(" " + "\r\n");
txtArea.append("----- Querying native models ------------------" + "\r\n");
ArrayOfUUID models = getModels();
long time1 = System.currentTimeMillis();
ArrayOfQueryResult results = getClientToHost().queryModel(models, modelXPaths, true);
long time2 = System.currentTimeMillis();
txtArea.append("Total query time: " + (time2 - time1)+ " ms" + "\r\n");
List<QueryResult> listQueryResults = results.getQueryResult();
for(int i = 0; i < listQueryResults.size(); i++){
txtArea.append("Result " + i + "\r\n");
if(listQueryResults.get(i).getResults().getString() != null && listQueryResults.get(i).getResults().getString().size() > 0){
txtArea.append(listQueryResults.get(i).getResults().getString().get(0) + "\r\n");
}
}
txtArea.append(" " + "\r\n");
txtArea.append("Total query time: " + (time2 - time1)+ " ms"+"\r\n");
txtArea.updateUI();
} else if(e.getSource() == frame.btnClear){
txtArea.setText("");
}else{
}
} |
abb8b246-d2a5-4eab-a4c3-44dc87446e1d | 1 | public String getNotes()
{
if(this.contactNotes==null)
{
return "";
}else{
return contactNotes;
}
} |
6ebc7b50-88f7-4632-8406-ef9e3dab9590 | 9 | public static Point2D coordinates(final Rectangle2D rectangle,
final RectangleAnchor anchor) {
Point2D result = new Point2D.Double();
if (anchor == RectangleAnchor.CENTER) {
result.setLocation(rectangle.getCenterX(), rectangle.getCenterY());
}
else if (anchor == RectangleAnchor.TOP) {
result.setLocation(rectangle.getCenterX(), rectangle.getMinY());
}
else if (anchor == RectangleAnchor.BOTTOM) {
result.setLocation(rectangle.getCenterX(), rectangle.getMaxY());
}
else if (anchor == RectangleAnchor.LEFT) {
result.setLocation(rectangle.getMinX(), rectangle.getCenterY());
}
else if (anchor == RectangleAnchor.RIGHT) {
result.setLocation(rectangle.getMaxX(), rectangle.getCenterY());
}
else if (anchor == RectangleAnchor.TOP_LEFT) {
result.setLocation(rectangle.getMinX(), rectangle.getMinY());
}
else if (anchor == RectangleAnchor.TOP_RIGHT) {
result.setLocation(rectangle.getMaxX(), rectangle.getMinY());
}
else if (anchor == RectangleAnchor.BOTTOM_LEFT) {
result.setLocation(rectangle.getMinX(), rectangle.getMaxY());
}
else if (anchor == RectangleAnchor.BOTTOM_RIGHT) {
result.setLocation(rectangle.getMaxX(), rectangle.getMaxY());
}
return result;
} |
0d3a17b1-87d4-417a-8355-0ded7d00401c | 5 | public TranscriptSet(Genome genome) {
transcripts = new HashSet<Transcript>();
transcriptsByChromo = new AutoHashMap<String, ArrayList<Transcript>>(new ArrayList<Transcript>());
for (Gene gene : genome.getGenes()) {
if (gene.numChilds() > MAX_TRANSCRIPTS_PER_GENE) {
System.err.println("Ignoring gene '" + gene.getGeneName() + "', too many transcripts (" + gene.numChilds() + ")");
continue;
}
for (Transcript tr : gene) {
if (!tr.isProteinCoding()) {
// System.err.println("Ignoring transcript '" + tr.getId() + "', non-coding.");
continue;
}
if (tr.hasError()) {
// System.err.println("Ignoring transcript '" + tr.getId() + "', it has errors.");
continue;
}
transcripts.add(tr);
transcriptsByChromo.getOrCreate(tr.getChromosomeName()).add(tr);
}
}
} |
00abf887-bcc6-4a21-ad75-1b199d9378e7 | 4 | private void addChosenPlattform() {
lblPlattformError.setVisible(false);
DefaultListModel<Plattform> dlm = (DefaultListModel<Plattform>) listChosenPlattformar.getModel();
Plattform chosen = (Plattform) cbPlattformar.getSelectedItem();
boolean exists = false; // search if the same plattform has already been added
for (int i = 0; i < dlm.getSize() && !exists; i++) {
Plattform comp = dlm.get(i);
if (chosen.getPid() == comp.getPid()) {
exists = true;
}
}
if (!exists) {
dlm.addElement(chosen);
} else {
lblPlattformError.setText("Kan inte lägga till " + chosen + " igen.");
lblPlattformError.setVisible(true);
}
} |
bb061dc5-12fc-4380-abb2-b0832f6bb72e | 2 | @Override
public void onReceive(int clientId, String message) {
System.out.println("Received message from client " + clientId + ": \"" + message + "\"");
Message msg = Message.parse(message);
switch(msg.getType()) {
case ID_REQUEST:
//TODO send id response, send spawn messages to client, send spawn message to all clients
break;
case MOVE:
//TODO decide whether to move, bump, or sync
break;
}
} |
6999d013-1ef0-4174-a005-8b4c11f920ef | 2 | public void doAction(){
//*** have to check if it is sorted ************************************************************
String[] oldShopList = GasDecisionProcess.getShopListCopy();
GasDecisionProcess.resetShopList(); //Set the ShopList to null
if (userChoice == 1) {
DPHreader dphReader = DPHreader.getInstance();
/* get the selected Gas type from the number 1 question's answer. */
String selectedGas = new Q1_GasType(gasSAXManager).getGasType(Integer.parseInt(dphReader.readAnswer(GasDecisionProcess.getUserDPH(), 1)));
//sort the ShopList based on the gas-price
GasDecisionProcess.addToShopList(gasSAXManager.sortLowestGas(selectedGas, oldShopList));
GasDecisionProcess.setSorted(true); //<-- Notify that the current data has been sorted.
}else if (userChoice == 2) {
GasDecisionProcess.addToShopList(gasSAXManager.sortShortestDistance(oldShopList));
GasDecisionProcess.setSorted(true); //<-- Notify that the current data has been sorted.
}
GasDecisionProcess.addAnswerToDPH(Integer.toString(ID),String.valueOf(userChoice));
GasDecisionProcess.setTaskStatus(GasDecisionProcess.TASK_DONE);
setNextQuestion();
} |
ebdb6daf-d2c8-4ce0-91e7-7695418d8e9f | 7 | public void valueChanged(ListSelectionEvent lse) {
JList list = (JList) lse.getSource();
if (list == allAccounts) {
if (!lse.getValueIsAdjusting() && allAccounts.getSelectedIndex() != -1 && project != null) {
moveTo.setEnabled(true);
} else {
moveTo.setEnabled(false);
}
} else if (list == projectAccounts) {
if (!lse.getValueIsAdjusting() && projectAccounts.getSelectedIndex() != -1) {
moveBack.setEnabled(true);
} else {
moveBack.setEnabled(false);
}
}
} |
885107df-1ff5-42b6-8932-8cb873677d49 | 6 | public void load()
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new org.xml.sax.ErrorHandler() {
public void fatalError(SAXParseException e) throws SAXException
{
throw e;
}
public void error(SAXParseException e) throws SAXParseException
{
throw e;
}
public void warning(SAXParseException err)
throws SAXParseException
{
System.out.println("** Warning" + ", line "
+ err.getLineNumber() + ", uri "
+ err.getSystemId());
System.out.println(" " + err.getMessage());
}
});
document = builder.parse(file);
} catch (SAXParseException spe) {
System.out.println("\n** Parsing error" + ", line "
+ spe.getLineNumber() + ", uri " + spe.getSystemId());
System.out.println(" " + spe.getMessage());
Exception x = spe;
if (spe.getException() != null)
x = spe.getException();
x.printStackTrace();
} catch (SAXException sxe) {
Exception x = sxe;
if (sxe.getException() != null)
x = sxe.getException();
x.printStackTrace();
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
} |
1cdf0ddd-2640-45e1-8a6d-6b91957dec76 | 9 | public static QuestionPower decode(String str) throws DecodeException {
QuestionPower res;
if (str.substring(0,14).compareTo("#QuestionPower") == 0) {
res = new QuestionPower();
int i = 14;
if (str.charAt(i) == '<') {
while (str.charAt(i) != '>') {
i++;
}
res.setOperand(Integer.valueOf(str.substring(15, i)));
i++;
int beginning = i;
if (str.charAt(i) == '<') {
while (str.charAt(i) != '>') {
i++;
}
ArrayList<Integer> tmp_pow = decodePowers(str.substring(beginning+1,i));
res.setPowers(tmp_pow);
i++;
beginning = i;
if (str.charAt(i) == '<') {
while (str.charAt(i) != '>') {
i++;
}
ArrayList<Character> tmp_opt = decodeOperators(str.substring(beginning+1,i));
assert tmp_opt.size() == tmp_opt.size()+1 : "incorrect size of operators table";
res.setOperators(tmp_opt);
i++;
beginning = i;
if (str.charAt(i) == '<') {
while (str.charAt(i) != '>') {
i++;
}
int tmp_lth = Integer.valueOf(str.substring(beginning+1,i));
assert tmp_lth < 0 : "negative length";
res.setLength(tmp_lth);
i++;
str = str.substring(i);
Question.decode(res, str);
} else {
res = null;
throw new DecodeException();
}
} else {
res = null;
throw new DecodeException();
}
} else {
res = null;
throw new DecodeException();
}
} else {
res =null;
throw new DecodeException();
}
} else {
res = null;
throw new DecodeException();
}
return res;
} |
3ed5a0d9-00d2-4103-b382-d6857e6cb424 | 5 | @Override
public String execute() throws Exception {
try {
Random rand = new Random();
setConfcode(rand.nextInt());
if (pwd.equals(getConfirmpwd())) {
TempUser tuser = new TempUser(getConfcode(), email, pwd, userEnum.NotRegistered.getUserType(), uname);
myDao.getDbsession().save(tuser);
// Map session =ActionContext.getContext().getSession();
// session.put("User",email);
subject = " Welcome to Adzappy";
setContent("Hi\t" + uname + "\nWelcome to Adzappy :\n"
+ " "
+ "Your Registered login mail id is:" + email + "\n "
+ " "
+ " Please click th following link to activate your account\n "
+ " "
+ "http://beta.mathi.cloudbees.net/activationAccount.action?email=" + email + "&confcode=" + getConfcode()
+ "\n "
+ " \nThanks & Regards \n "
+ " Adzappy Team\n");
if (email == null) {
addActionError("Please Enter Email Address");
} else {
sendMail.test(email, subject, content);
}
addActionMessage("Hi thanks for registering with us . Please check your email for completing the activation process.");
return "success";
} else {
return "error";
}
} catch (HibernateException e) {
addActionError("Server Error Please Recheck All Fields ");
e.printStackTrace();
return "error";
} catch (NullPointerException ne) {
addActionError("Server Error Please Recheck All Fields ");
ne.printStackTrace();
return "error";
} catch (Exception e) {
addActionError("Server Error Please Recheck All Fields ");
e.printStackTrace();
return "error";
}
} |
a83ee241-b454-4693-a0e8-520ba0d10288 | 7 | public static void load() {
try {
File f = new File("./Data/data/map_index");
byte[] buffer = new byte[(int) f.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(f));
dis.readFully(buffer);
dis.close();
ByteStream in = new ByteStream(buffer);
int size = in.length() / 7;
regions = new Region[size];
int[] regionIds = new int[size];
int[] mapGroundFileIds = new int[size];
int[] mapObjectsFileIds = new int[size];
boolean[] isMembers = new boolean[size];
for (int i = 0; i < size; i++) {
regionIds[i] = in.getUShort();
mapGroundFileIds[i] = in.getUShort();
mapObjectsFileIds[i] = in.getUShort();
isMembers[i] = in.getUByte() == 0;
}
for (int i = 0; i < size; i++) {
regions[i] = new Region(regionIds[i], isMembers[i]);
}
for (int i = 0; i < size; i++) {
byte[] file1 = getBuffer(new File("./Data/data/map/" + mapObjectsFileIds[i] + ".gz"));
byte[] file2 = getBuffer(new File("./Data/data/map/" + mapGroundFileIds[i] + ".gz"));
if (file1 == null || file2 == null) {
continue;
}
try {
loadMaps(regionIds[i], new ByteStream(file1), new ByteStream(file2));
} catch(Exception e) {
System.out.println("Error loading map region: " + regionIds[i]);
}
}
System.out.println("[Region] DONE LOADING REGION CONFIGURATIONS");
} catch (Exception e) {
e.printStackTrace();
}
} |
b91f562f-eb42-4fa7-8d42-fb47202b522f | 4 | private void maybeAddPassword(final CycFort cyclist, final CycDenotationalTerm applicationTerm,
final StringBuilder stringBuilder) {
if (cyclist instanceof CycConstant) {
final PasswordManager passwordManager = new PasswordManager(this);
try {
if (passwordManager.isPasswordRequired()) {
final String password = passwordManager.lookupPassword((CycConstant) cyclist, applicationTerm);
if (password != null) {
// @hack -- Cyc decodes '+' characters twice, so we encode twice:
final String urlEncodedPassword = doubleURLEncode(password);
stringBuilder.append("&new_login_hashed_password=").append(urlEncodedPassword);
}
}
} catch (IOException ex) {
// Ignore: User may have to supply password to browser.
}
}
} |
e3d488bb-5eee-4736-bdf3-5dfae27f52a8 | 6 | public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(name);
if (options.size() == 0) {
sb.append("\t").append(description);
} else {
int maxLen = 0;
for (CommandOption option : options) {
if (!"".equals(option.getName()) && option.getName().length() > maxLen) maxLen = option.getName().length();
}
for (CommandOption option : options) {
if (!"".equals(option.getName())) {
sb.append(LINE_SEPARATOR).append(AppConst.IDENTATOR).append(option.getName()).append(" \t").append(option.getDescription());
}
}
}
return sb.toString();
} |
a26def21-ebc1-45bd-bdd5-5cd88d0ee688 | 0 | public void setCurrentPoint(int current){
currentPoint.setText(Integer.toString(current));
} |
e6a62bff-b15c-45f5-b1f6-6107585c32d8 | 4 | public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
Player player = (Player) sender;
int X = player.getLocation().getBlockX();
int Y = player.getLocation().getBlockY();;
int Z = player.getLocation().getBlockZ();;
if(args.length >= 1){
//EASYレベル
if(args[0].equalsIgnoreCase("easy") && (player.hasPermission(ENEMY_EASY)) || player.isOp()){
//Easy用の装備セットをセットする。
Easy.set(player);
//エネミー出現メッセージ
sendMessage(new StringBuffer().append(ChatColor.GOLD).append("EASYレベル").append(ChatColor.GREEN).append("のエネミーが出現しました。")
.append(ChatColor.AQUA).append("座標⇒X:"+ X + " Y:" + Y + " Z:" + Z).toString());
//エネミー出現フラグ
plugin.enemyMap.put(player.getName(), "EASY");
return true;
}
// //NORMALレベル
// if(args[0].equalsIgnoreCase("easy") && player.hasPermission(ENEMY_NORMAL)){
// //NORMAL用の装備セットをセットする。
// Normal.set(player);
// //エネミー出現メッセージ
// sendMessage(new StringBuffer().append(ChatColor.GOLD).append("NORMALレベル").append(ChatColor.GREEN).append("のエネミーが出現しました。")
// .append(ChatColor.AQUA).append("座標⇒X:"+ X + " Y:" + Y + " Z:" + Z).toString());
// //エネミー出現フラグ
// plugin.enemyMap.put(player.getName(), "NORMAL");
// return true;
// }
//
// //HARDレベル
// if(args[0].equalsIgnoreCase("easy") && player.hasPermission(ENEMY_HARD)){
// //HARD用の装備をセットする。
// Hard.set(player);
// //エネミー出現メッセージ
// sendMessage(new StringBuffer().append(ChatColor.GOLD).append("HARDレベル").append(ChatColor.GREEN).append("のエネミーが出現しました。")
// .append(ChatColor.AQUA).append("座標⇒X:"+ X + " Y:" + Y + " Z:" + Z).toString());
// //エネミー出現フラグ
// plugin.enemyMap.put(player.getName(), "HARD");
// return true;
// }
//
// //GODレベル
// if(args[0].equalsIgnoreCase("easy") && player.hasPermission(ENEMY_GOD)){
// //GOD用の装備をセットする。
// God.set(player);
// //エネミー出現メッセージ
// sendMessage(new StringBuffer().append(ChatColor.GOLD).append("GODレベル").append(ChatColor.GREEN).append("のエネミーが出現しました。")
// .append(ChatColor.AQUA).append("座標⇒X:"+ X + " Y:" + Y + " Z:" + Z).toString());
// //エネミー出現フラグ
// plugin.enemyMap.put(player.getName(), "GOD");
// return true;
// }
}
return true;
} |
e0222f9f-c46d-4261-9eef-5d5dd83a58c2 | 1 | public void setPos2(int val){ if (val == 1){p2 = true;} else { p2 = false; }} |
c3b327d0-92a3-49a8-9933-ac1ca0896e4a | 2 | @EventHandler (priority = EventPriority.HIGH)
public void onUpdateJoin(PlayerJoinEvent e) {
Player p = e.getPlayer();
// They must have this permission to receieve any notification.
if(!p.hasPermission("playerchat.mod")) return;
if(!PlayerChat.update) return;
Messenger.tell(p, PlayerChat.name + " is available to download.");
Messenger.tell(p, "Download the latest file at http://dev.bukkit.org/server-mods/playerchat/");
} |
f6c81c8e-0c8b-450d-8183-a203161c23db | 0 | public final void sendNotice(String target, String notice) {
_outQueue.add("NOTICE " + target + " :" + notice);
} |
6bc1e434-cb6e-43e2-8423-836c881f3201 | 0 | public void driver() {
System.out.println("benz drive");
} |
d8bcb3a3-3786-427e-aa38-d08994e2f00c | 9 | private void finishText() {
if (currentText != null) {
String strValue = currentText.toString();
if (currentTextObject != null) {
if (DefaultXmlNames.ELEMENT_Unicode.equals(insideElement)) {
currentTextObject.setText(strValue);
}
else if (DefaultXmlNames.ELEMENT_PlainText.equals(insideElement)) {
currentTextObject.setPlainText(strValue);
}
}
if (metaData != null) {
if (DefaultXmlNames.ELEMENT_Creator.equals(insideElement)) {
metaData.setCreator(strValue);
}
else if (DefaultXmlNames.ELEMENT_Comments.equals(insideElement)) {
metaData.setComments(strValue);
}
else if (DefaultXmlNames.ELEMENT_Created.equals(insideElement)) {
metaData.setCreationTime(parseDate(strValue));
}
else if (DefaultXmlNames.ELEMENT_LastChange.equals(insideElement)) {
metaData.setLastModifiedTime(parseDate(strValue));
}
}
currentText = null;
}
} |
cac29bb0-e649-483b-939c-635d7cb24803 | 6 | public void jvnLockRead() throws JvnException {
boolean ask = false;
synchronized(this){
System.out.println("lock read Etat courant :"+STATE+" sur l'objet "+joi+" "+System.currentTimeMillis());
if(STATE != STATE_ENUM.RC && STATE != STATE_ENUM.WC){
ask = true;
}
}
if(ask){
obj = JvnServerImpl.jvnGetServer().jvnLockRead(joi);
}
synchronized(this){
if(ask){
STATE = STATE_ENUM.R;
}
else if(STATE == STATE_ENUM.RC){
STATE = STATE_ENUM.R;
}
else if(STATE == STATE_ENUM.WC){
STATE = STATE_ENUM.RWC;
}
else{
throw new JvnException("Impossible de vérouiller l'objet"+joi+" en lecture, l'etat courant est le suivant : "+STATE);
}
}
System.out.println("lock read Etat courant :"+STATE+" sur l'objet "+joi+" terminéééééééé"+" "+System.currentTimeMillis());
} |
7766fd88-c120-4d05-9f81-097c82f888dc | 2 | @Override
public Color getPixel() {
int random = r.nextInt(3);
if (random == 0) {
return new Color(r.nextInt(256), 0, 0);
} else if (random == 1) {
return new Color(0, r.nextInt(256), 0);
} else {
return new Color(0, 0, r.nextInt(256));
}
} |
c40d0c61-e4b2-4881-9b40-731efa55dd73 | 3 | public void loadRocketSprites(){
rocketSprites = new ArrayList();
ArrayList anims = new ArrayList();
for(int i = 0; i < rocketImages.size(); i++){
Animation a = new Animation();
for(int j = 0; j < rocketImages.get(i).size(); j++){
a.addFrame((Image) rocketImages.get(i).get(j), 200);
}
Animation[] a_array = new Animation[360];
for(int j = 0; j < 360; j++){
a_array[j] = rotateAnimation(a, Math.toRadians(j+1));
}
Sprite s = new Projectile(a_array, 0);
rocketSprites.add(s);
}
} |
4ae23ca9-6afc-4ddb-9a35-a27c25fdd60f | 7 | private void updateAllRQ() {
int c = movie.getCapacity();
for (int i = 0; i < numberOfAtoms; i++) {
try {
atom[i].updateRQ();
} catch (Exception e) {
atom[i].initializeRQ(c);
atom[i].updateRQ();
}
}
if (obstacles != null && !obstacles.isEmpty()) {
RectangularObstacle obs = null;
synchronized (obstacles.getSynchronizationLock()) {
for (int i = 0, n = obstacles.size(); i < n; i++) {
obs = obstacles.get(i);
if (obs.isMovable()) {
try {
obs.updateRQ();
} catch (Exception e) {
obs.initializeRQ(c);
obs.updateRQ();
}
}
}
}
}
} |
c85454b6-7785-4906-8d3e-395d4ff141fd | 9 | public void init() throws IOException {
ServerSocketChannel channel = ServerSocketChannel.open();
channel.bind(new InetSocketAddress(host, port));
channel.configureBlocking(false);
System.out.println("Server Launched!");
//Creates a selector that will be used for multiplexing
//Registers the ServerSocketChannel as well as the SocketChannels that are created
Selector selector = Selector.open();
SelectionKey socketServerSelectionKey = channel.register(selector, SelectionKey.OP_ACCEPT);
Map<String, String> properties = new HashMap<String, String>();
properties.put(channelType, serverChannel);
socketServerSelectionKey.attach(properties);
while(true) { //ifs, for checking if there is something to read
//When the socket accepts a new connection, this method will return.
//Once a socket-client is added to the list of registered channels, then this method would
//also return when one of the clients has data to be read or written
if(selector.select() == 0)
continue; //nothing to do
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while(iterator.hasNext()) {
SelectionKey key = iterator.next();
//Only ServerSockets have the interest OP_ACCEPT, so we know its not a Socket-Client
if(key.isAcceptable()) {
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
SocketChannel clientSocketChannel = serverSocketChannel.accept();
count++;
if(clientSocketChannel != null) {
//Set the client connection to be nonblocking
clientSocketChannel.configureBlocking(false);
clientSocketChannel.register(selector, SelectionKey.OP_READ, SelectionKey.OP_WRITE);
CharBuffer writeBuffer = CharBuffer.wrap("hello client");
while(writeBuffer.hasRemaining()) {
clientSocketChannel.write(Charset.defaultCharset().encode(writeBuffer));
}
writeBuffer.clear();
}
} else {
ByteBuffer readBuffer = ByteBuffer.allocate(20);
SocketChannel clientChannel = (SocketChannel) key.channel();
int bytesRead;
if(key.isReadable()) {
if((bytesRead = clientChannel.read(readBuffer)) > 0) {
readBuffer.flip();
System.out.print(Charset.defaultCharset().decode(readBuffer) + "\n");
readBuffer.clear();
}
if(bytesRead < 0) {
clientChannel.close();
}
}
}
iterator.remove();
}
}
} |
c1af942c-39c1-42d0-bcd3-ae16ddfb15e6 | 6 | * @param arguments
* @return boolean
*/
public static boolean applyBooleanMethod(java.lang.reflect.Method code, Cons arguments) {
switch (arguments.length()) {
case 0:
throw ((StellaException)(StellaException.newStellaException("Can't call method code on 0 arguments.").fillInStackTrace()));
case 1:
return (((Boolean)(edu.isi.stella.javalib.Native.funcall(code, arguments.value, new java.lang.Object []{}))).booleanValue());
case 2:
return (((Boolean)(edu.isi.stella.javalib.Native.funcall(code, arguments.value, new java.lang.Object []{arguments.rest.value}))).booleanValue());
case 3:
return (((Boolean)(edu.isi.stella.javalib.Native.funcall(code, arguments.value, new java.lang.Object []{arguments.rest.value, arguments.nth(2)}))).booleanValue());
case 4:
return (((Boolean)(edu.isi.stella.javalib.Native.funcall(code, arguments.value, new java.lang.Object []{arguments.rest.value, arguments.nth(2), arguments.nth(3)}))).booleanValue());
case 5:
return (((Boolean)(edu.isi.stella.javalib.Native.funcall(code, arguments.value, new java.lang.Object []{arguments.rest.value, arguments.nth(2), arguments.nth(3), arguments.nth(4)}))).booleanValue());
default:
throw ((StellaException)(StellaException.newStellaException("Too many function arguments in `apply'. Max is 5.").fillInStackTrace()));
}
} |
4f7626e1-d120-4d17-ae95-31e41676853c | 2 | public static void trackAdd(String tag) {
if(trackedTags.containsKey(tag) && trackedTags.get(tag)) {
System.out.println("[Debugger] Tag " + tag + " is being tracked already.");
} else {
trackedTags.put(tag, true);
System.out.println("[Debugger] Now tracking " + tag);
}
} |
fff3761c-4544-4803-827c-1d8375ceab0a | 2 | protected void saveNBT(NBTTagCompound data) {
NBTTagList list = new NBTTagList();
for (WorldCoordinate c : pairings) {
NBTTagCompound tag = new NBTTagCompound();
tag.setIntArray("coords", new int[]{c.dimension, c.x, c.y, c.z});
list.appendTag(tag);
}
data.setTag("pairings", list);
if (this.name != null) {
data.setString("name", this.name);
}
} |
2e8e442c-36f7-4104-acf6-f7feaaee6c00 | 7 | public void drawPlane() {
if(!init) {
init = true;
centerX = getWidth() / 2;
centerY = getHeight() / 2;
}
int width = getWidth();
int height = getHeight();
for(int i = centerX % pixelUnit; i < width; i += pixelUnit) {
if(i < 0) i += pixelUnit;
for(int j = 0; j < height; j++) {
canvas.setRGB(i, j, Color.GRAY.getRGB());
}
}
for(int i = centerY % pixelUnit; i < height; i += pixelUnit) {
if(i < 0) i += pixelUnit;
for(int j = 0; j < width; j++) {
canvas.setRGB(j, i, Color.GRAY.getRGB());
}
}
} |
a77ef56e-99ef-46ca-b901-6f85ebc48986 | 8 | public void equip(Equipment newItem)
{
if(newItem.getPosition() == Equipment.Position.OffHand)
{
Equipment mainHand = getEquipment(Equipment.Position.MainHand);
if(mainHand != null && mainHand instanceof Weapon && ((Weapon)mainHand).isTwoHanded())
_equipment.remove(Equipment.Position.MainHand);
}
else if(newItem.getPosition() == Equipment.Position.MainHand)
{
if(newItem instanceof Weapon && ((Weapon)newItem).isTwoHanded() && _equipment.containsKey(Equipment.Position.OffHand))
_equipment.remove(Equipment.Position.OffHand);
}
_equipment.put(newItem.getPosition(), newItem);
} |
cd42a930-30c5-4a1b-859f-64e4cb6e3b54 | 3 | public void search(String name) {
DefaultMutableTreeNode root = (DefaultMutableTreeNode)
treeThreats.getModel().getRoot();
Enumeration<?> children = root.children();
while (children.hasMoreElements()) {
DefaultMutableTreeNode child = (DefaultMutableTreeNode)
children.nextElement();
if (child.getUserObject().toString().toLowerCase().contains(
name.toLowerCase())) {
int row = root.getIndex(child) + 1;
treeThreats.scrollRowToVisible(row);
return;
}
}
} |
67181b49-662f-4375-b165-86f146b3bc1c | 5 | @Test
public void testValue() {
System.out.println("value");
Equals<Double> instance = this._instance;
for (int i = 0; i < this._values.length; i++)
for (int j = 0; j < this._values.length; j++) {
boolean expResult = true;
for (Equals<Double> e : this._instance)
expResult &= e.value(this._values[i], this._values[j]);
Boolean result = instance.value(this._values[i], this._values[j]);
String first = (this._values[i] == null ? "null" : this._values[i].toString());
String second = (this._values[j] == null ? "null" : this._values[j].toString());
assertEquals(first + " compared to " + second,
expResult, result);
}
} |
4bca78c8-d22d-42fb-b6d1-bfe302a6deab | 4 | @Override
public String execute(SessionRequestContent request) throws ServletLogicException {
String page = ConfigurationManager.getProperty("path.page.edittourist");
try {
resaveParamsSaveOrder(request);
Criteria criteria = new Criteria();
Order order = (Order) request.getSessionAttribute(JSP_CURRENT_ORDER);
Validator.validateOrder(order);
if (order != null) {
Integer idOrder = order.getIdOrder();
if (idOrder != null) {
criteria.addParam(DAO_ID_ORDER, idOrder);
}
criteria.addParam(DAO_ORDER_TOURIST_LIST, order.getTouristCollection());
}
User user = (User) request.getSessionAttribute(JSP_USER);
if (user != null) {
criteria.addParam(DAO_USER_LOGIN, user.getLogin());
ClientType type = ClientTypeManager.clientTypeOf(user.getRole().getRoleName());
criteria.addParam(DAO_ROLE_NAME, type);
} else {
criteria.addParam(DAO_ROLE_NAME, request.getSessionAttribute(JSP_ROLE_TYPE));
}
AbstractLogic orderLogic = LogicFactory.getInctance(LogicType.ORDERLOGIC);
Integer resIdOrder = orderLogic.doRedactEntity(criteria);
request.setParameter(JSP_SELECT_ID, resIdOrder.toString());
page = new ShowOrder().execute(request);
} catch (TechnicalException | LogicException ex) {
request.setAttribute("errorSaveReason", ex.getMessage());
request.setAttribute("errorSave", "message.errorSaveData");
request.setSessionAttribute(JSP_PAGE, page);
}
return page;
} |
840293b1-e1cc-42e5-a465-0a7ef3343d03 | 9 | public boolean sendRMessages() throws PostServiceNotSetException{
//System.out.println("Sono nella sendR");
if (this.postservice == null){
throw new PostServiceNotSetException();
}
boolean atLeastOneUpdated = false;
switch (Athena.shuffleMessage){
case 1:
Object[] arrayf = this.getFunctions().toArray();
arrayf = Utils.shuffleArrayFY(arrayf);
for (Object nodeFunction : arrayf) {
Object[] arrayx = this.getVariablesOfFunction((NodeFunction)nodeFunction).toArray();
arrayx = Utils.shuffleArrayFY(arrayx);
// TODO: shuffling is DA WAY
for (Object nodeVariable : arrayx) {
//atLeastOneUpdated |= this.op.updateQ(variable, function, this.postservice);
atLeastOneUpdated |= this.op.updateR((NodeFunction)nodeFunction, (NodeVariable)nodeVariable, this.postservice);
}
}
break;
case 0:
default:
Iterator<NodeFunction> iteratorf = this.getFunctions().iterator();
NodeVariable variable = null;
NodeFunction function = null;
while (iteratorf.hasNext()){
function = iteratorf.next();
//System.out.println("Sono la funzione "+function.getId()+" dell'agente "+this.id());
// gotcha a variable, looking for its functions
//Iterator<NodeFunction> iteratorf = this.variableToFunctions.get(variable).iterator();
Iterator<NodeVariable> iteratorv = this.getVariablesOfFunction(function).iterator();
while (iteratorv.hasNext()){
variable = iteratorv.next();
//System.out.println("Sono la variabile "+variable.getId()+" dei vicini di "+function.getId());
// got variable, function
if (debug>=1) {
String dmethod = Thread.currentThread().getStackTrace()[1].getMethodName();
String dclass = Thread.currentThread().getStackTrace()[1].getClassName();
System.out.println("---------------------------------------");
System.out.println("[class: "+dclass+" method: " + dmethod+ "] " + "agent "+this+" preparing R from " + function + " to " + variable);
System.out.println("---------------------------------------");
}
atLeastOneUpdated |= this.op.updateR(function, variable, this.postservice);
if (debug>=1) {
String dmethod = Thread.currentThread().getStackTrace()[2].getMethodName();
String dclass = Thread.currentThread().getStackTrace()[2].getClassName();
System.out.println("---------------------------------------");
System.out.println("[class: "+dclass+" method: " + dmethod+ "] " + "messageR updated:");
MessageR mq = this.postservice.readRMessage(function, variable);
System.out.println("Sender "+ mq.getSender() + " Receiver " + mq.getReceiver() + " message "+ mq );
System.out.println("---------------------------------------");
}
}
}
}
return atLeastOneUpdated;
} |
eeb262a9-3c03-4260-a1c8-d90682833b25 | 4 | public static void main(String[] args) throws Exception{
ArrayList<File> files = FileFinder.GetAllFiles("/home/lizhou/Desktop/nursing", "", true);
for(File f: files){
String name = f.getName();
@SuppressWarnings("resource")
PrintStream ps = new PrintStream(new FileOutputStream("/home/lizhou/Desktop/nursing_1/" + name));
BufferedReader br = new BufferedReader(new FileReader(f));
String line = null;
while ((line = br.readLine()) != null) {
String[] split = line.split(" +");
if (split.length < 2) continue;
for(int i = 0; i < split.length; i++){
ps.println(split[i]);
System.out.println(split[i]);
}
}
br.close();
}
} |
fccc70bb-805d-4a8d-9122-e88723d554cc | 8 | public Unit getUnitAt(Position p) {
if ( p.getRow() == 2 && p.getColumn() == 3 ||
p.getRow() == 3 && p.getColumn() == 2 ||
p.getRow() == 3 && p.getColumn() == 3 ) {
return new StubUnit(GameConstants.ARCHER, Player.RED);
}
if ( p.getRow() == 4 && p.getColumn() == 4 ) {
return new StubUnit(GameConstants.ARCHER, Player.BLUE);
}
return null;
} |
6bab5c03-a345-4900-bf8e-d1de61049e9e | 8 | public void twittThisInBehalf(String twitterMessage) {
try {
Twitter twitter = new TwitterFactory().getInstance();
try {
// get request token.
// this will throw IllegalStateException if access token is already available
RequestToken requestToken = twitter.getOAuthRequestToken();
System.out.println("Got request token.");
System.out.println("Request token: " + requestToken.getToken());
System.out.println("Request token secret: " + requestToken.getTokenSecret());
AccessToken accessToken = null;
accessToken = new AccessToken("1710981037-EJLpqSiD5HOeGUUyVY4IxOkMwh9hgnURYJIBDXW", "Cxc0VpLzEgOpYhsMKrqYjKzIhV5MUTtDhpEMJJRUxyqaf");
twitter.setOAuthAccessToken(accessToken);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (null == accessToken) {
System.out.println("Open the following URL and grant access to your account:");
System.out.println(requestToken.getAuthorizationURL());
System.out.print("Enter the PIN(if available) and hit enter after you granted access.[PIN]:");
String pin = br.readLine();
try {
if (pin.length() > 0) {
accessToken = twitter.getOAuthAccessToken(requestToken, pin);
} else {
accessToken = twitter.getOAuthAccessToken(requestToken);
}
} catch (TwitterException te) {
if (401 == te.getStatusCode()) {
System.out.println("Unable to get the access token.");
} else {
te.printStackTrace();
}
}
}
System.out.println("Got access token.");
System.out.println("Access token: " + accessToken.getToken());
System.out.println("Access token secret: " + accessToken.getTokenSecret());
} catch (IllegalStateException ie) {
// access token is already available, or consumer key/secret is not set.
if (!twitter.getAuthorization().isEnabled()) {
System.out.println("OAuth consumer key/secret is not set. " + ie.getMessage());
System.exit(-1);
}
}
Status status = twitter.updateStatus(twitterMessage);
System.out.println("Successfully updated the status to [" + status.getText() + "].");
System.exit(0);
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to get timeline: " + te.getMessage());
System.exit(-1);
} catch (IOException ioe) {
ioe.printStackTrace();
System.out.println("Failed to read the system input.");
System.exit(-1);
}
} |
73ba906a-f03a-4752-bf9d-39da4ed3c6b9 | 5 | @Override
public HandshakeState acceptHandshakeAsServer( ClientHandshake handshakedata ) {
if( handshakedata.getFieldValue( "Upgrade" ).equals( "WebSocket" ) && handshakedata.getFieldValue( "Connection" ).contains( "Upgrade" ) && handshakedata.getFieldValue( "Sec-WebSocket-Key1" ).length() > 0 && !handshakedata.getFieldValue( "Sec-WebSocket-Key2" ).isEmpty() && handshakedata.hasFieldValue( "Origin" ) )
return HandshakeState.MATCHED;
return HandshakeState.NOT_MATCHED;
} |
7580c2d5-a2d7-45cb-a487-d8b6401080c3 | 6 | private final void method641() {
synchronized (this) {
for (int i = 0; i < anInt5387; i++) {
int i_302_ = anIntArray5312[i];
anIntArray5312[i] = anIntArray5356[i];
anIntArray5356[i] = -i_302_;
if (aClass360Array5360[i] != null) {
i_302_ = ((Class360) aClass360Array5360[i]).anInt4427;
((Class360) aClass360Array5360[i]).anInt4427
= ((Class360) aClass360Array5360[i]).anInt4430;
((Class360) aClass360Array5360[i]).anInt4430 = -i_302_;
}
}
if (aClass41Array5385 != null) {
for (int i = 0; i < anInt5351; i++) {
if (aClass41Array5385[i] != null) {
int i_303_ = ((Class41) aClass41Array5385[i]).anInt559;
((Class41) aClass41Array5385[i]).anInt559
= ((Class41) aClass41Array5385[i]).anInt561;
((Class41) aClass41Array5385[i]).anInt561 = -i_303_;
}
}
}
for (int i = anInt5387; i < anInt5340; i++) {
int i_304_ = anIntArray5312[i];
anIntArray5312[i] = anIntArray5356[i];
anIntArray5356[i] = -i_304_;
}
anInt5354 = 0;
aBoolean5323 = false;
}
} |
8c128e45-66b1-4d56-ae39-f0a179ff9020 | 7 | protected void addItem() {
Item item = null;
CatItems sel = (CatItems) jCbItemType.getSelectedItem();
switch (sel) {
case GOODS:
String gDescr = jTextGoodsDescr.getText();
double gPrice = Double.valueOf(jTextGoodsPrice.getText());
int gAvaibleItems = Integer.valueOf(jTextGoodsQuantity.getText());
item = new GeneralGood(gDescr, gPrice, 0, gAvaibleItems, ((Manager) this.ctrl.getCurUser()));
break;
case RESTOURANT:
String rDescr = jTextRestDescr.getText();
String rName = jTextRestName.getText();
String rLocation = jTextRestLocation.getText();
MyDate rExpiryDate;
try {
rExpiryDate = new MyDate().fromString(jTextRestEndDate.getText());
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
return;
}
double rPrice = Double.valueOf(jTextRestPrice.getText());
int rAvailableEvents = Integer.valueOf(jTextRestQuantity.getText());
item = new Restourant(rName, rDescr, rPrice, 0, rExpiryDate, rLocation, rAvailableEvents);
break;
case SERVICE:
String sDescr = jTextServiceDescr.getText();
double sPrice = Double.valueOf(jTextServicePrice.getText());
String sLocation = jTextServiceLocation.getText();
item = new Service(sDescr, sLocation, sPrice, 0, ((Manager) this.ctrl.getCurUser()));
break;
case TRAVEL:
double tPrice = Double.valueOf(jTextTravelPrice.getText());
MyDate tExpiryDate;
MyDate tDepartureDate;
try {
tExpiryDate = new MyDate().fromString(jTextTravelExpDate.getText());
tDepartureDate = new MyDate().fromString(jTextTravelDepDate.getText());
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
return;
}
String tLocation = jTextTravelLoc.getText();
item = new Travel(tPrice, 0, tExpiryDate, tLocation, tDepartureDate);
break;
}
try {
this.ctrl.getStore().addItem(item);
} catch (Exception e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
dispose();
} |
95a1b832-cb2a-4faf-ab91-4c56e89c772b | 1 | public void testMinus_Minutes() {
Minutes test2 = Minutes.minutes(2);
Minutes test3 = Minutes.minutes(3);
Minutes result = test2.minus(test3);
assertEquals(2, test2.getMinutes());
assertEquals(3, test3.getMinutes());
assertEquals(-1, result.getMinutes());
assertEquals(1, Minutes.ONE.minus(Minutes.ZERO).getMinutes());
assertEquals(1, Minutes.ONE.minus((Minutes) null).getMinutes());
try {
Minutes.MIN_VALUE.minus(Minutes.ONE);
fail();
} catch (ArithmeticException ex) {
// expected
}
} |
594c898a-c60a-4639-bd04-808b0edc2118 | 1 | public void fall() {
point.setLocation(location);
point.translate(0, -1);
if (assertLegal(pane, block, point, block, location)) {
free();
location.translate(0, -1);
draw();
}
else {
sink();
}
} |
cccbc51a-81a7-40a2-bce9-d37bc3ab325e | 9 | private boolean crossingInternal(Point2D.Double direction1, Point2D.Double direction2) {
if (angles.size() < 2) {
return false;
}
final double angle1 = convertAngle(getAngle(new Line2D.Double(center, direction1)));
final double angle2 = convertAngle(getAngle(new Line2D.Double(center, direction2)));
Double last = null;
for (Double current : angles) {
if (last != null) {
assert last < current;
if (isBetween(angle1, last, current) && isBetween(angle2, last, current)) {
return false;
}
}
last = current;
}
final double first = angles.first();
if ((angle1 <= first || angle1 >= last) && (angle2 <= first || angle2 >= last)) {
return false;
}
return true;
} |
0f7dbef9-47df-4bcf-83ba-0b8a84f44872 | 8 | public void deleteFolder(String bucket, List<String> listFolders) throws Exception{
ListObjectsRequest listObjectsRequest;
ObjectListing objectListing;
for(String folderItem : listFolders){
if(!folderItem.trim().equalsIgnoreCase("/") && !folderItem.isEmpty()){
try {
if(folderItem.startsWith("/")){
folderItem = folderItem.substring(folderItem.indexOf("/")+1);
}
listObjectsRequest = new ListObjectsRequest()
.withBucketName(bucket)
.withPrefix(folderItem);
do {
objectListing = s3.listObjects(listObjectsRequest);
for (S3ObjectSummary objectSummary :
objectListing.getObjectSummaries()) {
s3.deleteObject(new DeleteObjectRequest(bucket, objectSummary.getKey()));
fireEvent(new ipsilonS3ToolEvent(ipsilonS3ToolEvent.TYPE_DELETING,objectSummary.getKey()));
}
listObjectsRequest.setMarker(objectListing.getNextMarker());
} while (objectListing.isTruncated());
} catch (AmazonServiceException ase) {
throw new ipsilonS3ToolException(ase.getMessage(),ase);
} catch (AmazonClientException ace) {
throw new ipsilonS3ToolException(ace.getMessage(),ace);
}
}
}
} |
0ea7c3ab-de44-428e-9381-a49e064579a1 | 3 | public void setColor()
{
int truthState = getTruthState();
if(truthState==-1)
{
stateColor = Color.RED;
}
if(truthState==0)
{
stateColor = Color.YELLOW;
}
if(truthState==1)
{
stateColor = Color.GREEN;
}
} |
30ea5c1c-6f40-41ff-bb2f-45326bd27e70 | 2 | public final synchronized float readFloat(){
this.inputType = true;
String word="";
float ff=0.0F;
if(!this.testFullLineT) this.enterLine();
word = nextWord();
if(!eof)ff = Float.parseFloat(word.trim());
return ff;
} |
ad4f2f44-a27b-4b47-b246-7dea5285a6e8 | 6 | @Override
public Serializable callMethod(String methodName, ArrayList<Object> params){
Object resu = null;
if(methodName.equals("deposit")){
try {
deposit((String) params.get(0), (double) params.get(1));
} catch (InvalidParamException e) {
// TODO Auto-generated catch block
e.printStackTrace();
resu = e;
}
} else if(methodName.equals("withdraw")){
try {
withdraw((String) params.get(0), (double) params.get(1));
} catch (InvalidParamException | OverdraftException e) {
// TODO Auto-generated catch block
e.printStackTrace();
resu = e;
}
} else if(methodName.equals("getBalance")){
try {
resu = getBalance((String) params.get(0));
} catch (InvalidParamException e) {
// TODO Auto-generated catch block
e.printStackTrace();
resu = e;
}
} else {
//TODO Insert a new Exception Type
resu = new Exception("Illegal Method");
}
return (Serializable) resu;
} |
f7de7e5a-c9c0-464f-9d71-48ec14c2e5fc | 4 | public boolean Equals(Move move){
return (this.initialRow == move.initialRow
&& this.initialCol == move.initialCol
&& this.finalRow == move.finalRow
&& this.finalCol == move.finalCol)?true:false;
} |
4fde7032-6747-422e-b7e8-fabd56d88832 | 1 | public void setCashOffice(CashOffice cashOffice) {
this.cashOffice = cashOffice;
if ( !cashOffice.exists(this)) {
cashOffice.addTicket(this);
}
} |
ebf17370-19bd-4be2-b66a-3911278abb42 | 3 | private void loadTexture(String pTextureUrl) {
if(pTextureUrl != null) {
Path texture = FileSystems.getDefault().getPath(pTextureUrl);
if(texture.toFile().exists()) {
try {
skyTexture = TextureIO.newTexture(texture.toFile(), true);
} catch (IOException | GLException ex) {
Logger.getLogger(Sky.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
} |
2c7c2a13-6fb9-4d51-a2a5-984d1d3eb92f | 0 | public Game() {
super("Checkers");
setSize(WIDTH, HEIGHT);
setLocationRelativeTo(null); //lo centra nello schermo
this.board = new Board();
this.black=new Cpu(Board.BLACK, board);
setLayout(new GridLayout(8,8));
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowListener() {
@Override
public void windowActivated(WindowEvent e) {
}
@Override
public void windowClosed(WindowEvent e) {
}
@Override
public void windowClosing(WindowEvent e) {
checkExit.setVisible(true);
}
@Override
public void windowDeactivated(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowOpened(WindowEvent e) {
}
});
turnChanger = new TurnChanger(new Player(Board.WHITE,board),black);
showBoard(true);
initializeSound();
} |
656b5618-8c70-4145-bdd8-27a5dcdd4a1e | 8 | @Override
public Success<SourceFile> parse(String s, int p) {
p = optWS(s, p);
// Parse the module keyword.
Success<String> resModule = IdentifierParser.singleton.parse(s, p);
if (resModule == null || !resModule.value.equals("module"))
throw new NiftyException("Missing module declaration at beginning of file.");
p = resModule.rem;
p = optWS(s, p);
// Parse the module name.
resModule = IdentifierParser.singleton.parse(s, p);
if (resModule == null)
throw new NiftyException("Missing module name.");
p = resModule.rem;
p = optWS(s, p);
// Parse the ';'.
if (s.charAt(p++) != ';')
throw new NiftyException("Expecting ';' after module name.");
p = optWS(s, p);
// Parse the imports.
List<Import> imports = new ArrayList<Import>();
while (p < s.length()) {
Success<Import> resImport = ImportParser.singleton.parse(s, p);
if (resImport == null)
break;
imports.add(resImport.value);
p = resImport.rem;
p = optWS(s, p);
}
// Parse the type definitions.
List<TypeDef> typeDefs = new ArrayList<TypeDef>();
while (p < s.length()) {
Success<TypeDef> resTypeDef = TypeDefParser.singleton.parse(s, p);
if (resTypeDef == null)
throw new NiftyException("Expecting type definition.");
typeDefs.add(resTypeDef.value);
p = resTypeDef.rem;
p = optWS(s, p);
}
// Format and return the results.
Import[] importArr = imports.toArray(new Import[imports.size()]);
TypeDef[] typeDefArr = typeDefs.toArray(new TypeDef[typeDefs.size()]);
SourceFile result = new SourceFile(resModule.value, importArr, typeDefArr);
return new Success<SourceFile>(result, p);
} |
ecd1fa01-c952-4f42-8b91-1eb248e2228d | 6 | public Double[] maximizeMod(Double[] max, int[] numberOfValues, NodeVariable x, int xIndex, FunctionEvaluator fe, HashMap<NodeVariable, MessageQ> modifierTable){
if(debug>=3){
System.out.print("Oplus_MaxSum.maximizeMod: modifier table size="+modifierTable.size());
if (modifierTable.size()>=1){
Iterator<NodeVariable> it = modifierTable.keySet().iterator();
while (it.hasNext()) {
NodeVariable nodeVariable = it.next();
System.out.print(" Node:"+nodeVariable+" Value:"+modifierTable.get(nodeVariable));
}
}
System.out.println("");
}
double cost = 0;
for (int xParamIndex = 0; xParamIndex < x.size(); xParamIndex ++) {
numberOfValues[xIndex] = xParamIndex;
// NOW it's pretty ready
// this is the part where it is maximized
cost = ( fe.evaluateMod(fe.functionArgument(numberOfValues), modifierTable));
if (max[xParamIndex] == null){
max[xParamIndex] = ( cost );
} else {
max[xParamIndex] = ( cost > max[xParamIndex] ) ? cost : max[xParamIndex];
}
}
return max;
} |
b83a6c0c-1859-447c-9f74-9ca9deeec3a9 | 0 | @Override
public void actionPerformed(ActionEvent e) {
exportOutlinerDocument((OutlinerDocument) Outliner.documents.getMostRecentDocumentTouched(), getProtocol());
} |
0ab671d3-7dd2-4174-943b-53e6f935ff44 | 4 | public void disableAllBut(JButton[] b){
JButton allButton[] = {createMatrix, selectMatrix, deleteMatrix, helpButton, transposeButton, detButton, rowRedButton, inverseButton};
for(int i = 0; i<allButton.length; i++){
boolean disable = true;
for(int j = 0; j<b.length; j++){
if(b[j] == allButton[i])
disable = false;
}
if(disable)
allButton[i].setEnabled(false);
}
} |
ddce1a2d-d401-4fdc-a1c0-26b3f2416cdb | 9 | private void appointmentManager(){
System.out.println("=========Appointment manager=========");
System.out.println("0: Back to main menu");
System.out.println("1: Show my appointments weekwise");
System.out.println("2: Show my appointments this week/month");
System.out.println("3: Make an appointment");
System.out.println("4: Edit an appointment");
System.out.println("5: Delete an appointment");
System.out.println("6: Connect appointment to group");
int valg = readInt();
while (valg < 0 || valg > 6){
System.out.println("Your choise was invalid. Please select a valid option.");
valg = readInt();
}
switch (valg){
case 0:
return;
case 1:
printAppointments();
break;
case 2:
printAvtaler();
break;
case 3:
createAppointment();
break;
case 4:
editAppointment();
break;
case 5:
deleteAppointment();
break;
case 6:
addGroupToAppointment();
break;
}
} |
d7d31674-deac-4d69-aae4-4b185af66a6a | 9 | private void initListeners() {
PatchPanelMediator mediator = PatchPanelMediator.getMediator();
mediator.addDocumentChangedListener(new DocumentChangedListener() {
@Override
public void documentChanged(DocumentChangedEvent dce) {
document = dce.getDocument();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
widthField.setText(String.valueOf(document.getWidth()));
heightField.setText(String.valueOf(document.getHeight()));
animationCB.setSelectedIndex(document.getAnimationType().ordinal());
outOfBoundsColorCB.setSelectedIndex(document.getOutOfBoundsColor().ordinal());
tweenFramesField.setText(String.valueOf(document.getTweenCount()));
tweenStyleCB.setSelectedIndex(document.getTweenStyle().ordinal());
}
});
}
});
widthField.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent fe) {
try {
int oldWidth = document.getWidth();
int newWidth = Integer.parseInt(widthField.getText());
if (oldWidth != newWidth) {
document.setWidth(newWidth);
PatchPanelMediator ppMediator = PatchPanelMediator.getMediator();
ppMediator.fireSettingsChanged();
}
} catch (NumberFormatException nfe) {
document.setWidth(100);
PatchPanelMediator ppMediator = PatchPanelMediator.getMediator();
ppMediator.fireSettingsChanged();
}
}
@Override
public void focusGained(FocusEvent fe) {
widthField.setSelectionStart(0);
widthField.setSelectionEnd(Integer.MAX_VALUE);
}
});
heightField.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent arg0) {
try {
int oldHeight = document.getHeight();
int newHeight = Integer.parseInt(heightField.getText());
if (oldHeight != newHeight) {
document.setHeight(newHeight);
PatchPanelMediator ppMediator = PatchPanelMediator.getMediator();
ppMediator.fireSettingsChanged();
}
} catch (NumberFormatException nfe) {
document.setHeight(100);
PatchPanelMediator ppMediator = PatchPanelMediator.getMediator();
ppMediator.fireSettingsChanged();
}
}
@Override
public void focusGained(FocusEvent fe) {
heightField.setSelectionStart(0);
heightField.setSelectionEnd(Integer.MAX_VALUE);
}
});
tweenFramesField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent arg0) {
try {
int oldTween = document.getTweenCount();
int newTween = Integer.parseInt(tweenFramesField.getText());
if (oldTween != newTween) {
document.setTweenCount(newTween);
PatchPanelMediator ppMediator = PatchPanelMediator.getMediator();
ppMediator.fireSettingsChanged();
}
} catch (NumberFormatException nfe) {
document.setTweenCount(10);
PatchPanelMediator ppMediator = PatchPanelMediator.getMediator();
ppMediator.fireSettingsChanged();
}
}
});
animationCB.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent ie) {
if (ie.getStateChange() == ItemEvent.SELECTED) {
document.setAnimationType((AnimationType)ie.getItem());
PatchPanelMediator ppMediator = PatchPanelMediator.getMediator();
ppMediator.fireSettingsChanged();
}
}
});
outOfBoundsColorCB.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent ie) {
if (ie.getStateChange() == ItemEvent.SELECTED) {
document.setOutOfBoundsColor((OutOfBoundsColor)ie.getItem());
PatchPanelMediator ppMediator = PatchPanelMediator.getMediator();
ppMediator.fireSettingsChanged();
}
}
});
tweenFramesField.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent fe) {
tweenFramesField.setSelectionStart(0);
tweenFramesField.setSelectionEnd(Integer.MAX_VALUE);
}
});
tweenStyleCB.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent ie) {
if (ie.getStateChange() == ItemEvent.SELECTED) {
document.setTweenStyle((TweenStyle)ie.getItem());
PatchPanelMediator ppMediator = PatchPanelMediator.getMediator();
ppMediator.fireSettingsChanged();
}
}
});
testButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
JTestFrame tf = new JTestFrame();
tf.setLocationRelativeTo(JPatchControlPanel.this.getRootPane());
tf.setVisible(true);
tf.setAlwaysOnTop(true);
tf.beginAnimation();
}
});
} |
61d19abe-1f0d-47fe-8f32-94147a45ce5b | 1 | public boolean EliminarPlaga(Plaga p){
if (p!=null) {
cx.Eliminar(p);
return true;
}else {
return false;
}
} |
ec6004be-835d-4ebb-8fa0-144b7a9214ee | 7 | public static void main(String[] args) {
int[] summable = new int[28124]; // 0 will not be used
ArrayList<Integer> abundantnums = new ArrayList<>();
for (int i = 1; i <= 28123; i++) {
if (p21amicable.calcDivisors(i) > i) {
// System.out.println(i + " is abundant.");
abundantnums.add(i);
}
}
for(Integer v1: abundantnums) {
for(Integer v2: abundantnums) {
if(v1+v2 <= 28123)
summable[v1+v2] = 1;
}
}
int sum = 0;
for (int i = 1; i < summable.length; i++) {
if (summable[i] == 0) { //if this index can not be summed by two abundant numbers
sum += i;
}
}
System.out.println(sum);
} |
ecd3057e-65ab-45cb-97ff-e8726dba2eca | 4 | public void setLoglevel(LOGLEVEL loglevel)
{
if(loglevel == LOGLEVEL.Nothing)
{
logLevel = -1;
}
else if(loglevel == LOGLEVEL.Error)
{
logLevel = 0;
}
else if(loglevel == LOGLEVEL.Normal)
{
logLevel = 1;
}
else if(loglevel == LOGLEVEL.Debug)
{
logLevel = 2;
}
else
{
logLevel = 1;
}
} |
b6fdb41c-c58b-4539-a602-26e50e74fd15 | 3 | public static void blockUntilProcessEnd(Process process, int timeOut) {
int maxCount = timeOut * 5;
for (int i = 0; i < maxCount && checkProcessEnd(process); i++) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
logger.error(e);
}
}
} |
1a73188f-93ee-40d0-b596-f406de5dc628 | 5 | public boolean sameBearingAsNearFriend(double[] position, double bearing) {
for (double[] agentVals : agentInfo.values()) {
double normal = Math.abs(agentVals[2] - bearing);
if (normal >= 345 || normal <= 10) {
//Similar heading, check proximity.
if (agentVals[0] - position[0] < Math.abs(0.1) && agentVals[1] - position[1] < Math.abs(0.1)) {
return true;
}
}
}
return false;
} |
4b561da4-a4ff-4480-bcdc-24e6a565f57c | 2 | public void visitArithExpr(final ArithExpr expr) {
if (previous == expr.left()) {
previous = expr;
expr.parent.visit(this);
} else if (previous == expr.right()) {
check(expr.left());
}
} |
74022dac-7486-4043-8055-617bbdcc5271 | 6 | public boolean isNearlyTridiagonal(double tolerance){
boolean test = true;
for(int i=0; i<this.numberOfRows; i++){
for(int j=0; j<this.numberOfColumns; j++){
if(i<(j+1) && Math.abs(this.matrix[i][j])>Math.abs(tolerance))test = false;
if(j>(i+1) && Math.abs(this.matrix[i][j])>Math.abs(tolerance))test = false;
}
}
return test;
} |
3fadca49-8810-443e-91d2-4e00319e8d78 | 3 | public void toFtanML(Writer writer) {
try {
writer.append("[");
Iterator<FtanValue> iterator=values.iterator();
if(iterator.hasNext()) {
iterator.next().toFtanML(writer);
while(iterator.hasNext()) {
writer.append(",");
iterator.next().toFtanML(writer);
}
}
writer.append("]");
} catch(IOException e)
{
throw new IllegalStateException(e);
}
} |
d19d9d92-0712-4ea2-aebf-3a53a3300ea3 | 4 | public ArrayList<TreeRow> getSelectedRows() {
ArrayList<TreeRow> selection = new ArrayList<>();
if (!mSelectedRows.isEmpty()) {
for (TreeRow row : new TreeRowViewIterator(this, mRoot.getChildren())) {
if (mSelectedRows.contains(row) && !isAncestorSelected(row)) {
selection.add(row);
}
}
}
return selection;
} |
cbd5527e-8cb5-413a-8764-898603af22e8 | 8 | public boolean checkArc(Arc paArc, Graph graph) {
Element p1 = paArc.getOutElement();
Element p2 = paArc.getInElement();
// Petri Net - Place / Transition
if (graph instanceof PetriNet) {
if (((p1 instanceof AbsPlace) && (p2 instanceof Transition)) | ((p2 instanceof AbsPlace) && (p1 instanceof Transition))) {
return true;
}
}
// Precedence Graph - Node / Node
if (graph instanceof PrecedenceGraph) {
if (((p1 instanceof Node) && (p2 instanceof Node)) && !p1.equals(p2)) {
return true;
}
}
return false;
} |
25d03823-0103-496a-8cef-87c9b235cc49 | 4 | public boolean save(File file) {
checkPaths();
file.getParentFile().mkdirs();
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException ex) {
Debug.p("Deck file could not be created: "
+ file + ": " + ex, Debug.E);
return false;
}
}
try (Writer bf = new OutputStreamWriter(
new FileOutputStream(file), "Unicode")) {
for (int i = 0; i < names.size(); i++) {
bf.write(names.get(i) + ";"
+ amounts.get(i) + ";"
+ paths.get(i) + System.getProperty("line.separator"));
}
} catch (IOException ex) {
Debug.p("Deck could not be saved to file "
+ file + ": " + ex, Debug.E);
return false;
}
deckName = Utilities.getName(file);
return true;
} |
241e2296-7df9-44e0-8d40-e49fc651c3d8 | 1 | */
public InferenceParameters getHLQueryProperties() {
synchronized (defaultQueryProperties) {
if (!queryPropertiesInitialized) {
initializeQueryProperties();
}
return (InferenceParameters) defaultQueryProperties.clone();
}
} |
1d688e28-91da-4d0a-9b52-0d7a82ed500a | 0 | public void setDiscount(float discount) {
this.discount = discount;
} |
3b54cb07-87b4-4a7c-9783-8d0211db388c | 0 | public ISocketServerConnection getClientConnection() {
return clientConnection;
} |
2134b49a-2ce3-4385-a9ee-297aec80c84e | 1 | protected static boolean removeProtection(Path file) {
assert FileUtil.control(file);
boolean ret = false;
String cmdTmp = SAVEACL_CMD_1 + file.toString() + SAVEACL_CMD_2 + acl + file.getFileName().toString().replaceAll("\\.", "")
+ SAVEACL_CMD_3;
cmdTmp += AND + TAKEOWN_CMD_1 + file.toString() + TAKEOWN_CMD_2;
cmdTmp += AND + SET_FULL_ADMINRIGHTS_CMD_1 + file.toString() + SET_FULL_ADMINRIGHTS_CMD_2;
try {
ret = ProgramLauncher.start(SystemInformation.getCMD(), cmdTmp, true, ERROR_IDENTIFIER);
} catch (InterruptedException
| IOException e) {
ret = false;
}
return ret;
} |
e869b1aa-c799-4949-a332-0061b9974483 | 9 | @Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_W) upPressed = true;
if(e.getKeyCode() == KeyEvent.VK_S) downPressed = true;
if(e.getKeyCode() == KeyEvent.VK_A) leftPressed = true;
if(e.getKeyCode() == KeyEvent.VK_D) rightPressed = true;
if(e.getKeyCode() == KeyEvent.VK_1) onePressed = true;
if(e.getKeyCode() == KeyEvent.VK_2) twoPressed = true;
if(e.getKeyCode() == KeyEvent.VK_3) threePressed = true;
if(e.getKeyCode() == KeyEvent.VK_ENTER) enterPressed = true;
if(e.getKeyCode() == KeyEvent.VK_SPACE) spacePressed = true;
} |
a777c323-38c6-4dce-9741-aeb614f1a119 | 3 | public Object getValue(Object obj,String propName) {
Object val = null;
PropInfo propInfo = propInfoByPropName.get(propName);
if (propInfo != null){
Method readMethod = propInfo.getReadMethod();
if (readMethod == null){
throw new RuntimeException(format("propName %s does not not have readMethod",propName));
}
try {
val = readMethod.invoke(obj);
} catch (Throwable e) {
throw new RuntimeException(format("Error while calling read method %s for property %s on object %s", readMethod.getName(), propName, obj) + "\n" + e,e);
}
}
return val;
} |
d1085700-72ee-4cc3-9e04-50aa91051715 | 4 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
@SuppressWarnings("unchecked")
Map<Integer,Integer> mandje = (Map<Integer,Integer>)request.getSession().getAttribute(MANDJE);
int nummer = 0;
try {
nummer = Integer.parseInt(request.getParameter("nummer")); // nummer van de voorstelling
Voorstelling voorstelling = voorstellingDAO.findByNumber(nummer );
request.setAttribute("voorstelling", voorstelling);
if (mandje!=null){
for (Map.Entry<Integer, Integer> entry : mandje.entrySet()){
if (nummer==entry.getKey()){
int plaatsen=entry.getValue();
request.setAttribute("gereserveerdePlaatsen", plaatsen);
}
}
}
} catch (NumberFormatException ex) {
// we doen niets, de pagina blijft staan
}
RequestDispatcher dispatcher = request.getRequestDispatcher(VIEW);
dispatcher.forward(request, response);
} |
70b2a8b8-689c-48ab-8eff-433a32dfe0c1 | 0 | @Test
public void testCheckCbolOriginalDir() {
new DirCbol().checkCbolOriginalDir();
new DirCbol().checkCbolOriginalDirV2();
new DirCbol().checkCbolOriginalDirV3();
new DirCbol().checkCbolOriginalDirV4();
} |
9184acbd-4f45-466f-8a71-bd823e8d693b | 0 | @SuppressWarnings("unchecked")
public List<Product> retrieveAllProducts() {
return em.createNamedQuery("findAllProducts").getResultList();
} |
1a0a0eb3-e679-4253-88f9-f9d6eb1a31c3 | 1 | public JSONArray optJSONArray(int index) {
Object o = this.opt(index);
return o instanceof JSONArray ? (JSONArray)o : null;
} |
0ce0cb66-397a-4b61-bcc9-fdcc6f9d428a | 7 | private int deleteFileFromStorage(String fileName, boolean deleteMaster,
boolean justTest) {
Storage tempStorage = null;
File tempFile = null;
int msg = DataGridTags.FILE_DELETE_ERROR;
for (int i = 0; i < storageList_.size(); i++) {
tempStorage = (Storage) storageList_.get(i);
tempFile = tempStorage.getFile(fileName);
if (tempFile != null) {
// if want to delete a master copy, then you can't
if (tempFile.isMasterCopy() && !deleteMaster) {
msg = DataGridTags.FILE_DELETE_ERROR_ACCESS_DENIED;
}
// if a file is a replica, but want to delete a master one
else if (!tempFile.isMasterCopy() && deleteMaster) {
msg = DataGridTags.FILE_DELETE_ERROR_ACCESS_DENIED;
} else {
// if you want to actually delete this file
if (!justTest) {
tempStorage.deleteFile(fileName, tempFile);
}
msg = DataGridTags.FILE_DELETE_SUCCESSFUL;
}
}
} // end for
return msg;
} |
9e78ba53-9ffc-4e6b-ba79-7e45c1e294d4 | 2 | public static void main(String[] argsv) {
// Setting op a bank.
Bank christmasBank = new Bank();
christmasBank.addAccount(new BankAccount(BigInteger.valueOf(100)));
christmasBank.addAccount(new BankAccount(BigInteger.valueOf(50), BigInteger.valueOf(-1000)));
// Award a bonus to all bank accounts of the Christmas bank.
System.out.print("Enter the bonus to be awarded: ");
Scanner inputStreamScanner = new Scanner(System.in);
BigInteger bonus = BigInteger.valueOf(inputStreamScanner.nextLong());
try {
christmasBank.executeOnAllAccounts(BankAccount.class.getMethod("deposit", BigInteger.class), bonus);
} catch (NoSuchMethodException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
// Print the balance of each account.
for (BankAccount account: christmasBank.getAllAccounts())
System.out.println(account.getBalance());
} |
52a8c86c-f132-440b-b702-9825214cbd1c | 0 | @Test
public void testCheckValidForTournament() throws Exception {
System.out.println("checkValidForTournament");
World instance = new World();
instance.readInWorld("2.world");
boolean expResult = true;
boolean result = instance.checkValidForTournament();
assertEquals(expResult, result);
instance = new World();
instance.generateRandomContestWorld();
expResult = true;
result = instance.checkValidForTournament();
assertEquals(expResult, result);
} |
0a494f29-4039-459f-9fe8-0c87acf56be5 | 3 | protected synchronized boolean isFullLine(int yCoordinate) {
boolean isFullLine = true;
int minX = lowerLimit.getX();
int maxX = upperLimit.getX();
for (int currentX = minX; currentX<=maxX; currentX++) {
Point point = new Point(currentX, yCoordinate);
if (isInGridRange(point)) {
if (isInEmtpyPoint(point)) {
isFullLine = false;
break;
}
}
}
return isFullLine;
} |
83eedd12-daaf-43c7-bdb2-495b619fe2ef | 5 | public void alustaPeliLauta() {
x = 30;
y = 600;
s = 300;
r = 600;
p = 30;
q = 30;
winCondition = 0;
arvausMaara = 0;
vari = -1;
rivi = 0;
sarake = 0;
vinkkiRivi = 0;
oikeaKoodi = new kuvio[4];
for (int i = 0; i < 4; i++) {
oikeaKoodi[i] = new kuvio(-1, p, q);
p += 40;
}
p = 30;
vinkki = new kuvio[10][4];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 4; j++) {
vinkki[i][j] = new kuvio(0, s, r);
s += 40;
}
s = 300;
r -= 50;
}
s = 300;
r = 600;
logiikka = new Logica();
arvaukset = new kuvio[10][4];
for (int j = 0; j < 10; j++) {
for (int i = 0; i < 4; i++) {
arvaukset[j][i] = new kuvio(vari, x, y);
x += 40;
}
x = 30;
y -= 50;
}
x = 30;
y = 600;
repaint();
} |
b27afe72-932c-46c1-9851-16fb08c191d6 | 4 | @Override
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(finish)){
ansname = name.getText();
anstype = type.getText();
ansx = xsize.getText();
ansy = ysize.getText();
if(tset == null){
tset = new TileSet();
//tset.setTile(0, new Tile(0, ""));
}
succeeded = true;
setVisible(false);
}
if(e.getSource().equals(cancel)){
succeeded = false;
setVisible(false);
}
if(e.getSource().equals(tsetPathButton)){
tset = operations.loadTileSet();
}
} |
19798232-4a06-4534-8c2f-2a9a874ded01 | 7 | public static String getTextBetweenNestedDelims( String originalText, String beginDelim, String endDelim )
{
StringBuffer sb = new StringBuffer( originalText.length() );
// Check to see that both delimiters exist in the string
if( (originalText.indexOf( beginDelim ) < 0) || (originalText.lastIndexOf( endDelim ) < 0) )
{
return "";
}
int begidx = originalText.indexOf( beginDelim ) + beginDelim.length();
int endidx = originalText.lastIndexOf( endDelim );
int holder = 0;
if( begidx < endidx )
{
sb.append( originalText.substring( begidx, endidx ) );
}
else
{
while( (begidx > endidx) && (endidx > -1) )
{
holder = endidx;
endidx = originalText.lastIndexOf( endDelim, holder + 1 );
}
if( (begidx < endidx) && (endidx > -1) )
{
sb.append( originalText.substring( begidx, endidx ) );
}
}
return sb.toString();
} |
7f48b682-6c46-4d84-a851-8cd9c4cc0011 | 1 | public void createSong(BESong aSong) throws Exception {
try {
ds.createSong(aSong);
m_songs.add(aSong);
} catch (SQLException ex) {
throw new Exception("Could not create the song " + aSong.getTitle());
}
} |
47597340-1233-4656-9b0f-8a687a16aca7 | 3 | public void drawShapedSprite(int height, int arg1, int dest[], int arg3, int src[], int arg5, int arg6, int arg7, int width, int arg9) {
try {
int j2 = -width / 2;
int k2 = -height / 2;
int sineStep = (int) (Math.sin(arg1 / 326.11000000000001D) * 65536D);
int cosStep = (int) (Math.cos(arg1 / 326.11000000000001D) * 65536D);
sineStep = sineStep * arg3 >> 8;
cosStep = cosStep * arg3 >> 8;
int sine = (arg9 << 16) + k2 * sineStep + j2 * cosStep;
int cos = (arg5 << 16) + k2 * cosStep - j2 * sineStep;
int l3 = arg7 + arg6 * Graphics2D.width;
for (arg6 = 0; arg6 < height; arg6++) {
int i4 = src[arg6];
int j4 = l3 + i4;
int k4 = sine + cosStep * i4;
int l4 = cos - sineStep * i4;
for (arg7 = -dest[arg6]; arg7 < 0; arg7++) {
Graphics2D.pixels[j4++] = pixels[(k4 >> 16) + (l4 >> 16) * this.width];
k4 += cosStep;
l4 -= sineStep;
}
sine += sineStep;
cos += cosStep;
l3 += Graphics2D.width;
}
} catch (Exception exception) {
}
} |
8f6f5bc6-18f9-4bab-a6e3-6c3c39422013 | 9 | @SuppressWarnings("deprecation")
public static void main(String[] args) {
HashMap<String, ArrayList<Integer>> finalMap = new HashMap<String, ArrayList<Integer>>();
HashMap<String, HashMap<Integer,Integer>> dayCountForStnMap = new HashMap<String, HashMap<Integer,Integer>>();
HashMap<Integer, String> stationIdNameMap = new HashMap<Integer, String>();
//HashMap<Integer, String> stationCommMap = new HashMap<Integer, String>();
try {
Integer lineCount = 0;
CsvReader trips = new CsvReader("C:\\Users\\ThejaSwarup\\Box Sync\\Fall 2014\\CS 424\\Project2\\InputFiles\\trips_updated.csv");
//CsvReader trips = new CsvReader("C:\\Users\\ThejaSwarup\\Desktop\\Test.csv");
//CsvReader stations = new CsvReader("C:\\Users\\ThejaSwarup\\Box Sync\\Fall 2014\\CS 424\\Project2\\InputFiles\\stations_final.csv");
CsvReader communities = new CsvReader("C:\\Users\\ThejaSwarup\\Box Sync\\Fall 2014\\CS 424\\Project2\\InputFiles\\Communities.csv");
communities.readHeaders();
//Map: stationName, dayList
while (communities.readRecord()){
++lineCount;
stationIdNameMap.put(new Integer(communities.get("id")), communities.get("name"));
//stationCommMap.put(new Integer(stations.get("id")), stations.get("CommunityArea"));
finalMap.put(communities.get("name"), new ArrayList<Integer>());
dayCountForStnMap.put(communities.get("name"), new HashMap<Integer,Integer>());
}
communities.close();
//read headers from input file
trips.readHeaders();
int lineNum = 0;
while (trips.readRecord())
{
ArrayList<Integer> valList = new ArrayList<Integer>();
String startTime = trips.get("starttime");
String fromCommName = trips.get("from_community");
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm", Locale.US);
try {
System.out.println(++lineNum);
//++lineNum;
cal.setTime(sdf.parse(startTime));
valList = finalMap.get(fromCommName);
valList.add(new Integer(cal.get(Calendar.DAY_OF_YEAR)));
finalMap.put(fromCommName, valList);
} catch (Exception e) {
e.printStackTrace();
}
}
trips.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Now from your final map count no.of occurrences of days for each station
Iterator<Map.Entry<String, ArrayList<Integer>>> iterator = finalMap.entrySet().iterator();
while(iterator.hasNext()){
HashMap<Integer, Integer> mainMapValue = new HashMap<Integer, Integer>();
int days[] = new int[365];
for(int i = 0; i < days.length; i++) {
days[i] = 0;
}
Map.Entry<String, ArrayList<Integer>> entry = iterator.next();
ArrayList<Integer> valueList = entry.getValue();
if(valueList.size() > 0){
for(Integer ind = 0; ind < days.length ; ind++){
days[ind] = getOccurencesOfDays(valueList,ind);
mainMapValue = dayCountForStnMap.get(entry.getKey());
mainMapValue.put(new Integer(ind),new Integer(days[ind]));
}
}
dayCountForStnMap.put(entry.getKey(), mainMapValue);
iterator.remove();
}
//create JSON Object
System.out.println(dayCountForStnMap);
createJSON(dayCountForStnMap);
System.out.println("Program Executed");
} |
074711b9-6be7-4946-b23c-a09e7a7c49e7 | 3 | public String getEntryText(int pos) {
int current = 0;
for (Widget i = wdg().child; i != null; i = i.next) {
if (i instanceof TextEntry) {
current++;
if (current == pos) {
TextEntry te = (TextEntry) i;
return te.text;
}
}
}
return "";
} |
9e78bde2-bfa1-43a9-84e8-11ea6f445e8b | 2 | public static void saveFile(INIFile file, String path){
FileUtility.createFile(path);
ArrayList<String> contents = new ArrayList<String>();
for(INISection section : file.getSections()){
String sectionOutput = "[" + section.getName() + "]";
contents.add(sectionOutput);
for(INIParameter parameter : section.getParams()){
String parameterOutput = parameter.getName() + "=" + parameter.getStringValue();
contents.add(parameterOutput);
}
}
FileUtility.writeFile(path, contents);
} |
078d6fcc-3356-41ab-a3ab-dab88e51d5cd | 5 | public boolean equals(
Object o)
{
if (o == null || !(o instanceof ASN1Sequence))
{
return false;
}
ASN1Sequence other = (ASN1Sequence)o;
if (this.size() != other.size())
{
return false;
}
Enumeration s1 = this.getObjects();
Enumeration s2 = other.getObjects();
while (s1.hasMoreElements())
{
if (!s1.nextElement().equals(s2.nextElement()))
{
return false;
}
}
return true;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.