问:
Sum of primes below 2 million
What am i doing wrong here?

```<code>  #include<stdio.h>

    int main(){
        int i,count;
        long long int sum = 0, num;

        for(num = 1; num <= 1000; num++){
            count = 0;
            for(i = 2; i <= num / 2; i++){
                if(num % i == 0){
                    count++;
                    break;
                }
            }
            if(count == 0 && num != 1)
                sum = sum + num;
        }
        printf("Sum of prime numbers is: %d ", sum);
        return 0;
    }
</code>```

I tried to make a program that outputs the sum of all primes below nth number, n being 2 million however when i try to run it, there is a slight delay and it outputs nothing... it works well enough  for small numbers like 1000 or 100 but big numbers it just does not output anything.There are no error or bugs that i know of either. (please help, i know nothing, so guide this young one)

答:
```<code>#include<stdio.h>
#include<math.h>
int main(){
int i,count;
long long int sum=0, num;
for(num = 1;num<=1000000;num++){
 count = 0;
for(i=2;i<=sqrt(num);i++){         //change here
if(num%i==0){
 count++;
 break;
  }
  }
     if(count==0 && num!= 1)
      sum = sum + num;
      }
  printf("Sum of prime numbers is: %lld ",sum);   //and here
     return 0;
    }
</code>```

Some simple maths, while checking for prime, check up to square root of a number. And in printf() the format specifier for long long int is %lld not %d.

Title: Sum of primes below 2 million

Body:
What am i doing wrong here?

  #include<stdio.h>

    int main(){
        int i,count;
        long long int sum = 0, num;

        for(num = 1; num <= 1000; num++){
            count = 0;
            for(i = 2; i <= num / 2; i++){
                if(num % i == 0){
                    count++;
                    break;
                }
            }
            if(count == 0 && num != 1)
                sum = sum + num;
        }
        printf("Sum of prime numbers is: %d ", sum);
        return 0;
    }

I tried to make a program that outputs the sum of all primes below nth number, n being 2 million however when i try to run it, there is a slight delay and it outputs nothing... it works well enough  for small numbers like 1000 or 100 but big numbers it just does not output anything.There are no error or bugs that i know of either. (please help, i know nothing, so guide this young one)

Body:
#include<stdio.h>
#include<math.h>
int main(){
int i,count;
long long int sum=0, num;
for(num = 1;num<=1000000;num++){
 count = 0;
for(i=2;i<=sqrt(num);i++){         //change here
if(num%i==0){
 count++;
 break;
  }
  }
     if(count==0 && num!= 1)
      sum = sum + num;
      }
  printf("Sum of prime numbers is: %lld ",sum);   //and here
     return 0;
    }

Some simple maths, while checking for prime, check up to square root of a number. And in printf() the format specifier for long long int is %lld not %d.


来源: stackexchange

问:
UWP - BackgroundTask and ContactManager
I am facing the problem that if I try to access the ContactManager from a BackgroundTask I get a System.IO.FileLoadException .

The same code works well when calling it from my main application:

```<code>    public async void Run(IBackgroundTaskInstance taskInstance)
    {
        BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
        test();
        deferral.Complete();

    }

    private async void test()
    {
        ContactStore contactStore = await ContactManager.RequestStoreAsync();
    }
</code>```

The BackgroundTasks starts normally, but as soon as I call "test" the exception is thrown.

答:
Unfortunately I am now uninstalling VS2015 to install 2017 one so I can't test by my own but some of APIs are not available in Background Tasks so test the method I will mention :

1- Create a new Solution with type Class Library .

2- Put methods you want there .

3- Make the class library a reference for your background task solution .

3- Call your methods in this way classLib.className.FuncName();

4- See if it work or not.

ContentLicense: CC BY-SA 3.0

Title: UWP - BackgroundTask and ContactManager

Body:
I am facing the problem that if I try to access the ContactManager from a BackgroundTask I get a System.IO.FileLoadException .

The same code works well when calling it from my main application:

    public async void Run(IBackgroundTaskInstance taskInstance)
    {
        BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
        test();
        deferral.Complete();

    }

    private async void test()
    {
        ContactStore contactStore = await ContactManager.RequestStoreAsync();
    }

The BackgroundTasks starts normally, but as soon as I call "test" the exception is thrown.


问:
SQL export to ListView using C#
I have a query that selects 3 columns from a SQL table, I need to export the resulting query into a listview.  I don't need any help with the SQL setup, just how to format it into the listview.  There is where I am stuck.  Any help is appreciated.  Thanks!

```<code>string sql = "select distinct pro,ds,date from dbo.Sge where date IN (select max(date) from dbo.Storage) order by project";
SqlConnection con = new SqlConnection("Data Source= ;Initial Catalog= ;Integrated Security= SSPI");
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(sql,con);
adapter.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
    for(int i=0; i< ds.Tables[0].Columns.Count; i++))
}
</code>```

Edit: Sorry guys, i mentioned ListBox originally and i meant ListView. My ListView is detailed and had a column for each of my columns in my select, i just simply need the SQL export to go to the right column.

This is what I have come up with, but it doesn't add to each column, just to the first column

```<code>foreach (DataRow row in poplb6ds.Tables[0].Rows)
{
    listView1.Items.Add(row["Pro"].ToString());
    listView1.Items.Add(row["size"].ToString());
    listView1.Items.Add(row["Date"].ToString());
}
</code>```

答:
Check this out:

C# listView, how do I add items to columns 2, 3 and 4 etc?

ContentLicense: CC BY-SA 2.5

Title: SQL export to ListView using C#

Body:
I have a query that selects 3 columns from a SQL table, I need to export the resulting query into a listview.  I don't need any help with the SQL setup, just how to format it into the listview.  There is where I am stuck.  Any help is appreciated.  Thanks!

string sql = "select distinct pro,ds,date from dbo.Sge where date IN (select max(date) from dbo.Storage) order by project";
SqlConnection con = new SqlConnection("Data Source= ;Initial Catalog= ;Integrated Security= SSPI");
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(sql,con);
adapter.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
    for(int i=0; i< ds.Tables[0].Columns.Count; i++))
}

Edit: Sorry guys, i mentioned ListBox originally and i meant ListView. My ListView is detailed and had a column for each of my columns in my select, i just simply need the SQL export to go to the right column.

This is what I have come up with, but it doesn't add to each column, just to the first column

foreach (DataRow row in poplb6ds.Tables[0].Rows)
{
    listView1.Items.Add(row["Pro"].ToString());
    listView1.Items.Add(row["size"].ToString());
    listView1.Items.Add(row["Date"].ToString());
}


问:
What is the date format for this string?
I've got the following date as a string

```<code>2017-03-01T10:15:41-0800
</code>```

that I'm trying to use with

```<code>new Date().parse('dd/mm/yyyy', dateString)
</code>```

However, I can't figure out the format.

答:
Date class contains its own, static parse method (JB Nizet was wrong in his comment to your question).

For details see http://docs.groovy-lang.org/latest/html/groovy-jdk/java/util/Date.html#parse(java.lang.String,%20java.lang.String)

So if you perform this parsing only once, use just this method.

On the other hand, if you plan to perform such a conversion multiple times,
it is more efficient to create a SimpleDateFormat instance (once)
and then use it multiple times.

Body:
I've got the following date as a string

2017-03-01T10:15:41-0800

that I'm trying to use with

new Date().parse('dd/mm/yyyy', dateString)

However, I can't figure out the format.


问:
How to implement a Spring Rest client
Spring contains some nice guide how to setup a simple service for a pojo/data repository based on JPA. Unfortunately I can not find the client side implementation or a good example how to access this service via Java itself. In the example there is only shown basic curl access. Maybe I am missing some fundamental basics but in the WEB I only found some basic Rest examples and also a consuming guide by Spring itself. IMHO these are quite low level, I am looking for a more sophisticated annotation driven implementation possibility.</p>

答:
Why not look at Feign in the context of spring-cloud. It is an declarative Rest client that is originally developed at netflix and has become part of spring-cloud. It also nicely integrates some service discovery solutions that are available in the spring-cloud context.

http://projects.spring.io/spring-cloud/spring-cloud.html#spring-cloud-feign

Feign is a declarative web service client. It makes writing web
  service clients easier. To use Feign create an interface and annotate
  it. It has pluggable annotation support including Feign annotations
  and JAX-RS annotations. Feign also supports pluggable encoders and
  decoders. Spring Cloud adds support for Spring MVC annotations and for
  using the same HttpMessageConverters used by default in Spring Web.
  Spring Cloud integrates Ribbon and Eureka to provide a load balanced
  http client when using Feign.

A feign client could look like this:

```<code>@FeignClient("stores")
public interface StoreClient {
    @RequestMapping(method = RequestMethod.GET, value = "/stores")
    List<Store> getStores();

    @RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
    Store update(@PathVariable("storeId") Long storeId, Store store);
}
</code>```

Title: How to implement a Spring Rest client

Body:
Why not look at Feign in the context of spring-cloud. It is an declarative Rest client that is originally developed at netflix and has become part of spring-cloud. It also nicely integrates some service discovery solutions that are available in the spring-cloud context.

http://projects.spring.io/spring-cloud/spring-cloud.html#spring-cloud-feign

Feign is a declarative web service client. It makes writing web
  service clients easier. To use Feign create an interface and annotate
  it. It has pluggable annotation support including Feign annotations
  and JAX-RS annotations. Feign also supports pluggable encoders and
  decoders. Spring Cloud adds support for Spring MVC annotations and for
  using the same HttpMessageConverters used by default in Spring Web.
  Spring Cloud integrates Ribbon and Eureka to provide a load balanced
  http client when using Feign.

A feign client could look like this:

@FeignClient("stores")
public interface StoreClient {
    @RequestMapping(method = RequestMethod.GET, value = "/stores")
    List<Store> getStores();

    @RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
    Store update(@PathVariable("storeId") Long storeId, Store store);
}


问:
compiler error: is private within this context
I'm writing a class and when I compile, I get one error message that says, "is private within this context" and another that says, "invalid use of non-static data member".  But if I comment out everything before the addShipment function in my cpp file, it compiles just fine.  Can someone please explain to me what is different to sometimes cause an error and sometimes not, and if the two different types of errors are related.

Product.h:

```<code>#ifndef PRODUCT_H
#define PRODUCT_H

#include <iostream>

class Product {
    public:
        Product(int productID, std::string productName);
        std::string getDescription();
        void setDescription(std::string description);
        std::string getName();
        int getID();
        int getNumberSold();
        double getTotalPaid();
        int getInventoryCount();
        void addShipment(int shipmentQuantity, double shipmentCost);
        void reduceInventory(int purchaseQuantity);
        double getPrice();
    private:
        int productID;
        std::string name;
        std::string description;
        double totalPaid;
        int inventoryCount;
        int numSold;
};

#endif
</code>```

Product.cpp:

```<code>#include <iostream>
#include "Product.h"
using namespace std;

Product::Product(int productID, string productName) {
    Product::productID = productID;
    Product::name = productName;
}

string Product::getDescription() {
    return Product::description;
}

void Product::setDescription(string description) {
    Product::description = description;
}

string Product::getName() {
    return Product::name;
}

int Product::getID() {
    return Product::productID;
}

int Product::getNumberSold() {
    return Product::numSold;
}

double Product::getTotalPaid() {
    if(Product::totalPaid < 1) {
        totalPaid = 0;
    }
    return Product::totalPaid;
}

int Product::getInventoryCount() {
    Product::inventoryCount = 0;
    return Product::inventoryCount;
}

void addShipment(int shipmentQuantity, double shipmentCost) {
    Product::inventoryCount = Product::inventoryCount + shipmentQuantity;
    Product::totalPaid = Product::totalPaid + shipmentCost;
}

void reduceInventory(int purchaseQuantity) {
    Product::inventoryCount = Product::inventoryCount - purchaseQuantity;
    Product::numSold = Product::numSold + purchaseQuantity;
}

double getPrice() {
    int price = (Product::totalPaid / static_cast<double>(Product::inventoryCount + Product::numSold)) * 1.25;
    return price;
}
</code>```

答:
There are mainly 2 problems in your code, first, you are confusing static and non-static member variables and second, your last 3 functions are declared in the class declaration but you didn't qualify them with Product:: so they are free standing functions with the same names. If you intended them to be the definitions of the members, qualify them.

To fix the first point, when you have a class like the following:

```<code>struct some_class
{
    int nonstatic_member;
    static int static_member;
}
</code>```

You access the static ones using the TypeName::MemberName syntax:

```<code>some_class::static_member = 5;
</code>```

However, when a member is not static, you need an instance of that class to access the member:

```<code>some_class some_object;
some_object.nonstatic_member = 10;
</code>```

The same rules apply for member functions as well:

```<code>void some_class::some_function()
{
    some_class::nonstatic_member = 10; // error
    this->nonstatic_member = 10; // fine
    nonstatic_member = 10; // fine

    static_member = 5; // fine
    some_class::static_member = 5; // fine
}
</code>```

Since none of your member variables are static, your use of Product:: everywhere is the cause of the second error.

If you're not sure about the static member concept, here is a read: http://en.cppreference.com/w/cpp/language/static

Body:
I'm writing a class and when I compile, I get one error message that says, "is private within this context" and another that says, "invalid use of non-static data member".  But if I comment out everything before the addShipment function in my cpp file, it compiles just fine.  Can someone please explain to me what is different to sometimes cause an error and sometimes not, and if the two different types of errors are related.

Product.h:

#ifndef PRODUCT_H
#define PRODUCT_H

#include <iostream>

class Product {
    public:
        Product(int productID, std::string productName);
        std::string getDescription();
        void setDescription(std::string description);
        std::string getName();
        int getID();
        int getNumberSold();
        double getTotalPaid();
        int getInventoryCount();
        void addShipment(int shipmentQuantity, double shipmentCost);
        void reduceInventory(int purchaseQuantity);
        double getPrice();
    private:
        int productID;
        std::string name;
        std::string description;
        double totalPaid;
        int inventoryCount;
        int numSold;
};

#endif

Product.cpp:

#include <iostream>
#include "Product.h"
using namespace std;

Product::Product(int productID, string productName) {
    Product::productID = productID;
    Product::name = productName;
}

string Product::getDescription() {
    return Product::description;
}

void Product::setDescription(string description) {
    Product::description = description;
}

string Product::getName() {
    return Product::name;
}

int Product::getID() {
    return Product::productID;
}

int Product::getNumberSold() {
    return Product::numSold;
}

double Product::getTotalPaid() {
    if(Product::totalPaid < 1) {
        totalPaid = 0;
    }
    return Product::totalPaid;
}

int Product::getInventoryCount() {
    Product::inventoryCount = 0;
    return Product::inventoryCount;
}

void addShipment(int shipmentQuantity, double shipmentCost) {
    Product::inventoryCount = Product::inventoryCount + shipmentQuantity;
    Product::totalPaid = Product::totalPaid + shipmentCost;
}

void reduceInventory(int purchaseQuantity) {
    Product::inventoryCount = Product::inventoryCount - purchaseQuantity;
    Product::numSold = Product::numSold + purchaseQuantity;
}

double getPrice() {
    int price = (Product::totalPaid / static_cast<double>(Product::inventoryCount + Product::numSold)) * 1.25;
    return price;
}

Body:
There are mainly 2 problems in your code, first, you are confusing static and non-static member variables and second, your last 3 functions are declared in the class declaration but you didn't qualify them with Product:: so they are free standing functions with the same names. If you intended them to be the definitions of the members, qualify them.

To fix the first point, when you have a class like the following:

struct some_class
{
    int nonstatic_member;
    static int static_member;
}

You access the static ones using the TypeName::MemberName syntax:

some_class::static_member = 5;

However, when a member is not static, you need an instance of that class to access the member:

some_class some_object;
some_object.nonstatic_member = 10;

The same rules apply for member functions as well:

void some_class::some_function()
{
    some_class::nonstatic_member = 10; // error
    this->nonstatic_member = 10; // fine
    nonstatic_member = 10; // fine

    static_member = 5; // fine
    some_class::static_member = 5; // fine
}

Since none of your member variables are static, your use of Product:: everywhere is the cause of the second error.

If you're not sure about the static member concept, here is a read: http://en.cppreference.com/w/cpp/language/static


问:
How can I determine if a matrix is 'positive definite' via SQL?
Is there any way, purely in MSSQL, to determine if the following maxtrix would calculate out as positive definite?

```<code>A C D G H I
A 1.00 0.68 0.24 0.62 0.90 0.00
C 0.68 1.00 0.25 0.46 0.61 0.00
D 0.24 0.25 1.00 0.60 0.08 0.00
G 0.62 0.46 0.60 1.00 0.46 0.00
H 0.90 0.61 0.08 0.46 1.00 0.00
I 0.00 0.00 0.00 0.00 0.00 1.00
</code>```

Right now we're using a 3rd party app, ExtremeNumerics, to handle the determination in a rather blackbox way.  If I had a SQL table that I could enter the assets, the correlated asset and the value, would there be a way to do the math?

I poked around some and I haven't really seen anything in MSSQL that handles matrix math.

thanks.

edit: Microsoft SQL 2008

答:
Right, here we go. This works, but does give the feeling that we are having to strong-arm SQL Server into doing things it doesn't really want to. I'd be disinclined to recommend doing this in real life - it's going to scale as O(n^3) in matrix size, I'm reasonably sure. Perhaps there's a better way, doing Cholesky decomposition rather than this way - I might look into this at a later date. With the caveats out of the say, let's proceed:

This requires SQL Server 2008, for its table datatype

(and even that falls somewhat short of being as helpful as it might be, as we'll see...)

First, the approach. We're going to use Sylvester's criterion, as it's the easiest to understand: a real symmetric matrix is PD iff the determinants of all the principal minors are positive. So we'll need a way of calculating determinants. Again, we're going to use a simple approach (Laplace expansion) rather than anything designed for computational efficiency.

Groundwork

We start with defining the user-defined table type we're going to use to pass matrices around:

```<code>create type Matrix
as table ( Row int, Col int, Val float )
go
</code>```

Calculating determinants

For this, we're going to define two mutually-recursive functions, because that was the only way I could make it work given the limited capabilities of table type data in SQL Server 2008.

First, the entry point (which also handles the base case):

```<code>create function Determinant ( @matrix Matrix readonly )
returns float
as
begin
    -- Base case of recursion
    if ((select count(*) from @matrix) = 1)
        return (select Val from @matrix)
</code>```

Having established we're not at the base case (a 1x1 matrix), we now have work to do. The first thing is to 'canonicalize' the row and column numbers in our input from whatever they are now to 1..n

```<code>    -- canonicalize row and col numbers (doesn't affect answer)
    declare @rowMap table ( fr_row int, to_row int )
    declare @colMap table ( fr_col int, to_col int )

    insert @rowMap
    select row, row_number() over(order by row) from @matrix
    group by row

    insert @colMap
    select col, row_number() over(order by col) from @matrix
    group by col

    declare @canonicalMatrix Matrix
    insert @canonicalMatrix
    select
        to_row, to_col, Val
    from @matrix m
    inner join @rowMap rm on m.row = rm.fr_row
    inner join @colMap cm on m.col = cm.fr_col
</code>```

We're now ready to recursively compute the determinant using Laplace expansion. This involves a call out to our mutually-recursive comrade, which will minorize by the row and column we request, then call us back to compute the determinant of the minor

```<code>    -- apply laplace expansion on first row
    return
    (
        select sum(
            (case col % 2
            when 1 then 1   -- odd col
            when 0 then -1  -- even col
            end
            )
                    * Val
                    * dbo.DeterminantOfMinor ( @canonicalMatrix, 1, col )
            ) from @canonicalMatrix where row = 1
    )
end
go
</code>```

As it turns out DeterminantOfMinor is very simple, and wouldn't be necessary if table values were more first-class in SQL Server:

```<code>create function dbo.DeterminantOfMinor (
    @matrix Matrix readonly
    , @drop_row int
    , @drop_col int
)
returns float
as
begin

    declare @minor Matrix
    insert @minor select * from @matrix
        where row <> @drop_row and col <> @drop_col
    return
        dbo.Determinant( @minor )

end
go
</code>```

With a determinant calculator available, we're nearly there.

Testing for positive-definiteness

According to Sylvester's criterion, a matrix is PD iff the determinants of all its principal minors are positive. So we can build a (self-)recursive function to check this, the only twist being that it's worth making sure we do the cheap determinants (the smaller matrices) first:

```<code>create function dbo.is_positive_definite ( @matrix Matrix readonly )
returns bit
as
begin
    -- base case of recursion
    -- a 1x1 matrix is PD iff the single value is positive
    if ((select count(*) from @matrix) = 1)
        return (select case when Val > 0 then 1 else 0 end from @matrix)
</code>```

We build the matrix which is our input without its last row and column:

```<code>    declare @smallerMat Matrix
    insert @smallerMat
    select row, col, Val from @matrix
    where row < (select max(row) from @matrix)
    and col < (select max(col) from @matrix)
</code>```

and recurse down, only computing the determinant of our input if all our principal minors are confirmed to be PD:

```<code>    -- for our input to be PD, its smaller version must be PD:
    return
        ( select case dbo.is_positive_definite( @smallerMat )
        when 1 then
                (select case
                     when dbo.Determinant ( @matrix ) > 0
                     then 1
                     else 0
                     end)
        else 0
        end
        )

end
go
</code>```

And that's it!

Testing

I used your sample:

```<code>declare @test Matrix

insert @test values ( 1, 1, 1.00 )
insert @test values ( 1, 2, 0.68 )
insert @test values ( 1, 3, 0.24 )
/* snip */
insert @test values ( 6, 4, 0.00 )
insert @test values ( 6, 5, 0.00 )
insert @test values ( 6, 6, 1.00 )

select dbo.Determinant ( @test )
select dbo.is_positive_definite ( @test )

----------------------
0.0333962320000001

(1 row(s) affected)

-----
1

(1 row(s) affected)
</code>```

These results agree with what I got from this online calculator, so I'm happy this works.

Timings

Using the first n columns of your test data, on the system I tested on:

```<code>n   Time (s)
1   < 1
2   < 1
3   < 1
4   < 1
5   1
6   17
</code>```

Worrying trend, I'm sure you'll agree. Hence my:

Caveats

I would regard this code as no more than a proof of concept:

Execution time for calculating determinants in this naive fashion grows as O(n^3) in matrix size

This code repeatedly calculates the same values doing no memoization

There's absolutely no sanity- or error- checking - a matrix which is not square, for example, or values in the Matrix input value that don't make sense, will cause everything to fall in a heap

I have given no consideration to numerical stability, which is a must for real-world numerical calculations

That said, it's an interesting exercise and hopefully will give you some useful pointers as to how you might actually approach this in real life.

Perhaps I'll look at doing it using Cholesky decomposition at a later date...

Body:
Is there any way, purely in MSSQL, to determine if the following maxtrix would calculate out as positive definite?

A C D G H I
A 1.00 0.68 0.24 0.62 0.90 0.00
C 0.68 1.00 0.25 0.46 0.61 0.00
D 0.24 0.25 1.00 0.60 0.08 0.00
G 0.62 0.46 0.60 1.00 0.46 0.00
H 0.90 0.61 0.08 0.46 1.00 0.00
I 0.00 0.00 0.00 0.00 0.00 1.00

Right now we're using a 3rd party app, ExtremeNumerics, to handle the determination in a rather blackbox way.  If I had a SQL table that I could enter the assets, the correlated asset and the value, would there be a way to do the math?

I poked around some and I haven't really seen anything in MSSQL that handles matrix math.

thanks.

edit: Microsoft SQL 2008

Body:
Right, here we go. This works, but does give the feeling that we are having to strong-arm SQL Server into doing things it doesn't really want to. I'd be disinclined to recommend doing this in real life - it's going to scale as O(n^3) in matrix size, I'm reasonably sure. Perhaps there's a better way, doing Cholesky decomposition rather than this way - I might look into this at a later date. With the caveats out of the say, let's proceed:

This requires SQL Server 2008, for its table datatype

(and even that falls somewhat short of being as helpful as it might be, as we'll see...)

First, the approach. We're going to use Sylvester's criterion, as it's the easiest to understand: a real symmetric matrix is PD iff the determinants of all the principal minors are positive. So we'll need a way of calculating determinants. Again, we're going to use a simple approach (Laplace expansion) rather than anything designed for computational efficiency.

Groundwork

We start with defining the user-defined table type we're going to use to pass matrices around:

create type Matrix
as table ( Row int, Col int, Val float )
go

Calculating determinants

For this, we're going to define two mutually-recursive functions, because that was the only way I could make it work given the limited capabilities of table type data in SQL Server 2008.

First, the entry point (which also handles the base case):

create function Determinant ( @matrix Matrix readonly )
returns float
as
begin
    -- Base case of recursion
    if ((select count(*) from @matrix) = 1)
        return (select Val from @matrix)

Having established we're not at the base case (a 1x1 matrix), we now have work to do. The first thing is to 'canonicalize' the row and column numbers in our input from whatever they are now to 1..n

    -- canonicalize row and col numbers (doesn't affect answer)
    declare @rowMap table ( fr_row int, to_row int )
    declare @colMap table ( fr_col int, to_col int )

    insert @rowMap
    select row, row_number() over(order by row) from @matrix
    group by row

    insert @colMap
    select col, row_number() over(order by col) from @matrix
    group by col

    declare @canonicalMatrix Matrix
    insert @canonicalMatrix
    select
        to_row, to_col, Val
    from @matrix m
    inner join @rowMap rm on m.row = rm.fr_row
    inner join @colMap cm on m.col = cm.fr_col

We're now ready to recursively compute the determinant using Laplace expansion. This involves a call out to our mutually-recursive comrade, which will minorize by the row and column we request, then call us back to compute the determinant of the minor

    -- apply laplace expansion on first row
    return
    (
        select sum(
            (case col % 2
            when 1 then 1   -- odd col
            when 0 then -1  -- even col
            end
            )
                    * Val
                    * dbo.DeterminantOfMinor ( @canonicalMatrix, 1, col )
            ) from @canonicalMatrix where row = 1
    )
end
go

As it turns out DeterminantOfMinor is very simple, and wouldn't be necessary if table values were more first-class in SQL Server:

create function dbo.DeterminantOfMinor (
    @matrix Matrix readonly
    , @drop_row int
    , @drop_col int
)
returns float
as
begin

    declare @minor Matrix
    insert @minor select * from @matrix
        where row <> @drop_row and col <> @drop_col
    return
        dbo.Determinant( @minor )

end
go

With a determinant calculator available, we're nearly there.

Testing for positive-definiteness

According to Sylvester's criterion, a matrix is PD iff the determinants of all its principal minors are positive. So we can build a (self-)recursive function to check this, the only twist being that it's worth making sure we do the cheap determinants (the smaller matrices) first:

create function dbo.is_positive_definite ( @matrix Matrix readonly )
returns bit
as
begin
    -- base case of recursion
    -- a 1x1 matrix is PD iff the single value is positive
    if ((select count(*) from @matrix) = 1)
        return (select case when Val > 0 then 1 else 0 end from @matrix)

We build the matrix which is our input without its last row and column:

    declare @smallerMat Matrix
    insert @smallerMat
    select row, col, Val from @matrix
    where row < (select max(row) from @matrix)
    and col < (select max(col) from @matrix)

and recurse down, only computing the determinant of our input if all our principal minors are confirmed to be PD:

    -- for our input to be PD, its smaller version must be PD:
    return
        ( select case dbo.is_positive_definite( @smallerMat )
        when 1 then
                (select case
                     when dbo.Determinant ( @matrix ) > 0
                     then 1
                     else 0
                     end)
        else 0
        end
        )

end
go

And that's it!

Testing

I used your sample:

declare @test Matrix

insert @test values ( 1, 1, 1.00 )
insert @test values ( 1, 2, 0.68 )
insert @test values ( 1, 3, 0.24 )
/* snip */
insert @test values ( 6, 4, 0.00 )
insert @test values ( 6, 5, 0.00 )
insert @test values ( 6, 6, 1.00 )

select dbo.Determinant ( @test )
select dbo.is_positive_definite ( @test )

----------------------
0.0333962320000001

(1 row(s) affected)

-----
1

(1 row(s) affected)

These results agree with what I got from this online calculator, so I'm happy this works.

Timings

Using the first n columns of your test data, on the system I tested on:

n   Time (s)
1   < 1
2   < 1
3   < 1
4   < 1
5   1
6   17

Worrying trend, I'm sure you'll agree. Hence my:

Caveats

I would regard this code as no more than a proof of concept:

Execution time for calculating determinants in this naive fashion grows as O(n^3) in matrix size

This code repeatedly calculates the same values doing no memoization

There's absolutely no sanity- or error- checking - a matrix which is not square, for example, or values in the Matrix input value that don't make sense, will cause everything to fall in a heap

I have given no consideration to numerical stability, which is a must for real-world numerical calculations

That said, it's an interesting exercise and hopefully will give you some useful pointers as to how you might actually approach this in real life.

Perhaps I'll look at doing it using Cholesky decomposition at a later date...


问:
Cannot push an element in attribute of an object
I'm building a stack but I don't know why when try to push I get: "Cannot read property 'push' of undefined".

```<code>function stack(n) {
  return {
    size: n,
    elements: [],
    push: (item) => {
      if ( this.elements.length < this.size) {
        this.elements.push(item);
        return this.elements;
      } else {
        return this.elements.length !== n ? true : 'Stack Overflow';
      }
    },
    pop: () => {
      if (n !== 0) {
        return n !== 0 ? this.elements.pop() : 'Stack Underflow';
      }
    },
    isEmpty: () => {
      return this.elements === undefined;
    },
    isFull: () => {
      return elements.length === n ? true : false;
    },
  };
};
</code>```

What is happening? Thanks a lot.

答:
I modified your code a bit and it works fine. Basically it inits a stack with size n, n = number. Then it performs the methods relative to the size n.

```<code> function stack(n) {
  return {
    size: n,
    elements: [],
    push: function(item){
      if (this.elements.length < this.size) {
        this.elements.push(1);
        return this.elements;
      } else {
        return 'Stack Overflow';
      }
    },
    pop: function(){
        return (this.size !== 0 && this.elements.length) ? this.elements.pop() : 'Stack Underflow';
    },
    isEmpty: function(){
      return (this.elements.length < this.size) ? true : false;
    },
    isFull: function(){
      return (this.elements.length == this.size) ? true : false;
    },
  };
};
</code>```

initialize your stack here with a size.

```<code>var init = stack(2);
</code>```

now call the methods to see whats it doing.

```<code>    init.pop()
   "Stack Underflow"

    init.isEmpty()
    true

    init.isFull();
    false

    init.push(33)
    [1]

    init.push(67)
    [1, 1]

    init.push(3432)
    "Stack Overflow"
</code>```

Body:
I'm building a stack but I don't know why when try to push I get: "Cannot read property 'push' of undefined".

function stack(n) {
  return {
    size: n,
    elements: [],
    push: (item) => {
      if ( this.elements.length < this.size) {
        this.elements.push(item);
        return this.elements;
      } else {
        return this.elements.length !== n ? true : 'Stack Overflow';
      }
    },
    pop: () => {
      if (n !== 0) {
        return n !== 0 ? this.elements.pop() : 'Stack Underflow';
      }
    },
    isEmpty: () => {
      return this.elements === undefined;
    },
    isFull: () => {
      return elements.length === n ? true : false;
    },
  };
};

What is happening? Thanks a lot.

Body:
I modified your code a bit and it works fine. Basically it inits a stack with size n, n = number. Then it performs the methods relative to the size n.

 function stack(n) {
  return {
    size: n,
    elements: [],
    push: function(item){
      if (this.elements.length < this.size) {
        this.elements.push(1);
        return this.elements;
      } else {
        return 'Stack Overflow';
      }
    },
    pop: function(){
        return (this.size !== 0 && this.elements.length) ? this.elements.pop() : 'Stack Underflow';
    },
    isEmpty: function(){
      return (this.elements.length < this.size) ? true : false;
    },
    isFull: function(){
      return (this.elements.length == this.size) ? true : false;
    },
  };
};

initialize your stack here with a size.

var init = stack(2);

now call the methods to see whats it doing.

    init.pop()
   "Stack Underflow"

    init.isEmpty()
    true

    init.isFull();
    false

    init.push(33)
    [1]

    init.push(67)
    [1, 1]

    init.push(3432)
    "Stack Overflow"


问:
Apply CSS conditionally to last list item without JavaScript
Say you have a list of items:

```<code><li>abc</li>
<li>efg</li>
<li>hij</li>
</code>```

You want the last item to be red, but only if there is more than one
, is that possible without JavaScript?

答:
you can try using nth-child.

For example if you have an ordered list and you want to target the 2nd li you use the code as below:

ul ol:nth-last-child(2){color:#ff0000;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <ul>
    <ol>list 1</ol>
    <ol>list 2</ol>
    <ol>list 3</ol>
    <ul></code>```

Once you run the code you will see the last child of the UL is colored red.

Body:
Say you have a list of items:

abc

efg

hij

You want the last item to be red, but only if there is more than one
, is that possible without JavaScript?

Body:
you can try using nth-child.

For example if you have an ordered list and you want to target the 2nd li you use the code as below:

ul ol:nth-last-child(2){color:#ff0000;}

    <ul>
    <ol>list 1</ol>
    <ol>list 2</ol>
    <ol>list 3</ol>
    <ul>

Once you run the code you will see the last child of the UL is colored red.


问:
Run a command in a shell and keep running the command when you close the session
I am using Putty to connect to a remote server. What I want to know is if there is any way to write my commands and allow them to keep running after I close the session with Putty. The reason for this is that I do not want to keep the computer ON all the time. Is there any way to do this?.

Update with the solution

For my question as it is presented the best solution is use one of the commands provided such as nohup, because you do not have to install any additional software. But if you are in the same problem use screen, install it and use it. It is amazing.

I have selected the answer of Norman Ramsey as favourite because propose several solutions using commands and screen. But please check the other answers specially the one of PEZ, then you get an insight of what screen is able todo.

答:
screen! It's the best thing since sliced bread. (Yeah, I know others have already suggested it, but it's so good the whole world should join in and suggest it too.)

screen is like, like, ummmm ... like using VNC or the like to connect to a GUI destop, but for command shell windows. You can have several shell "windows" open at once in the same screen session. You can do stuff like:

Start a screens session using "screen -dR" (get used to using -dR)

run some commands in one window

press CTRL-A,C to create a new window open a file there in vim

press CTRL-A,0 to go back to the first window and issue some command on the file you just edited

CTRL-A, 1 to go back to your vim session

CTRL-A, C for yet another window and maybe do "sudo - su" (because you just happen to need a full root shell)

CTRL-A, 0 and start a background process

CTRL-A, C to create yet a new window, "tail -f" the log for that background process

CTRL-A, d to disconnect your screen then CTRL-D to disconnect from the server

Go on vacation for three weeks

Log on to the server again and issue "screen -dR" to connect to your existing screen session

check the log in the the fourth window with CTRL-A, 3 (it's like you've been there watching it all the time)

CTRL-A, 1 to pick up that vim session again

I guess you're starting to get the picture now? =)

It's like magic. I've been using screen for longer than I can remember and I'm still totally amazed with how bloody great it is.

EDIT: Just want to mention there's now also tmux. Very much like screen, but has some unique features, splitting the windows being the most prominent one.

OwnerDisplayName: Eduardo

LastEditorDisplayName: Eduardo

OwnerDisplayName: PEZ

LastEditorDisplayName: PEZ


问:
Do I have to pay an annual fee, simply to test/deploy my software on my own phone?
I cant see any way to get around this...</p>

答:
You can use Chevron WP7 to unlock your device to install applications that aren't on the Marketplace, like self-made apps.
http://www.chevronwp7.com/</p>


问:
Progress bar according to countdown
I want to display a progress bar based on a countdown of 7 minutes that is displayed in a div:
 0:06:24

I need if the page is reloaded don´t reset the progress bar. Would it be possible with CSS and a script that the bar represents what the timer displays?

I use this css progress bar:

```<code> #quiz-time-left {
width: 0;
    height: 100%;
    -webkit-animation: progreso 420s linear;
            animation: progreso 420s linear;
color: #eb7260;
background: #eb7260;
 }
#page-mod-quiz-summary #quiz-timer {
    text-align: center;
    display: none;
position: absolute;
    left: -50px;
    top: -50px;
}
#quiz-timer {
border: 2px solid #eb7260;
text-indent: -9999px;
display:block;
    font-size: 0px;
    height: 35px;
}
@-webkit-keyframes progreso {
    0% {
        width: 100%;;
    }
    100% {
        width: 0;
    }
}

@keyframes progreso {
    0% {
        width: 100%;
    }
    100% {
        width: 0;
    }
}
</code>```

html

```<code><div id="quiz-timer" role="timer" aria-atomic="true" aria-relevant="text" style="display: block;">Time left: <div id="quiz-time-left">0:06:41</div></div>
</code>```

Thank you. Best regards.

答:
What you can do is using localStorage to store the current state of the timer and each second decrease this number.

So when the page has finished loading, test if localStorage is undefined, if it is then set it to 420. If localStorage != undefined then resume the animation from the time stored in localStorage.

Title: Progress bar according to countdown

Body:
I want to display a progress bar based on a countdown of 7 minutes that is displayed in a div:
 0:06:24

I need if the page is reloaded don´t reset the progress bar. Would it be possible with CSS and a script that the bar represents what the timer displays?

I use this css progress bar:

 #quiz-time-left {
width: 0;
    height: 100%;
    -webkit-animation: progreso 420s linear;
            animation: progreso 420s linear;
color: #eb7260;
background: #eb7260;
 }
#page-mod-quiz-summary #quiz-timer {
    text-align: center;
    display: none;
position: absolute;
    left: -50px;
    top: -50px;
}
#quiz-timer {
border: 2px solid #eb7260;
text-indent: -9999px;
display:block;
    font-size: 0px;
    height: 35px;
}
@-webkit-keyframes progreso {
    0% {
        width: 100%;;
    }
    100% {
        width: 0;
    }
}

@keyframes progreso {
    0% {
        width: 100%;
    }
    100% {
        width: 0;
    }
}

html

Time left:
0:06:41

Thank you. Best regards.


问:
How to set different color to some text of a textiew and make that text clickable?
In my app i want to use a text view that should have half of its text black and second half should be green, also i want the green part to be clickable.
I found some posts that show how to change color or how to make clickable but i am unable to find a combination of both. i have implemented this idea by myself, but the problem is that the string that should be clickable is not clickable. How to fix this?
Any help will be appreciated.
Here is my code</p>

```<code>String firststring="Hello i am a textiew";
lString secondstring="ClickMe";
SpannableStringBuilder builder = new SpannableStringBuilder();
SpannableString firstStringSpannable = new SpannableString(firststring);
firstStringSpannable .setSpan(new ForegroundColorSpan(Color.BLACK), 0, firststring.length(), 0);
builder.append(firstStringSpannable );

String space = " ";
SpannableString spaceSpannable = new SpannableString(space);
builder.append(spaceSpannable);

SpannableString secondSpannable = new SpannableString(secondstring);
secondSpannable .setSpan(new ForegroundColorSpan(Color.GREEN), 0,
builder.append(secondSpannable );

textview.setText(builder, TextView.BufferType.SPANNABLE);
String comepleteString = firststring + " " + secondstring;
SpannableString spannableString = new SpannableString(comepleteString);
int startIndex = comepleteString.indexOf(secondstring);
int endIndex = startIndex + secondstring.length();

Spannable Spannable = (Spannable) textview.getText();
ClickableSpan myClickableSpan = new ClickableSpan() {
    @Override
    public void onClick(View widget) {
//performing some function
    }
};
Spannable.setSpan(myClickableSpan, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
</code>```

答:
first of all you can put two textview one by one horizontally.
than after activity class count character of given string than after split two same numbering (example : 26 char having than divide by 2 so basically ans will be 13 char in first text view and second 13 char in second textview)

how to work this:

```<code>string msg;
int lenght = msg.length();
int half = lenght/2;

String msg1 = msg.subString(0,half);
String msg2 = msg.subString(half,lenght);
</code>```

This two string set on your two textView and which you want click event than plz manage it on your requirement textView also you con change color of textview by programmatically or xml file also

Body:
In my app i want to use a text view that should have half of its text black and second half should be green, also i want the green part to be clickable.
I found some posts that show how to change color or how to make clickable but i am unable to find a combination of both. i have implemented this idea by myself, but the problem is that the string that should be clickable is not clickable. How to fix this?
Any help will be appreciated.
Here is my code

String firststring="Hello i am a textiew";
lString secondstring="ClickMe";
SpannableStringBuilder builder = new SpannableStringBuilder();
SpannableString firstStringSpannable = new SpannableString(firststring);
firstStringSpannable .setSpan(new ForegroundColorSpan(Color.BLACK), 0, firststring.length(), 0);
builder.append(firstStringSpannable );

String space = " ";
SpannableString spaceSpannable = new SpannableString(space);
builder.append(spaceSpannable);

SpannableString secondSpannable = new SpannableString(secondstring);
secondSpannable .setSpan(new ForegroundColorSpan(Color.GREEN), 0,
builder.append(secondSpannable );

textview.setText(builder, TextView.BufferType.SPANNABLE);
String comepleteString = firststring + " " + secondstring;
SpannableString spannableString = new SpannableString(comepleteString);
int startIndex = comepleteString.indexOf(secondstring);
int endIndex = startIndex + secondstring.length();

Spannable Spannable = (Spannable) textview.getText();
ClickableSpan myClickableSpan = new ClickableSpan() {
    @Override
    public void onClick(View widget) {
//performing some function
    }
};
Spannable.setSpan(myClickableSpan, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

Body:
first of all you can put two textview one by one horizontally.
than after activity class count character of given string than after split two same numbering (example : 26 char having than divide by 2 so basically ans will be 13 char in first text view and second 13 char in second textview)

how to work this:

string msg;
int lenght = msg.length();
int half = lenght/2;

String msg1 = msg.subString(0,half);
String msg2 = msg.subString(half,lenght);

This two string set on your two textView and which you want click event than plz manage it on your requirement textView also you con change color of textview by programmatically or xml file also


答:
You can use CSS :first-child and :last-child selectors, and you have different options to achieve this:

Play with definitions order

Define first-child styles after defining last-child, so the last-child styles are overwritten by first-child styles.

ul li:last-child{
  color: red;
}

ul li:first-child{
  color: inherit;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>First element</li>
</ul>

<ul>
  <li>First element</li>
  <li>Second element</li>
  <li>Third element</li>
</ul></code>```

Use !important

Define first-child styles with !important, so they takes preference over last-child styles.

ul li:first-child{
  color: inherit !important;
}

ul li:last-child{
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>First element</li>
</ul>

<ul>
  <li>First element</li>
  <li>Second element</li>
  <li>Third element</li>
</ul></code>```

Use a selector with a heavier preference

id and class selectors in CSS have a heavier preference than tag selectors, so if you define the first-child with one of these, it will have more importance than the last-child who is defined in a tag selector.

.list li:first-child{
  color: inherit;
}

ul li:last-child{
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="list">
  <li>First element</li>
</ul>

<ul class="list">
  <li>First element</li>
  <li>Second element</li>
  <li>Third element</li>
</ul></code>```

CSS conditionals

As @george said on his answer, you can simply use the CSS :not() conditional to check that the last-child isn't also first-child. That is the best option for your specific case.

li:last-child:not(:first-child) {
  color: red
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>First element</li>
</ul>

<ul>
  <li>First element</li>
  <li>Second element</li>
  <li>Third element</li>
</ul></code>```

Title: Apply CSS conditionally to last list item without JavaScript

Body:
You can use CSS :first-child and :last-child selectors, and you have different options to achieve this:

Play with definitions order

Define first-child styles after defining last-child, so the last-child styles are overwritten by first-child styles.

ul li:last-child{
  color: red;
}

ul li:first-child{
  color: inherit;
}

<ul>
  <li>First element</li>
</ul>

<ul>
  <li>First element</li>
  <li>Second element</li>
  <li>Third element</li>
</ul>

Use !important

Define first-child styles with !important, so they takes preference over last-child styles.

ul li:first-child{
  color: inherit !important;
}

ul li:last-child{
  color: red;
}

<ul>
  <li>First element</li>
</ul>

<ul>
  <li>First element</li>
  <li>Second element</li>
  <li>Third element</li>
</ul>

Use a selector with a heavier preference

id and class selectors in CSS have a heavier preference than tag selectors, so if you define the first-child with one of these, it will have more importance than the last-child who is defined in a tag selector.

.list li:first-child{
  color: inherit;
}

ul li:last-child{
  color: red;
}

<ul class="list">
  <li>First element</li>
</ul>

<ul class="list">
  <li>First element</li>
  <li>Second element</li>
  <li>Third element</li>
</ul>

CSS conditionals

As @george said on his answer, you can simply use the CSS :not() conditional to check that the last-child isn't also first-child. That is the best option for your specific case.

li:last-child:not(:first-child) {
  color: red
}

<ul>
  <li>First element</li>
</ul>

<ul>
  <li>First element</li>
  <li>Second element</li>
  <li>Third element</li>
</ul>


问:
How to copy only the commit messages of Android Studio from log of Version Control

When i block and copy those logs, it will copy the hash, committer, and time too.
For example:

```<code>7e15726 hendrawd on 11/13/16 at 10:18 PM Merge remote-tracking branch 'origin/master'
a464db8 hendrawd on 11/13/16 at 10:16 PM fix ignored files
094ef35 Hendra Wijaya Djiono on 11/10/16 at 4:59 PM Swipe refresh will refresh notification count too
4759306 Hendra Wijaya Djiono on 11/10/16 at 12:51 PM Restructure
33ad61b Hendra Wijaya Djiono on 11/10/16 at 12:46 PM Fix force closed when crop picture on create group
8763667 Hendra Wijaya Djiono on 11/9/16 at 7:02 PM Fix duplicate notification
</code>```

I don't remember when it was implemented, maybe in Android Studio 2.2. It used to be just copy commit messages.

So how i can get only commit messages? Because i just need that instead of the full detail and it is very inconvenience to edit the lines one by one to just get the commit messages.

My Android Studio version is:

```<code>Android Studio 2.3
Build #AI-162.3764568, built on February 24, 2017
JRE: 1.8.0_112-release-b06 x86_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
</code>```

答: Android studio is not support to export the messages directly (no such button or setting). But you can use git command in Terminal window on android studio.

Body:
When i block and copy those logs, it will copy the hash, committer, and time too.
For example:

7e15726 hendrawd on 11/13/16 at 10:18 PM Merge remote-tracking branch 'origin/master'
a464db8 hendrawd on 11/13/16 at 10:16 PM fix ignored files
094ef35 Hendra Wijaya Djiono on 11/10/16 at 4:59 PM Swipe refresh will refresh notification count too
4759306 Hendra Wijaya Djiono on 11/10/16 at 12:51 PM Restructure
33ad61b Hendra Wijaya Djiono on 11/10/16 at 12:46 PM Fix force closed when crop picture on create group
8763667 Hendra Wijaya Djiono on 11/9/16 at 7:02 PM Fix duplicate notification

I don't remember when it was implemented, maybe in Android Studio 2.2. It used to be just copy commit messages.

So how i can get only commit messages? Because i just need that instead of the full detail and it is very inconvenience to edit the lines one by one to just get the commit messages.

My Android Studio version is:

Android Studio 2.3
Build #AI-162.3764568, built on February 24, 2017
JRE: 1.8.0_112-release-b06 x86_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o


问:
Reading non-js files in node js with combination of typescript and webpack
I have a backend NodeJS setup written in TypeScript and using webpack to compile it.

When I try to read a text file I get this error while I made sure that source/test.txt is getting copied to build folder.

Error:

```<code>fs.js:640
  return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
                 ^

Error: ENOENT: no such file or directory, open '/source/test.txt'
    at Error (native)
    at Object.fs.openSync (fs.js:640:18)
    at Object.fs.readFileSync (fs.js:508:33)
</code>```

My Project Structure

```<code>project
-- build
-- server
---- server.tsx
---- source
------ test.txt
</code>```

server.tsx

```<code>import * as express from 'express'
import * as Path from 'path'
import * as fs from 'fs'

const app = express()

const textFile = fs.readFileSync(Path.join(__dirname, "./source/test.txt"))

app.listen(3000, () => console.log(`running on port 3000`))
</code>```

$ webpack && node build/server.js

tsconfig.json

```<code>{
    "compilerOptions": {
        "outDir": "./build",
        "sourceMap": false,
        "noImplicitAny": false,
        "module": "commonjs",
        "target": "es5",
        "strictNullChecks": true
    },
    "include": [
        "./server/**/*"
    ],
    "exclude": [
        "node_modules"
    ]
}
</code>```

webpack.config.js

```<code>const CopyWebpackPlugin = require('copy-webpack-plugin')
const Path = require('path')

module.exports = {
    entry: "./server/server.tsx",
    target: 'node',
    output: {
        filename: "server.js",
        path: __dirname + "/build"
    },

    resolve: {
        extensions: [".ts", ".tsx", ".js", ".json"]
    },

    module: {
        rules: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
            { test: /\.tsx?$/, loader: "awesome-typescript-loader" },

            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            { enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
        ]
    },

    plugins: [
      new CopyWebpackPlugin([
        { from: Path.join(__dirname, './server/source'), to: Path.join(__dirname, './build/source') }
      ])
    ]
};
</code>```

答:
__dirname is being set to / by webpack. Currently it tries to find /source/test.txt as the error messages says, which is the root of your file system. You can tell webpack not to inject the __dirname by setting node.dirname to false, so it will correctly use the Node.js __dirname:

```<code>node: {
  __dirname: false
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a backend NodeJS setup written in TypeScript and using webpack to compile it.

When I try to read a text file I get this error while I made sure that source/test.txt is getting copied to build folder.

Error:

fs.js:640
  return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
                 ^

Error: ENOENT: no such file or directory, open '/source/test.txt'
    at Error (native)
    at Object.fs.openSync (fs.js:640:18)
    at Object.fs.readFileSync (fs.js:508:33)

My Project Structure

project
-- build
-- server
---- server.tsx
---- source
------ test.txt

server.tsx

import * as express from 'express'
import * as Path from 'path'
import * as fs from 'fs'

const app = express()

const textFile = fs.readFileSync(Path.join(__dirname, "./source/test.txt"))

app.listen(3000, () => console.log(`running on port 3000`))

$ webpack && node build/server.js

tsconfig.json

{
    "compilerOptions": {
        "outDir": "./build",
        "sourceMap": false,
        "noImplicitAny": false,
        "module": "commonjs",
        "target": "es5",
        "strictNullChecks": true
    },
    "include": [
        "./server/**/*"
    ],
    "exclude": [
        "node_modules"
    ]
}

webpack.config.js

const CopyWebpackPlugin = require('copy-webpack-plugin')
const Path = require('path')

module.exports = {
    entry: "./server/server.tsx",
    target: 'node',
    output: {
        filename: "server.js",
        path: __dirname + "/build"
    },

    resolve: {
        extensions: [".ts", ".tsx", ".js", ".json"]
    },

    module: {
        rules: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
            { test: /\.tsx?$/, loader: "awesome-typescript-loader" },

            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            { enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
        ]
    },

    plugins: [
      new CopyWebpackPlugin([
        { from: Path.join(__dirname, './server/source'), to: Path.join(__dirname, './build/source') }
      ])
    ]
};

Body:
__dirname is being set to / by webpack. Currently it tries to find /source/test.txt as the error messages says, which is the root of your file system. You can tell webpack not to inject the __dirname by setting node.dirname to false, so it will correctly use the Node.js __dirname:

node: {
  __dirname: false
}


问:
javascript/browser: when does event dispatching exactly happen?
This SO question & answers and DOM level3 docs states that manual events are dispatched synchronously in browsers. My question, however, relates to user-related events (real clicks), not manually triggered ones.

I created a small jsfiddle demo with a button + onclick handler, the handler does some synchronous work for 2 seconds (blocking sync wait, long enough for my eye to see what's going on). Open console to see console.logs.

The test. I click several times on the button. Although the first click (and its synchronous processing) makes the button pushed down (looks like disabled), other clicks are stored as well and processed later, asynchronously, via event loop.

The questions are:

when does event dispatching exactly happen? Are user events (e.g. a click) immediately pushed to JS message queue or is there an intermediate Web API queue... or in other words - which queue is this event dispatching related to?

what does it mean that most events (click, blur, etc - except for load) are processed synchronously in case of user events (not manual ones)? Given the test above, 1st click makes synchronous blocking callback executed (I expect nothing else to happen in the meantime) and, anyway, next clicks are stored in a queue. So storing events is parallel anyway (has to be, since main javascirpt thread is busy). Would there be any difference, theoretically, it events were processed asynchronously?

slightly modified demo shows that for a given click event, the event bubbles up and calls all related event handlers, like if event bubbling was blocking, until anything else (timeout in this example) can happen. But still it's not clear why is event dispatching synchronous.

答:
It makes little sense to speak of synchronous in the context of real events, since the event queue is only processed when the current execution stack has been emptied, i.e. when there is no more synchronous code to execute. That makes the related event handlers asynchronous. This is also true for the click event handler you provided in a fiddle.

That the running code blocks any other action while it runs is no indication of how that code was triggered: asynchronously or synchronously. In both cases a busy loop for 2 seconds will be blocking for 2 seconds. When we say code runs asynchronously, it only says something of how/when the code was invoked, not on how it runs. Both synchronous and asynchronous code run in a way that they are blocking. There are some exceptions to this -- for instance web workers run in their own thread.

These "real" events are pushed on the JS message queue. Of course, they first are consumed from an OS event queue, but this is  implementation specific. The important thing is that they end up in the JS message queue, together with a handler for them. The JavaScript engine only processes events when the previously running code ran to completion. By consequence these event handlers are called asynchronously.

In case of "manual" events, i.e. events triggered by code such as jQuery's .trigger() method, there is a sense in making the difference between asynchronous and synchronous. In the asynchronous case, the event would be put on the JS queue, and the current code would first run to completion. In the synchronous case, the event would not be put on the JS queue, but be executed like a function call. So the handling of the event happens as an additional call on the call stack, after which your code will resume, just like after the return from a normal function call: this is synchronous behaviour.

I ignore here the concept of micro tasks, which just means there are different priorities for executing asynchronous code.


答:
You are referring to The JavaScript Event Loop.

To answer your question as to why dispatching, also known as processing items off the message queue, happens synchronously: JavaScript is single threaded, so there is no way 2 messages could be processing at exactly the same time.

Some extra information about the JS Event Loop:

In web browsers, messages are added any time an event occurs and there
  is an event listener attached to it. If there is no listener, the
  event is lost. So a click on an element with a click event handler
  will add a message--likewise with any other event.

Taken from https://developer.mozilla.org/nl/docs/Web/JavaScript/EventLoop

And here's a different take on that, taken from
http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/:

JavaScript runtimes contain a message queue which stores a list of
  messages to be processed and their associated callback functions.
  These messages are queued in response to external events (such as a
  mouse being clicked or receiving the response to an HTTP request)
  given a callback function has been provided. If, for example a user
  were to click a button and no callback function was provided – no
  message would have been enqueued.

And here's the part about synchronous processing items off the message queue:

In a loop, the queue is polled for the next message (each poll
  referred to as a “tick”) and when a message is encountered, the
  callback for that message is executed.

And finally:

Would there be any difference, theoretically, it events were processed asynchronously?

Totally. If you were to expect three queue'd messages to log 1, 2 and 3 somewhere, it might log the sequence in an alternate order, like 2, 1, 3.

Title: javascript/browser: when does event dispatching exactly happen?

Body:
This SO question & answers and DOM level3 docs states that manual events are dispatched synchronously in browsers. My question, however, relates to user-related events (real clicks), not manually triggered ones.

I created a small jsfiddle demo with a button + onclick handler, the handler does some synchronous work for 2 seconds (blocking sync wait, long enough for my eye to see what's going on). Open console to see console.logs.

The test. I click several times on the button. Although the first click (and its synchronous processing) makes the button pushed down (looks like disabled), other clicks are stored as well and processed later, asynchronously, via event loop.

The questions are:

when does event dispatching exactly happen? Are user events (e.g. a click) immediately pushed to JS message queue or is there an intermediate Web API queue... or in other words - which queue is this event dispatching related to?

what does it mean that most events (click, blur, etc - except for load) are processed synchronously in case of user events (not manual ones)? Given the test above, 1st click makes synchronous blocking callback executed (I expect nothing else to happen in the meantime) and, anyway, next clicks are stored in a queue. So storing events is parallel anyway (has to be, since main javascirpt thread is busy). Would there be any difference, theoretically, it events were processed asynchronously?

slightly modified demo shows that for a given click event, the event bubbles up and calls all related event handlers, like if event bubbling was blocking, until anything else (timeout in this example) can happen. But still it's not clear why is event dispatching synchronous.


问:
How should I index my columns in my MySQL table?
I have a simple SQL table designed as such:

```<code>id, username, platform, time
</code>```

The Id and Username are strings, Platform and Time are ints.

I'm getting slow queries with 1 million rows, especially when I'm ordering the top rows by time played. How could I improve all my use cases in one pass?

I need to:

paginate, ordered by descending time played

get the row number of a id / username / platform combo

update the time played on a id / username / platform combo

Thank you for you help.

Edit:

Here are the queries.

```<code>SELECT *
FROM (SELECT @rownum:=@rownum+1 `rank`, `id`
FROM leaderboard, (SELECT @rownum:=0) r ORDER BY `time` DESC)
AS `ranks` WHERE `id`=:id;

SELECT *
FROM leaderboard
ORDER BY `time` DESC
LIMIT 10 OFFSET :page;

REPLACE INTO leaderboard
(`platform`, `id`, `username`, `time`)
VALUES (:platform, :id, :username, :time);
</code>```

答:
To order by descending time, you want an index on t(time).  This assumes that there are no where clauses or group by clauses in the query.

To access by id/username/platform combos, you want an index on (id, username, platform).  This assumes that the comparisons are all equality and connect by a and.

Body:
I have a simple SQL table designed as such:

id, username, platform, time

The Id and Username are strings, Platform and Time are ints.

I'm getting slow queries with 1 million rows, especially when I'm ordering the top rows by time played. How could I improve all my use cases in one pass?

I need to:

paginate, ordered by descending time played

get the row number of a id / username / platform combo

update the time played on a id / username / platform combo

Thank you for you help.

Edit:

Here are the queries.

SELECT *
FROM (SELECT @rownum:=@rownum+1 `rank`, `id`
FROM leaderboard, (SELECT @rownum:=0) r ORDER BY `time` DESC)
AS `ranks` WHERE `id`=:id;

SELECT *
FROM leaderboard
ORDER BY `time` DESC
LIMIT 10 OFFSET :page;

REPLACE INTO leaderboard
(`platform`, `id`, `username`, `time`)
VALUES (:platform, :id, :username, :time);


问:
Require paths for rspec tests in a Ruby Gem
I am creating a simple Ruby Gem which is currently laid out as per the example in the Making your own gem documentation.

My directory structure:

```<code>.
├── Gemfile
├── Gemfile.lock
├── lib
│   ├── go_run
│   │   ├── parser.rb
│   │   └── runner.rb
│   └── go_run.rb
└── spec
    ├── go_run_spec.rb
    ├── parser_spec.rb
    └── runner_spec.rb
</code>```

I originally called the Runner class in lib/go_run/runner.rb just Runner, but now, as per the documented example I have namespaced it under GoRun::Runner. The code works. The problem is that now running bundle exec rspec spec/parser_spec.rb does not. It fails with:

```<code>/home/smurf/dev/ruby/go_run/lib/go_run/parser.rb:3:in `<top (required)>': uninitialized constant GoRun (NameError)
</code>```

The 3rd line of that file is:

```<code>class GoRun::Parser
</code>```

I am requireing the library code in spec/parser_spec.rb using require 'go_run/parser'.

I tried including it with require_relative '../lib/go_run/parser', but that produced the same error.

Does anybody know what I am doing wrong?

Update: I have uploaded the complete code on this branch: https://github.com/henrytk/go_run/tree/stackoverflow-43155117

答:
The problem is originating in lib/go_run/parser.rb rather than from the test itself. Whenever Ruby finds the GoRun::Parser definition, it goes looking for GoRun in the constant lookup table, but it won't be there, and so the program exits with an error.

Note that using lib/go_run.rb as an entry point also will not work, because go_run/parser.rb is required before GoRun is defined.

Part of the problem is using GoRun as both the project level namespace, and an entry point class.

There are a couple of idioms you should consider to fix this situation:

Make GoRun a top level module, used purely for namespacing. Move the logic that lives in the current logic into its own class, for example go_run/cli.rb. The go_run.rb file is then kept as a sort of manifest file, that requires the classes of your project.

Use the nested module- and class syntax. This will define the outer module if it isn't already.

Use a spec_helper.rb file that bootstraps your project using require 'go_run', to make sure everything is properly loaded before running your tests.

Body:
I am creating a simple Ruby Gem which is currently laid out as per the example in the Making your own gem documentation.

My directory structure:

.
├── Gemfile
├── Gemfile.lock
├── lib
│   ├── go_run
│   │   ├── parser.rb
│   │   └── runner.rb
│   └── go_run.rb
└── spec
    ├── go_run_spec.rb
    ├── parser_spec.rb
    └── runner_spec.rb

I originally called the Runner class in lib/go_run/runner.rb just Runner, but now, as per the documented example I have namespaced it under GoRun::Runner. The code works. The problem is that now running bundle exec rspec spec/parser_spec.rb does not. It fails with:

/home/smurf/dev/ruby/go_run/lib/go_run/parser.rb:3:in `<top (required)>': uninitialized constant GoRun (NameError)

The 3rd line of that file is:

class GoRun::Parser

I am requireing the library code in spec/parser_spec.rb using require 'go_run/parser'.

I tried including it with require_relative '../lib/go_run/parser', but that produced the same error.

Does anybody know what I am doing wrong?

Update: I have uploaded the complete code on this branch: https://github.com/henrytk/go_run/tree/stackoverflow-43155117


问:
How would browser cookies look from TCP server point of view?
So imagine we have TCP server recieving all browser requests. How a cookie generated by some JavaScript function like:

```<code>function writeCookie()
{

var the_cookie = "users_resolution="+ screen.width +"x"+ screen.height;

document.cookie=the_cookie

location = location.href;
}
</code>```

Will loock  if some browser like chrome will come to such server? what will full page requesl look like?

答: Fire up WireShark and take a look.</p>

Body:
So imagine we have TCP server recieving all browser requests. How a cookie generated by some JavaScript function like:

function writeCookie()
{

var the_cookie = "users_resolution="+ screen.width +"x"+ screen.height;

document.cookie=the_cookie

location = location.href;
}

Will loock  if some browser like chrome will come to such server? what will full page requesl look like?

Body: Fire up WireShark and take a look.


问:
Using Dynamic Class Objects - C#
There are two different services. Those services have different processes but give us same result. A helper method needs to use that services and service responses. User is going to choose the which service will using. So, I am going to create a helper method and it takes chosen service and its parameters. The problem is that services need different parameters with different size.(a few of them is common but not most of them)

I create an  abstract class and then two class inherited from it. Abstract class contains an standart method. But inherited class methods needs different type and size parameters. Because of that, I planning to use dynamic class object as a parameter. Is that proper solution?

```<code>public abstract class ServiceBase
{
    public abstract int StandartMethod(dynamic parameters);
}

public class ServiceForA : ServiceBase
{
    public override int StandartMethod(dynamic parameters)
    {
        //Service Request is send to ServiceA with spesific parameters
        //(parameters.Ticket, parameter.myType1, string p1 , int n1, ..)
        //----
        //Service Response received and processed
        return requiredInfo;
    }
}

public class ServiceForB : ServiceBase
{
    public override int StandartMethod(dynamic parameters)
    {
        //Service Request is send to ServiceB with spesific parameters
        //(parameters.UserName,parameters.Password, parameters.myType1,int beginRange, ..)
        //----
        //Service Response received and processed
        return requiredInfo;
    }
}

public static int HelperMethod(ServiceBase service, ServiceParameters parameters)
{
   //Do required stuff
   return service.StandartMethod(parameters);
}

static void Main(string[] args)
        {
            ServiceBase serviceA = new ServiceForA();

            dynamic obj1 = new ServiceParameters();

            obj1.Ticket = GetTicket(UserName,Pass);
            obj1.p1 = "Parameter1";
            obj1.n1 = 10;

            var result = HelperMethod(serviceA, obj1);

            Console.WriteLine("RESULT 1: " + result);

            ServiceBase serviceB = new ServiceForB();

            dynamic obj2 = new ServiceParameters();
            obj2.UserName = "slyn";
            obj2.Password = "****";
            ...
            obj2.beginRange = 1;

            var result2 = HelperMethod(serviceB, obj2);

            Console.WriteLine("RESULT2: " + result2);

        }
</code>```

Service object type will be ServiceForA or ServiceForB. It doesn't matter, StandartMethod is implemented both classes. And ServiceParameters class is inherited from System.Dynamic.DynamicObject

It seems solve the problem, but is it proper solution?
Any suggestion?

答:
using Strategy pattern at run time you are changing the strategy based on user selection( as both are yielding the same result). You can change the access modifier if you want to expose the underlying service implementation to public

```<code>public interface ICaller{
    int DoStuff(dynamic parameters);
}
internal class ServiceForA : ICaller
{
    internal int DoStuff(dynamic parameters)
    {
       //implementation
    }
}
internal class ServiceForB : ICaller
{
    internal int DoStuff(dynamic parameters)
    {
       //implementation
    }
}
public class ServiceProcessor
{
    private ICaller _service;
    public ServiceProcessor(ICaller service)
    {
        _service = service;
    }
    public int Invoke(ICaller service)
    {
        return _service.DoStuff(dynamic parameters);
    }
}
static void Main()
{
    var processor = new ServiceProcessor(new ServiceForA());
    processor.Invoke();
    var processor = new ServiceProcessor(new ServiceForB());
    processor.Invoke();
}
</code>```

Title: Using Dynamic Class Objects - C#

Body:
There are two different services. Those services have different processes but give us same result. A helper method needs to use that services and service responses. User is going to choose the which service will using. So, I am going to create a helper method and it takes chosen service and its parameters. The problem is that services need different parameters with different size.(a few of them is common but not most of them)

I create an  abstract class and then two class inherited from it. Abstract class contains an standart method. But inherited class methods needs different type and size parameters. Because of that, I planning to use dynamic class object as a parameter. Is that proper solution?

public abstract class ServiceBase
{
    public abstract int StandartMethod(dynamic parameters);
}

public class ServiceForA : ServiceBase
{
    public override int StandartMethod(dynamic parameters)
    {
        //Service Request is send to ServiceA with spesific parameters
        //(parameters.Ticket, parameter.myType1, string p1 , int n1, ..)
        //----
        //Service Response received and processed
        return requiredInfo;
    }
}

public class ServiceForB : ServiceBase
{
    public override int StandartMethod(dynamic parameters)
    {
        //Service Request is send to ServiceB with spesific parameters
        //(parameters.UserName,parameters.Password, parameters.myType1,int beginRange, ..)
        //----
        //Service Response received and processed
        return requiredInfo;
    }
}

public static int HelperMethod(ServiceBase service, ServiceParameters parameters)
{
   //Do required stuff
   return service.StandartMethod(parameters);
}

static void Main(string[] args)
        {
            ServiceBase serviceA = new ServiceForA();

            dynamic obj1 = new ServiceParameters();

            obj1.Ticket = GetTicket(UserName,Pass);
            obj1.p1 = "Parameter1";
            obj1.n1 = 10;

            var result = HelperMethod(serviceA, obj1);

            Console.WriteLine("RESULT 1: " + result);

            ServiceBase serviceB = new ServiceForB();

            dynamic obj2 = new ServiceParameters();
            obj2.UserName = "slyn";
            obj2.Password = "****";
            ...
            obj2.beginRange = 1;

            var result2 = HelperMethod(serviceB, obj2);

            Console.WriteLine("RESULT2: " + result2);

        }

Service object type will be ServiceForA or ServiceForB. It doesn't matter, StandartMethod is implemented both classes. And ServiceParameters class is inherited from System.Dynamic.DynamicObject

It seems solve the problem, but is it proper solution?
Any suggestion?

Body:
using Strategy pattern at run time you are changing the strategy based on user selection( as both are yielding the same result). You can change the access modifier if you want to expose the underlying service implementation to public

public interface ICaller{
    int DoStuff(dynamic parameters);
}
internal class ServiceForA : ICaller
{
    internal int DoStuff(dynamic parameters)
    {
       //implementation
    }
}
internal class ServiceForB : ICaller
{
    internal int DoStuff(dynamic parameters)
    {
       //implementation
    }
}
public class ServiceProcessor
{
    private ICaller _service;
    public ServiceProcessor(ICaller service)
    {
        _service = service;
    }
    public int Invoke(ICaller service)
    {
        return _service.DoStuff(dynamic parameters);
    }
}
static void Main()
{
    var processor = new ServiceProcessor(new ServiceForA());
    processor.Invoke();
    var processor = new ServiceProcessor(new ServiceForB());
    processor.Invoke();
}


问:
Regex matching and printing string issue

In Perl, I am trying to match three groups. Some groups have two question marks around them, others have one. I need to be able to distinguish between the two.

Sample Input:

The box is ?Red? in colour.
The box is ??green?? in colour.
```

<p><strong>Current Output:</strong></p>

<pre class="lang-none prettyprint-override"><code>The box isRedin colour.

The box is green in colour.
</code>```

Desired Output:

The box is Red in colour.

The box is green in colour.
```

<p>Here is what is almost working perfectly:</p>

<pre class="lang-perl prettyprint-override"><code>my $pattern_q  = '(.*\s?)[^\?]\?(\w.*)\?[^\?](.*)';
my $pattern_qq = '(.*\s?)\?\?(\w.*)\?\?(.*)';

if ( $line =~ /$pattern_q/ ) {
    print "\n" . $1 . $2 . $3 . "\n";
}

if ( $line =~ /$pattern_qq/ ) {
    print "\n" . $1 . $2 . $3 . "\n";
</code>```

When I get a match against $pattern_qq - it handles everything correctly, except for the \n at the end, which I can live with.

When I get a match against $pattern_q - It removes the spaces between the three groups, which I want to retain.

答:
You said: I need to be able to distinguish between the two. But because your wanted output is the same in both cases and doesn't show any difference, in the following examples it is demonstrated by:

the ??str?? going to be uppercase,

the ?str? lowercase.

```<code>use 5.014;
use warnings;

while(<DATA>) {
    chomp;
    say "orig: [$_]";
    s/ (\?(\?)?) (\w+?) (\1) / $2 ? uc($3) : lc($3) /gex;
    say "new : [$_]";
}

__DATA__
The box is ?Red? in colour.
The box is ??green?? in colour.
The box is ?Red? but inside is an ??green?? one
Aren't nicer the ?blue?? Or the ??violet???
What?  ??blue?  ???violet??!
</code>```

output:

```<code>orig: [The box is ?Red? in colour.]
new : [The box is red in colour.]
orig: [The box is ??green?? in colour. ]
new : [The box is GREEN in colour. ]
orig: [The box is ?Red? but inside is an ??green?? one]
new : [The box is red but inside is an GREEN one]
orig: [Aren't nicer the ?blue?? Or the ??violet???]
new : [Aren't nicer the blue? Or the VIOLET?]
orig: [What?  ??blue?  ???violet??!]
new : [What?  ?blue  ?VIOLET!]
</code>```

you can also replace the $2 ? uc($3) : lc($3) with a subroutine call, like:

```<code>while(<DATA>) {
    chomp;
    say "orig: [$_]";
    s/ (\?(\?)?) (\w+?) (\1) / make_result($3,$2) /gex;
    say "new : [$_]";
}

sub make_result {
    my($str, $two) = @_;
    return uc($str) if $two;
    return lc($str);
}
</code>```

with the same output.

Body:
In Perl, I am trying to match three groups. Some groups have two question marks around them, others have one. I need to be able to distinguish between the two.

Sample Input:

The box is ?Red? in colour.
The box is ??green?? in colour.

Current Output:

The box isRedin colour.

The box is green in colour.

Desired Output:

The box is Red in colour.

The box is green in colour.

Here is what is almost working perfectly:

my $pattern_q  = '(.*\s?)[^\?]\?(\w.*)\?[^\?](.*)';
my $pattern_qq = '(.*\s?)\?\?(\w.*)\?\?(.*)';

if ( $line =~ /$pattern_q/ ) {
    print "\n" . $1 . $2 . $3 . "\n";
}

if ( $line =~ /$pattern_qq/ ) {
    print "\n" . $1 . $2 . $3 . "\n";

When I get a match against $pattern_qq - it handles everything correctly, except for the \n at the end, which I can live with.

When I get a match against $pattern_q - It removes the spaces between the three groups, which I want to retain.

Body:
You said: I need to be able to distinguish between the two. But because your wanted output is the same in both cases and doesn't show any difference, in the following examples it is demonstrated by:

the ??str?? going to be uppercase,

the ?str? lowercase.

use 5.014;
use warnings;

while(<DATA>) {
    chomp;
    say "orig: [$_]";
    s/ (\?(\?)?) (\w+?) (\1) / $2 ? uc($3) : lc($3) /gex;
    say "new : [$_]";
}

__DATA__
The box is ?Red? in colour.
The box is ??green?? in colour.
The box is ?Red? but inside is an ??green?? one
Aren't nicer the ?blue?? Or the ??violet???
What?  ??blue?  ???violet??!

output:

orig: [The box is ?Red? in colour.]
new : [The box is red in colour.]
orig: [The box is ??green?? in colour. ]
new : [The box is GREEN in colour. ]
orig: [The box is ?Red? but inside is an ??green?? one]
new : [The box is red but inside is an GREEN one]
orig: [Aren't nicer the ?blue?? Or the ??violet???]
new : [Aren't nicer the blue? Or the VIOLET?]
orig: [What?  ??blue?  ???violet??!]
new : [What?  ?blue  ?VIOLET!]

you can also replace the $2 ? uc($3) : lc($3) with a subroutine call, like:

while(<DATA>) {
    chomp;
    say "orig: [$_]";
    s/ (\?(\?)?) (\w+?) (\1) / make_result($3,$2) /gex;
    say "new : [$_]";
}

sub make_result {
    my($str, $two) = @_;
    return uc($str) if $two;
    return lc($str);
}

with the same output.


问:
Can't apply KB3165756 to Visual Studio 2015 Professional
I have a licensed version of Microsoft's Visual Studio 2015 Professional operating on Windows 10 Enterprise. The Help/About displays this, in part:

```<code>Microsoft Visual Studio Professional 2015
Version 14.0.25424.00 Update 3
Microsoft .NET Framework
Version 4.6.01038

Installed Version: Professional
</code>```

Visual Studio has been pestering me to apply KB3165756 for more than a week, so as to update things from 14.0.25424.0 to 14.0.25425.01. I select the link and it downloads vs14-kb3165756.exe to my computer. I start this program and run it. After a short delay (and getting through a few security prompts), the program aborts with this display:

I click on the link to examine the log file (the common issues and workarounds link is completely worthless so far as I'm able to see) and I get quite a long laundry list of errors near the bottom. This is the error log file I get.

I have re-tried this any number of times, including completely shutting down the computer and rebooting and then re-trying the operation. It always fails at the same point. It also always adds the point about "user cancelled installation." But I didn't actually participate. All I did was watch the installation process acquire some files and then fail. Perhaps just a few minutes' time to get there.

(I do have a few add-ons in Visual Studio 2015. I can provide a complete list, if that is needed. Or I can check an item if someone feels it's important to check for particular ones. Most of them are from Microsoft, though. And no, I have not removed them all and tried to go back to the beginning installation process and then re-apply everything in some different order.)

I'd appreciate any productive thoughts about how to get this patch applied. I'm getting to the point of considering a complete uninstall of Visual Studio, a re-install from the original DVD, and then re-application of patches. (But, of course, I'd like to avoid that.)

答:
Even I faced the same issue, which looks like a problem with the online installer of this KB update. I could resolve it by making an offline installer and installing it using the following steps:

Download the installer of the KB3165756 from https://msdn.microsoft.com/en-us/library/mt752379.aspx. It is an online installer (A minimal installer VS14-KB3165756.exe of 2.45 MB, which will download the content on the go from internet).

Open a command prompt and point to the location where VS14-KB3165756.exe is located.

Run the command VS14-KB3165756.exe /layout. It will start a Visual Studio Setup Window asking for the download location where you want to download this.
Select and location as the file location of VS14-KB3165756.exe. For example if your VS14-KB3165756.exe is in C:\VS14-KB3165756.exe then select the download location as C:\packages and it will download there.

Now, keep your system network disconnected and try to install the VS14-KB3165756.exe and it will take the offline package and install successfully instead of trying to download. For example, if you are running VS14-KB3165756.exe from C:\VS14-KB3165756.exe, then it will look for packages files from C:\packages.

Body:
I have a licensed version of Microsoft's Visual Studio 2015 Professional operating on Windows 10 Enterprise. The Help/About displays this, in part:

Microsoft Visual Studio Professional 2015
Version 14.0.25424.00 Update 3
Microsoft .NET Framework
Version 4.6.01038

Installed Version: Professional

Visual Studio has been pestering me to apply KB3165756 for more than a week, so as to update things from 14.0.25424.0 to 14.0.25425.01. I select the link and it downloads vs14-kb3165756.exe to my computer. I start this program and run it. After a short delay (and getting through a few security prompts), the program aborts with this display:

I click on the link to examine the log file (the common issues and workarounds link is completely worthless so far as I'm able to see) and I get quite a long laundry list of errors near the bottom. This is the error log file I get.

I have re-tried this any number of times, including completely shutting down the computer and rebooting and then re-trying the operation. It always fails at the same point. It also always adds the point about "user cancelled installation." But I didn't actually participate. All I did was watch the installation process acquire some files and then fail. Perhaps just a few minutes' time to get there.

(I do have a few add-ons in Visual Studio 2015. I can provide a complete list, if that is needed. Or I can check an item if someone feels it's important to check for particular ones. Most of them are from Microsoft, though. And no, I have not removed them all and tried to go back to the beginning installation process and then re-apply everything in some different order.)

I'd appreciate any productive thoughts about how to get this patch applied. I'm getting to the point of considering a complete uninstall of Visual Studio, a re-install from the original DVD, and then re-application of patches. (But, of course, I'd like to avoid that.)


问:
C++ - removal of a node in an AVL Tree
I'm currently trying to implement an AVL tree in C++, so far I've done pretty much everything except a node removal.

1) Can someone confirm that my algorithm for removing a node is correct?

Find the node to delete in the tree

if the node has 0 child : delete the node

else, if the node has 1 child: delete the node, and re-link his child

else (2 children): find its successor, and swap the node to delete with its successor. then repeat the steps to delete the node (which is now where its successor was).

Rebalance the tree after the insertion (it'll rebalance the tree recursively...)

I've done this, but the part where I'm not sure, is the step where I delete the node. Do I have to delete the reference to the node also, or it'll be managed? (Because I've passed in parameter a Node*&, but the successor is only a Node* in the function...)

I'm not sure I'm being super clear, let me know if you need more details.

(I would post some code, but unfortunately I speak french, so you won't understand much from it, I guess)

答:
If the node was created using 'new' than it needs to be explicitly deleted, absolutely.  They question will be where.  If you are deleting the node, (the assumption is nobody else needs the contents of the node) then you should also delete the node itself after completing the nodes removal from the tree.

Now, the reference to the node is another matter.  If the reference is an artifact of a method argument definition, you don't have to do anything with it.  The reference was created on the stack to help with the method call.  If I remember my C++, references can never be null, which means never having to say you're sorry(bad joke), er never having to delete them.

[EDIT]
The OP says, "Because I've passed in parameter a Node*&, but the successor is only a Node* in the function...)" so I assumed you meant something like:

```<code>void removeNode(Node*& node)
</code>```

which is then called using

```<code>void foo()
{
    Node* n = new Node();
    // for example
    removeNode(n);
}
</code>```

My C++ is a bit rusty but the idea here is that 'n' is a pointer but the argument type of removeNode() is a reference to a pointer.  The caller doesn't know that a reference is involved, it just passes 'n' expecting the arg type to be pointer-to-node (Node*).  The compiler is creating the reference as a wrapper around the argument so only the callee is aware of the reference.  Since the reference is created on the stack, it will be 'managed' properly when removeNode() returns.  The node pointed to by 'n' still needs to be deleted, the question is which code should handle it.

First thought would be for 'removeNode()' to do it. One problem is that it only has a reference to it and if you delete the pointer (the target of the reference) the reference will be null which is a bad idea / not allowed.  Just thinking of the syntax to attempt it made me cringe.

So, have the client code to do it, like so:

```<code>void foo()
{
    Node* n = new Node();
    // for example
    removeNode(n);
    delete n;
}
</code>```

Basically, you need to have a plan for the scope of your node pointers.  As long as it is consistent, you could do it in several different ways.  If you wanted removeNode() to handle the deletion, then change the argument type to a pointer instead of a reference and document the call so the expectation is it both removes the node from the tree and deletes the memory as well.

Title: C++ - removal of a node in an AVL Tree

Body:
If the node was created using 'new' than it needs to be explicitly deleted, absolutely.  They question will be where.  If you are deleting the node, (the assumption is nobody else needs the contents of the node) then you should also delete the node itself after completing the nodes removal from the tree.

Now, the reference to the node is another matter.  If the reference is an artifact of a method argument definition, you don't have to do anything with it.  The reference was created on the stack to help with the method call.  If I remember my C++, references can never be null, which means never having to say you're sorry(bad joke), er never having to delete them.

[EDIT]
The OP says, "Because I've passed in parameter a Node*&, but the successor is only a Node* in the function...)" so I assumed you meant something like:

void removeNode(Node*& node)

which is then called using

void foo()
{
    Node* n = new Node();
    // for example
    removeNode(n);
}

My C++ is a bit rusty but the idea here is that 'n' is a pointer but the argument type of removeNode() is a reference to a pointer.  The caller doesn't know that a reference is involved, it just passes 'n' expecting the arg type to be pointer-to-node (Node*).  The compiler is creating the reference as a wrapper around the argument so only the callee is aware of the reference.  Since the reference is created on the stack, it will be 'managed' properly when removeNode() returns.  The node pointed to by 'n' still needs to be deleted, the question is which code should handle it.

First thought would be for 'removeNode()' to do it. One problem is that it only has a reference to it and if you delete the pointer (the target of the reference) the reference will be null which is a bad idea / not allowed.  Just thinking of the syntax to attempt it made me cringe.

So, have the client code to do it, like so:

void foo()
{
    Node* n = new Node();
    // for example
    removeNode(n);
    delete n;
}

Basically, you need to have a plan for the scope of your node pointers.  As long as it is consistent, you could do it in several different ways.  If you wanted removeNode() to handle the deletion, then change the argument type to a pointer instead of a reference and document the call so the expectation is it both removes the node from the tree and deletes the memory as well.