问:
find missing entries - improve efficiency by eliminating nested loop
I would like to eliminate nested loop used to create data in m inside the function. The missing_entries() function is trying to identify and return values of col1 missing for groups in col2. Is there any alternative way to approach this problem in order to improve efficiency?

```<code>missing_entries <- function( data, x, y )
{
  # find missing entries in x for the group in y
  # by comparing other groups in y
  require( 'data.table' )

  # require class of data to be data.table
  stopifnot( "data.table" %in% class(data) )

  # the outer loop with i refers to each unique value of column y
  # the inner loop with j refers to all unique values of column y
  # except the value in i under current iteration
  uniq_col2 <- unique( data[, get(y) ] )
  m <- lapply( uniq_col2, function(i){
    lapply( setdiff( uniq_col2, i ), function( j ) {
      z <- setdiff( data[ get(y) == i, get(x)], data[ get(y) == j, get(x)])
      if( length(z) > 0 ){
        return( data.frame( v1 = z, v2 = j,
                            stringsAsFactors = FALSE ) )
      } else{
        return()
      }
    } )
  })

  # row bind
  m <- lapply( m, function(k) {
    if(!is.null(k)) {
      rbindlist(l = k)
    }})

  # collect only not null data
  m <- rbindlist( l = m[lapply(m, nrow) > 0] )
  colnames( m ) <- c( x, y )

  return( m )
}

# testing
test_data <- structure(list(cardnty = c("many", "many", "many", "many", "many", "many",
                                        "many", "many", "many", "many", "many", "many",
                                        "many", "many", "many", "many", "many", "many",
                                        "many", "many", "many", "many", "many", "many"),
                            col1 = c(2L, 4L, 3L, 13L, 5L, 6L, 7L, 17L, 9L, 4L, 3L,
                                           2L, 8L, 5L, 6L, 7L, 14L, 17L, 19L, 13L,
                                           9L, 12L, 11L, 20L),
                            N = c(599L, 43L, 111L, 12L, 11L, 5L, 4L,
                                  8L, 2L, 72L, 230L, 617L, 13L, 58L, 19L, 9L,
                                  5L, 3L, 2L, 1L, 11L, 1L, 1L, 1L),
                            col2 = c("cat", "cat", "cat", "cat", "cat",
                                   "cat", "cat", "cat", "cat", "dog",
                                   "dog", "dog", "dog",
                                   "dog", "dog", "dog",
                                   "dog", "dog", "dog",
                                   "dog", "dog", "dog",
                                   "dog", "dog" )),
                       .Names = c("cardnty", "col1", "N", "col2"),
                       row.names = c(NA, -24L),
                       class = "data.frame")

require('data.table')
setDT(test_data)
results <- missing_entries(data = test_data, x = "col1", y = "col2")
setDF(results)

test_results <- structure(list(col1 = c(8L, 14L, 19L, 12L, 11L, 20L),
                               col2 = c("cat", "cat", "cat", "cat", "cat", "cat")),
                          .Names = c("col1", "col2"),
                          row.names = c(NA, -6L),
                          class = "data.frame")

identical( results, test_results)
# TRUE
</code>```

答:
Here's a suggestion: Use dcast to convert the dataframe to wide, which fills in 0 for missing values, then converting back to long and pulling out the zero's.

```<code>library(reshape2)
df <- dcast(test_data,col1 ~ col2 ,fill=0,value.var="col2",fun.aggregate=length)
df2 <- melt(df,id.vars="col1")
results <- df2[which(df2$value==0),c("col1","variable")]
</code>```

The time comparison suggests this runs a bit quicker.

```<code>start_time <- Sys.time()
for (x in c(1:10000)){
  results <- missing_entries(data = test_data, x = "col1", y = "col2")
  setDF(results)
}
end_time <- Sys.time()
timeA <- end_time-start_time
# Time difference of 1.725317 mins

start_time <- Sys.time()
for (x in c(1:10000)){
df <- dcast(test_data,col1 ~ col2 ,fill=0,value.var="col2",fun.aggregate=length)
df2 <- melt(df,id.vars="col1")
results <- df2[which(df2$value==0),c("col1","variable")]
}
end_time <- Sys.time()
timeB <- end_time-start_time
# Time difference of 1.368845 mins
</code>```

Body:
I would like to eliminate nested loop used to create data in m inside the function. The missing_entries() function is trying to identify and return values of col1 missing for groups in col2. Is there any alternative way to approach this problem in order to improve efficiency?

missing_entries <- function( data, x, y )
{
  # find missing entries in x for the group in y
  # by comparing other groups in y
  require( 'data.table' )

  # require class of data to be data.table
  stopifnot( "data.table" %in% class(data) )

  # the outer loop with i refers to each unique value of column y
  # the inner loop with j refers to all unique values of column y
  # except the value in i under current iteration
  uniq_col2 <- unique( data[, get(y) ] )
  m <- lapply( uniq_col2, function(i){
    lapply( setdiff( uniq_col2, i ), function( j ) {
      z <- setdiff( data[ get(y) == i, get(x)], data[ get(y) == j, get(x)])
      if( length(z) > 0 ){
        return( data.frame( v1 = z, v2 = j,
                            stringsAsFactors = FALSE ) )
      } else{
        return()
      }
    } )
  })

  # row bind
  m <- lapply( m, function(k) {
    if(!is.null(k)) {
      rbindlist(l = k)
    }})

  # collect only not null data
  m <- rbindlist( l = m[lapply(m, nrow) > 0] )
  colnames( m ) <- c( x, y )

  return( m )
}

# testing
test_data <- structure(list(cardnty = c("many", "many", "many", "many", "many", "many",
                                        "many", "many", "many", "many", "many", "many",
                                        "many", "many", "many", "many", "many", "many",
                                        "many", "many", "many", "many", "many", "many"),
                            col1 = c(2L, 4L, 3L, 13L, 5L, 6L, 7L, 17L, 9L, 4L, 3L,
                                           2L, 8L, 5L, 6L, 7L, 14L, 17L, 19L, 13L,
                                           9L, 12L, 11L, 20L),
                            N = c(599L, 43L, 111L, 12L, 11L, 5L, 4L,
                                  8L, 2L, 72L, 230L, 617L, 13L, 58L, 19L, 9L,
                                  5L, 3L, 2L, 1L, 11L, 1L, 1L, 1L),
                            col2 = c("cat", "cat", "cat", "cat", "cat",
                                   "cat", "cat", "cat", "cat", "dog",
                                   "dog", "dog", "dog",
                                   "dog", "dog", "dog",
                                   "dog", "dog", "dog",
                                   "dog", "dog", "dog",
                                   "dog", "dog" )),
                       .Names = c("cardnty", "col1", "N", "col2"),
                       row.names = c(NA, -24L),
                       class = "data.frame")

require('data.table')
setDT(test_data)
results <- missing_entries(data = test_data, x = "col1", y = "col2")
setDF(results)

test_results <- structure(list(col1 = c(8L, 14L, 19L, 12L, 11L, 20L),
                               col2 = c("cat", "cat", "cat", "cat", "cat", "cat")),
                          .Names = c("col1", "col2"),
                          row.names = c(NA, -6L),
                          class = "data.frame")

identical( results, test_results)
# TRUE

Body:
Here's a suggestion: Use dcast to convert the dataframe to wide, which fills in 0 for missing values, then converting back to long and pulling out the zero's.

library(reshape2)
df <- dcast(test_data,col1 ~ col2 ,fill=0,value.var="col2",fun.aggregate=length)
df2 <- melt(df,id.vars="col1")
results <- df2[which(df2$value==0),c("col1","variable")]

The time comparison suggests this runs a bit quicker.

start_time <- Sys.time()
for (x in c(1:10000)){
  results <- missing_entries(data = test_data, x = "col1", y = "col2")
  setDF(results)
}
end_time <- Sys.time()
timeA <- end_time-start_time
# Time difference of 1.725317 mins

start_time <- Sys.time()
for (x in c(1:10000)){
df <- dcast(test_data,col1 ~ col2 ,fill=0,value.var="col2",fun.aggregate=length)
df2 <- melt(df,id.vars="col1")
results <- df2[which(df2$value==0),c("col1","variable")]
}
end_time <- Sys.time()
timeB <- end_time-start_time
# Time difference of 1.368845 mins


来源: stackexchange

问:
Visual Studio Code for .NET Framework
I am having difficulty figuring out if and how I can use Visual Studio Code to develop and debug command-line/console/libraries of C# .NET programs which can not run on .NET Core, i.e. they require .NET Framework.
I need to access Oracle which do not have a .NET Core provider but it does have a Managed .NET Framework provider.
I use VS 2015/2017 for this task but would like to switch to VS Code if I could code, build and debug .NET Framework target C# programs.
I have tried Google search and could not find anything.

答:
Unfortunately, it doesn't feature intellisense for C/C++, only syntax
  highlighting: code.visualstudio.com/docs/languages EDIT: no debugger
  integration for C/C++ either. The git integration is really nice
  though! Seems more designed for web applications, the debugger works
  for node.js

Whilst this does not specify C#, it stands to reason that the same standards apply (which is that there is no debugger and no compile functionality).

Quote taken from comment on first answer of What exactly is Visual Studio Code?

ContentLicense: CC BY-SA 4.0

Title: Visual Studio Code for .NET Framework

ContentLicense: CC BY-SA 3.0


问:
Update progressbar from worker thread
I'm building a java program that downloads N elements from a server. I'd like to have a working progress bar, that shows "already downloaded elements"/N percentage. Right now, I update progressbar value by passing to the thread a reference to the GUI object, but it makes the code "ugly" ( GUI class creates the thread, that contains a reference to the GUI itself, creating a sort of loop).
Is there a better way to do it?</p>

答: In order to remove the "loop".  Create a interface that the GUI extends that is passed to the working thread.</p>

ContentLicense: CC BY-SA 2.5

Title: Update progressbar from worker thread


问:
this.name is undefined in my Mongoose schema
I'm having a problem. In my kittySchema Mongoose schema. Line 21. I'm trying to get this.name from within the schema object but I'm getting undefined.
I know what the problem is. I'm using an arrow function and It's looking for the this.name property in the arrow function instead of the object that the arrow function is in. Is there a way around this instead of me using a regular vanilla js function?
`

```<code>// Requiring Mongoose
const mongoose = require("mongoose");

const establishConnection = () => {
    // Establishing a connection to Mongoose
    mongoose.connect("mongodb://localhost/kittens");

    // Getting the Mongoose database from the pending connection
    const db = mongoose.connection;

    // Watching for Mongoose errors
    db.on("error", console.error.bind(console, "Connection error:"))
    // A connection was succesfully established
    db.once("open", () => {
        console.log("A connection was established");
        const kittySchema = mongoose.Schema({
            name: String
        });`enter code here`
        mongoose.
        kittySchema.methods.speak = () => {
            console.log(this.name ? `Meow, My name is ${this.name}.` : "I don't have a name.");
        }
        const Kitten = mongoose.model("Kitten", kittySchema);
        const silence = new Kitten({ name: "Silence" });
        console.log(`A new kitty named ${silence.name} was successfully added to your database!`);
        silence.speak();
    })
}

module.exports = {
    establishConnection
}
</code>```

`

答:
I'm using an arrow function and It's looking for the this.name
  property in the arrow function instead of the object that the arrow
  function is in

This assumption is slightly wrong. The arrow function looks for the value in the lexical scope. In this case, it happens to be global object.

On the other hand, if you used a 'regular' function, the 'this' would be bound to the new object that is created when you instantiate the new Kitten.

To fix your issue, simply use a regular function in place of the arrow function.

```<code>kittySchema.methods.speak = function() {
    console.log(this.name ? `Meow, My name is ${this.name}.` : "I don't have a name.");
}
</code>```

There is no need to wrap the arrow function.

You can read more about when not to use arrow functions here.

Body:
I'm having a problem. In my kittySchema Mongoose schema. Line 21. I'm trying to get this.name from within the schema object but I'm getting undefined.
I know what the problem is. I'm using an arrow function and It's looking for the this.name property in the arrow function instead of the object that the arrow function is in. Is there a way around this instead of me using a regular vanilla js function?
`

// Requiring Mongoose
const mongoose = require("mongoose");

const establishConnection = () => {
    // Establishing a connection to Mongoose
    mongoose.connect("mongodb://localhost/kittens");

    // Getting the Mongoose database from the pending connection
    const db = mongoose.connection;

    // Watching for Mongoose errors
    db.on("error", console.error.bind(console, "Connection error:"))
    // A connection was succesfully established
    db.once("open", () => {
        console.log("A connection was established");
        const kittySchema = mongoose.Schema({
            name: String
        });`enter code here`
        mongoose.
        kittySchema.methods.speak = () => {
            console.log(this.name ? `Meow, My name is ${this.name}.` : "I don't have a name.");
        }
        const Kitten = mongoose.model("Kitten", kittySchema);
        const silence = new Kitten({ name: "Silence" });
        console.log(`A new kitty named ${silence.name} was successfully added to your database!`);
        silence.speak();
    })
}

module.exports = {
    establishConnection
}

`

Body:
I'm using an arrow function and It's looking for the this.name
  property in the arrow function instead of the object that the arrow
  function is in

This assumption is slightly wrong. The arrow function looks for the value in the lexical scope. In this case, it happens to be global object.

On the other hand, if you used a 'regular' function, the 'this' would be bound to the new object that is created when you instantiate the new Kitten.

To fix your issue, simply use a regular function in place of the arrow function.

kittySchema.methods.speak = function() {
    console.log(this.name ? `Meow, My name is ${this.name}.` : "I don't have a name.");
}

There is no need to wrap the arrow function.

You can read more about when not to use arrow functions here.


问:
Error RPN in PHP
I'm trying to use RPN in order to do a simple calculator in PHP.
I tried to follow the wiki description and several tutorial in order to do it but i'm currently meeting a an issue with the first Operand. I can't assign it with the end().

My issue come from the line $nb1 = end($stack);

```<code><?php

function add($stack, $nb1, $nb2)
{
    array_push($stack, $nb1 + $nb2);
    $result = $nb1 + $nb2;
    echo $nb1 . ' + ' . $nb2 . ' = ' . $result . "\n";
}

function sub($stack, $nb1, $nb2)
{
    array_push($stack, $nb1 - $nb2);
    $result = $nb1 - $nb2;
    echo $nb1 . ' - ' . $nb2 . ' = ' . $result . "\n";
}

function div($stack, $nb1, $nb2)
{
    array_push($stack, $nb1 / $nb2);
    $result = $nb1 / $nb2;
    echo $nb1 . ' / ' . $nb2 . ' = ' . $result . "\n";
}

function mul($stack, $nb1, $nb2)
{
    array_push($stack, $nb1 * $nb2);
    $result = $nb1 * $nb2;
    echo $nb1 . ' * ' . $nb2 . ' = ' . $result . "\n";
}

function calc($input)
{
$stack = array();
$token = explode(" ", trim($input));
$count = count($token);
// echo $count . "\n";
// print_r($token);

for ($i = 0; $i < $count; $i++) {
    $tokenNUm = "";

    if (is_numeric($token[$i])) {
        array_push($stack, $token[$i]);
        print_r($token);
    } else {
        $nb2 = end($stack);
        array_pop($stack);
        $nb1 = end($stack);
        array_pop($stack);
        echo "nb1 : ". $nb1 . "\n";
        echo "nb2 : ". $nb2 . "\n";

        switch($token[$i]) {
        case '+':
            add($stack, $nb1, $nb2);
        case '-':
            sub($stack, $nb1, $nb2);
        case '/':
            div($stack, $nb1, $nb2);
        case '*':
            mul($stack, $nb1, $nb2);
        default:
            die('Error');
        }
    }
    return end($stack);
    }
}

echo "Final result = " . calc($argv[1]) . "\n";
</code>```

答:
Not diving too deep into the logic I can point out on couple mistakes you made:

Your return end($stack); is inside the for loop. Basically, your loop will only run the first iteration and then exits the function.

You have to put break; in every case block, otherwise it will execute every single function in the switch block and die with error:

```<code>switch($token[$i]) {
    case '+':
        add($stack, $nb1, $nb2);
        break;
    case '-':
        sub($stack, $nb1, $nb2);
        break;
    case '/':
        div($stack, $nb1, $nb2);
        break;
    case '*':
        mul($stack, $nb1, $nb2);
        break;
    default:
        die('Error');
}
</code>```

Hope these would help.

Update:

Forgot to mention that you have to run you script like that php rpn.php "1 + 2" because you are using $argv[1]. Assuming rpn.php is the name of your file. Here is the DEMO. Try running it with and without my suggestions, you will see the difference. It doesn't fix your algorithm but it fixes the error you were talking about.

Title: Error RPN in PHP

Body:
I'm trying to use RPN in order to do a simple calculator in PHP.
I tried to follow the wiki description and several tutorial in order to do it but i'm currently meeting a an issue with the first Operand. I can't assign it with the end().

My issue come from the line $nb1 = end($stack);

<?php

function add($stack, $nb1, $nb2)
{
    array_push($stack, $nb1 + $nb2);
    $result = $nb1 + $nb2;
    echo $nb1 . ' + ' . $nb2 . ' = ' . $result . "\n";
}

function sub($stack, $nb1, $nb2)
{
    array_push($stack, $nb1 - $nb2);
    $result = $nb1 - $nb2;
    echo $nb1 . ' - ' . $nb2 . ' = ' . $result . "\n";
}

function div($stack, $nb1, $nb2)
{
    array_push($stack, $nb1 / $nb2);
    $result = $nb1 / $nb2;
    echo $nb1 . ' / ' . $nb2 . ' = ' . $result . "\n";
}

function mul($stack, $nb1, $nb2)
{
    array_push($stack, $nb1 * $nb2);
    $result = $nb1 * $nb2;
    echo $nb1 . ' * ' . $nb2 . ' = ' . $result . "\n";
}

function calc($input)
{
$stack = array();
$token = explode(" ", trim($input));
$count = count($token);
// echo $count . "\n";
// print_r($token);

for ($i = 0; $i < $count; $i++) {
    $tokenNUm = "";

    if (is_numeric($token[$i])) {
        array_push($stack, $token[$i]);
        print_r($token);
    } else {
        $nb2 = end($stack);
        array_pop($stack);
        $nb1 = end($stack);
        array_pop($stack);
        echo "nb1 : ". $nb1 . "\n";
        echo "nb2 : ". $nb2 . "\n";

        switch($token[$i]) {
        case '+':
            add($stack, $nb1, $nb2);
        case '-':
            sub($stack, $nb1, $nb2);
        case '/':
            div($stack, $nb1, $nb2);
        case '*':
            mul($stack, $nb1, $nb2);
        default:
            die('Error');
        }
    }
    return end($stack);
    }
}

echo "Final result = " . calc($argv[1]) . "\n";

Body:
Not diving too deep into the logic I can point out on couple mistakes you made:

Your return end($stack); is inside the for loop. Basically, your loop will only run the first iteration and then exits the function.

You have to put break; in every case block, otherwise it will execute every single function in the switch block and die with error:

switch($token[$i]) {
    case '+':
        add($stack, $nb1, $nb2);
        break;
    case '-':
        sub($stack, $nb1, $nb2);
        break;
    case '/':
        div($stack, $nb1, $nb2);
        break;
    case '*':
        mul($stack, $nb1, $nb2);
        break;
    default:
        die('Error');
}

Hope these would help.

Update:

Forgot to mention that you have to run you script like that php rpn.php "1 + 2" because you are using $argv[1]. Assuming rpn.php is the name of your file. Here is the DEMO. Try running it with and without my suggestions, you will see the difference. It doesn't fix your algorithm but it fixes the error you were talking about.


问:
Why do I get Use of undeclared identifier 'downloadDataFromURL' when method is defined in same class?
I have written a method that I want to reuse from another method in the same class but I am getting this error message and I don't understand why, how can it be undeclared when it is declared in the same class?

the h file looks like this

```<code>#import <Foundation/Foundation.h>
#import "AppDelegate.h"
#import "NWTillHelper.h"

@interface JoshuaWebServices : NSObject

+ (void)downloadDataFromURL:(NSURL *)url withCompletionHandler:(void (^)(NSData *))completionHandler;

- (void)downloadCollections;

@end
</code>```

And the m file as follows

```<code>#import "JoshuaWebServices.h"

@implementation JoshuaWebServices

@synthesize xmlParser;

+ (void)downloadDataFromURL:(NSURL *)url withCompletionHandler:(void (^)(NSData *))completionHandler {
    if([NWTillHelper isDebug] == 1) {
        NSLog(@"%s entered", __PRETTY_FUNCTION__);
    }
// Lots of irrelevant code here
}

- (void)downloadCollections {
    // Prepare the URL that we'll get the neighbour countries from.
    NSString *URLString = [NSString stringWithFormat:@"https://url.is.not.here"];

    NSURL *url = [NSURL URLWithString:URLString];

    // Download the data.
    [downloadDataFromURL:url withCompletionHandler:^(NSData *data) {
        // Make sure that there is data.
        if (data != nil) {
            self.xmlParser = [[NSXMLParser alloc] initWithData:data];
            self.xmlParser.delegate = self;

            // Initialize the mutable string that we'll use during parsing.
            self.foundValue = [[NSMutableString alloc] init];

            // Start parsing.
            [self.xmlParser parse];
        }
    }];
}
</code>```

Why can I not use the method declared in same class?

答:
Your method needs a receiver. Unlike functions that can just be called on there own. Methods must be called by something, either the class, or an instance of a class. In your case you should use a class because it's a class method.

Change

```<code>[downloadDataFromURL:url withCompletionHandler:^(NSData *data) {
    // Make sure that there is data.
    if (data != nil) {
        self.xmlParser = [[NSXMLParser alloc] initWithData:data];
        self.xmlParser.delegate = self;

        // Initialize the mutable string that we'll use during parsing.
        self.foundValue = [[NSMutableString alloc] init];

        // Start parsing.
        [self.xmlParser parse];
    }
}];
</code>```

to be

```<code>[JoshuaWebServices  downloadDataFromURL:url withCompletionHandler:^(NSData *data) {
    // Make sure that there is data.
    if (data != nil) {
        self.xmlParser = [[NSXMLParser alloc] initWithData:data];
        self.xmlParser.delegate = self;

        // Initialize the mutable string that we'll use during parsing.
        self.foundValue = [[NSMutableString alloc] init];

        // Start parsing.
        [self.xmlParser parse];
    }
}];
</code>```

Body:
I have written a method that I want to reuse from another method in the same class but I am getting this error message and I don't understand why, how can it be undeclared when it is declared in the same class?

the h file looks like this

#import <Foundation/Foundation.h>
#import "AppDelegate.h"
#import "NWTillHelper.h"

@interface JoshuaWebServices : NSObject

+ (void)downloadDataFromURL:(NSURL *)url withCompletionHandler:(void (^)(NSData *))completionHandler;

- (void)downloadCollections;

@end

And the m file as follows

#import "JoshuaWebServices.h"

@implementation JoshuaWebServices

@synthesize xmlParser;

+ (void)downloadDataFromURL:(NSURL *)url withCompletionHandler:(void (^)(NSData *))completionHandler {
    if([NWTillHelper isDebug] == 1) {
        NSLog(@"%s entered", __PRETTY_FUNCTION__);
    }
// Lots of irrelevant code here
}

- (void)downloadCollections {
    // Prepare the URL that we'll get the neighbour countries from.
    NSString *URLString = [NSString stringWithFormat:@"https://url.is.not.here"];

    NSURL *url = [NSURL URLWithString:URLString];

    // Download the data.
    [downloadDataFromURL:url withCompletionHandler:^(NSData *data) {
        // Make sure that there is data.
        if (data != nil) {
            self.xmlParser = [[NSXMLParser alloc] initWithData:data];
            self.xmlParser.delegate = self;

            // Initialize the mutable string that we'll use during parsing.
            self.foundValue = [[NSMutableString alloc] init];

            // Start parsing.
            [self.xmlParser parse];
        }
    }];
}

Why can I not use the method declared in same class?

Body:
Your method needs a receiver. Unlike functions that can just be called on there own. Methods must be called by something, either the class, or an instance of a class. In your case you should use a class because it's a class method.

Change

[downloadDataFromURL:url withCompletionHandler:^(NSData *data) {
    // Make sure that there is data.
    if (data != nil) {
        self.xmlParser = [[NSXMLParser alloc] initWithData:data];
        self.xmlParser.delegate = self;

        // Initialize the mutable string that we'll use during parsing.
        self.foundValue = [[NSMutableString alloc] init];

        // Start parsing.
        [self.xmlParser parse];
    }
}];

to be

[JoshuaWebServices  downloadDataFromURL:url withCompletionHandler:^(NSData *data) {
    // Make sure that there is data.
    if (data != nil) {
        self.xmlParser = [[NSXMLParser alloc] initWithData:data];
        self.xmlParser.delegate = self;

        // Initialize the mutable string that we'll use during parsing.
        self.foundValue = [[NSMutableString alloc] init];

        // Start parsing.
        [self.xmlParser parse];
    }
}];


问:
Tinymce - want contents unmodifiable but formattable
There is plugin called uneditable content in tinymce, but we can still delete/remove the content and it is not formattable even. Is there any plugin through which I can achieve following:

Contents are uneditable, for instance if the content is

```<code>     uneditablecontent
</code>```

the value of content should persist througout(nobody can add/update/delete the content).
But I should be able to add various formatting effects like bold, alignments, change font size etc.

Any other opensource plugins with such features are also welcomed.
I want to use such feature to format contents of td within table.

答: You'll need to write/find your own implementation of this. There is no core function of TinyMCE that can accomplish what you're asking - the noneditable plugin is probably the closest thing you'll be able to find for this.

Body:
There is plugin called uneditable content in tinymce, but we can still delete/remove the content and it is not formattable even. Is there any plugin through which I can achieve following:

Contents are uneditable, for instance if the content is

     uneditablecontent

the value of content should persist througout(nobody can add/update/delete the content).
But I should be able to add various formatting effects like bold, alignments, change font size etc.

Any other opensource plugins with such features are also welcomed.
I want to use such feature to format contents of td within table.


问:
Android Studio Emulator and "Process finished with exit code -1073741511 (0xC0000139)"
I'm trying to emulate my application using Android Studio Emulator (i'm developing by Android Studio) but I receive this error message:

Emulator: Process finished with exit code -1073741511 (0xC0000139)

Do what can I do?

Problem image:

答: Android Studio Emulator: Process finished with exit code 1. Maybe disk drive is FULL. You can delete some virtual devices unused. It works for me.


问:
Add a class to the HTML  tag with React?
I'm making a modal in my React project that requires a class to be added to the body when the modal is open and removed when it is closed.

I could do this the old jQuery way by running some vanilla JavaScript which adds / removes a class, however this doesn't feel like the normal React philosophy.

Should I instead setState on my top level component to say whether the modal is open or closed? Even if I did this, as it's rendered into the div on the page it's still a side-effect to edit the body element, so is there any benefit for this extra wiring?

答: ReactJS has an official React Modal component, I would just use that: https://github.com/reactjs/react-modal</p>

Title: Add a class to the HTML <body> tag with React?


问:
What is the best way to avoid keyError when using python dictionary?
```<code>    for target, source ,in zip(self.tCorpus, self.fCorpus):
        #print(target, source)
        self.pairLength[len(target), len(source)] += 1
</code>```

It's obvious that this will give me a key error since I did not initialize the key len(target), len(source) before using this. I know I could use default dict to avoid this kind of error, but I am not sure how to avoid it in this particular case. Is there a way to prevent keyerror and increment values for len(target), len(source) ?

答:
Using the get () with default value param:
self.pairLength.get((len(target), len(source)),0)+=1

Body:
    for target, source ,in zip(self.tCorpus, self.fCorpus):
        #print(target, source)
        self.pairLength[len(target), len(source)] += 1

It's obvious that this will give me a key error since I did not initialize the key len(target), len(source) before using this. I know I could use default dict to avoid this kind of error, but I am not sure how to avoid it in this particular case. Is there a way to prevent keyerror and increment values for len(target), len(source) ?


问:
store a queryset in the session with django
I have problem storing a big queryset in the session. This queryset is from a search and I need to store it for paginate inside every result. This is the code in my view:

```<code>c = queryset.order_by('-order')
request.session['query_search'] = c
</code>```

You can see an example in my site: http://www.lukmi.com/escorts/barcelona/
This is a list of results(the queryset) and I store it in the session because I need to use it in each profile to go to next profile.

I have some problems to store it because is very big. Anybody knows a good solution?

答:
Big sessions eat ressources (I suppose Django makes no exception to this).

Make it a JSON list, then use the user's browser local storage : http://jstorage.info , a jQuery plugin, cross-browser.

You'll need a way to tell if the data is outdated (checksum? did not find the solution yet) to get back to the server and ask for a new JSON var in the template.

Body:
I have problem storing a big queryset in the session. This queryset is from a search and I need to store it for paginate inside every result. This is the code in my view:

c = queryset.order_by('-order')
request.session['query_search'] = c

You can see an example in my site: http://www.lukmi.com/escorts/barcelona/
This is a list of results(the queryset) and I store it in the session because I need to use it in each profile to go to next profile.

I have some problems to store it because is very big. Anybody knows a good solution?


问:
C# ef second operation started before previous asynchronous operation completed
Just trying to do normal query on ef but getting below error message

"A second operation started on this context before a previous asynchronous operation completed"

I am using await for all aync call but not sure what could be causing this issue.

here' code

```<code>    var sids = await context.Sites.Where(s => slist.Contains(s.JVSiteID)).ToListAsync();

    var header = await context.GenericCsvHeaders.FirstOrDefaultAsync(x => x.Header == csvh) ?? new GenericCsvHeader { Header = csvh };

    context.Entry<GenericCsvHeader>(header).State = (header.GenericCsvHeaderID == 0) ? EntityState.Added : EntityState.Unchanged;

    var sa = await context.SAs.Where(x => x.StatusID == Data.Enum.Status.Active && mapkeys.Contains(x.SAName)).Select(x => new { x.SAName, x.SACode, x.SAID }).ToListAsync();

    if (sa.Count > 0)
        sasitelist = await context.Site_SA.Where(x => x.StatusID == Data.Enum.Status.Active && siteids.Contains(x.SiteID ?? 0)).ToListAsync();

    var az = await context.Azimuths.Where(x => x.StatusID == Data.Enum.Status.Active && mapkeys.Contains(x.AzimuthName)).Select(x => new { x.AzimuthName, x.AzimuthID }).ToListAsync();

    if (az.Count > 0)
           azsitelist = await context.Site_Azimuth.Where(x => x.StatusID == Data.Enum.Status.Active && siteids.Contains(x.SiteID ?? 0)).ToListAsync();

    var rows = new List<dynamic>(); //getting this list from csv file via csvHelper

     foreach (var r in rows)
       {
           var s = sids.FirstOrDefault(x => x.JVSiteID == (((IDictionary<String, Object>)r)[siteid]).ToString()) ?? new Site();
            UpdateSite(s, r, map);
       }

    private async void UpdateSite(Site site, dynamic csvSite, IDictionary<string, string> map)
    {

       context.Entry(site).State = (site.StateID == 0) ? EntityState.Added : EntityState.Modified;
       site.SiteForAuditTrail = site;
       if (map.ContainsKey("SiteName") && !String.IsNullOrWhiteSpace(GetStringOfDynamic(map,csvSite,"SiteName")))
             site.SiteName = GetStringOfDynamic(map,csvSite, "SiteName");

       if (map.ContainsKey("State") && !String.IsNullOrWhiteSpace(GetStringOfDynamic(map,csvSite, "State")))
         {
            //getting exception at below line
             var state = (await GetRefTypeList<State>(x => x.StateCode == GetStringOfDynamic(map,csvSite, "State"))) ?? new State { StateCode = GetStringOfDynamic(map,csvSite, "State") };

          context.Entry(state).State = (state.StateID == 0) ? EntityState.Added : EntityState.Unchanged;
           site.State = state;
          state.SiteForAuditTrail = site;
     }

  }

private async Task<T> GetRefTypeList<T>(Func<T, bool> expression) where T : EntityBase
 {
       if (!refTypes.ContainsKey(typeof(T).Name))
              refTypes[typeof(T).Name] = (await context.Set<T>().Where(x => x.StatusID == Data.Enum.Status.Active).ToListAsync());

       return (refTypes[typeof(T).Name] as List<T>)?.FirstOrDefault(expression);
 }

private string GetStringOfDynamic(IDictionary<string, string> map,dynamic obj, string propertyName)
 {
    if (((IDictionary<String, Object>)obj).ContainsKey(map[propertyName]))
          return (((IDictionary<String, Object>)obj)[map[propertyName]]??"").ToString();

         return "";
 }
</code>```

答:
You are having a race condition here. While you are using await you have other code executing potentially before the variable sids, header, sa and az, have been returned.

You should refactor your code so that the remaining code is not executed until these variables are returned. You can do this by using a task and then using the extension WhenAll which will ensure each await has been completed before proceeding. Here is a link to MS docs on Task and WhenAll implementation

Body:
Just trying to do normal query on ef but getting below error message

"A second operation started on this context before a previous asynchronous operation completed"

I am using await for all aync call but not sure what could be causing this issue.

here' code

    var sids = await context.Sites.Where(s => slist.Contains(s.JVSiteID)).ToListAsync();

    var header = await context.GenericCsvHeaders.FirstOrDefaultAsync(x => x.Header == csvh) ?? new GenericCsvHeader { Header = csvh };

    context.Entry<GenericCsvHeader>(header).State = (header.GenericCsvHeaderID == 0) ? EntityState.Added : EntityState.Unchanged;

    var sa = await context.SAs.Where(x => x.StatusID == Data.Enum.Status.Active && mapkeys.Contains(x.SAName)).Select(x => new { x.SAName, x.SACode, x.SAID }).ToListAsync();

    if (sa.Count > 0)
        sasitelist = await context.Site_SA.Where(x => x.StatusID == Data.Enum.Status.Active && siteids.Contains(x.SiteID ?? 0)).ToListAsync();

    var az = await context.Azimuths.Where(x => x.StatusID == Data.Enum.Status.Active && mapkeys.Contains(x.AzimuthName)).Select(x => new { x.AzimuthName, x.AzimuthID }).ToListAsync();

    if (az.Count > 0)
           azsitelist = await context.Site_Azimuth.Where(x => x.StatusID == Data.Enum.Status.Active && siteids.Contains(x.SiteID ?? 0)).ToListAsync();

    var rows = new List<dynamic>(); //getting this list from csv file via csvHelper

     foreach (var r in rows)
       {
           var s = sids.FirstOrDefault(x => x.JVSiteID == (((IDictionary<String, Object>)r)[siteid]).ToString()) ?? new Site();
            UpdateSite(s, r, map);
       }

    private async void UpdateSite(Site site, dynamic csvSite, IDictionary<string, string> map)
    {

       context.Entry(site).State = (site.StateID == 0) ? EntityState.Added : EntityState.Modified;
       site.SiteForAuditTrail = site;
       if (map.ContainsKey("SiteName") && !String.IsNullOrWhiteSpace(GetStringOfDynamic(map,csvSite,"SiteName")))
             site.SiteName = GetStringOfDynamic(map,csvSite, "SiteName");

       if (map.ContainsKey("State") && !String.IsNullOrWhiteSpace(GetStringOfDynamic(map,csvSite, "State")))
         {
            //getting exception at below line
             var state = (await GetRefTypeList<State>(x => x.StateCode == GetStringOfDynamic(map,csvSite, "State"))) ?? new State { StateCode = GetStringOfDynamic(map,csvSite, "State") };

          context.Entry(state).State = (state.StateID == 0) ? EntityState.Added : EntityState.Unchanged;
           site.State = state;
          state.SiteForAuditTrail = site;
     }

  }

private async Task<T> GetRefTypeList<T>(Func<T, bool> expression) where T : EntityBase
 {
       if (!refTypes.ContainsKey(typeof(T).Name))
              refTypes[typeof(T).Name] = (await context.Set<T>().Where(x => x.StatusID == Data.Enum.Status.Active).ToListAsync());

       return (refTypes[typeof(T).Name] as List<T>)?.FirstOrDefault(expression);
 }

private string GetStringOfDynamic(IDictionary<string, string> map,dynamic obj, string propertyName)
 {
    if (((IDictionary<String, Object>)obj).ContainsKey(map[propertyName]))
          return (((IDictionary<String, Object>)obj)[map[propertyName]]??"").ToString();

         return "";
 }


问:
How to combine two RDD[String]s index-wise?
I'm working with Spark RDDs and created two idential length arrays, one is the hour of tweet, and the other is the text of a tweet.  I'm looking to combine these into one data structure (perhaps a tuple?) that I can filter by the hour and text of tweets, but I'm struggling after combining on how to perform this.

```<code>scala> val split_time = split_date.map(line => line.split(":")).map(word =>
(word(0)))
split_time: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[28] at map
at <console>:31

scala> split_time.take(10)
res8: Array[String] = Array(17, 17, 17, 17, 17, 17, 17, 17, 17, 17)

scala> val split_text = text.map(line => line.split(":")).map(word =>
(word(1).toLowerCase))
split_text: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[19] at map at <console>:29

scala> split_text.take(10)
res0: Array[String] = Array("add @joemontana to this pic and you've got
something #nfl https, "are you looking for photo editor, "#colts frank gore
needs 27 rushing yards to pass jerome bettis and 49 yards to pass ladainian
tomlinson to move int… https, "rt @nflstreamfree,.....

# combine into tuple
val tweet_tuple = (split_time, split_text)
</code>```

For example, I want to get all tweets for hour 17 with the word "colts" mentioned:

```<code>tweet_tuple.filter(tup => tup._1 == 17 && tup._2.toString.matches("colts"))

<console>:40: error: value filter is not a member of (org.apache.spark.rdd.RDD[String], org.apache.spark.rdd.RDD[String])
          tweet_tuple.map(line => line._1 == 17 && line._2.toString.matches("colts"))
</code>```

答:
You should go with .zip to combine both rdds into RDD[(String, String)]

for example I created two rdds

```<code>val split_time = sparkContext.parallelize(Array("17", "17", "17", "17", "17", "17", "17", "17", "17", "17"))
val split_text = sparkContext.parallelize(Array("17", "17", "17", "17", "colts", "17", "17", "colts", "17", "17"))
</code>```

zip combines both rdds as I have mentioned above into RDD[Tuple2[String, String]]

```<code>val tweet_tuple = split_time.zip(split_text)
</code>```

After combining all you need is to apply .filter

```<code>tweet_tuple.filter(line => line._1 == "17" && line._2.toString.matches("colts"))
</code>```

The output should be

```<code>(17,colts)
(17,colts)
</code>```

Updated

Since your split_text rdd are collection of sentences, contains should be used instead of matches. So the following logic should work after you've zipped.

```<code>tweet_tuple.filter(line => line._1 == "17" && line._2.toString.contains("colts"))
</code>```

Body:
I'm working with Spark RDDs and created two idential length arrays, one is the hour of tweet, and the other is the text of a tweet.  I'm looking to combine these into one data structure (perhaps a tuple?) that I can filter by the hour and text of tweets, but I'm struggling after combining on how to perform this.

scala> val split_time = split_date.map(line => line.split(":")).map(word =>
(word(0)))
split_time: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[28] at map
at <console>:31

scala> split_time.take(10)
res8: Array[String] = Array(17, 17, 17, 17, 17, 17, 17, 17, 17, 17)

scala> val split_text = text.map(line => line.split(":")).map(word =>
(word(1).toLowerCase))
split_text: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[19] at map at <console>:29

scala> split_text.take(10)
res0: Array[String] = Array("add @joemontana to this pic and you've got
something #nfl https, "are you looking for photo editor, "#colts frank gore
needs 27 rushing yards to pass jerome bettis and 49 yards to pass ladainian
tomlinson to move int… https, "rt @nflstreamfree,.....

# combine into tuple
val tweet_tuple = (split_time, split_text)

For example, I want to get all tweets for hour 17 with the word "colts" mentioned:

tweet_tuple.filter(tup => tup._1 == 17 && tup._2.toString.matches("colts"))

<console>:40: error: value filter is not a member of (org.apache.spark.rdd.RDD[String], org.apache.spark.rdd.RDD[String])
          tweet_tuple.map(line => line._1 == 17 && line._2.toString.matches("colts"))

Body:
You should go with .zip to combine both rdds into RDD[(String, String)]

for example I created two rdds

val split_time = sparkContext.parallelize(Array("17", "17", "17", "17", "17", "17", "17", "17", "17", "17"))
val split_text = sparkContext.parallelize(Array("17", "17", "17", "17", "colts", "17", "17", "colts", "17", "17"))

zip combines both rdds as I have mentioned above into RDD[Tuple2[String, String]]

val tweet_tuple = split_time.zip(split_text)

After combining all you need is to apply .filter

tweet_tuple.filter(line => line._1 == "17" && line._2.toString.matches("colts"))

The output should be

(17,colts)
(17,colts)

Updated

Since your split_text rdd are collection of sentences, contains should be used instead of matches. So the following logic should work after you've zipped.

tweet_tuple.filter(line => line._1 == "17" && line._2.toString.contains("colts"))


问:
Cosmos Db stored procedure appears to return partial aggregates
I wrote a stored procedure using aggregate functions.

```<code>SELECT

MIN(c.Reading) AS MinReading
, MAX(c.Reading) AS MaxReading
, COUNT(1) AS RecordCount

FROM

Readings c

WHERE

ReadingId = 1234
AND ReadingDate >= fromDate
AND ReadingDate <= toDate
</code>```

Note: The ReadingId in this example is the partition key.

The same parameter values are returning differenct results. It appears to be returning partial aggregates similar to warnings related to running aggregates in the web portal.

Is this a limitation of stored procedures, or is there an option I can set that will prevent partial aggregates?

答:
You can check if the queryDocuments call returns a continuation token, and discard the results if it is not null (or) post-process the min of mins/max of maxes/sum of counts over the partial results to compute the global aggregates.

Cosmos DB always returns partial aggregates for each page of results. The client SDKs internally paginate and compute the complete aggregate over these partial results. Since the query within stored procedures is a low-level API, you may get intermediate partial aggregates. But if you continue to paginate the query results, the final result will be complete/correct.

Body:
I wrote a stored procedure using aggregate functions.

SELECT

MIN(c.Reading) AS MinReading
, MAX(c.Reading) AS MaxReading
, COUNT(1) AS RecordCount

FROM

Readings c

WHERE

ReadingId = 1234
AND ReadingDate >= fromDate
AND ReadingDate <= toDate

Note: The ReadingId in this example is the partition key.

The same parameter values are returning differenct results. It appears to be returning partial aggregates similar to warnings related to running aggregates in the web portal.

Is this a limitation of stored procedures, or is there an option I can set that will prevent partial aggregates?


问:
Websphere Application Server 9.0.0.1 - EntityManager is null every other request
I'm trying to run a project on WAS 9.0.0.1, that currently works fine on WAS 8.5.5.x.  The problem seems to be that entitymanager is not being injected into the DAO, but this only happens every other request.  So when doing the em.createNamedQuery in the DAO it is throwing a NullPointerException because the em is null, like I explained above the strange thing is that it is only failing like this every other request.  Any ideas?

Persistence.xml:

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="OperationsAPI" transaction-type="JTA">
        <jta-data-source>jdbc/operations</jta-data-source>
        <class>com.i3.operations.entities.Operation</class>
        <properties>
            <property name="openjpa.Log" value="DefaultLevel=WARN, Runtime=INFO, Tool=INFO, SQL=TRACE"/>
        </properties>
    </persistence-unit>
</persistence>
</code>```

Resource class:

```<code>@Path("/operations")
@Api("Operations API")
@Stateless
public class OperationsService {

    public static Logger logger = Logger.getLogger(OperationsService.class.getName());

    @Context
    UriInfo uriInfo;

    @EJB
    private static OperationDAO operationDAO;

    public OperationsService() {
    operationDAO = new OperationDAO();
    }

    @GET
    @ApiOperation(value = "Gets all operations", response = Operation.class, responseContainer = "List")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getOperationsAll() {

    List<Operation> operations = operationDAO.getOperationsAll();

    return Response.ok().entity(operations).build();
    }
}
</code>```

DAO:

```<code>@Stateless
public class OperationDAO {

    public static Logger logger = Logger.getLogger(OperationDAO.class.getName());

    @PersistenceContext(unitName="OperationsAPI")
    private EntityManager em;

    public List<Operation> getOperationsAll() {

        logger.info("EntityManager: " + em);
        TypedQuery<Operation> query = em.createNamedQuery("Operation.findAll", Operation.class);
        return query.getResultList();

    }
}
</code>```

答:
You typically don't want to mix use of both the new operator and also dependency injection (CDI, etc.) to set the same object references in a given class.

If your dependency graph is mostly using dependency injection then dependency injection (DI) should be instantiating all the objects.  Otherwise you end up with the case that you create an object instance that DI doesn't know about, so it doesn't know to inject its dependencies into.

This is probably what's happening in your case.   Since these EJB instances are pooled, you may end up with some of your instances having been initialized correctly, and some not.

You probably want to change to just (or remove and default):

```<code> public OperationsService() {}
</code>```

I'll mention I'm not sure injecting into a static field  is a good idea, but I'm not really enough of an expert to suggest removing the static modifier from operationDAO.

Body:
I'm trying to run a project on WAS 9.0.0.1, that currently works fine on WAS 8.5.5.x.  The problem seems to be that entitymanager is not being injected into the DAO, but this only happens every other request.  So when doing the em.createNamedQuery in the DAO it is throwing a NullPointerException because the em is null, like I explained above the strange thing is that it is only failing like this every other request.  Any ideas?

Persistence.xml:

    <?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="OperationsAPI" transaction-type="JTA">
        <jta-data-source>jdbc/operations</jta-data-source>
        <class>com.i3.operations.entities.Operation</class>
        <properties>
            <property name="openjpa.Log" value="DefaultLevel=WARN, Runtime=INFO, Tool=INFO, SQL=TRACE"/>
        </properties>
    </persistence-unit>
</persistence>

Resource class:

@Path("/operations")
@Api("Operations API")
@Stateless
public class OperationsService {

    public static Logger logger = Logger.getLogger(OperationsService.class.getName());

    @Context
    UriInfo uriInfo;

    @EJB
    private static OperationDAO operationDAO;

    public OperationsService() {
    operationDAO = new OperationDAO();
    }

    @GET
    @ApiOperation(value = "Gets all operations", response = Operation.class, responseContainer = "List")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getOperationsAll() {

    List<Operation> operations = operationDAO.getOperationsAll();

    return Response.ok().entity(operations).build();
    }
}

DAO:

@Stateless
public class OperationDAO {

    public static Logger logger = Logger.getLogger(OperationDAO.class.getName());

    @PersistenceContext(unitName="OperationsAPI")
    private EntityManager em;

    public List<Operation> getOperationsAll() {

        logger.info("EntityManager: " + em);
        TypedQuery<Operation> query = em.createNamedQuery("Operation.findAll", Operation.class);
        return query.getResultList();

    }
}

Body:
You typically don't want to mix use of both the new operator and also dependency injection (CDI, etc.) to set the same object references in a given class.

If your dependency graph is mostly using dependency injection then dependency injection (DI) should be instantiating all the objects.  Otherwise you end up with the case that you create an object instance that DI doesn't know about, so it doesn't know to inject its dependencies into.

This is probably what's happening in your case.   Since these EJB instances are pooled, you may end up with some of your instances having been initialized correctly, and some not.

You probably want to change to just (or remove and default):

 public OperationsService() {}

I'll mention I'm not sure injecting into a static field  is a good idea, but I'm not really enough of an expert to suggest removing the static modifier from operationDAO.


问:
GraphQL - Passing an enum value directly to a mutation as an argument?
Given the following GraphQL type definition:

```<code>const typeDefs = `
  enum Action {
    update
    delete
  }

  type Mutation {
    doSomething(action: Action)
  }
`;
</code>```

This query works:

```<code>const query = `
  mutation($action: Action) {
    doSomething(action: $action)
  }
`
const variables = { action: "update" }
</code>```

But this one does not:

```<code>const query = `
  mutation {
    doSomething(action: "update")
  }
`
</code>```

Does GraphQL not support passing an enum value directly as an argument?

答:
GraphQL does support passing the enum directly as an argument; however, you'll need to omit the quotation marks around the value to get it to work:

const query = `
  mutation {
    doSomething(action: update)
  }
`
```

According to the spec:

Enum values are represented as unquoted names (ex. MOBILE_WEB).

So unlike a string value, an enum value should not be put inside quotation marks. The only reason we do so when using them for variables is to follow proper JSON formatting.

Body:
Given the following GraphQL type definition:

const typeDefs = `
  enum Action {
    update
    delete
  }

  type Mutation {
    doSomething(action: Action)
  }
`;

This query works:

const query = `
  mutation($action: Action) {
    doSomething(action: $action)
  }
`
const variables = { action: "update" }

But this one does not:

const query = `
  mutation {
    doSomething(action: "update")
  }
`

Does GraphQL not support passing an enum value directly as an argument?

Body:
GraphQL does support passing the enum directly as an argument; however, you'll need to omit the quotation marks around the value to get it to work:

const query = `
  mutation {
    doSomething(action: update)
  }
`

According to the spec:

Enum values are represented as unquoted names (ex. MOBILE_WEB).

So unlike a string value, an enum value should not be put inside quotation marks. The only reason we do so when using them for variables is to follow proper JSON formatting.


问:
GUI edge to node recursive path not finding first index of path
I wrote a program that allows a user to add nodes and connect them with edges with a GUI interface.  The first node is always labeled "0".  When I call the findPath method however it shows the entire path appropriately just lacking the 0.  For example if I want to find the path from 0-4, and they're all connected numerically it will show [1,2,3,4].  To get a proper reading of the path after connecting the nodes you need to hit the print adjacency button.  Everything else is running as expected but I can't seem to figure out why this won't add the first node.

Thanks Guys!

```<code>    import javax.swing.JFrame;//imports JFrame package

    public class Graph//class header
    {
       public static void main (String[] args)//main method
       {
          JFrame frame = new JFrame ("Directed Graph");//sets variable frame to a JFrame object and titles it
          frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);//exits application when it is closed
          frame.getContentPane().add (new GraphPanel());//adding GraphPanel() to the frame
          frame.setLocationRelativeTo(null);//sets location to the center
          frame.pack();//packs the frame, fits everything inside
          frame.setVisible(true);//makes frame visible
       }
    }

import java.util.ArrayList;//all of these are the required to get classes from other packages
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;

public class GraphPanel extends JPanel
{
    private final int SIZE = 10;  // radius of each node
    private double alpha; // double variable to define later
    private JButton print, create, delete, path1; //allpath;//button variables
    private JTextField label, label1;
    boolean mode = true;//sets boolean for entire class to true, until later when I define it as false for certain methods to be complete

    String x1, y1;
    String str1 = new String("Mode Chosen Is : create" );//when you choose create it will print this instead
    String str2 = new String("Mode Chosen Is : delete" );//when you choose delete it will print this

    int x, y;
    int mode1 = 1; // int mode1 variable, will comment why i need this when it is later defined/changed

    private Point point1 = null, point2 = null, point3 = null;//makes pointers null, i added a third pointer to put the distance from the first drawn string at the top right, but no longer needed it
    //keeping it incase I wanted to add it again

    private ArrayList<Point> nodeList;   // Graph nodes
    private ArrayList<Edge> edgeList;    // Graph edges

    static private int[][] a = new int[100][100];  // Graph adjacency matrix
    static ArrayList<Integer> path = new ArrayList<Integer>();

    public GraphPanel()
    {

        nodeList = new ArrayList<Point>();//declares ArrayList<Point>
        edgeList = new ArrayList<Edge>();//declares ArrayList<Edge>

        GraphListener listener = new GraphListener();//assigns 'listener' to a Graphlistener object
        addMouseListener (listener);//accepts and reads mouseListener methods to the GraphListener object
        addMouseMotionListener (listener);//accepts and reads MouseMotionListener methods to the GraphListener object

        label = new JTextField (1);
        label1 = new JTextField (1);

        //allpath = new JButton ("Find All Paths");
        path1 = new JButton ("Find Path");//path button
        create = new JButton("Create");//declares 'create' as a JButton object with text on it that says 'create'
        delete = new JButton("Delete");//declares 'delete' as a JButton object with text that says 'delete'
        JButton print = new JButton("Print adjacency matrix");//declares 'print' as a JButton object with text that reads 'print adjacency matrix'

        print.addActionListener (new ButtonListener());//adds an action listener to the print button from the buttonlistener object
        create.addActionListener (new ButtonListener1());//adds an actionListener to the create button from the buttonlistener1 object
        delete.addActionListener (new ButtonListener2());//adds an actionliseneer to the delete button from the buttonlistener2 object
        path1.addActionListener (new ButtonListener3());//adds button that will find path of nodes
        //allpath.addActionListener (new ButtonListener4());

        setBackground (Color.black);//sets backround as black
        setPreferredSize (new Dimension(400, 300));//this is preferred size of graphpanel
        add(print);//these next six add()'s add each button to GraphPanel
        add(delete);//
        add(create);//
        //add(allpath);
        add(path1);
        add(label);
        add(label1);
    }

    public static boolean findPath(int x, int y) //boolean method findpath that takes two ints as parameters
    {
        boolean found = false;

        if (a[x][y]==1) //base case
        {
            //System.out.println(x + " -> " + y);//prints node -> node
            found = true;//path is found
            path.add(0,y);
        }
        else
        {
            int z;
            for (z=0; !found& z<a.length; z++)
            {
                if (a[x][z]==1)
                {
                    a[x][z]=2;
                    found = findPath(z,y);

                }
                if (found)
                {
                    //System.out.println(x + " -> " + z);
                    path.add(0,z);
                }

            }
        }

        if (!found){
            System.out.println("Path Does Not Exist");
        }
        return found;
    }

    // public static ArrayList findPath1(int x, int y, ArrayList path)
    // {
    // System.out.println("CALL FIND: " + path);
    // ArrayList path2 = null;
    // if (a[x][y]==1)
    // {
    // ArrayList path3 = (ArrayList)path.clone();
    // path3.add(y);
    // System.out.println("EXIT BASE: " + path3);
    // path2 = path3;
    // }
    // else
    // {
    // int z;
    // for (z=0; z<a.length; z++)
    // if (a[x][z]==1)
    // {
    // ArrayList path3 = (ArrayList)path.clone();
    // path3.add(z);
    // path3 = findPath1(z,y,path3);
    // System.out.println("EXIT RECU: " + path);
    // path2 = path3;
    // }
    // }
    // return path2;
    // }
    //  Draws the graph
    public void paintComponent (Graphics page)
    {
        super.paintComponent(page);//using parent methods

        // Draws the edge that is being dragged
        page.setColor (Color.green);//setting color of what will be drawn to green
        if (mode1 == 1)//if mode1 is set to 1, which is when the create button is selected
        {
            page.drawString(str1, 125, 75);//then this is printed
        }
        if (mode1 == 2)//if mode1 is set to 2, which is when the delete button is selected
        {
            page.drawString(str2, 125, 75);//then this is printed
        }
        if (point1 != null && point2 != null)//if and only if both points are not null
        {
            page.drawLine (point1.x, point1.y, point2.x, point2.y);//then it draws the line from between point1(x, y cords), and point2(x, y cords)
            page.fillOval (point2.x-3, point2.y-3, 6, 6);//fills this oval by the rectangle it is specified from
        }
        // Draws the nodes
        for (int i=0; i<nodeList.size(); i++) //for loop going through the nodeList ArrayList
        {
            page.setColor (Color.green);//color is set to green
            page.fillOval (nodeList.get(i).x-SIZE, nodeList.get(i).y-SIZE, SIZE*2, SIZE*2);//fills oval by subtracting the SIZE from the x, y and setting the height and width as two times the SIZE
            page.setColor (Color.black);//sets next line to black
            page.drawString (String.valueOf(i), nodeList.get(i).x-SIZE/2, nodeList.get(i).y+SIZE/2);//writes inside the node what number index it is from the ArrayList with black text
        }
        // Draws the edges
        for (int i=0; i<edgeList.size(); i++) // for loop going through the edgeList ArrayList
        {
            page.setColor (Color.green);//sets the next line to green
            page.drawLine (edgeList.get(i).a.x, edgeList.get(i).a.y,edgeList.get(i).b.x, edgeList.get(i).b.y);//draws the line from x and y cords of where it starts to end
            //page.fillOval (edgeList.get(i).b.x-3, edgeList.get(i).b.y-3, 6, 6);

            //page.drawString (String.valueOf(point1.x*(point2.y-point3.y)+point2.x*(point3.y-point1.y)+point3.x*(point1.y-point2.y)), 5, 15);

            alpha = Math.atan((double)(edgeList.get(i).b.y-edgeList.get(i).a.y)/(edgeList.get(i).b.x-edgeList.get(i).a.x));//alpha = b.y-a.y cords/b.x-a.x chords as a double variable
            if (edgeList.get(i).a.x > edgeList.get(i).b.x)//if the x chord of a is greater than the x cordinate of b
            {
                alpha = alpha + Math.PI;//then alpha = previously defined alpha multiplied by PI
            }
            if (edgeList.get(i).a.x < edgeList.get(i).b.x && edgeList.get(i).a.y > edgeList.get(i).b.y)//if a.x is less than b.x and a.y is less than b.y
            {
                alpha = alpha + 2*Math.PI;//then alpha becomes the previously defined alpha multiplied by 2 PI
            }
            arrow(page,edgeList.get(i).b.x,edgeList.get(i).b.y,0,1.57-alpha);//arrow method, taking a x(edgeList.get(i).b.x, y(edgeList.get(i).b.y, length = 0 so arrow is at the
            // very end of the drawn line subtracted by a double aplha
        }
    }

    // arrow method to call when making an arrow
    private void arrow(Graphics page, int x, int y, int len, double alpha)//arrow method, taking a x, y, length and double parameter
    {
        page.setColor (Color.green);//sets arrow to green
        int x1 = x+(int)(len*Math.sin(alpha));//x1 is set to x plus length *sin of alpha
        int y1 = y+(int)(len*Math.cos(alpha));//y1 is set to y plus the length * cosin of alpha
        page.drawLine (x, y, x1, y1);//drawa the x and y, and then previously defined x1, and y1
        page.drawLine (x1, y1, x1+(int)(20*Math.sin(alpha+2.5)), y1+(int)(20*Math.cos(alpha+2.5)));//arithmatic to draw one side of the line for the arrow
        page.drawLine (x1, y1, x1+(int)(20*Math.sin(alpha+3.7)), y1+(int)(20*Math.cos(alpha+3.7)));//arithmatic to draw the corresponding line for the arrow to complete the arrow
    }

    //  The listener for mouse events.
    private class GraphListener implements MouseListener, MouseMotionListener//GraphListener which implements MouseListener and MouseMotionListener, meaning it takes methods from both of those classes
    {
        public void mouseClicked (MouseEvent event)//when mouse is clicked and released
        {
            if (mode == true)//if the mode is true
            {
                nodeList.add(event.getPoint());//the current point to the nodeList
                repaint();//whenever you change the look of a componenet you call this method
            }
            if (mode == false)//if boolean mode is false
            {
                for (int i=0; i<nodeList.size(); i++)//for loop to go through the nodeList ArrayList
                {
                    if (distance(nodeList.get(i), event.getPoint()) < SIZE)//if the distance between a specific node and the pointer is less than the radius of the node (SIZE)
                        nodeList.remove(i);//then remove that node
                }
                for (int i=0; i<edgeList.size(); i++)
                {
                    if (distance(edgeList.get(i).a, event.getPoint())+distance(event.getPoint(), edgeList.get(i).b)-distance(edgeList.get(i).a, edgeList.get(i).b) < SIZE)
                    //if the (distance between starting point of that edgelist index and the current point) plus (the distance between the current point and ending point of that edgeList index)
                    //subtracted by the (distance of the starting and ending point of that edgeList index)(AB+BC-AC) is all less than the size
                        edgeList.remove(i);//then remove that index
                }
            }
        }

        public void mousePressed (MouseEvent event)//when the mouse is pressed down
        {
            if (mode == true)//if the mode is true
            {
                point1 = event.getPoint();//you start that point
            }
        }

        public void mouseDragged (MouseEvent event)//when the mouse is dragged while pressed down
        {
            if (mode == true)//if the mode is true
            {
                point2 = event.getPoint();//then you get the second point
                repaint();//must use this method because you are making a change to the component
            }
        }

        public void mouseReleased (MouseEvent event)//when the mouse is released after being pressed (not to be confused with a click)
        {
            if (mode == true)//if the mode is true
            {
                point2 = event.getPoint();//then you set point2 to where that point landed
                if (point1.x != point2.x && point1.y != point2.y)//if the points are not in the same spots
                {
                    edgeList.add(new Edge(point1,point2));//then you add a new edgeList element to the ArrayList, by definition of Edge() object
                    repaint();//must use this method because changes to component have been made
                }
            }

        }

        public void mouseMoved (MouseEvent event)// if the mouse is moved, without it being clicked (not to be confused by mouseDragged)
        {
            point3 = event.getPoint();//point three is set to be where the mouse is at the current time(used this to find the distance of original edge drawn, keeping here incase I want to add)
            repaint();//must use this method because changes were made to component

        }

        //  Empty definitions for unused event methods.
        public void mouseEntered (MouseEvent event){}//when the mouse enters a component

        public void mouseExited (MouseEvent event) {}//when the mouse exits a component

        private int distance(Point p1, Point p2) //private distance formula but inside of this class so i was able to use it for determining how to erase nodes and edges
        {
            return (int)Math.sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));//square root of x cordinants of first point minus second point times its self plus the y coordinates
            //of first point minus second point times itself
        }
    }
    // Represents the graph edges
    private class Edge //defines how edges are made
    {
        Point a, b;

        public Edge(Point a, Point b)
        {
            this.a = a;
            this.b = b;
        }
    }

    private class ButtonListener implements ActionListener
    {
        public void actionPerformed (ActionEvent event)
        {

            if (event.getSource()== create)
            {
                mode = true;
                mode1 = 1;
            }
            if (event.getSource()==delete)
            {
                mode = !true;
                mode1 = 2;

            }

            // Initializes graph adjacency matrix
            for (int i=0; i<nodeList.size(); i++)
                for (int j=0; j<nodeList.size(); j++) a[i][j]=0;

            // Includes the edges in the graph adjacency matrix
            for (int i=0; i<edgeList.size(); i++)
            {
                for (int j=0; j<nodeList.size(); j++)
                    if (distance(nodeList.get(j),edgeList.get(i).a)<=SIZE+3)
                        for (int k=0; k<nodeList.size(); k++)
                            if (distance(nodeList.get(k),edgeList.get(i).b)<=SIZE+3)
                            {
                                System.out.println(j+"->"+k);
                                a[j][k]=1;
                            }
            }

            if (event.getSource()==print)
            {

                // Prints the graph adjacency matrix
                for (int i=0; i<nodeList.size(); i++)
                {
                    for (int j=0; j<nodeList.size(); j++)
                        System.out.print(a[i][j]+"\t");
                    System.out.println();
                }
            }
        }
        // Euclidean distance function
        private int distance(Point p1, Point p2)
        {
            return (int)Math.sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
        }
    }

    private class ButtonListener1 implements ActionListener
    {
        public void actionPerformed (ActionEvent event)
        {
            if (event.getSource()== create)//if create button is selected
            {
                mode = true;//then the mode is set to true
                mode1 = 1;//and mode1 is set to 1
            }
        }
    }

    private class ButtonListener2 implements ActionListener
    {
        public void actionPerformed (ActionEvent event)
        {
            if (event.getSource()== delete)//if create button is selected
            {
                mode = !true;//then the mode is set to true
                mode1 = 2;//and mode1 is set to 2, which would change the string that is output
            }
        }
    }

    private class ButtonListener3 implements ActionListener
    {
        public void actionPerformed (ActionEvent event)
        {
            x1 = label.getText();
            y1 = label1.getText();
            x = Integer.parseInt(x1);
            y = Integer.parseInt(y1);

            System.out.println("Path from " +x+" to " +y);
            System.out.println(findPath(x,y));
            System.out.println(path);

        }
    }
</code>```

答:
You just never add the first node to path. You can do it when you check if path exists:

```<code>if (!found){
    System.out.println("Path Does Not Exist");
} else {
    path.add(0, x);
}
</code>```

and then you also need to remove this block:

```<code>if (found) {
    //System.out.println(x + " -> " + z);
    path.add(0,z);
}
</code>```

So complete method will look like

```<code>public static boolean findPath(int x, int y) //boolean method findpath that takes two ints as parameters
{
    boolean found = false;

    if (a[x][y]==1) //base case
    {
        //System.out.println(x + " -> " + y);//prints node -> node
        found = true;//path is found
        path.add(0,y);
    }
    else
    {
        int z;
        for (z=0; !found& z<a.length; z++)
        {
            if (a[x][z]==1)
            {
                a[x][z]=2;
                found = findPath(z,y);

            }
            /*if (found)
            {
                //System.out.println(x + " -> " + z);
                path.add(0,z);
            }*/

        }
    }

    if (!found){
        System.out.println("Path Does Not Exist");
    } else {
        path.add(0,x);
    }
    return found;
}
</code>```

I also suggest you to look at Dijkstra's algorithm of finding the shortest path between nodes

Body:
I wrote a program that allows a user to add nodes and connect them with edges with a GUI interface.  The first node is always labeled "0".  When I call the findPath method however it shows the entire path appropriately just lacking the 0.  For example if I want to find the path from 0-4, and they're all connected numerically it will show [1,2,3,4].  To get a proper reading of the path after connecting the nodes you need to hit the print adjacency button.  Everything else is running as expected but I can't seem to figure out why this won't add the first node.

Thanks Guys!

    import javax.swing.JFrame;//imports JFrame package

    public class Graph//class header
    {
       public static void main (String[] args)//main method
       {
          JFrame frame = new JFrame ("Directed Graph");//sets variable frame to a JFrame object and titles it
          frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);//exits application when it is closed
          frame.getContentPane().add (new GraphPanel());//adding GraphPanel() to the frame
          frame.setLocationRelativeTo(null);//sets location to the center
          frame.pack();//packs the frame, fits everything inside
          frame.setVisible(true);//makes frame visible
       }
    }

import java.util.ArrayList;//all of these are the required to get classes from other packages
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;

public class GraphPanel extends JPanel
{
    private final int SIZE = 10;  // radius of each node
    private double alpha; // double variable to define later
    private JButton print, create, delete, path1; //allpath;//button variables
    private JTextField label, label1;
    boolean mode = true;//sets boolean for entire class to true, until later when I define it as false for certain methods to be complete

    String x1, y1;
    String str1 = new String("Mode Chosen Is : create" );//when you choose create it will print this instead
    String str2 = new String("Mode Chosen Is : delete" );//when you choose delete it will print this

    int x, y;
    int mode1 = 1; // int mode1 variable, will comment why i need this when it is later defined/changed

    private Point point1 = null, point2 = null, point3 = null;//makes pointers null, i added a third pointer to put the distance from the first drawn string at the top right, but no longer needed it
    //keeping it incase I wanted to add it again

    private ArrayList<Point> nodeList;   // Graph nodes
    private ArrayList<Edge> edgeList;    // Graph edges

    static private int[][] a = new int[100][100];  // Graph adjacency matrix
    static ArrayList<Integer> path = new ArrayList<Integer>();

    public GraphPanel()
    {

        nodeList = new ArrayList<Point>();//declares ArrayList<Point>
        edgeList = new ArrayList<Edge>();//declares ArrayList<Edge>

        GraphListener listener = new GraphListener();//assigns 'listener' to a Graphlistener object
        addMouseListener (listener);//accepts and reads mouseListener methods to the GraphListener object
        addMouseMotionListener (listener);//accepts and reads MouseMotionListener methods to the GraphListener object

        label = new JTextField (1);
        label1 = new JTextField (1);

        //allpath = new JButton ("Find All Paths");
        path1 = new JButton ("Find Path");//path button
        create = new JButton("Create");//declares 'create' as a JButton object with text on it that says 'create'
        delete = new JButton("Delete");//declares 'delete' as a JButton object with text that says 'delete'
        JButton print = new JButton("Print adjacency matrix");//declares 'print' as a JButton object with text that reads 'print adjacency matrix'

        print.addActionListener (new ButtonListener());//adds an action listener to the print button from the buttonlistener object
        create.addActionListener (new ButtonListener1());//adds an actionListener to the create button from the buttonlistener1 object
        delete.addActionListener (new ButtonListener2());//adds an actionliseneer to the delete button from the buttonlistener2 object
        path1.addActionListener (new ButtonListener3());//adds button that will find path of nodes
        //allpath.addActionListener (new ButtonListener4());

        setBackground (Color.black);//sets backround as black
        setPreferredSize (new Dimension(400, 300));//this is preferred size of graphpanel
        add(print);//these next six add()'s add each button to GraphPanel
        add(delete);//
        add(create);//
        //add(allpath);
        add(path1);
        add(label);
        add(label1);
    }

    public static boolean findPath(int x, int y) //boolean method findpath that takes two ints as parameters
    {
        boolean found = false;

        if (a[x][y]==1) //base case
        {
            //System.out.println(x + " -> " + y);//prints node -> node
            found = true;//path is found
            path.add(0,y);
        }
        else
        {
            int z;
            for (z=0; !found& z " + z);
                    path.add(0,z);
                }

            }
        }

        if (!found){
            System.out.println("Path Does Not Exist");
        }
        return found;
    }

    // public static ArrayList findPath1(int x, int y, ArrayList path)
    // {
    // System.out.println("CALL FIND: " + path);
    // ArrayList path2 = null;
    // if (a[x][y]==1)
    // {
    // ArrayList path3 = (ArrayList)path.clone();
    // path3.add(y);
    // System.out.println("EXIT BASE: " + path3);
    // path2 = path3;
    // }
    // else
    // {
    // int z;
    // for (z=0; z<a.length; z++)
    // if (a[x][z]==1)
    // {
    // ArrayList path3 = (ArrayList)path.clone();
    // path3.add(z);
    // path3 = findPath1(z,y,path3);
    // System.out.println("EXIT RECU: " + path);
    // path2 = path3;
    // }
    // }
    // return path2;
    // }
    //  Draws the graph
    public void paintComponent (Graphics page)
    {
        super.paintComponent(page);//using parent methods

        // Draws the edge that is being dragged
        page.setColor (Color.green);//setting color of what will be drawn to green
        if (mode1 == 1)//if mode1 is set to 1, which is when the create button is selected
        {
            page.drawString(str1, 125, 75);//then this is printed
        }
        if (mode1 == 2)//if mode1 is set to 2, which is when the delete button is selected
        {
            page.drawString(str2, 125, 75);//then this is printed
        }
        if (point1 != null && point2 != null)//if and only if both points are not null
        {
            page.drawLine (point1.x, point1.y, point2.x, point2.y);//then it draws the line from between point1(x, y cords), and point2(x, y cords)
            page.fillOval (point2.x-3, point2.y-3, 6, 6);//fills this oval by the rectangle it is specified from
        }
        // Draws the nodes
        for (int i=0; i<nodeList.size(); i++) //for loop going through the nodeList ArrayList
        {
            page.setColor (Color.green);//color is set to green
            page.fillOval (nodeList.get(i).x-SIZE, nodeList.get(i).y-SIZE, SIZE*2, SIZE*2);//fills oval by subtracting the SIZE from the x, y and setting the height and width as two times the SIZE
            page.setColor (Color.black);//sets next line to black
            page.drawString (String.valueOf(i), nodeList.get(i).x-SIZE/2, nodeList.get(i).y+SIZE/2);//writes inside the node what number index it is from the ArrayList with black text
        }
        // Draws the edges
        for (int i=0; i<edgeList.size(); i++) // for loop going through the edgeList ArrayList
        {
            page.setColor (Color.green);//sets the next line to green
            page.drawLine (edgeList.get(i).a.x, edgeList.get(i).a.y,edgeList.get(i).b.x, edgeList.get(i).b.y);//draws the line from x and y cords of where it starts to end
            //page.fillOval (edgeList.get(i).b.x-3, edgeList.get(i).b.y-3, 6, 6);

            //page.drawString (String.valueOf(point1.x*(point2.y-point3.y)+point2.x*(point3.y-point1.y)+point3.x*(point1.y-point2.y)), 5, 15);

            alpha = Math.atan((double)(edgeList.get(i).b.y-edgeList.get(i).a.y)/(edgeList.get(i).b.x-edgeList.get(i).a.x));//alpha = b.y-a.y cords/b.x-a.x chords as a double variable
            if (edgeList.get(i).a.x > edgeList.get(i).b.x)//if the x chord of a is greater than the x cordinate of b
            {
                alpha = alpha + Math.PI;//then alpha = previously defined alpha multiplied by PI
            }
            if (edgeList.get(i).a.x < edgeList.get(i).b.x && edgeList.get(i).a.y > edgeList.get(i).b.y)//if a.x is less than b.x and a.y is less than b.y
            {
                alpha = alpha + 2*Math.PI;//then alpha becomes the previously defined alpha multiplied by 2 PI
            }
            arrow(page,edgeList.get(i).b.x,edgeList.get(i).b.y,0,1.57-alpha);//arrow method, taking a x(edgeList.get(i).b.x, y(edgeList.get(i).b.y, length = 0 so arrow is at the
            // very end of the drawn line subtracted by a double aplha
        }
    }

    // arrow method to call when making an arrow
    private void arrow(Graphics page, int x, int y, int len, double alpha)//arrow method, taking a x, y, length and double parameter
    {
        page.setColor (Color.green);//sets arrow to green
        int x1 = x+(int)(len*Math.sin(alpha));//x1 is set to x plus length *sin of alpha
        int y1 = y+(int)(len*Math.cos(alpha));//y1 is set to y plus the length * cosin of alpha
        page.drawLine (x, y, x1, y1);//drawa the x and y, and then previously defined x1, and y1
        page.drawLine (x1, y1, x1+(int)(20*Math.sin(alpha+2.5)), y1+(int)(20*Math.cos(alpha+2.5)));//arithmatic to draw one side of the line for the arrow
        page.drawLine (x1, y1, x1+(int)(20*Math.sin(alpha+3.7)), y1+(int)(20*Math.cos(alpha+3.7)));//arithmatic to draw the corresponding line for the arrow to complete the arrow
    }

    //  The listener for mouse events.
    private class GraphListener implements MouseListener, MouseMotionListener//GraphListener which implements MouseListener and MouseMotionListener, meaning it takes methods from both of those classes
    {
        public void mouseClicked (MouseEvent event)//when mouse is clicked and released
        {
            if (mode == true)//if the mode is true
            {
                nodeList.add(event.getPoint());//the current point to the nodeList
                repaint();//whenever you change the look of a componenet you call this method
            }
            if (mode == false)//if boolean mode is false
            {
                for (int i=0; i<nodeList.size(); i++)//for loop to go through the nodeList ArrayList
                {
                    if (distance(nodeList.get(i), event.getPoint()) < SIZE)//if the distance between a specific node and the pointer is less than the radius of the node (SIZE)
                        nodeList.remove(i);//then remove that node
                }
                for (int i=0; i<edgeList.size(); i++)
                {
                    if (distance(edgeList.get(i).a, event.getPoint())+distance(event.getPoint(), edgeList.get(i).b)-distance(edgeList.get(i).a, edgeList.get(i).b) < SIZE)
                    //if the (distance between starting point of that edgelist index and the current point) plus (the distance between the current point and ending point of that edgeList index)
                    //subtracted by the (distance of the starting and ending point of that edgeList index)(AB+BC-AC) is all less than the size
                        edgeList.remove(i);//then remove that index
                }
            }
        }

        public void mousePressed (MouseEvent event)//when the mouse is pressed down
        {
            if (mode == true)//if the mode is true
            {
                point1 = event.getPoint();//you start that point
            }
        }

        public void mouseDragged (MouseEvent event)//when the mouse is dragged while pressed down
        {
            if (mode == true)//if the mode is true
            {
                point2 = event.getPoint();//then you get the second point
                repaint();//must use this method because you are making a change to the component
            }
        }

        public void mouseReleased (MouseEvent event)//when the mouse is released after being pressed (not to be confused with a click)
        {
            if (mode == true)//if the mode is true
            {
                point2 = event.getPoint();//then you set point2 to where that point landed
                if (point1.x != point2.x && point1.y != point2.y)//if the points are not in the same spots
                {
                    edgeList.add(new Edge(point1,point2));//then you add a new edgeList element to the ArrayList, by definition of Edge() object
                    repaint();//must use this method because changes to component have been made
                }
            }

        }

        public void mouseMoved (MouseEvent event)// if the mouse is moved, without it being clicked (not to be confused by mouseDragged)
        {
            point3 = event.getPoint();//point three is set to be where the mouse is at the current time(used this to find the distance of original edge drawn, keeping here incase I want to add)
            repaint();//must use this method because changes were made to component

        }

        //  Empty definitions for unused event methods.
        public void mouseEntered (MouseEvent event){}//when the mouse enters a component

        public void mouseExited (MouseEvent event) {}//when the mouse exits a component

        private int distance(Point p1, Point p2) //private distance formula but inside of this class so i was able to use it for determining how to erase nodes and edges
        {
            return (int)Math.sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));//square root of x cordinants of first point minus second point times its self plus the y coordinates
            //of first point minus second point times itself
        }
    }
    // Represents the graph edges
    private class Edge //defines how edges are made
    {
        Point a, b;

        public Edge(Point a, Point b)
        {
            this.a = a;
            this.b = b;
        }
    }

    private class ButtonListener implements ActionListener
    {
        public void actionPerformed (ActionEvent event)
        {

            if (event.getSource()== create)
            {
                mode = true;
                mode1 = 1;
            }
            if (event.getSource()==delete)
            {
                mode = !true;
                mode1 = 2;

            }

            // Initializes graph adjacency matrix
            for (int i=0; i<nodeList.size(); i++)
                for (int j=0; j<nodeList.size(); j++) a[i][j]=0;

            // Includes the edges in the graph adjacency matrix
            for (int i=0; i<edgeList.size(); i++)
            {
                for (int j=0; j<nodeList.size(); j++)
                    if (distance(nodeList.get(j),edgeList.get(i).a)<=SIZE+3)
                        for (int k=0; k<nodeList.size(); k++)
                            if (distance(nodeList.get(k),edgeList.get(i).b)<=SIZE+3)
                            {
                                System.out.println(j+"->"+k);
                                a[j][k]=1;
                            }
            }

            if (event.getSource()==print)
            {

                // Prints the graph adjacency matrix
                for (int i=0; i<nodeList.size(); i++)
                {
                    for (int j=0; j<nodeList.size(); j++)
                        System.out.print(a[i][j]+"\t");
                    System.out.println();
                }
            }
        }
        // Euclidean distance function
        private int distance(Point p1, Point p2)
        {
            return (int)Math.sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
        }
    }

    private class ButtonListener1 implements ActionListener
    {
        public void actionPerformed (ActionEvent event)
        {
            if (event.getSource()== create)//if create button is selected
            {
                mode = true;//then the mode is set to true
                mode1 = 1;//and mode1 is set to 1
            }
        }
    }

    private class ButtonListener2 implements ActionListener
    {
        public void actionPerformed (ActionEvent event)
        {
            if (event.getSource()== delete)//if create button is selected
            {
                mode = !true;//then the mode is set to true
                mode1 = 2;//and mode1 is set to 2, which would change the string that is output
            }
        }
    }

    private class ButtonListener3 implements ActionListener
    {
        public void actionPerformed (ActionEvent event)
        {
            x1 = label.getText();
            y1 = label1.getText();
            x = Integer.parseInt(x1);
            y = Integer.parseInt(y1);

            System.out.println("Path from " +x+" to " +y);
            System.out.println(findPath(x,y));
            System.out.println(path);

        }
    }

Body:
You just never add the first node to path. You can do it when you check if path exists:

if (!found){
    System.out.println("Path Does Not Exist");
} else {
    path.add(0, x);
}

and then you also need to remove this block:

if (found) {
    //System.out.println(x + " -> " + z);
    path.add(0,z);
}

So complete method will look like

public static boolean findPath(int x, int y) //boolean method findpath that takes two ints as parameters
{
    boolean found = false;

    if (a[x][y]==1) //base case
    {
        //System.out.println(x + " -> " + y);//prints node -> node
        found = true;//path is found
        path.add(0,y);
    }
    else
    {
        int z;
        for (z=0; !found& z<a.length; z++)
        {
            if (a[x][z]==1)
            {
                a[x][z]=2;
                found = findPath(z,y);

            }
            /*if (found)
            {
                //System.out.println(x + " -> " + z);
                path.add(0,z);
            }*/

        }
    }

    if (!found){
        System.out.println("Path Does Not Exist");
    } else {
        path.add(0,x);
    }
    return found;
}

I also suggest you to look at Dijkstra's algorithm of finding the shortest path between nodes


问:
Java Swing aligning buttons, labels, and text fields
I am trying to align my JButton and JTextArea to the bottom middle of my code, side by side. I followed a few tutorials and came to this point. When I execute my program, the text area and the button are still both aligned at the top. Help!</p>

```<code>import java.awt.BorderLayout;
import java.awt.FlowLayout;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class Main extends JFrame implements ActionListener{

JPanel panel = new JPanel();
JButton button = new JButton("Confirm!");
JTextArea text = new JTextArea(1, 20);
public Main() {
    super("Battleship!");
    setLayout(new FlowLayout());
    button.addActionListener(this);
    setSize(600, 500);
    setResizable(true);
    button.setLayout(new FlowLayout(FlowLayout.CENTER));
    text.setLayout(new FlowLayout(FlowLayout.CENTER));
    panel.add(text, BorderLayout.SOUTH);
    panel.add(button, BorderLayout.SOUTH);
    add(panel);

    setVisible(true);
}
public static void main(String[] args) {
    new Main();
}
@Override
public void actionPerformed(ActionEvent e) {
    button.setText(text.getText());
}

}
</code>```

答:
See the notes in the code comments.</p>

```<code>import java.awt.*;
import javax.swing.*;

public class MainLayout extends JFrame {

    // A panel defaults to flow layout. Use the default
    JPanel panel = new JPanel();
    JButton button = new JButton("Confirm!");
    JTextArea text = new JTextArea(1, 20);

    public MainLayout() {
        super("Battleship!");
        //setLayout(new FlowLayout()); // use the default border layout
        setSize(600, 500); // should be packed after components added.
        //setResizable(true); // this is the default
        /* Don't set layouts on things like buttons or text areas
        This is only useful for containers to which we add other
        components, and it is rarely, if ever, useful to add components
        to these types of GUI elements. */
        //button.setLayout(new FlowLayout(FlowLayout.CENTER));
        // text.setLayout(new FlowLayout(FlowLayout.CENTER));

        /* No need for layout constraints when adding these to
        a flow layout */
        //panel.add(text, BorderLayout.SOUTH);
        panel.add(text);
        //panel.add(button, BorderLayout.SOUTH);
        panel.add(button);

        // NOW we need the constraint!
        add(panel, BorderLayout.PAGE_END);

        setVisible(true);
    }

    public static void main(String[] args) {
        /* Swing/AWT GUIs should be started on the EDT.
        Left as an exercise for the reader */
        new MainLayout();
    }
}
</code>```

Body:
I am trying to align my JButton and JTextArea to the bottom middle of my code, side by side. I followed a few tutorials and came to this point. When I execute my program, the text area and the button are still both aligned at the top. Help!

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class Main extends JFrame implements ActionListener{

JPanel panel = new JPanel();
JButton button = new JButton("Confirm!");
JTextArea text = new JTextArea(1, 20);
public Main() {
    super("Battleship!");
    setLayout(new FlowLayout());
    button.addActionListener(this);
    setSize(600, 500);
    setResizable(true);
    button.setLayout(new FlowLayout(FlowLayout.CENTER));
    text.setLayout(new FlowLayout(FlowLayout.CENTER));
    panel.add(text, BorderLayout.SOUTH);
    panel.add(button, BorderLayout.SOUTH);
    add(panel);

    setVisible(true);
}
public static void main(String[] args) {
    new Main();
}
@Override
public void actionPerformed(ActionEvent e) {
    button.setText(text.getText());
}

}

Body:
See the notes in the code comments.

import java.awt.*;
import javax.swing.*;

public class MainLayout extends JFrame {

    // A panel defaults to flow layout. Use the default
    JPanel panel = new JPanel();
    JButton button = new JButton("Confirm!");
    JTextArea text = new JTextArea(1, 20);

    public MainLayout() {
        super("Battleship!");
        //setLayout(new FlowLayout()); // use the default border layout
        setSize(600, 500); // should be packed after components added.
        //setResizable(true); // this is the default
        /* Don't set layouts on things like buttons or text areas
        This is only useful for containers to which we add other
        components, and it is rarely, if ever, useful to add components
        to these types of GUI elements. */
        //button.setLayout(new FlowLayout(FlowLayout.CENTER));
        // text.setLayout(new FlowLayout(FlowLayout.CENTER));

        /* No need for layout constraints when adding these to
        a flow layout */
        //panel.add(text, BorderLayout.SOUTH);
        panel.add(text);
        //panel.add(button, BorderLayout.SOUTH);
        panel.add(button);

        // NOW we need the constraint!
        add(panel, BorderLayout.PAGE_END);

        setVisible(true);
    }

    public static void main(String[] args) {
        /* Swing/AWT GUIs should be started on the EDT.
        Left as an exercise for the reader */
        new MainLayout();
    }
}


问:
Create a PHP Class Outline
I am looking for a function or class that can effectively outline a class:

```<code>class MyClass{

  /*
  * Perhaps include the function comments
  * in the function.
  */
  function mainFunction(){
    //Does Something
  }

  function functionWithArgs($arg1,$arg2=false){
    //Does Something
    //The function I want will give e the arguments w/default values
  }

}
</code>```

Is there a function or library in existence that can give me some kind of access to the information about this class, or even the file.

ex.

get_file_outline('fileWithAboveClass.php');

or

get_class_outline('MyClass');

Does anybody know of either, or know a way of easily writing this?

答:
There's also a command line option available for inspecting functions and classes.

```<code>$ php --rc DateTime
</code>```

will give you all the details about the DateTime-class, while

```<code>$ php --rf in_array
</code>```

will give you the arguments of the "in_array" function.

If you're using the Terminal when coding it can be quite handy to use instead of looking it up in the PHP Manual all the time ;)

Title: Create a PHP Class Outline

Body:
I am looking for a function or class that can effectively outline a class:

class MyClass{

  /*
  * Perhaps include the function comments
  * in the function.
  */
  function mainFunction(){
    //Does Something
  }

  function functionWithArgs($arg1,$arg2=false){
    //Does Something
    //The function I want will give e the arguments w/default values
  }

}

Is there a function or library in existence that can give me some kind of access to the information about this class, or even the file.

ex.

get_file_outline('fileWithAboveClass.php');

or

get_class_outline('MyClass');

Does anybody know of either, or know a way of easily writing this?

Body:
There's also a command line option available for inspecting functions and classes.

$ php --rc DateTime

will give you all the details about the DateTime-class, while

$ php --rf in_array

will give you the arguments of the "in_array" function.

If you're using the Terminal when coding it can be quite handy to use instead of looking it up in the PHP Manual all the time ;)