问:
iOS - Run async operations in serial manner on non-main thread
```<code>- (void) fetchOperation:(NSString *c){
    async_method(c):^{
      NSLog(@"%@ completed.",c);
    }
  }
// call fetchOperation:@"A"
// call fetchOperation:@"B"
// call fetchOperation:@"C"

//Expecting output: A completed, B completed, C Completed.
</code>```

Please note I want fetch to happen on non-main thread. Their could be 1 to n fetchOperation calls. And each fetchOperation call can happen as a result of some other user action like user tapped.
I tried semaphores, nsoperationQueue but no luck so far.

答:
Check out the documentation for maxconcurrentoperationcount property of NSOperation .

The maximum number of queued operations that can execute at the same
  time.

The default value of this property is
  NSOperationQueueDefaultMaxConcurrentOperationCount.

Setting it to 1 should only run one at a time as you need.

Edit:

To make sure you wait for the other to complete you should look into dependencies

This property contains an array of NSOperation objects. To add an object to this array, use the addDependency: method.
  An operation object must not execute until all of its dependent operations finish executing. Operations are not removed from this dependency list as they finish executing. You can use this list to track all dependent operations, including those that have already finished executing. The only way to remove an operation from this list is to use the removeDependency: method.

and addDependency and KVO observing isReady , isFinished among others as you need it.

Good sources for more information and details on the properties above:

Tutorial

Tutorial (by Mattt)

Apple WWDC

Body:
- (void) fetchOperation:(NSString *c){
    async_method(c):^{
      NSLog(@"%@ completed.",c);
    }
  }
// call fetchOperation:@"A"
// call fetchOperation:@"B"
// call fetchOperation:@"C"

//Expecting output: A completed, B completed, C Completed.

Please note I want fetch to happen on non-main thread. Their could be 1 to n fetchOperation calls. And each fetchOperation call can happen as a result of some other user action like user tapped.
I tried semaphores, nsoperationQueue but no luck so far.


来源: stackexchange

问:
Interactive R Shiny plot with and without using ggplot
I modified the interactive R Shiny plot from the R Shiny gallery to plot an interactive standard curve. I would like to plot the interactive plot without using ggplot2 library with just using R base plotting functions.

```<code>library(ggplot2)

XYdata <- data.frame(cbind(Values = c(91.8, 95.3,   99.8,   123.3,  202.9,  619.8,  1214.2, 1519.1, 1509.2, 1523.3, 1595.2, 1625.1),
                           Concn = c(1000, 300,    100,    30, 10, 3,  1,  0.3,    0.1,    0.03,   0.01,   0)))
ui <- fluidPage(
  fluidRow(
    column(width = 6,
           plotOutput("plot1", height = 350,
                      click = "plot1_click",
                      brush = brushOpts(
                        id = "plot1_brush"
                      )
           ),
           actionButton("exclude_toggle", "Toggle points"),
           actionButton("exclude_reset", "Reset")
    )
  )
)

server <- function(input, output) {
  # For storing which rows have been excluded
  vals <- reactiveValues(
    keeprows = rep(TRUE, nrow(XYdata))
  )
  NonScientific <- function(l) {l <- format(l, scientific = FALSE); parse(text=l)}

  output$plot1 <- renderPlot({
    # Plot the kept and excluded points as two separate data sets

    XYdata <- data.frame(cbind(Values = c(91.8, 95.3,   99.8,   123.3,  202.9,  619.8,  1214.2, 1519.1, 1509.2, 1523.3, 1595.2, 1625.1),
                           Concn = c(1000, 300,    100,    30, 10, 3,  1,  0.3,    0.1,    0.03,   0.01,   0)))
    keep    <- XYdata[ vals$keeprows, , drop = FALSE]
    exclude <- XYdata[!vals$keeprows, , drop = FALSE]
    keep <- subset(keep, Concn > 0)
    exclude <- subset(exclude, Concn > 0)
    nls.fit <- nls(Values ~ (ymax* keep$Concn / (ec50 + keep$Concn)) + Ns*keep$Concn + ymin, data=keep,
                   start=list(ymax=max(keep$Values), ymin = min(keep$Values), ec50 = 3, Ns = 0.2045514))
    keep$nls.pred <- fitted(nls.fit)

    ggplot(keep, aes(y = Values,x = Concn))+geom_point(size = 5,colour="red")+
    geom_smooth(method = "loess",fullrange = F, se = T, aes(Concn, nls.pred),size = 1.5,colour="blue1")+
      geom_point(data = exclude, shape = 21, fill = NA, color = "black",size = 5, alpha = 0.7) +
      xlab('Concentration (nM)')+ ylab('Units')+
      scale_x_log10(labels=NonScientific)+ggtitle("Standard Curve")+theme_classic()+
      theme(panel.background = element_rect(colour = "black", size=1),
            plot.margin = margin(1, 3, 0.5, 1, "cm"),
            plot.title = element_text(hjust = 0, face="bold",color="#993333", size=16),
            axis.title = element_text(face="bold", color="#993333", size=14),
            axis.text.x = element_text(face="bold", color="#666666", size=12),
            axis.text.y = element_text(face="bold", color="#666666", size=12))
  })

  # Toggle points that are clicked
  observeEvent(input$plot1_click, {
    res <- nearPoints(XYdata, input$plot1_click, allRows = TRUE)

    vals$keeprows <- xor(vals$keeprows, res$selected_)
  })

  # Toggle points that are brushed, when button is clicked
  observeEvent(input$exclude_toggle, {
    res <- brushedPoints(XYdata, input$plot1_brush, allRows = TRUE)

    vals$keeprows <- xor(vals$keeprows, res$selected_)
  })

  # Reset all points
  observeEvent(input$exclude_reset, {
    vals$keeprows <- rep(TRUE, nrow(XYdata))
  })

}

shinyApp(ui, server)
</code>```

I tried replacing the plotting portion of the script with the following but I am not able to interactively plot. What am I doing wrong here?

```<code> plot(Values ~ Concn, keep, subset = Concn > 0, col = 4, cex = 2, log = "x")
 title(main = "XY Std curve")
 lines(predict(nls.fit, new = list(Concn = Concn)) ~ Concn, keep)
 points(Values ~ Concn, exclude, subset = Concn > 0, col = 1, cex = 2, log = "x")
</code>```

答:
You have to add xvarand yvar parameters to nearPoints:

```<code>res <- nearPoints(XYdata, input$plot1_click, xvar="Concn", yvar="Values", allRows = TRUE)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I modified the interactive R Shiny plot from the R Shiny gallery to plot an interactive standard curve. I would like to plot the interactive plot without using ggplot2 library with just using R base plotting functions.

library(ggplot2)

XYdata <- data.frame(cbind(Values = c(91.8, 95.3,   99.8,   123.3,  202.9,  619.8,  1214.2, 1519.1, 1509.2, 1523.3, 1595.2, 1625.1),
                           Concn = c(1000, 300,    100,    30, 10, 3,  1,  0.3,    0.1,    0.03,   0.01,   0)))
ui <- fluidPage(
  fluidRow(
    column(width = 6,
           plotOutput("plot1", height = 350,
                      click = "plot1_click",
                      brush = brushOpts(
                        id = "plot1_brush"
                      )
           ),
           actionButton("exclude_toggle", "Toggle points"),
           actionButton("exclude_reset", "Reset")
    )
  )
)

server <- function(input, output) {
  # For storing which rows have been excluded
  vals <- reactiveValues(
    keeprows = rep(TRUE, nrow(XYdata))
  )
  NonScientific <- function(l) {l <- format(l, scientific = FALSE); parse(text=l)}

  output$plot1 <- renderPlot({
    # Plot the kept and excluded points as two separate data sets

    XYdata <- data.frame(cbind(Values = c(91.8, 95.3,   99.8,   123.3,  202.9,  619.8,  1214.2, 1519.1, 1509.2, 1523.3, 1595.2, 1625.1),
                           Concn = c(1000, 300,    100,    30, 10, 3,  1,  0.3,    0.1,    0.03,   0.01,   0)))
    keep    <- XYdata[ vals$keeprows, , drop = FALSE]
    exclude <- XYdata[!vals$keeprows, , drop = FALSE]
    keep <- subset(keep, Concn > 0)
    exclude <- subset(exclude, Concn > 0)
    nls.fit <- nls(Values ~ (ymax* keep$Concn / (ec50 + keep$Concn)) + Ns*keep$Concn + ymin, data=keep,
                   start=list(ymax=max(keep$Values), ymin = min(keep$Values), ec50 = 3, Ns = 0.2045514))
    keep$nls.pred <- fitted(nls.fit)

    ggplot(keep, aes(y = Values,x = Concn))+geom_point(size = 5,colour="red")+
    geom_smooth(method = "loess",fullrange = F, se = T, aes(Concn, nls.pred),size = 1.5,colour="blue1")+
      geom_point(data = exclude, shape = 21, fill = NA, color = "black",size = 5, alpha = 0.7) +
      xlab('Concentration (nM)')+ ylab('Units')+
      scale_x_log10(labels=NonScientific)+ggtitle("Standard Curve")+theme_classic()+
      theme(panel.background = element_rect(colour = "black", size=1),
            plot.margin = margin(1, 3, 0.5, 1, "cm"),
            plot.title = element_text(hjust = 0, face="bold",color="#993333", size=16),
            axis.title = element_text(face="bold", color="#993333", size=14),
            axis.text.x = element_text(face="bold", color="#666666", size=12),
            axis.text.y = element_text(face="bold", color="#666666", size=12))
  })

  # Toggle points that are clicked
  observeEvent(input$plot1_click, {
    res <- nearPoints(XYdata, input$plot1_click, allRows = TRUE)

    vals$keeprows <- xor(vals$keeprows, res$selected_)
  })

  # Toggle points that are brushed, when button is clicked
  observeEvent(input$exclude_toggle, {
    res <- brushedPoints(XYdata, input$plot1_brush, allRows = TRUE)

    vals$keeprows <- xor(vals$keeprows, res$selected_)
  })

  # Reset all points
  observeEvent(input$exclude_reset, {
    vals$keeprows <- rep(TRUE, nrow(XYdata))
  })

}

shinyApp(ui, server)

I tried replacing the plotting portion of the script with the following but I am not able to interactively plot. What am I doing wrong here?

 plot(Values ~ Concn, keep, subset = Concn > 0, col = 4, cex = 2, log = "x")
 title(main = "XY Std curve")
 lines(predict(nls.fit, new = list(Concn = Concn)) ~ Concn, keep)
 points(Values ~ Concn, exclude, subset = Concn > 0, col = 1, cex = 2, log = "x")

Body:
You have to add xvarand yvar parameters to nearPoints:

res <- nearPoints(XYdata, input$plot1_click, xvar="Concn", yvar="Values", allRows = TRUE)


问:
How to run selenium scripts written in java from jmeter?
I am trying to use my Selenium scripts in java with JMeter's WebDriver  Sampler.

Inside the webdriver sampler, the language is seleced to java, and the following code added:

```<code>package automationFramework;

public class FirstTestCase {

    public static void main(String[] args) {

        // Create a new instance of the Firefox driver
        WebDriver driver = new ChromeDriver();

        //Launch the Online Store Website
        driver.get("www.google.com");

        // Print a Log In message to the screen
        System.out.println("Successfully opened the website www.google.com");

        //Wait for 5 Sec
        Thread.sleep(5);

        // Close the driver
        driver.quit();
    }
}
</code>```

I am facing the following error:

```<code>java.net.MalformedURLException: unknown protocol: data
at java.net.URL.<init>(URL.java:600)
at java.net.URL.<init>(URL.java:490)
at java.net.URL.<init>(URL.java:439)
at com.googlecode.jmeter.plugins.webdriver.sampler.WebDriverSampler.sample(WebDriverSampler.java:80)
at org.apache.jmeter.threads.JMeterThread.executeSamplePackage(JMeterThread.java:475)
at org.apache.jmeter.threads.JMeterThread.processSampler(JMeterThread.java:418)
at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:249)
at java.lang.Thread.run(Thread.java:745)
</code>```

However, tests written in javascripts work just fine.

What is the problem here? How to solve it?

答:
If you are using Chrome driver 2.28 with Selenium 3.x.x you have to set the path of the Chrome driver before you open the browser.

Add this line:
System.setProperty("webdriver.chrome.driver", "C:\\your_folder\\chrome.exe");

Next, WebDriver driver;

Let me know if this helps you.

Body:
I am trying to use my Selenium scripts in java with JMeter's WebDriver  Sampler.

Inside the webdriver sampler, the language is seleced to java, and the following code added:

package automationFramework;

public class FirstTestCase {

    public static void main(String[] args) {

        // Create a new instance of the Firefox driver
        WebDriver driver = new ChromeDriver();

        //Launch the Online Store Website
        driver.get("www.google.com");

        // Print a Log In message to the screen
        System.out.println("Successfully opened the website www.google.com");

        //Wait for 5 Sec
        Thread.sleep(5);

        // Close the driver
        driver.quit();
    }
}

I am facing the following error:

java.net.MalformedURLException: unknown protocol: data
at java.net.URL.<init>(URL.java:600)
at java.net.URL.<init>(URL.java:490)
at java.net.URL.<init>(URL.java:439)
at com.googlecode.jmeter.plugins.webdriver.sampler.WebDriverSampler.sample(WebDriverSampler.java:80)
at org.apache.jmeter.threads.JMeterThread.executeSamplePackage(JMeterThread.java:475)
at org.apache.jmeter.threads.JMeterThread.processSampler(JMeterThread.java:418)
at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:249)
at java.lang.Thread.run(Thread.java:745)

However, tests written in javascripts work just fine.

What is the problem here? How to solve it?


问:
pointer to object == pointer to first member?
Why does the if condition in the following code yield true?

```<code>struct A
{
    int firstMember;
} a1;

if (&a1 == static_cast<void*>(&a1.firstMember)) std::cout << "equal";
</code>```

I got a bit confused when reading Stroustrup's FAQ on empty classes, specifically the statement below:

```<code>if (p1 == p2) cout << "nice: good optimizer";
</code>```

答:
There are no references involved in your code. Don't confuse the "address-of" operator (also &) with references.

Your condition returns true because in this case it happens that the object starts in the same place in memory as its first (and only) field. That's the case i.e. for so-called POD (plain-old-data) objects, but it's not always true.

For example it's likely for the condition to be false if your class contains any virtual functions. Don't depend on it.

ContentLicense: CC BY-SA 2.5

Body:
Why does the if condition in the following code yield true?

struct A
{
    int firstMember;
} a1;

if (&a1 == static_cast<void*>(&a1.firstMember)) std::cout << "equal";

I got a bit confused when reading Stroustrup's FAQ on empty classes, specifically the statement below:

if (p1 == p2) cout << "nice: good optimizer";


问:
PHP-generated XML Feed Displaying as Text
EDIT: HOW IS THIS TOO BROAD? My question was put on hold for being too broad, but I asked one question and provided screenshots and sourcecode. What more do I need? I feel this was flagged for closure before the people that flagged it read everything here. I provided the full source code of my file. HELP! I don't feel very welcome. :-(

I followed the answer in this question to take an existing XML feed, change some tag names, and then spit out a new feed:

How do I change XML tag names with PHP?

The issue I am having is that when the feed is displayed in any browser, it displays as text, instead of being nicely formatted like other 'normal' XML feeds. I assume that since I have not told PHP to render the page as XML, it assumes text/html by default, and that is why it is happening. HOWEVER, when I specify in the header that it's XML, it generates with some XML formatting, but all of my feed shows up bold between the 'pre' tags that are in that answer linked above. When removing the 'pre' tag from the source, it generates nothing.

Without Header Specifying XML:

Rendering as Text

With Header Specifying XML:

Rendering Improperly as XML

Does anyone have any hints to guide me to get this to render properly in a browser?

Thanks in Advance!

Source linked in comments below. StackOverflow would not let me add a third link.

答:
Fixed it!

I replaced:

```
    `echo 'PRETAG'; print_r(htmlspecialchars($xml)); echo 'PRETAG';`
```

with

```
    `print_r($xml);`
```

And added the XML content type to the header:

```
    `header ("Content-Type:text/xml");`
```

My original source (as posted in the comments above), is available here: Source: ufile.io/4fee1

Body:
Fixed it!

I replaced:

    `echo 'PRETAG'; print_r(htmlspecialchars($xml)); echo 'PRETAG';`

with

    `print_r($xml);`

And added the XML content type to the header:

    `header ("Content-Type:text/xml");`

My original source (as posted in the comments above), is available here: Source: ufile.io/4fee1


问:
(Bug?) Android button responds to hand gesture
I have Button in my Android application and I manage two states of affairs using an Enum. The button has two logical states defined by the Enum; Stopped and Recording.

When the button is clicked while in Stopped state, an instance of AudioRecorder starts recording the user's voice and the state advances to Recording.

When the button is clicked while in Recording state, the recording stops and the state goes back to Stopped.

Now, sometimes when I start recording then simply wave my hand without making any contact with the phone, the recording stops as if the button was clicked.

I only handle the button click events using the OnClickListener interface and nowhere have I setup to receive gesture events.

What is this? Has anyone experienced this before?

答:
Ok. So I found the culprit, I forgot to mention that I was using CountDownTimer which tends to skip ticks sometimes. The onFinish() method of this class was being called too early sometimes coincidentally with my hand over the phone.

I solved it by creating my own Timer class using a Handler.


问:
Using Actors to exploit cores
I'm new to Scala in general and Actors in particular and my problem is so basic, the online resources I have found don't cover it.

I have a CPU-intensive, easily parallelized algorithm that will be run on an n-core machine (I don't know n).  How do I implement this in Actors so that all available cores address the problem?

The first way I thought of was to simple break the problem into m pieces (where m is some medium number like 10,000) and create m Actors, one for each piece, give each Actor its little piece and let 'em go.

Somehow, this struck me as inefficient.  Zillions of Actors just hanging around, waiting for some CPU love, pointlessly switching contexts...

Then I thought, make some smaller number of Actors, and feed each one several pieces.  The problem was, there's no reason to expect the pieces are the same size, so one core might get bogged down, with many of its tasks still queued, while other cores are idle.

I noodled around with a Supervisor that knew which Actors were busy, and eventually realized that this has to be a solved problem.  There must be a standard pattern (maybe even a standard library) for dealing with this very generic issue.  Any suggestions?

答: Take a look at the Akka library, which includes an implementaton of actors. The Dispatchers Module gives you more options for limiting actors to cpu threads (HawtDispatch-based event-driven) and/or balancing the workload (Work-stealing event-based).</p>

Title: Using Actors to exploit cores


问:
How to move methods to external file in windows form C#
newbie question :(

I'm making a program using windows forms and i have a lot of small methods like this

```<code>    private void label1_Click(object sender, EventArgs e)
    {
        textBox1.Select();
    }

    private void label13_Click(object sender, EventArgs e)
    {
        textBox13.Select();
    }

    private void radioButton1_CheckedChanged(object sender, EventArgs e)
    {
        plotGraph(prostokat);
    }
</code>```

in the Form1.cs file and to make the code more transparent, I would like to move these small methods out somewhere to an external file (class?) but I don't really know how to do this. If they were normal methods I would just make a class and create an object of that class and just call the methods using that object but these are functions that "happen" when a user action is performed i.e. a textbox is clicked, so I'm not sure how to make this work.

答: You can create any number of partial class files mimicking your original and group methods inside as your functionally needs - however, you won't be able to use the designer to directly navigate to your callbacks. That is, if you double click a graphic element or click an event of a graphic element you will have an unexpected behavior: in both cases you will have an event handler generated in your first partial and a hook created to that . . . so you can't directly navigate to those handlers anymore, and you need to go trough your partial files looking for their definitions.   </p>

Body:
newbie question :(

I'm making a program using windows forms and i have a lot of small methods like this

    private void label1_Click(object sender, EventArgs e)
    {
        textBox1.Select();
    }

    private void label13_Click(object sender, EventArgs e)
    {
        textBox13.Select();
    }

    private void radioButton1_CheckedChanged(object sender, EventArgs e)
    {
        plotGraph(prostokat);
    }

in the Form1.cs file and to make the code more transparent, I would like to move these small methods out somewhere to an external file (class?) but I don't really know how to do this. If they were normal methods I would just make a class and create an object of that class and just call the methods using that object but these are functions that "happen" when a user action is performed i.e. a textbox is clicked, so I'm not sure how to make this work.


问:
How to make an MPMediaQuery to return results based on releaseDate
I'm trying to create an MPMediaQuery that will return results in chronological order, preferably ascending or descending based on the query itself.

Right now my query returns items in ascending chrono order (oldest at top) but I'd like to be able to reverse the order.
I need my results to be in an MPMediaQuery so that I can use it with the MPMediaPlayer.

```<code>var qryPodcasts = MPMediaQuery()
var titleFilter = MPMediaPropertyPredicate()
titleFilter = MPMediaPropertyPredicate(value: "This American Life", forProperty: MPMediaItemPropertyPodcastTitle, comparisonType: .equalTo)
qryPodcasts.addFilterPredicate(titleFilter)
</code>```

EDIT::

I've been able to get a step closer to my goal however I still have a problem that causes a crash.

I've added this code which will sort the resulting query based on "releaseDate" however not all Podcasts conform so this property can be nil causing a crash:

```<code>let myItems = qryPodcasts.items?.sorted{($0.releaseDate)! > ($1.releaseDate)!}
let podCollection = MPMediaItemCollection(items: myItems!)
myMP.setQueue(with: podCollection!)
</code>```

How can I avoid this error and how do I handle items without a releaseDate?

答:
Just for this part:
How can I avoid this error and how do I handle items without a releaseDate?

Avoid using forced-unwrapping (!) and provide default values for nil:

```<code>let myItems = qryPodcasts.items?.sorted{($0.releaseDate ?? Date.distantFuture) > ($1.releaseDate ?? Date.distantFuture)}
</code>```

You'd better check all other forced-unwrappings in your code, are you really 100% sure those never return nil?

Body:
I'm trying to create an MPMediaQuery that will return results in chronological order, preferably ascending or descending based on the query itself.

Right now my query returns items in ascending chrono order (oldest at top) but I'd like to be able to reverse the order.
I need my results to be in an MPMediaQuery so that I can use it with the MPMediaPlayer.

var qryPodcasts = MPMediaQuery()
var titleFilter = MPMediaPropertyPredicate()
titleFilter = MPMediaPropertyPredicate(value: "This American Life", forProperty: MPMediaItemPropertyPodcastTitle, comparisonType: .equalTo)
qryPodcasts.addFilterPredicate(titleFilter)

EDIT::

I've been able to get a step closer to my goal however I still have a problem that causes a crash.

I've added this code which will sort the resulting query based on "releaseDate" however not all Podcasts conform so this property can be nil causing a crash:

let myItems = qryPodcasts.items?.sorted{($0.releaseDate)! > ($1.releaseDate)!}
let podCollection = MPMediaItemCollection(items: myItems!)
myMP.setQueue(with: podCollection!)

How can I avoid this error and how do I handle items without a releaseDate?

Body:
Just for this part:
How can I avoid this error and how do I handle items without a releaseDate?

Avoid using forced-unwrapping (!) and provide default values for nil:

let myItems = qryPodcasts.items?.sorted{($0.releaseDate ?? Date.distantFuture) > ($1.releaseDate ?? Date.distantFuture)}

You'd better check all other forced-unwrappings in your code, are you really 100% sure those never return nil?


问:
Algorithm to randomly generate an aesthetically-pleasing color palette
I'm looking for a simple algorithm to generate a large number of random, aesthetically pleasing colors. So no crazy neon colors, colors reminiscent of feces, etc.

I've found solutions to this problem but they rely on alternative color palettes than RGB.
I would rather just use straight RGB than mapping back and forth. These other solutions also can at most generate only 32 or so pleasing random colors.

Any ideas would be great.

答:
you could have them be within a certain brightness. that would control the ammount of "neon" colors a bit. for instance, if the "brightness"

```<code>brightness = sqrt(R^2+G^2+B^2)
</code>```

was within a certain high bound, it would have a washed out, light color to it. Conversely, if it was within a certain low bound, it would be darker. This would eliminate any crazy, standout colors and if you chose a bound really high or really low, they would all be fairly close to either white or black.

OwnerDisplayName: Brian Gianforcaro

Body:
you could have them be within a certain brightness. that would control the ammount of "neon" colors a bit. for instance, if the "brightness"

brightness = sqrt(R^2+G^2+B^2)

was within a certain high bound, it would have a washed out, light color to it. Conversely, if it was within a certain low bound, it would be darker. This would eliminate any crazy, standout colors and if you chose a bound really high or really low, they would all be fairly close to either white or black.

OwnerDisplayName: contagious


问:
How do I determine whether the filesystem is case-sensitive in .net?
Does .net have a way to determine whether the local filesystem is case-sensitive?</p>

答:
Keep in mind that you might have multiple file systems with different casing rules. For example, the root filesystem could be case-sensitive, but you can have a case-insensitive filesystem (e.g. an USB stick with a FAT filesystem on it) mounted somewhere. So if you do such checks, make sure that you make them in the directory that you are going to access.

Also, what if the user copies the data from say a case-sensitive to a case-insensitive file system? If you have files that differ only by case, one of them will overwrite the other, causing data loss. When copying in the other direction, you might also run into problems, for example, if file A contains a reference to file "b", but the file is actually named "B". This works on the original case-insensitive file system, but not on the case-sensitive system.

Thus I would suggest that you avoid depending on whether the file system is case-sensitive or not if you can. Do not generate file names that differ only by case, use the standard file picker dialogs, be prepared that the case might change, etc.

OwnerDisplayName: Matt

OwnerDisplayName: oefe


问:
RegularExpressionValidator for more than just AlphaNumerics
I have a RegularExpressionValidator with:

```<code>ValidationExpression="^(a-zA-Z0-9 '-]+$"
</code>```

so this was working for alphanumerics, spaces, apostrophes and hyphen.

I was told that I now need it to additionally work for underscore, ampersand '&', comma, parentheses and fullstop.

I tried:

```<code>ValidationExpression="^(a-zA-Z0-9 '-_&,().]+$"
</code>```

but this made it accept virtually anything.

Could someone please tell me where I'm going wrong? I'm relatively new to Regex.

答:
be careful when  using a . in regular expressions, for it is a special character and it matches any character. You might want to escape it like this: \. or have it inside a character class like [.]. Take care of any other special characters too.

You can find a lot of interesting information regarding the dot here, make sure you check the rest of the links in that site, they will give you great insight on how regular expressions work!

Hope this helps.

Body:
I have a RegularExpressionValidator with:

ValidationExpression="^(a-zA-Z0-9 '-]+$"

so this was working for alphanumerics, spaces, apostrophes and hyphen.

I was told that I now need it to additionally work for underscore, ampersand '&', comma, parentheses and fullstop.

I tried:

ValidationExpression="^(a-zA-Z0-9 '-_&,().]+$"

but this made it accept virtually anything.

Could someone please tell me where I'm going wrong? I'm relatively new to Regex.


问:
How do I update a variable (which is a list) with an updated list after using a function to alter it?
I need some help please, I have some code I've written which should manipulate a list using a function. The problem I'm having is keeping hold of this manipulated list to use in the main coding. For example, I created a list which contains names for 4 people queuing in line for tickets, I then input this list in a function to remove the 3rd in line. This will create a new list which I want to be able to manipulate outside of the function. Here is my code so far

```<code>def aLeave(aList,usrstr):

    tempq = []
    idx = 0
    found = False
    while idx < len(aList) and not found: #This section works out the index
        if aList[idx] == usrstr:          # of the user string that needs removed
            found = True                  # from the queue list.
        else:
            idx = idx + 1

    if found:
        for i in range(len(aList)):           #This sections takes the index previously
            if i == idx:                      #found and uses it to create a new list
                continue                      #without the element the user has requested to be removed
            tempq.append(aList[i])

    aList = tempq
    print(aList)
    return aList

aList = ["john","mark","pete","dave"]

aLeave(aList,input("what do you want to remove"))

print (aList)
</code>```

Any help would be very much appreciated!

Thanks (The function is called 'aLeave')

答:
You just have to assign the return value of the function to a variable, and since you want to update the same list, you can do something like this while calling the function.

```<code>aList = aLeave(aList, input("Stuff"))
</code>```

Also, inside the function, aList = tempq is not necessary, since all it is doing is updating the local variable, aList. To update the aList in the global scope, you can write global aList at the top of the function, however, this is not considered good design practice, and should be avoided as far as possible.

Body:
I need some help please, I have some code I've written which should manipulate a list using a function. The problem I'm having is keeping hold of this manipulated list to use in the main coding. For example, I created a list which contains names for 4 people queuing in line for tickets, I then input this list in a function to remove the 3rd in line. This will create a new list which I want to be able to manipulate outside of the function. Here is my code so far

def aLeave(aList,usrstr):

    tempq = []
    idx = 0
    found = False
    while idx < len(aList) and not found: #This section works out the index
        if aList[idx] == usrstr:          # of the user string that needs removed
            found = True                  # from the queue list.
        else:
            idx = idx + 1

    if found:
        for i in range(len(aList)):           #This sections takes the index previously
            if i == idx:                      #found and uses it to create a new list
                continue                      #without the element the user has requested to be removed
            tempq.append(aList[i])

    aList = tempq
    print(aList)
    return aList

aList = ["john","mark","pete","dave"]

aLeave(aList,input("what do you want to remove"))

print (aList)

Any help would be very much appreciated!

Thanks (The function is called 'aLeave')

Body:
You just have to assign the return value of the function to a variable, and since you want to update the same list, you can do something like this while calling the function.

aList = aLeave(aList, input("Stuff"))

Also, inside the function, aList = tempq is not necessary, since all it is doing is updating the local variable, aList. To update the aList in the global scope, you can write global aList at the top of the function, however, this is not considered good design practice, and should be avoided as far as possible.


问:
Using pointers to remove item from singly-linked list
In a recent Slashdot Interview Linus Torvalds gave an example of how some people use pointers in a way that indicates they don't really understand how to use them correctly.

Unfortunately, since I'm one of the people he's talking about, I also failed to understand his example:

I've seen too many people who delete a singly-linked list entry by keeping track of the "prev" entry, and then to delete the entry, doing
  something like

```<code>if (prev)
    prev->next = entry->next;
else
    list_head = entry->next;
</code>```

and whenever I see code like that, I just go "This person doesn't
  understand pointers". And it's sadly quite common. People who
  understand pointers just use a "pointer to the entry pointer", and
  initialize that with the address of the list_head. And then as they
  traverse the list, they can remove the entry without using any
  conditionals, by just doing

```<code>*pp = entry->next
</code>```

Can someone provide a bit more explanation about why this approach is better, and how it can work without a conditional statement?

答:
Here's a complete code example, using a function-call to remove matching elements:

rem() removes matching elements, using prev

rem2() removes matching elements, using pointer-to-pointer

// code.c

#include <stdio.h>
#include <stdlib.h>

typedef struct list_entry {
    int val;
    struct list_entry *next;
} list_entry;

list_entry *new_node(list_entry *curr, int val)
{
    list_entry *new_n = malloc(sizeof(list_entry));
    if (new_n == NULL) {
        fputs("Error in malloc\n", stderr);
        exit(1);
    }
    new_n->val  = val;
    new_n->next = NULL;

    if (curr) {
        curr->next = new_n;
    }
    return new_n;
}

#define ARR_LEN(arr) (sizeof(arr)/sizeof((arr)[0]))

#define     CREATE_LIST(arr) create_list((arr), ARR_LEN(arr))

list_entry *create_list(const int arr[], size_t len)
{
    if (len == 0) {
        return NULL;
    }

    list_entry *node = NULL;
    list_entry *head = node = new_node(node, arr[0]);
    for (size_t i = 1; i < len; ++i) {
        node = new_node(node, arr[i]);
    }
    return head;
}

void rem(list_entry **head_p, int match_val)
// remove and free all entries with match_val
{
    list_entry *prev = NULL;
    for (list_entry *entry = *head_p; entry; ) {
        if (entry->val == match_val) {
            list_entry *del_entry = entry;
            entry = entry->next;
            if (prev) {
                prev->next = entry;
            } else {
                *head_p    = entry;
            }
            free(del_entry);
        } else {
            prev = entry;
            entry = entry->next;
        }
    }
}

void rem2(list_entry **pp, int match_val)
// remove and free all entries with match_val
{
    list_entry *entry;
    while ((entry = *pp)) { // assignment, not equality
        if (entry->val == match_val) {
            *pp =   entry->next;
            free(entry);
        } else {
            pp  =  &entry->next;
        }
    }
}

void print_and_free_list(list_entry *entry)
{
    list_entry *node;
    // iterate through, printing entries, and then freeing them
    for (;     entry != NULL;      node = entry, /* lag behind to free */
                                   entry = entry->next,
                                   free(node))           {
        printf("%d ", entry->val);
    }
    putchar('\n');
}

#define CREATELIST_REMOVEMATCHELEMS_PRINT(arr, match_val) createList_removeMatchElems_print((arr), ARR_LEN(arr), (match_val))

void    createList_removeMatchElems_print(const int arr[], size_t len, int match_val)
{
    list_entry *head = create_list(arr, len);
    rem2(&head, match_val);
    print_and_free_list(head);
}

int main()
{
    const int match_val = 2; // the value to remove
    {
        const int arr[] = {0, 1, 2, 3};
        CREATELIST_REMOVEMATCHELEMS_PRINT(arr, match_val);
    }
    {
        const int arr[] = {0, 2, 2, 3};
        CREATELIST_REMOVEMATCHELEMS_PRINT(arr, match_val);
    }
    {
        const int arr[] = {2, 7, 8, 2};
        CREATELIST_REMOVEMATCHELEMS_PRINT(arr, match_val);
    }
    {
        const int arr[] = {2, 2, 3, 3};
        CREATELIST_REMOVEMATCHELEMS_PRINT(arr, match_val);
    }
    {
        const int arr[] = {0, 0, 2, 2};
        CREATELIST_REMOVEMATCHELEMS_PRINT(arr, match_val);
    }
    {
        const int arr[] = {2, 2, 2, 2};
        CREATELIST_REMOVEMATCHELEMS_PRINT(arr, match_val);
    }
    {
        const int arr[] = {};
        CREATELIST_REMOVEMATCHELEMS_PRINT(arr, match_val);
    }

    return 0;
}
```

See the code in action here:

gcc https://wandbox.org/permlink/LxgMddqCZWyj7lMI

clang https://wandbox.org/permlink/5aEkxh24sGfAecwF

If compiling and using valgrind (a memory-leak checker) like this:

gcc -std=c11 -Wall -Wextra -Werror -o go code.c     &&     valgrind ./go

we see that all is good.

Body:
In a recent Slashdot Interview Linus Torvalds gave an example of how some people use pointers in a way that indicates they don't really understand how to use them correctly.

Unfortunately, since I'm one of the people he's talking about, I also failed to understand his example:

I've seen too many people who delete a singly-linked list entry by keeping track of the "prev" entry, and then to delete the entry, doing
  something like

if (prev)
    prev->next = entry->next;
else
    list_head = entry->next;

and whenever I see code like that, I just go "This person doesn't
  understand pointers". And it's sadly quite common. People who
  understand pointers just use a "pointer to the entry pointer", and
  initialize that with the address of the list_head. And then as they
  traverse the list, they can remove the entry without using any
  conditionals, by just doing

*pp = entry->next

Can someone provide a bit more explanation about why this approach is better, and how it can work without a conditional statement?

Body:
Here's a complete code example, using a function-call to remove matching elements:

rem() removes matching elements, using prev

rem2() removes matching elements, using pointer-to-pointer

// code.c

#include <stdio.h>
#include <stdlib.h>

typedef struct list_entry {
    int val;
    struct list_entry *next;
} list_entry;

list_entry *new_node(list_entry *curr, int val)
{
    list_entry *new_n = malloc(sizeof(list_entry));
    if (new_n == NULL) {
        fputs("Error in malloc\n", stderr);
        exit(1);
    }
    new_n->val  = val;
    new_n->next = NULL;

    if (curr) {
        curr->next = new_n;
    }
    return new_n;
}

#define ARR_LEN(arr) (sizeof(arr)/sizeof((arr)[0]))

#define     CREATE_LIST(arr) create_list((arr), ARR_LEN(arr))

list_entry *create_list(const int arr[], size_t len)
{
    if (len == 0) {
        return NULL;
    }

    list_entry *node = NULL;
    list_entry *head = node = new_node(node, arr[0]);
    for (size_t i = 1; i < len; ++i) {
        node = new_node(node, arr[i]);
    }
    return head;
}

void rem(list_entry **head_p, int match_val)
// remove and free all entries with match_val
{
    list_entry *prev = NULL;
    for (list_entry *entry = *head_p; entry; ) {
        if (entry->val == match_val) {
            list_entry *del_entry = entry;
            entry = entry->next;
            if (prev) {
                prev->next = entry;
            } else {
                *head_p    = entry;
            }
            free(del_entry);
        } else {
            prev = entry;
            entry = entry->next;
        }
    }
}

void rem2(list_entry **pp, int match_val)
// remove and free all entries with match_val
{
    list_entry *entry;
    while ((entry = *pp)) { // assignment, not equality
        if (entry->val == match_val) {
            *pp =   entry->next;
            free(entry);
        } else {
            pp  =  &entry->next;
        }
    }
}

void print_and_free_list(list_entry *entry)
{
    list_entry *node;
    // iterate through, printing entries, and then freeing them
    for (;     entry != NULL;      node = entry, /* lag behind to free */
                                   entry = entry->next,
                                   free(node))           {
        printf("%d ", entry->val);
    }
    putchar('\n');
}

#define CREATELIST_REMOVEMATCHELEMS_PRINT(arr, match_val) createList_removeMatchElems_print((arr), ARR_LEN(arr), (match_val))

void    createList_removeMatchElems_print(const int arr[], size_t len, int match_val)
{
    list_entry *head = create_list(arr, len);
    rem2(&head, match_val);
    print_and_free_list(head);
}

int main()
{
    const int match_val = 2; // the value to remove
    {
        const int arr[] = {0, 1, 2, 3};
        CREATELIST_REMOVEMATCHELEMS_PRINT(arr, match_val);
    }
    {
        const int arr[] = {0, 2, 2, 3};
        CREATELIST_REMOVEMATCHELEMS_PRINT(arr, match_val);
    }
    {
        const int arr[] = {2, 7, 8, 2};
        CREATELIST_REMOVEMATCHELEMS_PRINT(arr, match_val);
    }
    {
        const int arr[] = {2, 2, 3, 3};
        CREATELIST_REMOVEMATCHELEMS_PRINT(arr, match_val);
    }
    {
        const int arr[] = {0, 0, 2, 2};
        CREATELIST_REMOVEMATCHELEMS_PRINT(arr, match_val);
    }
    {
        const int arr[] = {2, 2, 2, 2};
        CREATELIST_REMOVEMATCHELEMS_PRINT(arr, match_val);
    }
    {
        const int arr[] = {};
        CREATELIST_REMOVEMATCHELEMS_PRINT(arr, match_val);
    }

    return 0;
}

See the code in action here:

gcc https://wandbox.org/permlink/LxgMddqCZWyj7lMI

clang https://wandbox.org/permlink/5aEkxh24sGfAecwF

If compiling and using valgrind (a memory-leak checker) like this:

gcc -std=c11 -Wall -Wextra -Werror -o go code.c     &&     valgrind ./go

we see that all is good.

ContentLicense: CC BY-SA 4.0


问:
Difference between mean and manual calculation in R?
I am writing a simple function in R to calculate percentage differences between two input numbers.

```<code>pdiff <-function(a,b)
    {
      if(length(a>=1)) a <- median(a)
      if(length(b>=1)) b <- median(b)
      (abs(a-b)/((a+b)/2))*100
    }

    pdiffa <-function(a,b)
    {
      if(length(a>=1)) a <- median(a)
      if(length(b>=1)) b <- median(b)
      (abs(a-b)/mean(a,b))*100
    }
</code>```

When you run it with a random value of a and b, the functions give different results

```<code>x <- 5
y <- 10
pdiff(x,y) #gives 66%
pdiffa(x,y) #gives 100%
</code>```

When I go into the code, apparently the values of (x+y)/2 = 7.5 and mean(x,y) = 5 differ......Am I missing something really obvious and stupid here?

答:
This is due to a nasty "gotcha" in the mean() function (not listed in the list of R traps, but probably should be): you want mean(c(a,b)), not mean(a,b). From ?mean:

mean(x, ...)

  [snip snip snip]

  ... further arguments passed to or from other methods.

So what happens if you call mean(5,10)? mean calls the mean.default method, which has trim as its second argument:

trim the fraction (0 to 0.5) of observations to be trimmed from each end of x before the mean is computed. Values of trim outside that range are taken as the nearest endpoint.

The last phrase "values of trim outside that range are taken as the nearest endpoint" means that values of trim larger than 0.5 are set to 0.5, which means that we're asking mean to throw away 50% of the data on either end of the data set, which means that all that's left is the median. Debugging our way through mean.default, we see that we indeed end up at this code ...

```<code>if (trim >= 0.5)
      return(stats::median(x, na.rm = FALSE))
</code>```

So mean(c(x,<value_greater_than_0.5>)) returns the median of c(5), which is just 5 ...

Body:
I am writing a simple function in R to calculate percentage differences between two input numbers.

pdiff <-function(a,b)
    {
      if(length(a>=1)) a <- median(a)
      if(length(b>=1)) b <- median(b)
      (abs(a-b)/((a+b)/2))*100
    }

    pdiffa <-function(a,b)
    {
      if(length(a>=1)) a <- median(a)
      if(length(b>=1)) b <- median(b)
      (abs(a-b)/mean(a,b))*100
    }

When you run it with a random value of a and b, the functions give different results

x <- 5
y <- 10
pdiff(x,y) #gives 66%
pdiffa(x,y) #gives 100%

When I go into the code, apparently the values of (x+y)/2 = 7.5 and mean(x,y) = 5 differ......Am I missing something really obvious and stupid here?

Body:
This is due to a nasty "gotcha" in the mean() function (not listed in the list of R traps, but probably should be): you want mean(c(a,b)), not mean(a,b). From ?mean:

mean(x, ...)

  [snip snip snip]

  ... further arguments passed to or from other methods.

So what happens if you call mean(5,10)? mean calls the mean.default method, which has trim as its second argument:

trim the fraction (0 to 0.5) of observations to be trimmed from each end of x before the mean is computed. Values of trim outside that range are taken as the nearest endpoint.

The last phrase "values of trim outside that range are taken as the nearest endpoint" means that values of trim larger than 0.5 are set to 0.5, which means that we're asking mean to throw away 50% of the data on either end of the data set, which means that all that's left is the median. Debugging our way through mean.default, we see that we indeed end up at this code ...

if (trim >= 0.5)
      return(stats::median(x, na.rm = FALSE))

So mean(c(x,<value_greater_than_0.5>)) returns the median of c(5), which is just 5 ...


问:
How do I get this module and program to run correctly (indentation error)?
I am going through a textbook and learning Python very successfully; more successfully than I would have imagined. While going through the current chapter of the book I am on, I have been instructed to create a module "games" to use for import in a program "Simple Game". I have done everything to the T that the book has said to do, yet I am constantly arriving at an indent error. I am not claiming that the author of this book has screwed up (since he is a lot more experienced than I), but I have done everything to the letter of instruction and it is not working correctly whatsoever.I have tried unindenting then unindenting the following lines accordingly,indenting the line above the error, and various other things, and I cant get this to work correctly. Please help.

Here's the "games" module:

```<code>class Player(object):
    """ A player for a game. """
    def __init__(self, name, score = 0):
        self.name = name
        self.score = score

    def __str__(self):
        rep = self.name + ":\t" + str(self.score)
        return rep

    def ask_y_n(question):
        """ Ask a yes or no question. """
        response = None
        while response not in ("y", "n"):
            response = input(question).lower()
        return response

    def ask_number(question, low, high):
        """ Ask for a number within a range. """
        response = None
        while response not in range(low, high):
            response = int(input(question))
        return response
    if __name__ == "__main__":
        print("You ran this module directly (and did not 'import' it).")
        input("\n\n\t\t\tPress the ENTER key to exit.")
</code>```

And next i will show you the code of the program that utilizes my created "games" module:

```<code>import games, random

print("Welcome to the world's simplest game!\n")

again = None
while again != "n":
    players = []
num = games.ask_number(question = "How many players? (2 - 5): ", low = 2, high = 5)
    for i in range(num):
        name = input("Player name: ")
        score = random.randrange(100) + 1
        player = games.Player(name, score)
        players.append(player)

    print("\nHere are the game results:")
    for player in players:
        print(player)
    again = games.ask_y_n("\nDo you want to play again? (y/n): ")

input("\n\n\t\t\tPress the ENTER key to exit.")
</code>```

The indentation error occurs in the main program at the point where it says: for i in range(num). that line is getting the error, but why?

答: This line: num = games.ask_number(question = "How many players? (2 - 5): ", low = 2, high = 5) should be indented. I suggest you look into a basic Python tutorial. Essentially, every time you type : and start writing code on the next line, you need to increase your indentation level.

Body:
I am going through a textbook and learning Python very successfully; more successfully than I would have imagined. While going through the current chapter of the book I am on, I have been instructed to create a module "games" to use for import in a program "Simple Game". I have done everything to the T that the book has said to do, yet I am constantly arriving at an indent error. I am not claiming that the author of this book has screwed up (since he is a lot more experienced than I), but I have done everything to the letter of instruction and it is not working correctly whatsoever.I have tried unindenting then unindenting the following lines accordingly,indenting the line above the error, and various other things, and I cant get this to work correctly. Please help.

Here's the "games" module:

class Player(object):
    """ A player for a game. """
    def __init__(self, name, score = 0):
        self.name = name
        self.score = score

    def __str__(self):
        rep = self.name + ":\t" + str(self.score)
        return rep

    def ask_y_n(question):
        """ Ask a yes or no question. """
        response = None
        while response not in ("y", "n"):
            response = input(question).lower()
        return response

    def ask_number(question, low, high):
        """ Ask for a number within a range. """
        response = None
        while response not in range(low, high):
            response = int(input(question))
        return response
    if __name__ == "__main__":
        print("You ran this module directly (and did not 'import' it).")
        input("\n\n\t\t\tPress the ENTER key to exit.")

And next i will show you the code of the program that utilizes my created "games" module:

import games, random

print("Welcome to the world's simplest game!\n")

again = None
while again != "n":
    players = []
num = games.ask_number(question = "How many players? (2 - 5): ", low = 2, high = 5)
    for i in range(num):
        name = input("Player name: ")
        score = random.randrange(100) + 1
        player = games.Player(name, score)
        players.append(player)

    print("\nHere are the game results:")
    for player in players:
        print(player)
    again = games.ask_y_n("\nDo you want to play again? (y/n): ")

input("\n\n\t\t\tPress the ENTER key to exit.")

The indentation error occurs in the main program at the point where it says: for i in range(num). that line is getting the error, but why?


问:
How to compute a power of a power using recursion?
I've recently been looking into recursion and it's been very confusing. I'm trying to write a java program which uses recursion to generate the result of a base number to a power, which also has a height of how many exponents the base has. For example, a base of two with a power of 3 and a height of 3 will result:

(((2^3)^3)^3)

Here is my (very flawed) code:

```<code>    public static void main(String[] args) {
    System.out.println(exponentWithHeight(2, 2, 3));
}

public static int exponentWithHeight(int base, int power, int height) {
    if (power < 0 || height < 0) {
        throw new IllegalArgumentException("Check input values.");
    }
    if (power == 0) {
        return 1;
    } else {
        return (base * height * exponentWithHeight(base, power - 1, height - 1));
    }
}
</code>```

I'm really not sure how to go about getting my desired output; As I said this is really confusing and new to me. Can someone help explain how to go about doing this?

答:
Are we forgetting that you can multiply a series of exponents together to simplify the equation?

The following should work.

```<code>public static int exponentWithHeight(int base, int power, int height) {
    if (power < 0 || height < 0) {
        throw new IllegalArgumentException("Invalid Input; Check power and/or height value.");
    }
    if (power == 0 || height == 0) {
        return 1;
    } else {
        return (int) Math.pow(base, Math.pow(power, height));
    }
}
</code>```

Body:
I've recently been looking into recursion and it's been very confusing. I'm trying to write a java program which uses recursion to generate the result of a base number to a power, which also has a height of how many exponents the base has. For example, a base of two with a power of 3 and a height of 3 will result:

(((2^3)^3)^3)

Here is my (very flawed) code:

    public static void main(String[] args) {
    System.out.println(exponentWithHeight(2, 2, 3));
}

public static int exponentWithHeight(int base, int power, int height) {
    if (power < 0 || height < 0) {
        throw new IllegalArgumentException("Check input values.");
    }
    if (power == 0) {
        return 1;
    } else {
        return (base * height * exponentWithHeight(base, power - 1, height - 1));
    }
}

I'm really not sure how to go about getting my desired output; As I said this is really confusing and new to me. Can someone help explain how to go about doing this?

Body:
Are we forgetting that you can multiply a series of exponents together to simplify the equation?

The following should work.

public static int exponentWithHeight(int base, int power, int height) {
    if (power < 0 || height < 0) {
        throw new IllegalArgumentException("Invalid Input; Check power and/or height value.");
    }
    if (power == 0 || height == 0) {
        return 1;
    } else {
        return (int) Math.pow(base, Math.pow(power, height));
    }
}


答:
Try mean(5, 10) by itself.

```<code>mean(5, 10)
[1] 5
</code>```

Now try mean(c(5, 10)).

```<code>mean(c(5, 10))
[1] 7.5
</code>```

mean takes a vector as its first argument.

Title: Difference between mean and manual calculation in R?

Body:
Try mean(5, 10) by itself.

mean(5, 10)
[1] 5

Now try mean(c(5, 10)).

mean(c(5, 10))
[1] 7.5

mean takes a vector as its first argument.


问:
Measure the runtime of a program run via perl "open"
I'm working on a library with a test suite that uses Perl open to run it's tests. It looks something like this:

```<code>open (MYOUT, "$myprog $arg1 $arg2 $arg3 2>&1 |") die "Bad stuff happened";
</code>```

What I'd really like to do is to measure the runtime of $myprog. Unfortunately, just grabbing a start time and end time around the open command just grabs roughly how long it takes to start up the process.

Is there some way of either forcing the open command to finish the process (and therefore accurately measure time) or perhaps something else that would accomplish the same thing?

Key constraints are that we need to capture (potentially a lot of) STDOUT and STDERR.

答:
Since you open a pipe, you need to time from before opening to at least after the reading

```<code>use warnings;
use strict;
use Time::HiRes qw(gettimeofday tv_interval sleep);

my $t0 = [gettimeofday];

open my $read, '-|', qw(ls -l) or die "Can't open process: $!";

while (<$read>)
{
    sleep 0.1;
    print;
}

print "It took ", tv_interval($t0), " seconds\n";
# close pipe and check
</code>```

or, to time the whole process, after calling close on the pipe (after all reading is done)

```<code>my $t0 = [gettimeofday];
open my $read, '-|', qw(ls -l)  or die "Can't open process: $!";
# ... while ($read) { ... }
close $read  or
    warn $! ? "Error closing pipe: $!" : "Exit status: $?";
print "It took ", tv_interval($t0), " seconds\n";
</code>```

The close blocks and waits for the program to finish

Closing a pipe also waits for the process executing on the pipe to exit--in case you wish to look at the output of the pipe afterwards--and implicitly puts the exit status value of that command into $? [...]

For the status check see $? variable in perlvar and system

If the timed program forks and doesn't wait on its children in a blocking way this won't time them correctly.
In that case you need to identify resources that they use (files?) and monitor that.

I'd like to add that external commands should be put together carefully, to avoid shell injection trouble.  A good module is String::ShellQuote. See for example this answer and this answer

Using a module for capturing streams would free you from the shell and perhaps open other ways to run and time this more reliably. A good one is Capture::Tiny (and there are others as well).

Thanks to HåkonHægland for comments.  Thanks to ikegami for setting me straight, to use close (and not waitpid).

Body:
I'm working on a library with a test suite that uses Perl open to run it's tests. It looks something like this:

open (MYOUT, "$myprog $arg1 $arg2 $arg3 2>&1 |") die "Bad stuff happened";

What I'd really like to do is to measure the runtime of $myprog. Unfortunately, just grabbing a start time and end time around the open command just grabs roughly how long it takes to start up the process.

Is there some way of either forcing the open command to finish the process (and therefore accurately measure time) or perhaps something else that would accomplish the same thing?

Key constraints are that we need to capture (potentially a lot of) STDOUT and STDERR.

Body:
Since you open a pipe, you need to time from before opening to at least after the reading

use warnings;
use strict;
use Time::HiRes qw(gettimeofday tv_interval sleep);

my $t0 = [gettimeofday];

open my $read, '-|', qw(ls -l) or die "Can't open process: $!";

while (<$read>)
{
    sleep 0.1;
    print;
}

print "It took ", tv_interval($t0), " seconds\n";
# close pipe and check

or, to time the whole process, after calling close on the pipe (after all reading is done)

my $t0 = [gettimeofday];
open my $read, '-|', qw(ls -l)  or die "Can't open process: $!";
# ... while ($read) { ... }
close $read  or
    warn $! ? "Error closing pipe: $!" : "Exit status: $?";
print "It took ", tv_interval($t0), " seconds\n";

The close blocks and waits for the program to finish

Closing a pipe also waits for the process executing on the pipe to exit--in case you wish to look at the output of the pipe afterwards--and implicitly puts the exit status value of that command into $? [...]

For the status check see $? variable in perlvar and system

If the timed program forks and doesn't wait on its children in a blocking way this won't time them correctly.
In that case you need to identify resources that they use (files?) and monitor that.

I'd like to add that external commands should be put together carefully, to avoid shell injection trouble.  A good module is String::ShellQuote. See for example this answer and this answer

Using a module for capturing streams would free you from the shell and perhaps open other ways to run and time this more reliably. A good one is Capture::Tiny (and there are others as well).

Thanks to HåkonHægland for comments.  Thanks to ikegami for setting me straight, to use close (and not waitpid).


问:
extending an object's parameter Javascript (Coffeescript code)
I have this code:

```<code>tickets = new Object()
$(this).parents('.request-form').find('.Single').each ->
    if $(this).find('.checkBoxParent input').prop('checked')
        params = new Object()
        params.sarId = $(this).parents('.request-form').find('.sarId').text()
        params.comments = $(this).find('.commentBoxParent textarea').val()
        params.serviceId = $(this).find('.serviceId').text()
        tickets[$(this).parents('.categoryQuestions').find('.form-label').text()] = params
</code>```

The idea is that tickets will stay empty, but as it looks through the html, it will add items and a list of sub items to it.

for example, it can find a label "classrooms" and the 3 parameters for that part of the form.

Thus I want the object to look like:

tickets[classrooms][{sarId: 1, serviceId: 3, comments: "hi"}]

Then it can find another "classroom" label and I want it to append, such that the object will now look like:

tickets[classrooms][{sarId: 1, serviceId: 3, comments: "hi"}, {sarId: 1, serviceId: 6, comments: "Another comment"}]

How can I make this happen?

答:
switching it to a multidimensional array/object worked like this: </p>

```<code>    requestForm = $(this).parents('.request-form');
    tickets = {}
    requestForm.find('.Single').each ->
        #alert("this should happen... 4 times")
        focus = $(this)
        if $(this).find('.checkBoxParent input').prop('checked')
            label = $(this).parents('.categoryQuestions').find('.form-label').text()
            if (!tickets.hasOwnProperty(label))
                tickets[label] = []
            tickets[label].push({
                sarId: requestForm.find('.sarId').text(),
                comments: $(this).find('.commentBoxParent textarea').val(),
                serviceId: $(this).find('.serviceId').text()
                })
</code>```

Body:
I have this code:

tickets = new Object()
$(this).parents('.request-form').find('.Single').each ->
    if $(this).find('.checkBoxParent input').prop('checked')
        params = new Object()
        params.sarId = $(this).parents('.request-form').find('.sarId').text()
        params.comments = $(this).find('.commentBoxParent textarea').val()
        params.serviceId = $(this).find('.serviceId').text()
        tickets[$(this).parents('.categoryQuestions').find('.form-label').text()] = params

The idea is that tickets will stay empty, but as it looks through the html, it will add items and a list of sub items to it.

for example, it can find a label "classrooms" and the 3 parameters for that part of the form.

Thus I want the object to look like:

tickets[classrooms][{sarId: 1, serviceId: 3, comments: "hi"}]

Then it can find another "classroom" label and I want it to append, such that the object will now look like:

tickets[classrooms][{sarId: 1, serviceId: 3, comments: "hi"}, {sarId: 1, serviceId: 6, comments: "Another comment"}]

How can I make this happen?

Body:
switching it to a multidimensional array/object worked like this:

    requestForm = $(this).parents('.request-form');
    tickets = {}
    requestForm.find('.Single').each ->
        #alert("this should happen... 4 times")
        focus = $(this)
        if $(this).find('.checkBoxParent input').prop('checked')
            label = $(this).parents('.categoryQuestions').find('.form-label').text()
            if (!tickets.hasOwnProperty(label))
                tickets[label] = []
            tickets[label].push({
                sarId: requestForm.find('.sarId').text(),
                comments: $(this).find('.commentBoxParent textarea').val(),
                serviceId: $(this).find('.serviceId').text()
                })


问:
Type mismatch in Play controller action when recovering a future
I'm having a problem to return the correct type in a scala play controller method can someone give me a hint here? I'm using for comprehantion to deal with two service methods that returns a Future, and I would like to handle elegantly the result and the errors.

What is the best practice to do this?

```<code> def registerUser = Action { implicit request =>
    Logger.info("Start play actoin")

    RegisterForm.form.bindFromRequest.fold(
      formWithErrors => {
        BadRequest(views.html.register(formWithErrors))
      },
      formData => {

        val registerResult = for {
          reCaptchaOk <- registerUserService.checkRecaptcha(formData.gRecaptchaResponse)
          userId <- registerUserService.registerUser(formData) if reCaptchaOk
        } yield userId

        registerResult.map(
          result => Redirect(routes.DashboardController.dashboard).withSession("USER_ID" -> result.toString))
        .recover{
          e => handleRegisterError(e)
        }

      })

  }

  def handleRegisterError(cause: Throwable)(implicit request: Request[_]) : Result = {
    val form = RegisterForm.form.bindFromRequest
    cause match {
      case dae: DataAccessException =>
        val globalError = dae.getCause.asInstanceOf[PSQLException].getSQLState match {
          case "23505" => GlobalMessages(Seq(GlobalMessage(Messages("errors.db.userAlreadyExists") ,ERROR)))
          case _ => GlobalMessages(Seq(GlobalMessage(Messages("errors.system.error"),ERROR)))
        }
        BadRequest(views.html.register(form,globalError))
      case _ =>
        BadRequest(views.html.register(form))
    }
</code>```

the error:

```<code>[error] (compile:compileIncremental) Compilation failed
[info] Compiling 1 Scala source to C:\repos\scala\SocerGladiatorWeb\target\scala-2.11\classes...
[error] C:\repos\scala\SocerGladiatorWeb\app\controllers\RegisterController.scala:56: type mismatch;
[error]  found   : Throwable => play.api.mvc.Result
[error]  required: PartialFunction[Throwable,?]
[error]           e => handleRegisterError(e)
[error]             ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed
</code>```

答:
Short answer

You need a partial function to recover future failures:

```<code>    def handleRegisterError(implicit request: Request[_]): PartialFunction[Throwable, Result] = {
      case dae: DataAccessException =>
        val form = RegisterForm.form.bindFromRequest
        val globalError = dae.getCause.asInstanceOf[PSQLException].getSQLState match {
          case "23505" => GlobalMessages(Seq(GlobalMessage(Messages("errors.db.userAlreadyExists"), ERROR)))
          case _ => GlobalMessages(Seq(GlobalMessage(Messages("errors.system.error"), ERROR)))
        }
        BadRequest(views.html.register(form, globalError))
      case _ =>
        val form = RegisterForm.form.bindFromRequest
        BadRequest(views.html.register(form))
    }
</code>```

then change the controller code to

```<code>  registerResult
    .map { result =>
      Redirect(routes.DashboardController.dashboard).withSession("USER_ID" -> result.toString)
    }
    .recover {
      handleRegisterError
    }
</code>```

Also note that you need an async action, i.e.

```<code>def registerUser = Action.async { implicit request =>
  ...
}
</code>```

because you are not returning a Result but a Future[Result]. You can find more about actions in Play docs.

Details

If you look at the docs of the recover method of Future (see :T](pf:PartialFunction[Throwable,U])(implicitexecutor:scala.concurrent.ExecutionContext):scala.concurrent.Future[U]" rel="nofollow noreferrer">here) you'll see that it needs a pf: PartialFunction[Throwable, U].

Partial functions are just like normal functions but they might reject some values (for instance here, the recover method does not accept all exceptions, but only those specified in the body).
Defining a partial function needs a special syntax. It's very much like pattern matching but with no match expression.

```<code>Future(someAsyncWork).recover {
    case my: MyException => ....
    case _ => ....
}
</code>```

Here we are using a partial recover function inline, so the type will be inferred automatically but if you want to define the recover as a separate function you need to explicitly state its type.

Advanced

The partial function syntax (pattern matching with no match keyword) is very concise and handy in most situations, but sometimes you need more than that.

For instance, note that using this syntax, we had to duplicate parts of the code (val form = RegisterForm.form.bindFromRequest) in the recover function.

Although in your case there might be better solutions but you can always convert a normal function to a partial function. First you need to define a function of the type Throwable => Option[Result] and then you can use Option[R]):PartialFunction[T,R]" rel="nofollow noreferrer">Function#unlift to convert it to the desired partial function.
Also you can directly inherit from a PartialFunction and implement its two methods (apply and isDefinedAt).

Body:
I'm having a problem to return the correct type in a scala play controller method can someone give me a hint here? I'm using for comprehantion to deal with two service methods that returns a Future, and I would like to handle elegantly the result and the errors.

What is the best practice to do this?

 def registerUser = Action { implicit request =>
    Logger.info("Start play actoin")

    RegisterForm.form.bindFromRequest.fold(
      formWithErrors => {
        BadRequest(views.html.register(formWithErrors))
      },
      formData => {

        val registerResult = for {
          reCaptchaOk <- registerUserService.checkRecaptcha(formData.gRecaptchaResponse)
          userId <- registerUserService.registerUser(formData) if reCaptchaOk
        } yield userId

        registerResult.map(
          result => Redirect(routes.DashboardController.dashboard).withSession("USER_ID" -> result.toString))
        .recover{
          e => handleRegisterError(e)
        }

      })

  }

  def handleRegisterError(cause: Throwable)(implicit request: Request[_]) : Result = {
    val form = RegisterForm.form.bindFromRequest
    cause match {
      case dae: DataAccessException =>
        val globalError = dae.getCause.asInstanceOf[PSQLException].getSQLState match {
          case "23505" => GlobalMessages(Seq(GlobalMessage(Messages("errors.db.userAlreadyExists") ,ERROR)))
          case _ => GlobalMessages(Seq(GlobalMessage(Messages("errors.system.error"),ERROR)))
        }
        BadRequest(views.html.register(form,globalError))
      case _ =>
        BadRequest(views.html.register(form))
    }

the error:

[error] (compile:compileIncremental) Compilation failed
[info] Compiling 1 Scala source to C:\repos\scala\SocerGladiatorWeb\target\scala-2.11\classes...
[error] C:\repos\scala\SocerGladiatorWeb\app\controllers\RegisterController.scala:56: type mismatch;
[error]  found   : Throwable => play.api.mvc.Result
[error]  required: PartialFunction[Throwable,?]
[error]           e => handleRegisterError(e)
[error]             ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed

Body:
Short answer

You need a partial function to recover future failures:

    def handleRegisterError(implicit request: Request[_]): PartialFunction[Throwable, Result] = {
      case dae: DataAccessException =>
        val form = RegisterForm.form.bindFromRequest
        val globalError = dae.getCause.asInstanceOf[PSQLException].getSQLState match {
          case "23505" => GlobalMessages(Seq(GlobalMessage(Messages("errors.db.userAlreadyExists"), ERROR)))
          case _ => GlobalMessages(Seq(GlobalMessage(Messages("errors.system.error"), ERROR)))
        }
        BadRequest(views.html.register(form, globalError))
      case _ =>
        val form = RegisterForm.form.bindFromRequest
        BadRequest(views.html.register(form))
    }

then change the controller code to

  registerResult
    .map { result =>
      Redirect(routes.DashboardController.dashboard).withSession("USER_ID" -> result.toString)
    }
    .recover {
      handleRegisterError
    }

Also note that you need an async action, i.e.

def registerUser = Action.async { implicit request =>
  ...
}

because you are not returning a Result but a Future[Result]. You can find more about actions in Play docs.

Details

If you look at the docs of the recover method of Future (see here) you'll see that it needs a pf: PartialFunction[Throwable, U].

Partial functions are just like normal functions but they might reject some values (for instance here, the recover method does not accept all exceptions, but only those specified in the body).
Defining a partial function needs a special syntax. It's very much like pattern matching but with no match expression.

Future(someAsyncWork).recover {
    case my: MyException => ....
    case _ => ....
}

Here we are using a partial recover function inline, so the type will be inferred automatically but if you want to define the recover as a separate function you need to explicitly state its type.

Advanced

The partial function syntax (pattern matching with no match keyword) is very concise and handy in most situations, but sometimes you need more than that.

For instance, note that using this syntax, we had to duplicate parts of the code (val form = RegisterForm.form.bindFromRequest) in the recover function.

Although in your case there might be better solutions but you can always convert a normal function to a partial function. First you need to define a function of the type Throwable => Option[Result] and then you can use Function#unlift to convert it to the desired partial function.
Also you can directly inherit from a PartialFunction and implement its two methods (apply and isDefinedAt).


问:
Ui-router State Change: Keep Controller and Scope but Destroy DOM
I am using ui-router 1.0.0-beta.3, angular 1.5. So far, ui-router is awesome!

I have a root state, with some child states so far, but I noticed switching between siblings (children of the same root parent) causes complete recreation of the state I transition/go to.

I'd like to keep the scope variables around because, in my app, users may toggle some buttons, enter dates, etc, then maybe switch to another state, do something, and switch back but now all their partial work is gone. I'd also like the option to be able to destroy DOM for "inactive" states since in practice some of the states can get pretty large or users might create a lot of DOM so I'd like to keep the DOM as light as possible for some states.

I understand that ui-router-extras sticky-states feature is exactly this! And I could use the $state.includes function to target when I want to destroy DOM on some components. However, it seems ui-router-extras does not work with ui-router 1.0.0-beta.3. The author did make a port for the newer ui-router, but the release is in typescript and I am not sure how to compile that into a single js file. See: https://github.com/ui-router/sticky-states/issues/4

Perhaps I need a solution that does not use sticky-states --- any ideas? I was thinking of using a service to cache the scope values, and indeed read some other SO answers to that affect. This means that, per component, I'd need to handle which scope values to cache, etc. This is definitely a possibility, but I am wondering if anyone has any other techniques or knowledge about ui-router such that maybe there is another way to accomplish what I am after: cached controller/scope on transition change.

答:
After reading the author's typescript source code (which was a pleasure, very well-written code) from:

https://github.com/ui-router/sticky-states/blob/master/src/stickyStates.ts

I decided to migrate it to my own service in javascript, which would be compatible with ui.router 1.0.0-beta.3. By the way, ui.router 1.0.0-beta.3 is available at:

https://unpkg.com/angular-ui-router@1.0.0-beta.3/release/angular-ui-router.js

My approach was: because 1.0.0-beta.3 appears to not have the onCreate transition hook, I would decorate the $transitions.create function itself. To do this, I needed to inject a lot of helper functions and the core functionality of sticky states into the decoration. So I made the StickyStatesUtil provider to do this for me.

The migration consists of 2 parts: (1) a module called sticky-states-util, which creates the StickyStatesUtil provider, as well as a useful service for checking if a state/state-name is inactive, and an inactiveEvent, which, if set to a value, will cause $rootScope to broadcast a json map of inactive state-names for anything in the app to consume. If not set, that is skipped. And (2), the actual config block in the angular app that injects $provide and uses that to decorate the $transitions service with a new "create" function.

Since a couple others are in the same spot as me, I made this code available on github:

https://github.com/dsills22/sticky-states-ui-router-1-js


问:
sql left join clarification
I have two tables.

I need all records from table A except where there is a match in table B, then take table B's matching value

So if table A has a match with table B, then I need to exclude that value from the results (i.e take all records from table A and replace records from table A with the matching value from table B).

from my understanding I left joined the two tables on the matching column and then added a where clause to exclude the null values but I'm not sure if that is correct.

data:

```<code>tableA (col1 =ID, col2 =value)
1, 5
2, 3
3, 7

tableB (col1 =ID, col2 =value)
4, 6
2, 9

expected result:

5

9

7
</code>```

This is the closest I've gotten but I'm not sure if it's correct:

```<code>select * from tableA tblA
left join tableB tblB
on tblA.matchingColumn = tblB.matchingColumn
where tblB.matchingColumn is null
</code>```

答:
Perform a left join from tablea to tableb and use the value from a or b depending on match in tableb</p>

```<code>select tablea.id, case when tableb.id is null then tablea.value else tableb.value end value
from tablea
left join tableb on tablea.id=tableb.id
</code>```

Title: sql left join clarification

Body:
I have two tables.

I need all records from table A except where there is a match in table B, then take table B's matching value

So if table A has a match with table B, then I need to exclude that value from the results (i.e take all records from table A and replace records from table A with the matching value from table B).

from my understanding I left joined the two tables on the matching column and then added a where clause to exclude the null values but I'm not sure if that is correct.

data:

tableA (col1 =ID, col2 =value)
1, 5
2, 3
3, 7

tableB (col1 =ID, col2 =value)
4, 6
2, 9

expected result:

5

9

7

This is the closest I've gotten but I'm not sure if it's correct:

select * from tableA tblA
left join tableB tblB
on tblA.matchingColumn = tblB.matchingColumn
where tblB.matchingColumn is null

Body:
Perform a left join from tablea to tableb and use the value from a or b depending on match in tableb

select tablea.id, case when tableb.id is null then tablea.value else tableb.value end value
from tablea
left join tableb on tablea.id=tableb.id


问:
Javascript Loop through data, process and append results
I have some data a function and need to loop the data process the lat and lon of each data field through the function and if result is smaller or equal to 20 then append the name into a div in the body of the html file.
This last I know how to do.

This is where I am:

The data:

```<code>[
  {
    "name": "Paul Brooks",
    "location": {
      "lat": 52.71423653147739,
      "lon": -0.6552093528558713
    }
  },
  {
    "name": "Jason Orange",
    "location": {
      "lat": 52.030778298795856,
      "lon": 0.364888567109396
    }
  },
  {
    "name": "Mark Way",
    "location": {
      "lat": 53.41899784623413,
      "lon": -1.9138465628943413
    }
  },
  {
    "name": "Ben Bon",
    "location": {
      "lat": 52.30976192959104,
      "lon": -0.4014670363034498
    }
  },
  {
    "name": "Chris Col",
    "location": {
      "lat": 53.45301856182801,
      "lon": -1.8765834388107732
    }
  },
  {
    "name": "Von Van",
    "location": {
      "lat": 53.82771812914788,
      "lon": -0.7563793003592991
    }
  }
]
</code>```

I also have a function have will check the distance is the lat lon.

```<code>function checkDistance(lat1, lon1, lat2, lon2) {

    //do the stuff

    return result

}
</code>```

What I need to do is I need a loop that will read each lat and lon.

So something like this:

```<code>fixedlat = 51.714236;
fixedlon = 50.710236

for data... {

    var result = checkDistance(fixedlat, fixedlon, datalat, datalon);

    if (result <= 20) {

      //append data[name] to div id="resultList"

    }

}
</code>```

How can I do this?

答:
There is a .forEach() function on an array by default.
So you can create the loop as the following.

var data = [] // Your data
data.forEach(function(item){
  var datalong = item.location.lon;
  var datalat = item.location.lat;

});```

Body:
I have some data a function and need to loop the data process the lat and lon of each data field through the function and if result is smaller or equal to 20 then append the name into a div in the body of the html file.
This last I know how to do.

This is where I am:

The data:

[
  {
    "name": "Paul Brooks",
    "location": {
      "lat": 52.71423653147739,
      "lon": -0.6552093528558713
    }
  },
  {
    "name": "Jason Orange",
    "location": {
      "lat": 52.030778298795856,
      "lon": 0.364888567109396
    }
  },
  {
    "name": "Mark Way",
    "location": {
      "lat": 53.41899784623413,
      "lon": -1.9138465628943413
    }
  },
  {
    "name": "Ben Bon",
    "location": {
      "lat": 52.30976192959104,
      "lon": -0.4014670363034498
    }
  },
  {
    "name": "Chris Col",
    "location": {
      "lat": 53.45301856182801,
      "lon": -1.8765834388107732
    }
  },
  {
    "name": "Von Van",
    "location": {
      "lat": 53.82771812914788,
      "lon": -0.7563793003592991
    }
  }
]

I also have a function have will check the distance is the lat lon.

function checkDistance(lat1, lon1, lat2, lon2) {

    //do the stuff

    return result

}

What I need to do is I need a loop that will read each lat and lon.

So something like this:

fixedlat = 51.714236;
fixedlon = 50.710236

for data... {

    var result = checkDistance(fixedlat, fixedlon, datalat, datalon);

    if (result <= 20) {

      //append data[name] to div id="resultList"

    }

}

How can I do this?


问:
AFRAME - Can a cursor work with both gazing and clicking?
It seems like when you set fuse = "true", a cursor becomes tied to gazing and no longer reads mouse clicks. Isn't there a way to have both options, gazing and clicking both triggering the same events?</p>

答:
The cursor component always reads mouse clicks, even if fuse is set: https://github.com/aframevr/aframe/blob/master/src/components/cursor.js#L61

If you want to point your cursor directly on the object, like a 2D web page, see https://github.com/mayognaise/aframe-mouse-cursor-component