问:
Lens lib: Is there an optic for this?
I have a family of fixed length vectors:

```<code>data family Vector (n :: Nat) a
data instance Vector 2 a = Vector2 a a
data instance Vector 3 a = Vector3 a a a
-- and so on
</code>```

and two functions to get and set a slice of a vector as a list:

```<code>getSlice :: Proxy i -> Proxy l -> Vector n a -> [a]
setSlice :: Proxy i -> Proxy l -> Vector n a -> [a] -> Maybe (Vector n a)
-- ^ setSlice is partial because list parameter may not have enough elements.
</code>```

I thought I could combine these getter and setter into a lens like this:

```<code>slice :: Proxy i -> Proxy l -> Lens (Vector n a) (Maybe (Vector n a)) [a] [a]
slice i l = lens (getSlice i l) (setSlice i l)
</code>```

but this violates lens laws(http://hackage.haskell.org/package/lens-4.15.2/docs/Control-Lens-Lens.html#t:Lens

So I wonder if there is a structure for this?

答:
I don't think you can get exactly what you're looking for, but you can get some related things. This answer is going to take a rather roundabout path to get to what I think you most likely want; this is the path my mind took approaching a conclusion, and I think justifies what I ended up with. The general theme is that there are a few different legitimate optics you can apply to your situation and that can be useful in different ways.

First, let's look at what sort of Lens you can get. The i and l Nats mark out a "window" in the Vector n. You haven't indicated what you want to happen if the window doesn't lie entirely within the vector. One option is to simply require it to fit. Another option is to clip the window to the size of the vector:

```<code>-- Minimum
type Min m n = Min' (m <=? n) m n
type family Min' m_le_n (m :: Nat) (n :: Nat) where
  Min' 'True m _ = m
  Min' 'False _ n = n

-- Saturated subtraction
type SatMinus m n = SatMinus' (n <=? m) m n
type family SatMinus' n_le_m m n where
  SatMinus' 'True m n = m - n
  SatMinus' 'False _ _ = 0

-- Window clipping
type ClippedLength i l n = Min l (SatMinus n i)
</code>```

Now you can certainly define (for each n, using a class; I'll ignore this detail in the rest of the post) a legitimate

```<code>vlCut :: (KnownNat i, KnownNat l)
   => Proxy i -> Proxy l
   -> Lens' (Vector n a) (Vector (ClippedLength i l n) a)
</code>```

Or, if you only want to allow windows that fit,

```<code>vl :: (KnownNat i, KnownNat j, i + l <= n)
   => Proxy i -> Proxy l
   -> Lens' (Vector n a) (Vector l a)
</code>```

We can now work through one of these lenses without losing any generality (although we will lose efficiency; more on getting around that later). Doing so means we get to completely ignore everything outside of the window, so we needn't mention the proxies anymore. If we have any optic from Vector w a to t, then we can produce an optic from Vector n a to t.

Reducing your slice-manipulating functions to the window, you get

```<code>getSliceW :: Vector w a -> [a]
setSliceWpartial :: Vector w a -> [a] -> Maybe (Vector w a)
</code>```

These don't make a Lens, as you discovered. But if you reduce just a bit further, replacing setSliceWpartial with

```<code>fromList :: [a] -> Maybe (Vector w a)
</code>```

you can make a lawful Prism:

```<code>slicep :: Prism' [a] (Vector w a)
</code>```

Given a Vector w a, you can always produce a [a], but the other way is only sometimes possible. You can certainly use this with vl or vlCut (if that's the problem you need to solve, that's a fine solution), but you can't compose it with them, because the types don't match up right. You can reverse the prism with re, but that only gives you a Getter in the end.

Since your types don't seem to work out so nicely, let's try changing them:

```<code>getSliceW :: Vector w a -> [a]
setSliceW :: Vector w a -> [a] -> Vector w a
</code>```

Now we're cooking with bass! This has the type of the pieces of a Lens' (Vector w a) [a], although it's not actually a lawful lens. It is, however, a very good clue. Control.Lens.Traversal offers

```<code>partsOf' :: ATraversal s t a a -> Lens s t [a] [a]
</code>```

which you can read, in this context, as

```<code>partsOf' :: Traversal' (Vector w a) a -> Lens' (Vector w a) [a]
</code>```

So (through the window), what we really want is

```<code>traverseVMono :: Traversal' (Vector w a) a
</code>```

Of course, that generalizes immediately; just write a Traversable instance for Vector n and use its traverse.

I mentioned earlier that working through a window Lens is inefficient. So how can you deal with that? Well, just don't bother actually constructing the window! What you want to go "from end to end" is just to traverse the window. So do that:

```<code>traverseWindow :: (KnownNat i, KnownNat l, Applicative f)
               -- optionally require i + l <= n
               => proxy1 i
               -> proxy2 l
               -> (a -> f a)
               -> Vector n a
               -> f (Vector n a)
</code>```

You can recover your original partial setSlice if you like; you just have to use traverseWindow with something like MaybeT (State [a]):

```<code>foldMapWindow :: (KnownNat i, KnownNat l, Monoid m)
  => proxy1 i
  -> proxy2 l
  -> (a -> m)
  -> Vector n a
  -> m
foldMapWindow p1 p2 f = getConst . traverseWindow p1 p2 (Const . f)

windowToList :: (KnownNat i, KnownNat l)
  => proxy1 i
  -> proxy2 l
  -> Vector n a
  -> [a]
windowToList p1 p2 = foldMapWindow p1 p2 (:[])

setSlice :: (KnownNat i, KnownNat l)
         => proxy1 i -> proxy2 l
         -> Vector n a -> [a] -> Maybe (Vector n a)
setSlice p1 p2 v xs = flip evalState (windowToList p1 p2 v) . runMaybeT $ flip (traverseWindow p1 p2) v $ \_ -> do
  y : ys <- get
  put ys
  pure y
</code>```

Title: Lens lib: Is there an optic for this?

Body:
I have a family of fixed length vectors:

data family Vector (n :: Nat) a
data instance Vector 2 a = Vector2 a a
data instance Vector 3 a = Vector3 a a a
-- and so on

and two functions to get and set a slice of a vector as a list:

getSlice :: Proxy i -> Proxy l -> Vector n a -> [a]
setSlice :: Proxy i -> Proxy l -> Vector n a -> [a] -> Maybe (Vector n a)
-- ^ setSlice is partial because list parameter may not have enough elements.

I thought I could combine these getter and setter into a lens like this:

slice :: Proxy i -> Proxy l -> Lens (Vector n a) (Maybe (Vector n a)) [a] [a]
slice i l = lens (getSlice i l) (setSlice i l)

but this violates lens laws(http://hackage.haskell.org/package/lens-4.15.2/docs/Control-Lens-Lens.html#t:Lens

So I wonder if there is a structure for this?

Body:
I don't think you can get exactly what you're looking for, but you can get some related things. This answer is going to take a rather roundabout path to get to what I think you most likely want; this is the path my mind took approaching a conclusion, and I think justifies what I ended up with. The general theme is that there are a few different legitimate optics you can apply to your situation and that can be useful in different ways.

First, let's look at what sort of Lens you can get. The i and l Nats mark out a "window" in the Vector n. You haven't indicated what you want to happen if the window doesn't lie entirely within the vector. One option is to simply require it to fit. Another option is to clip the window to the size of the vector:

-- Minimum
type Min m n = Min' (m <=? n) m n
type family Min' m_le_n (m :: Nat) (n :: Nat) where
  Min' 'True m _ = m
  Min' 'False _ n = n

-- Saturated subtraction
type SatMinus m n = SatMinus' (n <=? m) m n
type family SatMinus' n_le_m m n where
  SatMinus' 'True m n = m - n
  SatMinus' 'False _ _ = 0

-- Window clipping
type ClippedLength i l n = Min l (SatMinus n i)

Now you can certainly define (for each n, using a class; I'll ignore this detail in the rest of the post) a legitimate

vlCut :: (KnownNat i, KnownNat l)
   => Proxy i -> Proxy l
   -> Lens' (Vector n a) (Vector (ClippedLength i l n) a)

Or, if you only want to allow windows that fit,

vl :: (KnownNat i, KnownNat j, i + l <= n)
   => Proxy i -> Proxy l
   -> Lens' (Vector n a) (Vector l a)

We can now work through one of these lenses without losing any generality (although we will lose efficiency; more on getting around that later). Doing so means we get to completely ignore everything outside of the window, so we needn't mention the proxies anymore. If we have any optic from Vector w a to t, then we can produce an optic from Vector n a to t.

Reducing your slice-manipulating functions to the window, you get

getSliceW :: Vector w a -> [a]
setSliceWpartial :: Vector w a -> [a] -> Maybe (Vector w a)

These don't make a Lens, as you discovered. But if you reduce just a bit further, replacing setSliceWpartial with

fromList :: [a] -> Maybe (Vector w a)

you can make a lawful Prism:

slicep :: Prism' [a] (Vector w a)

Given a Vector w a, you can always produce a [a], but the other way is only sometimes possible. You can certainly use this with vl or vlCut (if that's the problem you need to solve, that's a fine solution), but you can't compose it with them, because the types don't match up right. You can reverse the prism with re, but that only gives you a Getter in the end.

Since your types don't seem to work out so nicely, let's try changing them:

getSliceW :: Vector w a -> [a]
setSliceW :: Vector w a -> [a] -> Vector w a

Now we're cooking with bass! This has the type of the pieces of a Lens' (Vector w a) [a], although it's not actually a lawful lens. It is, however, a very good clue. Control.Lens.Traversal offers

partsOf' :: ATraversal s t a a -> Lens s t [a] [a]

which you can read, in this context, as

partsOf' :: Traversal' (Vector w a) a -> Lens' (Vector w a) [a]

So (through the window), what we really want is

traverseVMono :: Traversal' (Vector w a) a

Of course, that generalizes immediately; just write a Traversable instance for Vector n and use its traverse.

I mentioned earlier that working through a window Lens is inefficient. So how can you deal with that? Well, just don't bother actually constructing the window! What you want to go "from end to end" is just to traverse the window. So do that:

traverseWindow :: (KnownNat i, KnownNat l, Applicative f)
               -- optionally require i + l <= n
               => proxy1 i
               -> proxy2 l
               -> (a -> f a)
               -> Vector n a
               -> f (Vector n a)

You can recover your original partial setSlice if you like; you just have to use traverseWindow with something like MaybeT (State [a]):

foldMapWindow :: (KnownNat i, KnownNat l, Monoid m)
  => proxy1 i
  -> proxy2 l
  -> (a -> m)
  -> Vector n a
  -> m
foldMapWindow p1 p2 f = getConst . traverseWindow p1 p2 (Const . f)

windowToList :: (KnownNat i, KnownNat l)
  => proxy1 i
  -> proxy2 l
  -> Vector n a
  -> [a]
windowToList p1 p2 = foldMapWindow p1 p2 (:[])

setSlice :: (KnownNat i, KnownNat l)
         => proxy1 i -> proxy2 l
         -> Vector n a -> [a] -> Maybe (Vector n a)
setSlice p1 p2 v xs = flip evalState (windowToList p1 p2 v) . runMaybeT $ flip (traverseWindow p1 p2) v $ \_ -> do
  y : ys <- get
  put ys
  pure y


来源: stackexchange

问:
Reading a line and assigning a default value to the variables in BASH
How do I read a row of data and assign them to variables while also giving them default values?

I wanted to achieve something like this, but can't get the syntax right.

```<code>{
read variable1=${variable1:=default1} variable2=${variable2:=default2}
read variable3=${variable3:=default3} variable4=${variable4:=default4}
} <fileList
</code>```

答:
Use a loop:

```<code>while read -r var1 var2 dummy; do
  var1=${var1:-default1}
  var2=${var2:-default2}
  # process this line
done < fileList
</code>```

read -r var1 var2 dummy - if a lines has more than two space separated tokens, they will be read into dummy and can be ignored

if a lines has less than two tokens, the default values will be effective

ContentLicense: CC BY-SA 3.0

Body:
How do I read a row of data and assign them to variables while also giving them default values?

I wanted to achieve something like this, but can't get the syntax right.

{
read variable1=${variable1:=default1} variable2=${variable2:=default2}
read variable3=${variable3:=default3} variable4=${variable4:=default4}
} <fileList

Body:
Use a loop:

while read -r var1 var2 dummy; do
  var1=${var1:-default1}
  var2=${var2:-default2}
  # process this line
done < fileList

read -r var1 var2 dummy - if a lines has more than two space separated tokens, they will be read into dummy and can be ignored

if a lines has less than two tokens, the default values will be effective


问:
ng-file-upload send array into database
i want to upload array of data that i have by using ng-file-upload, but if i repeat it, my database only got last image, can anyone know what's wrong with my code?

Here is my code

```<code>$scope.send = function () {
    console.log("aaa " + $scope.file);
    console.log("files total: " + $scope.portfolio_images_array.length);

    if ($scope.file && $scope.file1 && $scope.portfolio_images_array.length > 0) {
            Upload.upload({
                url: 'upload_url',
                data: {
                    user_id: 7,
                    profile_photo: $scope.file,
                    id_card_photo: $scope.file1,
                    name: $scope.name,
                    introduction: $scope.introduction,
                    portfolio_image: $scope.portfolio_images_array
                }
            }).then(function (resp) {
                console.log('Success ');
            }, function (resp) {
                console.log('Error status: ' + resp.status);
            }, function (evt) {
                var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                console.log('progress: ' + progressPercentage + '% ');
            });
        }
};
</code>```

portfolio_image should get all the images, but now it only get the last image from portfolio_images_array.
For adding the data to portolio_image_array, i use this code:

```<code>$scope.addFiles = function (file) {
    console.log(file);
    $scope.portfolio_images_array.push(file);
}
</code>```

Please help me with this, Thanks

答:
Upload.upload is in fact a http request.

What you are doing is looping through all your array and make a http request for each file.

This is already really bad, and you should send the array directly with a syntax like this :

```<code>Upload.upload({
            url: storageService.Address_of_your_server + '/your/route',
            file: file,
            arrayKey: '',
            data: data,
        }).success(function (resp) {
            cbfun(resp);
        });
}
</code>```

Where file is your array of files and data your json of data you want to send in the same time.

The fact you are receiving only the last image is a bit weird.

Two ideas comes to my mind :

Upload service stop the request if he is called another time while the request is not finished.

As you are looping in a synchronous way while using asynchronous functions into your loop. Consequently, the javascript excecutes very quickly the loop and the i is incremented before even sending the requests.

But I don't really think this is the second possibility, as this case should only happen if you use the i variable in the callback of your promise (then).

EDIT :

Why you need to use ArrayKey :

This is to accommodate server implementations expecting array data object keys in '[i]' or '[]' or ''(multiple entries with same key) format.

So if you are not using it, the server part won't understand the format of the request.

According to the official doc.

Also, if you are using NodeJS, it is almost sure you are using the multer middleware in the back-end.

Consequently, you should have a route like this in the back :

```<code>router.post('/your/route', upload.array('file'), function(req, res){
//Your files are in this variable
var files = req.files
}
</code>```

Title: ng-file-upload send array into database

Body:
i want to upload array of data that i have by using ng-file-upload, but if i repeat it, my database only got last image, can anyone know what's wrong with my code?

Here is my code

$scope.send = function () {
    console.log("aaa " + $scope.file);
    console.log("files total: " + $scope.portfolio_images_array.length);

    if ($scope.file && $scope.file1 && $scope.portfolio_images_array.length > 0) {
            Upload.upload({
                url: 'upload_url',
                data: {
                    user_id: 7,
                    profile_photo: $scope.file,
                    id_card_photo: $scope.file1,
                    name: $scope.name,
                    introduction: $scope.introduction,
                    portfolio_image: $scope.portfolio_images_array
                }
            }).then(function (resp) {
                console.log('Success ');
            }, function (resp) {
                console.log('Error status: ' + resp.status);
            }, function (evt) {
                var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                console.log('progress: ' + progressPercentage + '% ');
            });
        }
};

portfolio_image should get all the images, but now it only get the last image from portfolio_images_array.
For adding the data to portolio_image_array, i use this code:

$scope.addFiles = function (file) {
    console.log(file);
    $scope.portfolio_images_array.push(file);
}

Please help me with this, Thanks

Body:
Upload.upload is in fact a http request.

What you are doing is looping through all your array and make a http request for each file.

This is already really bad, and you should send the array directly with a syntax like this :

Upload.upload({
            url: storageService.Address_of_your_server + '/your/route',
            file: file,
            arrayKey: '',
            data: data,
        }).success(function (resp) {
            cbfun(resp);
        });
}

Where file is your array of files and data your json of data you want to send in the same time.

The fact you are receiving only the last image is a bit weird.

Two ideas comes to my mind :

Upload service stop the request if he is called another time while the request is not finished.

As you are looping in a synchronous way while using asynchronous functions into your loop. Consequently, the javascript excecutes very quickly the loop and the i is incremented before even sending the requests.

But I don't really think this is the second possibility, as this case should only happen if you use the i variable in the callback of your promise (then).

EDIT :

Why you need to use ArrayKey :

This is to accommodate server implementations expecting array data object keys in '[i]' or '[]' or ''(multiple entries with same key) format.

So if you are not using it, the server part won't understand the format of the request.

According to the official doc.

Also, if you are using NodeJS, it is almost sure you are using the multer middleware in the back-end.

Consequently, you should have a route like this in the back :

router.post('/your/route', upload.array('file'), function(req, res){
//Your files are in this variable
var files = req.files
}


问:
Fatal error: SFML/Graphics.hpp: no such file or directory exists
I'm running into problem after problem with SFML, but hopefully it will be worth it in the end.

Here's the error:

fatal error:  SFML/Graphics.hpp : No such file or directory

and the code:

```<code>#include < SFML/Graphics.hpp >
#include < SFML/Window.hpp >

int main(){
sf::RenderWindow Window;
Window.create(sf::VideoMode(800, 600), "SFML");

while(Window.isOpen()){
    sf::Event Event;
    while(Window.pollEvent(Event)){
        if(Event.type == sf::Event::Closed)
            Window.close();
    }
}
}
</code>```

答:
If you happen to be using the windows visual studio command line compiler, the include syntax is:</p>

```<code>/I"path\to\SFML\headers"
</code>```

Body:
I'm running into problem after problem with SFML, but hopefully it will be worth it in the end.

Here's the error:

fatal error:  SFML/Graphics.hpp : No such file or directory

and the code:

#include < SFML/Graphics.hpp >
#include < SFML/Window.hpp >

int main(){
sf::RenderWindow Window;
Window.create(sf::VideoMode(800, 600), "SFML");

while(Window.isOpen()){
    sf::Event Event;
    while(Window.pollEvent(Event)){
        if(Event.type == sf::Event::Closed)
            Window.close();
    }
}
}

Body:
If you happen to be using the windows visual studio command line compiler, the include syntax is:

/I"path\to\SFML\headers"


问:
how to get array data from XML loop foreach
I have sparql output in XML like this : `

```<code><sparql xmlns="http://www.w3.org/2005/sparql-results#">
<head>
    <variable name="Keyword2"/>
</head>
<results ordered="false" distinct="false">
    <result>
        <binding name="Keyword2">
            <uri>http://www.semanticweb.org/g/ontologies/2010/0/OntologiBatikTanty#Soga_Jawa</uri>
        </binding>
    </result>
    <result>
        <binding name="Keyword2">
            <uri>http://www.semanticweb.org/g/ontologies/2010/0/OntologiBatikTanty#Warna_Alami</uri>
        </binding>
    </result>
</results>
</sparql>
</code>```

`

I make foreach looping in php like this: `

```<code>$xml = simplexml_load_string($hasil) or die ("error cannot create object");
$results = $xml->results->result;
$jumlah=count($results);
echo "Total hasil pencarian : $jumlah <br><br>";
//$keyword2=array();
$output=array();
foreach($xml->results->result as $nodes){
$jumlah=count($nodes);
    foreach ($nodes->binding as $key =>$node) {
      $output=$node->uri;
      echo $output;
      echo "<br><br>";
      echo $keyword=substr($output,66);
      echo "<br><br>";
    }
    }
    echo"<hr>";
    echo $keyword[0];
</code>```

`

My question is how to acces the data array from outside looping. for example i want to acces index[0]. but the output only "W" it should be "Soga_Jawa"

答:
solved your issue please check this code

```<code>$xml = simplexml_load_string($hasil) or die ("error cannot create object");
$results = $xml->results->result;
$jumlah=count($results);
echo "Total hasil pencarian : $jumlah <br><br>";
//$keyword2=array();
$output=array();
$keyword = array();
foreach($xml->results->result as $nodes){
$jumlah=count($nodes);
    foreach ($nodes->binding as $key =>$node) {
      $output=$node->uri;
      echo $output;
      echo "<br><br>";
      echo $keyword[]=substr($output,66);
      echo "<br><br>";
    }
    }
    echo"<hr>";
    echo $keyword[0];
</code>```

use keyword as array type and get it to out of loop

Body:
I have sparql output in XML like this : `

<sparql xmlns="http://www.w3.org/2005/sparql-results#">

    <variable name="Keyword2"/>

<results ordered="false" distinct="false">
    <result>
        <binding name="Keyword2">
            <uri>http://www.semanticweb.org/g/ontologies/2010/0/OntologiBatikTanty#Soga_Jawa</uri>
        </binding>
    </result>
    <result>
        <binding name="Keyword2">
            <uri>http://www.semanticweb.org/g/ontologies/2010/0/OntologiBatikTanty#Warna_Alami</uri>
        </binding>
    </result>
</results>
</sparql>

`

I make foreach looping in php like this: `

$xml = simplexml_load_string($hasil) or die ("error cannot create object");
$results = $xml->results->result;
$jumlah=count($results);
echo "Total hasil pencarian : $jumlah

";
//$keyword2=array();
$output=array();
foreach($xml->results->result as $nodes){
$jumlah=count($nodes);
    foreach ($nodes->binding as $key =>$node) {
      $output=$node->uri;
      echo $output;
      echo "

";
      echo $keyword=substr($output,66);
      echo "

";
    }
    }
    echo"
";
    echo $keyword[0];

`

My question is how to acces the data array from outside looping. for example i want to acces index[0]. but the output only "W" it should be "Soga_Jawa"

Body:
solved your issue please check this code

$xml = simplexml_load_string($hasil) or die ("error cannot create object");
$results = $xml->results->result;
$jumlah=count($results);
echo "Total hasil pencarian : $jumlah <br><br>";
//$keyword2=array();
$output=array();
$keyword = array();
foreach($xml->results->result as $nodes){
$jumlah=count($nodes);
    foreach ($nodes->binding as $key =>$node) {
      $output=$node->uri;
      echo $output;
      echo "<br><br>";
      echo $keyword[]=substr($output,66);
      echo "<br><br>";
    }
    }
    echo"<hr>";
    echo $keyword[0];

use keyword as array type and get it to out of loop


问:
How do you use the jquery 'load' method to load a page fragment when passing a variable?
Not sure if this has been asked, but here it goes, given the following code...

```<code>$('#infoPane').load('showInfo.php #info');
</code>```

How do a pass variable to the page yet only just load the page fragment?

```<code>$('#imgPane').load('showInfo.php?q='+$q+ '#picture');
</code>```

The above code does not work so any help would be appreciated

答:
It probably doesn't work because the spacing is incorrect:

```<code>$('#imgPane').load('showInfo.php?q='+$q+' #picture');
</code>```

In your example, you're trying to load: showInfo.php?q=whatever#picture rather than showInfo.php?q=whatever #picture

However, you should be able to post data to your script similar to the following:

```<code>$('#imgPane').load('showInfo.php #picture', { 'q' : $q });
</code>```

Passing data is one of the jQuery .load() parameters.

ContentLicense: CC BY-SA 2.5

Body:
Not sure if this has been asked, but here it goes, given the following code...

$('#infoPane').load('showInfo.php #info');

How do a pass variable to the page yet only just load the page fragment?

$('#imgPane').load('showInfo.php?q='+$q+ '#picture');

The above code does not work so any help would be appreciated

Body:
It probably doesn't work because the spacing is incorrect:

$('#imgPane').load('showInfo.php?q='+$q+' #picture');

In your example, you're trying to load: showInfo.php?q=whatever#picture rather than showInfo.php?q=whatever #picture

However, you should be able to post data to your script similar to the following:

$('#imgPane').load('showInfo.php #picture', { 'q' : $q });

Passing data is one of the jQuery .load() parameters.


问:
In c# , how to iterate IEnumerable in multithreading environment
I am in this situation that there is a large dictionary that is randomly updated by one thread at a fairly high frequency, and there is another thread that tries to take a snapshot of the dictionary to save as history.
I currently using something like this:

```<code>Dictionary<string, object> dict = new Dictionary<string, object>();
var items = dict.Values.ToList();
</code>```

This works fine for most of the time, except it occasionally throws:

System.InvalidOperationException: Collection was modified; enumeration
  operation may not execute.

I understand why this happen, but I don't know what can I do to avoid the collection modified error.

What is the best approach to iterate such collection?

I also tried ConcurrentDictionary, but no luck.
Why? Is ConcurrentDictionary thread safe only at item level?

答:
According to the docs you should be able to use the GetEnumerator() method of ConcurrentDictionary to get a thread-safe iterator.

The enumerator returned from the dictionary is safe to use concurrently with reads and writes to the dictionary, however it does not represent a moment-in-time snapshot of the dictionary. The contents exposed through the enumerator may contain modifications made to the dictionary after GetEnumerator was called.

Since you're dealing with concurrent threads, it's not surprising to have some tradeoffs with consistency, but I would expect this approach to block less than the brute force approach given in other answers. This wouldn't have worked if you tried:

```<code>var items = concurrentDict.Items.ToList();
</code>```

but it's supposed to work for

```<code>var items = concurrentDict.GetEnumerator();
</code>```

or you could simply reference the iterator directly:

```<code>foreach(var item in concurrentDict)
{
    valueList.Add(item.Value);
}
</code>```

Body:
I am in this situation that there is a large dictionary that is randomly updated by one thread at a fairly high frequency, and there is another thread that tries to take a snapshot of the dictionary to save as history.
I currently using something like this:

Dictionary<string, object> dict = new Dictionary<string, object>();
var items = dict.Values.ToList();

This works fine for most of the time, except it occasionally throws:

System.InvalidOperationException: Collection was modified; enumeration
  operation may not execute.

I understand why this happen, but I don't know what can I do to avoid the collection modified error.

What is the best approach to iterate such collection?

I also tried ConcurrentDictionary, but no luck.
Why? Is ConcurrentDictionary thread safe only at item level?

Body:
According to the docs you should be able to use the GetEnumerator() method of ConcurrentDictionary to get a thread-safe iterator.

The enumerator returned from the dictionary is safe to use concurrently with reads and writes to the dictionary, however it does not represent a moment-in-time snapshot of the dictionary. The contents exposed through the enumerator may contain modifications made to the dictionary after GetEnumerator was called.

Since you're dealing with concurrent threads, it's not surprising to have some tradeoffs with consistency, but I would expect this approach to block less than the brute force approach given in other answers. This wouldn't have worked if you tried:

var items = concurrentDict.Items.ToList();

but it's supposed to work for

var items = concurrentDict.GetEnumerator();

or you could simply reference the iterator directly:

foreach(var item in concurrentDict)
{
    valueList.Add(item.Value);
}


问:
Codename One - Externalizable object not supported in web service
I have created a CN1 web service which some custom objects that I want to externalize in order to send over the network. I read through several articles on how to create the web service and how to work with the CN1 Externalizable interface.

This works well for web service methods that return a custom externalizable object, however the only indicator that I have is that a method which takes an externalizable object as an argument, I get the following error:

```<code>SCHWERWIEGEND: Servlet.service() for servlet  [CN1WebServiceServlet]
in context with path [/<myPath>] threw exception
java.io.IOException: Object type not supported: Post
</code>```

The object is properly registered with the Util class, as changing either the object ID or commenting out the register call will cause a null pointer instead of the IO exception.

The Post class looks like this (simplified to the minimum which already fails):

```<code>public class Post implements Externalizable {
public int postid;
public int userid;

// default constructor needed for web service marshalling
public Post() {

}

@Override
public int getVersion() {
    return 1;
}

@Override
public void externalize(DataOutputStream out) throws IOException {
    Util.writeUTF("" + postid, out);
    Util.writeUTF("" + userid, out);
}

@Override
public void internalize(int version, DataInputStream in) throws IOException {
    this.postid = Integer.parseInt(Util.readUTF(in));
    this.userid = Integer.parseInt(Util.readUTF(in));
}

@Override
public String getObjectId() {
    return "Post";
}
</code>```

Note that this Post object works well when I call a web service method which returns a post object, but not when I send a Post object to the web service:

```<code>// works
public static com.codename1.io.Externalizable getPostDetails(int postid) {
   return getPostDetails(postid);
}

// fails
public static void sendPost(com.codename1.io.Externalizable post) {
    sendPost(post);
}
</code>```

I am at a loss of what I missed here.

Thanks and best regards

答: In your Servlet code call Util.register("Post", Post.class); which should hopefully resolve this.

Body:
I have created a CN1 web service which some custom objects that I want to externalize in order to send over the network. I read through several articles on how to create the web service and how to work with the CN1 Externalizable interface.

This works well for web service methods that return a custom externalizable object, however the only indicator that I have is that a method which takes an externalizable object as an argument, I get the following error:

SCHWERWIEGEND: Servlet.service() for servlet  [CN1WebServiceServlet]
in context with path [/<myPath>] threw exception
java.io.IOException: Object type not supported: Post

The object is properly registered with the Util class, as changing either the object ID or commenting out the register call will cause a null pointer instead of the IO exception.

The Post class looks like this (simplified to the minimum which already fails):

public class Post implements Externalizable {
public int postid;
public int userid;

// default constructor needed for web service marshalling
public Post() {

}

@Override
public int getVersion() {
    return 1;
}

@Override
public void externalize(DataOutputStream out) throws IOException {
    Util.writeUTF("" + postid, out);
    Util.writeUTF("" + userid, out);
}

@Override
public void internalize(int version, DataInputStream in) throws IOException {
    this.postid = Integer.parseInt(Util.readUTF(in));
    this.userid = Integer.parseInt(Util.readUTF(in));
}

@Override
public String getObjectId() {
    return "Post";
}

Note that this Post object works well when I call a web service method which returns a post object, but not when I send a Post object to the web service:

// works
public static com.codename1.io.Externalizable getPostDetails(int postid) {
   return getPostDetails(postid);
}

// fails
public static void sendPost(com.codename1.io.Externalizable post) {
    sendPost(post);
}

I am at a loss of what I missed here.

Thanks and best regards


问:
Gam: Why can't I use s(PTT, bs = "re") inside gamm?
In the mgcv package, the gamm function can be used to model random effects.

In the usual gam function, we'd use

```<code>gam(y ~ s(Group, bs = "re")
</code>```

But in gamm, we use:

```<code>gamm(y ~ 1, random = list(Group = ~1))
</code>```

My question is: why can't we just use this below code inside gamm as well?

```<code>gamm(y ~ s(Group, bs = "re"))
</code>```

It seems to work just fine?

答: Short answer is that gamm models random effects by calling lme from the nlme package, so the syntax is the same as for that. If you call it with the gam syntax, then something different is happening.

ContentLicense: CC BY-SA 4.0

Body:
In the mgcv package, the gamm function can be used to model random effects.

In the usual gam function, we'd use

gam(y ~ s(Group, bs = "re")

But in gamm, we use:

gamm(y ~ 1, random = list(Group = ~1))

My question is: why can't we just use this below code inside gamm as well?

gamm(y ~ s(Group, bs = "re"))

It seems to work just fine?


问:
Change Silverlight install URL?
I'm writing a web application that might use Silverlight. Before we get the go ahead, Project Managers are wondering if we can change the install URL for Silverlight so that the install package can be hosted inside a local Sharepoint server.

In other words:

User browses our web app

User does not have silverlight installed.

User is redirected to install package (Its this we want hosted in a local sharepoint site)

User installs from our silverlight package

User is happy camper and now has silverlight installed

Is this possible, or do you have to get the install package each time from MS site?

答:
Sure you can,

if you look at the default.aspx (or html page) which hosts the silverlight object you will see a part where you set the link to download the silverlight installer. :

```<code><a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50401.0" style="text-decoration:none">
   <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
 </a>
</code>```

Just change the url to your Sharepoint Server File.

(You can event change what it displays when silverlight is not installed by changing the content of the  tag)

Title: Change Silverlight install URL?

Body:
Sure you can,

if you look at the default.aspx (or html page) which hosts the silverlight object you will see a part where you set the link to download the silverlight installer. :

<a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50401.0" style="text-decoration:none">
   <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
 </a>

Just change the url to your Sharepoint Server File.

(You can event change what it displays when silverlight is not installed by changing the content of the  tag)


问:
can pimpl idiom's impl class has destructor？
I learn pimpl in effective modern cpp,after do some search,no one has talk about the pimpl idiom's impl class's destructor implement, is it unnecessary?</p>

```<code>//in widget.h
#include <memory>
class Widget{
public:
    Widget();
private:
    struct Impl;
    std::unique_ptr<Impl> pImpl;
};
//in widget.cpp
........
struct Widget::Impl{
  std::string name;                // Widget::Impl
  std::vector<double> data;
};

struct Widget::~Impl()   //error!!!,how can we implement it
{
};
</code>```

答:
The PIMPL idiom's implementation interface structure cannot be declared as a private field of a class. Also, the declaration of a unique_ptr to an incomplete datatype is not allowed in C++ so we have to opt for plain old pointers to declare the PIMPL and manually new and delete it appropriately.

The destructor of the struct Impl can be defined like this in widget.cpp:

```<code>Widget::Impl::~Impl()
{

};
</code>```

The final code may look something like this:

widget.h

```<code>class Widget
{
public:
    Widget();
    ~Widget();
    struct Impl;
private:
    Impl* pImpl;
};
</code>```

widget.cpp

```<code>struct Widget::Impl
{
  Impl();
  std::string name;                // Widget::Impl
  std::vector<double> data;

  ~Impl();
};

//Widget Impl Constructor
Widget::Impl::Impl()
{

}

//Widget Impl Destructor
Widget::Impl::~Impl()
{

};

//Widget Constructor
Widget::Widget() : pImpl(nullptr)
{
    pImpl = new Impl();
}

//Widget Destructor
Widget::~Widget()
{
    delete pImpl;
    pImpl = nullptr;
}
</code>```

Body:
I learn pimpl in effective modern cpp,after do some search,no one has talk about the pimpl idiom's impl class's destructor implement, is it unnecessary?

//in widget.h
#include <memory>
class Widget{
public:
    Widget();
private:
    struct Impl;
    std::unique_ptr<Impl> pImpl;
};
//in widget.cpp
........
struct Widget::Impl{
  std::string name;                // Widget::Impl
  std::vector<double> data;
};

struct Widget::~Impl()   //error!!!,how can we implement it
{
};

Body:
The PIMPL idiom's implementation interface structure cannot be declared as a private field of a class. Also, the declaration of a unique_ptr to an incomplete datatype is not allowed in C++ so we have to opt for plain old pointers to declare the PIMPL and manually new and delete it appropriately.

The destructor of the struct Impl can be defined like this in widget.cpp:

Widget::Impl::~Impl()
{

};

The final code may look something like this:

widget.h

class Widget
{
public:
    Widget();
    ~Widget();
    struct Impl;
private:
    Impl* pImpl;
};

widget.cpp

struct Widget::Impl
{
  Impl();
  std::string name;                // Widget::Impl
  std::vector<double> data;

  ~Impl();
};

//Widget Impl Constructor
Widget::Impl::Impl()
{

}

//Widget Impl Destructor
Widget::Impl::~Impl()
{

};

//Widget Constructor
Widget::Widget() : pImpl(nullptr)
{
    pImpl = new Impl();
}

//Widget Destructor
Widget::~Widget()
{
    delete pImpl;
    pImpl = nullptr;
}


问:
PhoneRTC in Ionic 2
I'm planning to create a WebRTC based Ionic 2 application so was wondering if PhoneRTC is fully supported in Ionic 2.

Also, what are the alternatives available if it's not.

答:
first phone rtc https://github.com/alongubkin/phonertc  is a cordova plugin but it is nit supported under the hood of ionic native.

But you can still use third party plugins functionality through the plugins namespace on Window:

window.plugins.somePlugin.doSomething();

See this too(see it under the title Using a Plugin Not Included in Ionic Native)

Title: PhoneRTC in Ionic 2


问:
How to make a drawable Shape programmatically (Android)
i'm making a custom TextView (Java class) and i'm having trouble "to translate" the line (on "original TextView" xml)

```<code>android:background="@drawable/myDrawableShape"
</code>```

to a java void to change the color of the "myDrawableShape"

myDrawableShape.xml

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#ffafafaf" />
<corners android:radius="15dp" />
</code>```

I'll get the color to set from a String, the void to change the color programmatically could be (for example)

```<code>void colorSet(String color)
</code>```

Thanks in advance!

答:
Change Color:</p>

```<code>  TextView tv= (TextView) findViewById(R.id.txt_time);

    Drawable background = getResources().getDrawable(R.drawable.test);

    if (background instanceof ShapeDrawable) {
        // If 'ShapeDrawable'
        ShapeDrawable shapeDrawable = (ShapeDrawable) background;
        shapeDrawable.getPaint().setColor(ContextCompat.getColor(this,R.color.colorAccent));
    } else if (background instanceof GradientDrawable) {
        // If'GradientDrawable'
        GradientDrawable gradientDrawable = (GradientDrawable) background;
        gradientDrawable.setColor(ContextCompat.getColor(this,R.color.colorPrimary));
    } else if (background instanceof ColorDrawable) {
        // If ColorDrawable
        ColorDrawable colorDrawable = (ColorDrawable) background;
        colorDrawable.setColor(ContextCompat.getColor(this,R.color.colorPrimaryDark));
    }
    tv.setBackground(background);
</code>```

Body:
i'm making a custom TextView (Java class) and i'm having trouble "to translate" the line (on "original TextView" xml)

android:background="@drawable/myDrawableShape"

to a java void to change the color of the "myDrawableShape"

myDrawableShape.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#ffafafaf" />
<corners android:radius="15dp" />

I'll get the color to set from a String, the void to change the color programmatically could be (for example)

void colorSet(String color)

Thanks in advance!

Body:
Change Color:

  TextView tv= (TextView) findViewById(R.id.txt_time);

    Drawable background = getResources().getDrawable(R.drawable.test);

    if (background instanceof ShapeDrawable) {
        // If 'ShapeDrawable'
        ShapeDrawable shapeDrawable = (ShapeDrawable) background;
        shapeDrawable.getPaint().setColor(ContextCompat.getColor(this,R.color.colorAccent));
    } else if (background instanceof GradientDrawable) {
        // If'GradientDrawable'
        GradientDrawable gradientDrawable = (GradientDrawable) background;
        gradientDrawable.setColor(ContextCompat.getColor(this,R.color.colorPrimary));
    } else if (background instanceof ColorDrawable) {
        // If ColorDrawable
        ColorDrawable colorDrawable = (ColorDrawable) background;
        colorDrawable.setColor(ContextCompat.getColor(this,R.color.colorPrimaryDark));
    }
    tv.setBackground(background);


问:
Maven does not create the "/target/m2e-wtp/web-resources" folder
I'm using Eclipse Luna. I'm working on a Maven project. When I try to run my application on a weblogic's application server, and exception is thrown with the message:

```<code>weblogic.application.ModuleException: [HTTP:101027][WebAppModule(_auto_generated_ear_:MyAppName)] Document root: "D:\MGelbana\workspace\my-app-name\target\m2e-wtp\web-resources" does not exist.
</code>```

I looked into the project's deployment assembly configuration and found the following error message: Cannot find entry: "/target/m2e-wtp/web-resources"

So I thought Luna's default Maven installation isn't what I need to I uninstalled it and I installed M2E-WTP from this URL (http://download.eclipse.org/m2e-wtp/releases/luna/) but I believe I ended up with the same version and same options.

I understand that this plugin has the option of generating this folder /target/m2e-wtp/web-resources which helps Eclipse to deploy an application into an application server (Run on server option)

(Which is my end goal but I'm having issues with deploying
  the application with it's needed dependencies. If I generate the
  application's WAR file by Installing the maven project and deploying the generated
  that WAR manually, the application works, but I need to be able to debug\run
  it on the application server using Eclipse.)

But this folder (i.e. /target/m2e-wtp/web-resources) isn't created !

In Eclipse's  Maven > Java EE Integration > WAR project preferences > Maven archiver generated files under the build directory (I checked this option)

In the project-specific options, I only have a Maven menu and a Lifecycle mapping sub-menu and nothing to do with the maven archiver generating files or not !

So how can I direct maven to output the WTP related files ?

答:
Nothing wrong with the tomcat plugin or the application, it only needed a refresh once in a while. Also, because maven was cleaning up target. I just had to setup my maven build to also refresh the project including target folder.

Check the option to automatically refresh resources in your maven build

Body:
I'm using Eclipse Luna. I'm working on a Maven project. When I try to run my application on a weblogic's application server, and exception is thrown with the message:

weblogic.application.ModuleException: [HTTP:101027][WebAppModule(_auto_generated_ear_:MyAppName)] Document root: "D:\MGelbana\workspace\my-app-name\target\m2e-wtp\web-resources" does not exist.

I looked into the project's deployment assembly configuration and found the following error message: Cannot find entry: "/target/m2e-wtp/web-resources"

So I thought Luna's default Maven installation isn't what I need to I uninstalled it and I installed M2E-WTP from this URL (http://download.eclipse.org/m2e-wtp/releases/luna/) but I believe I ended up with the same version and same options.

I understand that this plugin has the option of generating this folder /target/m2e-wtp/web-resources which helps Eclipse to deploy an application into an application server (Run on server option)

(Which is my end goal but I'm having issues with deploying
  the application with it's needed dependencies. If I generate the
  application's WAR file by Installing the maven project and deploying the generated
  that WAR manually, the application works, but I need to be able to debug\run
  it on the application server using Eclipse.)

But this folder (i.e. /target/m2e-wtp/web-resources) isn't created !

In Eclipse's  Maven > Java EE Integration > WAR project preferences > Maven archiver generated files under the build directory (I checked this option)

In the project-specific options, I only have a Maven menu and a Lifecycle mapping sub-menu and nothing to do with the maven archiver generating files or not !

So how can I direct maven to output the WTP related files ?


问:
Android Emulator not running for Cordova App - adb -s emulator-5584 shell cat /proc/cpuinfo
I'm trying to make my environment work with Cordova and Android emulator with no success. I have installed the Android Studio and I can successfully start the Android Emulator.

I have created a cordova application with the command below:

```<code>cordova create myApp
</code>```

I added support for the Android platform:

```<code>cordova plataform add android
</code>```

I had the following output:

```<code>Using cordova-fetch for cordova-android@~6.2.2
Adding android project...
Creating Cordova project for the Android platform:
        Path: platforms\android
        Package: io.cordova.hellocordova
        Name: HelloCordova
        Activity: MainActivity
        Android target: android-25
Subproject Path: CordovaLib
Android project created with cordova-android@6.2.3
Installing "cordova-plugin-whitelist" for android

   This plugin is only applicable for versions of cordova-android greater than 4.0. If you have a previous platform version, you do *not* need this plugin since the whitelist will be built in.

--save flag or autosave detected
Saving android@~6.2.3 into config.xml file ...
</code>```

Then I try to run the application:

```<code>cordova run android
</code>```

The emulator starts, after a while, that I have the error below in the command prompt:

```<code>No target specified and no devices found, deploying to emulator
No emulator specified, defaulting to Nexus_5X_API_24
Waiting for emulator to start...
Error: Failed to execute shell command "getprop,dev.bootcomplete"" on device:
Error: C:\Users\username\AppData\Local\Android\sdk\platform-tools\adb.exe: Command failed with exit code 3221226356
</code>```

Does anyone knows how to fix this error?

Some others environment info:

```<code>C:\>node -v
v7.4.0

C:\>cordova -v
7.0.1

C:\>java -version
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)
</code>```

Edit 1

I have done those steps:

Uninstalled "Android SDK Tools"

Uninstalled "Android Studio"

Deleted files from "C:\Users\USER\AppData\Local\Android\sdk" and "C:\Program Files\Android\Android Studio" files (Because some maybe in use during the uninstallation)

Installed Android Studio

Updated Android Studio

When I execute the command below, I have more information about the error:

```<code>cordova run android --verbose
</code>```

With this output:

Command finished with error code 3221226356:
  C:\Users\USER\AppData\Local\Android\sdk\platform-tools\adb.exe
  -s,emulator-5584,shell,cat,/proc/cpuinfo Error: Failed to execute shell command "cat,/proc/cpuinfo"" on device: Error:
  C:\Users\USER\AppData\Local\Android\sdk\platform-tools\adb.exe:Command
  failed with exit code 3221226356

When I execute the command below, the adb shows the emulator cpu info, after that, the process stops and the windows ask to break or debug

```<code>adb -s emulator-5584 shell cat /proc/cpuinfo
</code>```

答:
Edit your virtual device (ADV) and go into advanced settings and uncheck Multi-Core CPU.

Work fine to me.

Body:
I'm trying to make my environment work with Cordova and Android emulator with no success. I have installed the Android Studio and I can successfully start the Android Emulator.

I have created a cordova application with the command below:

cordova create myApp

I added support for the Android platform:

cordova plataform add android

I had the following output:

Using cordova-fetch for cordova-android@~6.2.2
Adding android project...
Creating Cordova project for the Android platform:
        Path: platforms\android
        Package: io.cordova.hellocordova
        Name: HelloCordova
        Activity: MainActivity
        Android target: android-25
Subproject Path: CordovaLib
Android project created with cordova-android@6.2.3
Installing "cordova-plugin-whitelist" for android

   This plugin is only applicable for versions of cordova-android greater than 4.0. If you have a previous platform version, you do *not* need this plugin since the whitelist will be built in.

--save flag or autosave detected
Saving android@~6.2.3 into config.xml file ...

Then I try to run the application:

cordova run android

The emulator starts, after a while, that I have the error below in the command prompt:

No target specified and no devices found, deploying to emulator
No emulator specified, defaulting to Nexus_5X_API_24
Waiting for emulator to start...
Error: Failed to execute shell command "getprop,dev.bootcomplete"" on device:
Error: C:\Users\username\AppData\Local\Android\sdk\platform-tools\adb.exe: Command failed with exit code 3221226356

Does anyone knows how to fix this error?

Some others environment info:

C:\>node -v
v7.4.0

C:\>cordova -v
7.0.1

C:\>java -version
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)

Edit 1

I have done those steps:

Uninstalled "Android SDK Tools"

Uninstalled "Android Studio"

Deleted files from "C:\Users\USER\AppData\Local\Android\sdk" and "C:\Program Files\Android\Android Studio" files (Because some maybe in use during the uninstallation)

Installed Android Studio

Updated Android Studio

When I execute the command below, I have more information about the error:

cordova run android --verbose

With this output:

Command finished with error code 3221226356:
  C:\Users\USER\AppData\Local\Android\sdk\platform-tools\adb.exe
  -s,emulator-5584,shell,cat,/proc/cpuinfo Error: Failed to execute shell command "cat,/proc/cpuinfo"" on device: Error:
  C:\Users\USER\AppData\Local\Android\sdk\platform-tools\adb.exe:Command
  failed with exit code 3221226356

When I execute the command below, the adb shows the emulator cpu info, after that, the process stops and the windows ask to break or debug

adb -s emulator-5584 shell cat /proc/cpuinfo


问:
are global variables available anywhere in a React app?
res.locals.user

Would I have access to "user" inside any component to toggle visibility of other components.  Such as: if user exists, render LogOut button component.

答: Usually it's not a good practice to use global variables. If u want to use the variable in your component or its child tree, pass that as a prop to the component. More details about your component to give a precise answer.</p>


问:
How to Implement Drag and Drop using React With Redux , ES6?
I have to implement Drag And Drop using the
`

react-dnd https://www.npmjs.com/package/react-dnd

We knew that Redux makes things easier , But when we integrating React , Redux , to make use of Drag And Drop its get complicated , I am facing the following issues when i do this.

Examples are mostly from ES7 ,

When Connecting to Redux no idea "how to dispatch actions" (in a Proper Way),

Too hard to understand the flow as a Beginner

Is There any Right way to Do it ? or Any Simple Examples

答:
After Some research i got to know that ,

1.react-dnd is inbuild with redux there are no difficulties in Dispatch actions ,

2.We have to convert ES7 to ES6 in the following way

ES7

```<code>import { DragSource } from 'react-dnd';

@DragSource(type, spec, collect)
export default class MyComponent {
  /* ... */
}
</code>```

We have make use of ES6 in the below way

```<code>import { DragSource } from 'react-dnd';

class MyComponent {
  /* ... */
}

export default DragSource(type, spec, collect)(MyComponent);
</code>```

You can get the examples from the below link

```<code>https://react-dnd.github.io/react-dnd/docs-faq.html
</code>```

Body:
After Some research i got to know that ,

1.react-dnd is inbuild with redux there are no difficulties in Dispatch actions ,

2.We have to convert ES7 to ES6 in the following way

ES7

import { DragSource } from 'react-dnd';

@DragSource(type, spec, collect)
export default class MyComponent {
  /* ... */
}

We have make use of ES6 in the below way

import { DragSource } from 'react-dnd';

class MyComponent {
  /* ... */
}

export default DragSource(type, spec, collect)(MyComponent);

You can get the examples from the below link

https://react-dnd.github.io/react-dnd/docs-faq.html


问:
Yii2 Count all record in table
How to count all the records in database and post the result?
This is my codes i don't know whats wrong the result is only 0.</p>

```<code>$id = new reportDetails();
        $id->report_id;
        $dataProvider = new ActiveDataProvider([
        'query' => reportDetails::find()
                ->where(['report_id'=> $id]),
        ]);

        echo $dataProvider->getCount();
</code>```

答:
Use all(); after Query and then try </p>

```<code>$id = new reportDetails();
        $id->report_id;
        $dataProvider = new ActiveDataProvider([
        'query' => reportDetails::find()
                ->where(['report_id'=> $id])->all(),
        ]);

        echo $dataProvider->getCount();
</code>```

Title: Yii2 Count all record in table

Body:
How to count all the records in database and post the result?
This is my codes i don't know whats wrong the result is only 0.

$id = new reportDetails();
        $id->report_id;
        $dataProvider = new ActiveDataProvider([
        'query' => reportDetails::find()
                ->where(['report_id'=> $id]),
        ]);

        echo $dataProvider->getCount();

Body:
Use all(); after Query and then try

$id = new reportDetails();
        $id->report_id;
        $dataProvider = new ActiveDataProvider([
        'query' => reportDetails::find()
                ->where(['report_id'=> $id])->all(),
        ]);

        echo $dataProvider->getCount();


问:
Where should the authorization logic go in an api based application?
I have a brand new Rails api based application, where i need to implement authorization.

Overall Architecture:

React frontend -> Rails API layer -> Rails model/server layer

While exploring different approaches, I have got a confusion.

Should we put the authorization logic in API layer or Service layer?

API Layer Approach:   We will build some authorization middleware that will sit between our front end and API layer and all our api calls will be routed thorough the authorization middleware to check if the user is allowed to call that parituclar api.

Service Layer: All the authorization check will go to service layer and we will have check before every db operation if the user is allowed to do so. (Using cancancan / pundit) and if the user is not allowed throw the error message to API layer.

It would be a great help, if someone could suggest based on their experience.

答:
tl;dr

Outside the app - always externalize authorization. Decouple your authorization logic from your business logic.

Longer answer

Since the beginning of SOA (service-oriented architecture), API architectures and now microservices, the trend has been towards breaking down application silos and designing systems in such a way you can reuse common functionality. For instance, you use a central authentication service (you wouldn't, I hope, implement your own authentication scheme) and a central logging mechanism.

The same applies to authorization. There is something called externalized authorization which promotes:

decoupling authorization logic from the application. Many dev frameworks already do that (Spring Security, Microsoft Claims, Ruby CanCanCan...)

centralizing authorization logic into a single point of management.

expressing authorization logic as human-readable policies. This means you can write policies such as

Doctors can view the medical records of patients they have a relationship with

using attributes to define these policies: this is called attribute-based access control (ABAC). It is the de factor authorization model for new app developments (such as API). NIST published an excellent report on the topic in 2013.

Architecture

ABAC promotes the following architecture and flow (more details here)

Policy Enforcement Point

Policy Decision Point

Policy Information Point

Policy Administration Point

ABAC Implementation: XACML & ALFA

Generic approaches

There are 2 standards that implement ABAC today. XACML provides both a language and an architecture (see above). ALFA provides a language.

ABAC in Ruby

Check out this project: CanCanCan.


问:
XML file or database in this particular case (file updated frequently)
I have a list of URL and I should loop over them every minute or so and save the last successful access time into an XML file or database. Obviously, the URL and some short description will be saved in file as well.

I'm wondering whether XML files are reliable enough or I'm better with a database? If I must go with the database option, which one?

Please advise. Thanks.

答:
You can use XML file for this purpose.

There are lot of options for XML like XML Data Binding, TXMLDocument, XML with ClientDatasets etc.

The simplest option is XML with ClientDataSet.

This is the procedure:

Drop a ClientDataSet on the the form.

Add FieldDefs you need to the ClientDataSet.

Right click on the ClientDataSet component and click Create Dataset.

Right click again and click Save To MyBase XML Table.

You XML is ready and from now onwards you can use ClientDataSet1.LoadFromFile() and   ClientDataSet1.SaveToFile() functions to load and save data.

Then you can assign ClientDataSet DataSource to the DBGrid.


问:
AdellePE Bold font in css
I have a text whose font-family is AdellePE Bold I am wondering how can I use it in our CSS?

```<code>.blog-text
{
    position: absolute;
    top: 200px;
    font-weight: bold;
    left: 100px;
    color: rgb(254, 91, 31);
    font-family: AdellePE Bold ;
    font-size: 30px;
    letter-spacing: .24em;
}
</code>```

I am using the above code but unfortunately its not matching the font of the text.

答:
Declare the font-face as below with

```<code>@font-face {
font-family: AdellePE Bold;
src: url(fonts/[FONT NAME].woff);
}
</code>```

Replace [FONT NAME] above with your font name for the font file. Your font might need single quotes to work so be sure to check that.

```<code>.blog-text
{
position: absolute;
top: 200px;
font-weight: bold;
left: 100px;
color: rgb(254, 91, 31);
font-family: AdellePE Bold ;
font-size: 30px;
letter-spacing: .24em;
}
</code>```

Let me know if it works.

Title: AdellePE Bold font in css

Body:
I have a text whose font-family is AdellePE Bold I am wondering how can I use it in our CSS?

.blog-text
{
    position: absolute;
    top: 200px;
    font-weight: bold;
    left: 100px;
    color: rgb(254, 91, 31);
    font-family: AdellePE Bold ;
    font-size: 30px;
    letter-spacing: .24em;
}

I am using the above code but unfortunately its not matching the font of the text.

Body:
Declare the font-face as below with

@font-face {
font-family: AdellePE Bold;
src: url(fonts/[FONT NAME].woff);
}

Replace [FONT NAME] above with your font name for the font file. Your font might need single quotes to work so be sure to check that.

.blog-text
{
position: absolute;
top: 200px;
font-weight: bold;
left: 100px;
color: rgb(254, 91, 31);
font-family: AdellePE Bold ;
font-size: 30px;
letter-spacing: .24em;
}

Let me know if it works.


问:
Apache OFBiz installation trouble with BIRT container
I am new to Apache OFBiz. I have downloaded and installing the OFBiz by instructions. I have loaded the data successfully.

But when am running OFBiz using gradlew it stopped at birt-container. I have added the console information here.

Build process stopped at 91% with the message of "Started container birt-container" for 5 hours and I have stopped the process. Still no idea why it is stopping here.

```<code>2017-05-04 11:01:42,143 |main                 |CatalinaContainer             |I| Connector HTTP/1.1 @ 8443 - secure [org.apache.coyote.http11.Http11NioProtocol] started.
2017-05-04 11:01:42,143 |main                 |CatalinaContainer             |I| Started Apache Tomcat/8.0.37
2017-05-04 11:01:42,143 |main                 |ContainerLoader               |I| Started container catalina-container
2017-05-04 11:01:42,143 |main                 |ContainerLoader               |I| Starting container birt-container
2017-05-04 11:01:42,143 |main                 |BirtContainer                 |I| Start BIRT container
2017-05-04 11:01:42,152 |main                 |BirtContainer                 |I| Startup BIRT platform
2017-05-04 11:01:43,034 |main                 |BirtContainer                 |I| Create factory object
2017-05-04 11:01:43,052 |main                 |BirtContainer                 |I| Create report engine
2017-05-04 11:01:43,130 |main                 |BirtContainer                 |I| BIRT supported formats: xlsx, postscript, docx, pptx, pdf, ppt, xls_spudsoft, doc, html,
odp, xls, odt, ods
2017-05-04 11:01:43,130 |main                 |ContainerLoader               |I| Started container birt-container
> Building 91% > :ofbiz
</code>```

答:
Prepare OFBiz:

Clean all:
gradlew cleanAll loadDefault testIntegration

Note: Depending on your Internet connection speed it might take a long time for this step to complete if you are using OFBiz for the first time as it needs to download all dependencies. So please be patient!

MS Windows: gradlew cleanAll loadDefault

Unix-like OS: ./gradlew cleanAll loadDefault

Start OFBiz:

MS Windows: gradlew ofbiz

Unix-like OS: ./gradlew ofbiz

Reference: After download http://www.apache.org/dyn/closer.lua/ofbiz/apache-ofbiz-16.11.02.zip , unzip, look for
apache-ofbiz-16.11.02/tools/documentation/README.md.html

Body:
I am new to Apache OFBiz. I have downloaded and installing the OFBiz by instructions. I have loaded the data successfully.

But when am running OFBiz using gradlew it stopped at birt-container. I have added the console information here.

Build process stopped at 91% with the message of "Started container birt-container" for 5 hours and I have stopped the process. Still no idea why it is stopping here.

2017-05-04 11:01:42,143 |main                 |CatalinaContainer             |I| Connector HTTP/1.1 @ 8443 - secure [org.apache.coyote.http11.Http11NioProtocol] started.
2017-05-04 11:01:42,143 |main                 |CatalinaContainer             |I| Started Apache Tomcat/8.0.37
2017-05-04 11:01:42,143 |main                 |ContainerLoader               |I| Started container catalina-container
2017-05-04 11:01:42,143 |main                 |ContainerLoader               |I| Starting container birt-container
2017-05-04 11:01:42,143 |main                 |BirtContainer                 |I| Start BIRT container
2017-05-04 11:01:42,152 |main                 |BirtContainer                 |I| Startup BIRT platform
2017-05-04 11:01:43,034 |main                 |BirtContainer                 |I| Create factory object
2017-05-04 11:01:43,052 |main                 |BirtContainer                 |I| Create report engine
2017-05-04 11:01:43,130 |main                 |BirtContainer                 |I| BIRT supported formats: xlsx, postscript, docx, pptx, pdf, ppt, xls_spudsoft, doc, html,
odp, xls, odt, ods
2017-05-04 11:01:43,130 |main                 |ContainerLoader               |I| Started container birt-container
> Building 91% > :ofbiz


问:
how to flip a pixmap to draw to a texture in libgdx?
So what I'm trying to do is to generate a background image for my game by drawing pixmaps to a texture. So far I can do that, but now I need to draw the pixmaps flipped in the X or Y axis to the texture. However I can't find anything to do so. The pixmap class does not provide that functionality. Then I thought I could draw a flipped texture region to a texture, but so far I haven't found how to do so. So I was wondering how can I do such a thing, would it be possible to flip a png image with other java libraries and then create a pixmap from that flipped image?</p>

答:
Here's a solution that doesn't require the creation of a new Pixmap. This code can also be modified to flip a Pixmap horizontally and vertically by swapping corners of a pixmap image instead of swapping pixels on opposite sides of the image. </p>

```<code>public static void flipPixmap( Pixmap p ){
    int w = p.getWidth();
    int h = p.getHeight();
    int hold;

    //change blending to 'none' so that alpha areas will not show
      //previous orientation of image
    p.setBlending(Pixmap.Blending.None);
    for (int y = 0; y < h / 2; y++) {
        for (int x = 0; x < w / 2; x++) {
            //get color of current pixel
            hold = p.getPixel(x,y);
            //draw color of pixel from opposite side of pixmap to current position
            p.drawPixel(x,y, p.getPixel(w-x-1, y));
            //draw saved color to other side of pixmap
            p.drawPixel(w-x-1,y, hold);
            //repeat for height/width inverted pixels
            hold = p.getPixel(x, h-y-1);
            p.drawPixel(x,h-y-1, p.getPixel(w-x-1,h-y-1));
            p.drawPixel(w-x-1,h-y-1, hold);
        }
    }
    //set blending back to default
    p.setBlending(Pixmap.Blending.SourceOver);
}
</code>```

Body:
Here's a solution that doesn't require the creation of a new Pixmap. This code can also be modified to flip a Pixmap horizontally and vertically by swapping corners of a pixmap image instead of swapping pixels on opposite sides of the image.

public static void flipPixmap( Pixmap p ){
    int w = p.getWidth();
    int h = p.getHeight();
    int hold;

    //change blending to 'none' so that alpha areas will not show
      //previous orientation of image
    p.setBlending(Pixmap.Blending.None);
    for (int y = 0; y < h / 2; y++) {
        for (int x = 0; x < w / 2; x++) {
            //get color of current pixel
            hold = p.getPixel(x,y);
            //draw color of pixel from opposite side of pixmap to current position
            p.drawPixel(x,y, p.getPixel(w-x-1, y));
            //draw saved color to other side of pixmap
            p.drawPixel(w-x-1,y, hold);
            //repeat for height/width inverted pixels
            hold = p.getPixel(x, h-y-1);
            p.drawPixel(x,h-y-1, p.getPixel(w-x-1,h-y-1));
            p.drawPixel(w-x-1,h-y-1, hold);
        }
    }
    //set blending back to default
    p.setBlending(Pixmap.Blending.SourceOver);
}


问:
Download Image attached using Paperclip
Is there a way to make the users download the images attached using paperclip?

I just made a link like this:

```<code>link_to 'imagename', image.attachment.url
</code>```

But this makes the browser open the image. I want the browser to ask the user to save the image. Is there a way to do that?

答:
Here's a simple solution using the HTML5 download attribute </p>

```<code><%= link_to image.name, image.attachment.url, download: image.attachment.original_filename %>
</code>```

Title: Download Image attached using Paperclip

Body:
Is there a way to make the users download the images attached using paperclip?

I just made a link like this:

link_to 'imagename', image.attachment.url

But this makes the browser open the image. I want the browser to ask the user to save the image. Is there a way to do that?

Body:
Here's a simple solution using the HTML5 download attribute

<%= link_to image.name, image.attachment.url, download: image.attachment.original_filename %>


问:
How can do multiple stationary tests for multiple timeseries in a dataframe
I have the following df:

```<code>head(vardata)
       Month repo Callrate  WPI GDP  FED    nse   usd
1 2001-04-01 9.00     7.49 5.41 4.6 4.50 1125.2 46.79
2 2001-05-01 8.75     8.03 5.60 4.6 4.00 1167.9 46.92
3 2001-06-01 8.50     7.24 5.30 4.6 3.75 1107.9 47.00
4 2001-07-01 8.50     7.19 5.23 5.3 3.75 1072.8 47.14
5 2001-08-01 8.50     6.94 5.41 5.3 3.50 1053.8 47.13
6 2001-09-01 8.50     7.30 4.52 5.3 3.00  913.9 47.65

vardata_num<-df[,2:8]
</code>```

I want to conduct Box.test, adf.test, and kpss.test for all the 7 var with following set of rules:

Say I set a significance level of 5%. Then the rules are:

1) For the Box.test, if p-value < 0.05 => stationary

2) For the adf.test, if p-value < 0.05 => stationary

3) For the kpss.test, if p-value > 0.05 => stationary (note change of inequality)

Individually i did the tests as:

```<code>Box.test(ts(vardata_num$repo),lag=20,type="Ljung-Box")

    Box-Ljung test

data:  ts(vardata_num$repo)
X-squared = 1100, df = 20, p-value <2e-16

adf.test(ts(vardata_num$repo),alternative = "stationary")

    Augmented Dickey-Fuller Test

data:  ts(vardata_num$repo)
Dickey-Fuller = -2.7, Lag order = 5, p-value = 0.3
alternative hypothesis: stationary

kpss.test(ts(vardata_num$repo))

    KPSS Test for Level Stationarity

data:  ts(vardata_num$repo)
KPSS Level = 0.32, Truncation lag parameter = 3, p-value = 0.1

# to extract p values
Box.test(ts(vardata_num$repo),lag=20,type="Ljung-Box")$p.value
adf.test(ts(vardata_num$repo),alternative = "stationary")$p.value
kpss.test(ts(vardata_num$repo))$p.value
</code>```

This was done one at a time for all the variables.....

But I would like to do all these tests in one go for all the var & the outputted in some sort of a data frame if possible maybe like this:

```<code>   var         box.pvalue  box  adf.pvalue adf  kpss.pvalue kpss
   repo          0.03      TRUE    0.03   TRUE     0.03    FALSE
   Callrate      0.03      TRUE    0.03   TRUE     0.03    FALSE
   WPI           0.03      TRUE    0.03   TRUE     0.03    FALSE
   GDP           0.03      TRUE    0.03   TRUE     0.03    FALSE
   FED           0.51      FALSE   0.03   TRUE     0.03    FALSE
   nse           0.03      TRUE    0.03   TRUE     0.03    FALSE
   usd           0.45      FALSE   0.03   TRUE     0.03    FALSE
</code>```

Where TRUE= series is stationary ; FALSE= series is NON-stationary

update--- my attempt

stationarity tests for multiple time series

```<code>multi_stat_tests<- function(df){
  for(i in 1:dim(df)[2]){
    df_multi<-data.frame(var=names(df)[i],box.pvalue=Box.test(ts(df[,i]),lag=20,type="Ljung-Box")$p.value,adf.pvalue=adf.test(ts(df[,i]),alternative = "stationary")$p.value,kpss.pvalue=kpss.test(ts(df[,i]))$p.value,
box=Box.test(ts(df[,i]),lag=20,type="Ljung-Box")$p.value<0.05,
adf=adf.test(ts(df[,i]),alternative = "stationary")$p.value<0.05,
kpss=kpss.test(ts(df[,i]))$p.value>0.05
)
    return(df_multi)
  }
}

>multi_stat_tests(vardata_num)

  var box.pvalue adf.pvalue  kpss.pvalue  box  adf  kpss
1 repo          0     0.2859         0.1 TRUE FALSE TRUE
</code>```

Its just picking up only one var......its not iterating across all the variables...missing something here....HELP required!!!!!

答:
Here is the usual and not so efficient way of doing the same

```<code>multi_stat_tests<- function(df){
    p <- ncol(df)
    df_multi <- data.frame(var=names(df),
                           box.pvalue=sapply(df, function(v) Box.test(ts(v),lag=20,type="Ljung-Box")$p.value),
                           adf.pvalue=sapply(df, function(v) adf.test(ts(v),alternative = "stationary")$p.value),
                           kpss.pvalue=sapply(df, function(v) kpss.test(ts(v))$p.value)
                           )
    df_multi$box <- df_multi$box.pvalue < 0.05
    df_multi$adf <- df_multi$adf.pvalue < 0.05
    df_multi$kpss <- df_multi$kpss.pvalue > 0.05
    row.names(df_multi) <- c()
    df_multi[,c(1,2,5,3,6,4,7)]
}

df2<-multi_stat_tests(vardata_num)
df2
##        var box.pvalue  box adf.pvalue   adf kpss.pvalue  kpss
## 1     repo          0 TRUE    0.28593 FALSE     0.10000  TRUE
## 2 Callrate          0 TRUE    0.06008 FALSE     0.01000 FALSE
## 3      WPI          0 TRUE    0.28803 FALSE     0.03910 FALSE
## 4      GDP          0 TRUE    0.04358  TRUE     0.06211  TRUE
## 5      FED          0 TRUE    0.43113 FALSE     0.01000 FALSE
## 6      nse          0 TRUE    0.02745  TRUE     0.01000 FALSE
</code>```

Body:
I have the following df:

head(vardata)
       Month repo Callrate  WPI GDP  FED    nse   usd
1 2001-04-01 9.00     7.49 5.41 4.6 4.50 1125.2 46.79
2 2001-05-01 8.75     8.03 5.60 4.6 4.00 1167.9 46.92
3 2001-06-01 8.50     7.24 5.30 4.6 3.75 1107.9 47.00
4 2001-07-01 8.50     7.19 5.23 5.3 3.75 1072.8 47.14
5 2001-08-01 8.50     6.94 5.41 5.3 3.50 1053.8 47.13
6 2001-09-01 8.50     7.30 4.52 5.3 3.00  913.9 47.65

vardata_num<-df[,2:8]

I want to conduct Box.test, adf.test, and kpss.test for all the 7 var with following set of rules:

Say I set a significance level of 5%. Then the rules are:

1) For the Box.test, if p-value < 0.05 => stationary

2) For the adf.test, if p-value < 0.05 => stationary

3) For the kpss.test, if p-value > 0.05 => stationary (note change of inequality)

Individually i did the tests as:

Box.test(ts(vardata_num$repo),lag=20,type="Ljung-Box")

    Box-Ljung test

data:  ts(vardata_num$repo)
X-squared = 1100, df = 20, p-value <2e-16

adf.test(ts(vardata_num$repo),alternative = "stationary")

    Augmented Dickey-Fuller Test

data:  ts(vardata_num$repo)
Dickey-Fuller = -2.7, Lag order = 5, p-value = 0.3
alternative hypothesis: stationary

kpss.test(ts(vardata_num$repo))

    KPSS Test for Level Stationarity

data:  ts(vardata_num$repo)
KPSS Level = 0.32, Truncation lag parameter = 3, p-value = 0.1

# to extract p values
Box.test(ts(vardata_num$repo),lag=20,type="Ljung-Box")$p.value
adf.test(ts(vardata_num$repo),alternative = "stationary")$p.value
kpss.test(ts(vardata_num$repo))$p.value

This was done one at a time for all the variables.....

But I would like to do all these tests in one go for all the var & the outputted in some sort of a data frame if possible maybe like this:

   var         box.pvalue  box  adf.pvalue adf  kpss.pvalue kpss
   repo          0.03      TRUE    0.03   TRUE     0.03    FALSE
   Callrate      0.03      TRUE    0.03   TRUE     0.03    FALSE
   WPI           0.03      TRUE    0.03   TRUE     0.03    FALSE
   GDP           0.03      TRUE    0.03   TRUE     0.03    FALSE
   FED           0.51      FALSE   0.03   TRUE     0.03    FALSE
   nse           0.03      TRUE    0.03   TRUE     0.03    FALSE
   usd           0.45      FALSE   0.03   TRUE     0.03    FALSE

Where TRUE= series is stationary ; FALSE= series is NON-stationary

update--- my attempt

stationarity tests for multiple time series

multi_stat_tests<- function(df){
  for(i in 1:dim(df)[2]){
    df_multi<-data.frame(var=names(df)[i],box.pvalue=Box.test(ts(df[,i]),lag=20,type="Ljung-Box")$p.value,adf.pvalue=adf.test(ts(df[,i]),alternative = "stationary")$p.value,kpss.pvalue=kpss.test(ts(df[,i]))$p.value,
box=Box.test(ts(df[,i]),lag=20,type="Ljung-Box")$p.value<0.05,
adf=adf.test(ts(df[,i]),alternative = "stationary")$p.value<0.05,
kpss=kpss.test(ts(df[,i]))$p.value>0.05
)
    return(df_multi)
  }
}

>multi_stat_tests(vardata_num)

  var box.pvalue adf.pvalue  kpss.pvalue  box  adf  kpss
1 repo          0     0.2859         0.1 TRUE FALSE TRUE

Its just picking up only one var......its not iterating across all the variables...missing something here....HELP required!!!!!

Body:
Here is the usual and not so efficient way of doing the same

multi_stat_tests<- function(df){
    p <- ncol(df)
    df_multi <- data.frame(var=names(df),
                           box.pvalue=sapply(df, function(v) Box.test(ts(v),lag=20,type="Ljung-Box")$p.value),
                           adf.pvalue=sapply(df, function(v) adf.test(ts(v),alternative = "stationary")$p.value),
                           kpss.pvalue=sapply(df, function(v) kpss.test(ts(v))$p.value)
                           )
    df_multi$box <- df_multi$box.pvalue < 0.05
    df_multi$adf <- df_multi$adf.pvalue < 0.05
    df_multi$kpss <- df_multi$kpss.pvalue > 0.05
    row.names(df_multi) <- c()
    df_multi[,c(1,2,5,3,6,4,7)]
}

df2<-multi_stat_tests(vardata_num)
df2
##        var box.pvalue  box adf.pvalue   adf kpss.pvalue  kpss
## 1     repo          0 TRUE    0.28593 FALSE     0.10000  TRUE
## 2 Callrate          0 TRUE    0.06008 FALSE     0.01000 FALSE
## 3      WPI          0 TRUE    0.28803 FALSE     0.03910 FALSE
## 4      GDP          0 TRUE    0.04358  TRUE     0.06211  TRUE
## 5      FED          0 TRUE    0.43113 FALSE     0.01000 FALSE
## 6      nse          0 TRUE    0.02745  TRUE     0.01000 FALSE


问:
cancel canvas animation by adding eventListener
I am trying to reset my rectangle animation from the starting point when I resize the browser, the code is like this:

```<code>/*from basic setup*/
canvas = document.getElementById("myCanvas");
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
ctx = canvas.getContext("2d");

/*the "resize" event and the reset function should be triggered */
window.addEventListener("resize",function(){
     canvas.height = window.innerHeight;
     canvas.width = window.innerWidth;
     //cancelAnimationFrame(timeID)
     //theRect();
});

/*drawing the rectangle*/
var x = 0,y = canvas.height - 100,w = 100, h = 100,dx=1;

function theRect(){
 ctx.fillStyle = "lightblue";
 ctx.fillRect(x,y,w,h)
 x+=dx;
 if(x+w>canvas.width/2 || x<0){
    dx=-dx;
 }
}

/*start animation*/

function animate(){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    theRect();
    requestAnimationFrame(animate);

}
//var timeID = requestAnimationFrame(animate)

animate();
</code>```

I was thinking if each time the browser resized, the rectangle has to be reset to the starting point asctx.fillRect(0,canvas.height-100,100,100)and continue its animation.

So my original approach to solve this is using cancelAnimationFrame()this method to kill the animation first and calling this function again within my eventlistener so each time the event was fired, the animation will stop and run again.

but cancellAnimationFrame()function requires the target animation timeID, and there is no way to track this timeID inside my animate()function since if I am calling var timeID = requestionAnimationFrame(animate)it will come to huge lag spikes on my browser

just the more I want to modify to more I become to loss with this, so my questions are:

1, is this wise to use cancelAnimationFrame here as the first step to reset my animation?

2, is there any other good way to achieve this "reset" purpose?

Could someone please help me with this? thanks in advance.

答:
There is no need to use cancelAnimationFrame() function at all in this case scenario.

You could just simply change / reset the value  (position) of x and y variable accordingly on window resize and that will reset the rectangle's starting position / point.

Since, the animate function is running in a recursive manner hence, changes to any variable's (used inside animate function) value will take effect immediately.

/*from basic setup*/
canvas = document.getElementById("myCanvas");
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
ctx = canvas.getContext("2d");

/*drawing the rectangle*/
var x = 0,
   y = canvas.height - 100,
   w = 100,
   h = 100,
   dx = 1;

/*the "resize" event and the reset function should be triggered */
window.addEventListener("resize", function() {
   canvas.height = window.innerHeight;
   canvas.width = window.innerWidth;
   x = 0; //reset starting point (x-axis)
   y = canvas.height - 100; //reset starting point (y-axis)
});

function theRect() {
   ctx.fillStyle = "lightblue";
   ctx.fillRect(x, y, w, h);
   x += dx;
   if (x + w > canvas.width / 2 || x < 0) {
      dx = -dx;
   }
}

/*start animation*/
function animate() {
   ctx.clearRect(0, 0, canvas.width, canvas.height);
   theRect();
   requestAnimationFrame(animate);
}
animate();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{margin:0;overflow:hidden}</code>```

<canvas id="myCanvas"></canvas>```

also, see a demo on JSBin

Body:
I am trying to reset my rectangle animation from the starting point when I resize the browser, the code is like this:

/*from basic setup*/
canvas = document.getElementById("myCanvas");
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
ctx = canvas.getContext("2d");

/*the "resize" event and the reset function should be triggered */
window.addEventListener("resize",function(){
     canvas.height = window.innerHeight;
     canvas.width = window.innerWidth;
     //cancelAnimationFrame(timeID)
     //theRect();
});

/*drawing the rectangle*/
var x = 0,y = canvas.height - 100,w = 100, h = 100,dx=1;

function theRect(){
 ctx.fillStyle = "lightblue";
 ctx.fillRect(x,y,w,h)
 x+=dx;
 if(x+w>canvas.width/2 || x<0){
    dx=-dx;
 }
}

/*start animation*/

function animate(){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    theRect();
    requestAnimationFrame(animate);

}
//var timeID = requestAnimationFrame(animate)

animate();

I was thinking if each time the browser resized, the rectangle has to be reset to the starting point asctx.fillRect(0,canvas.height-100,100,100)and continue its animation.

So my original approach to solve this is using cancelAnimationFrame()this method to kill the animation first and calling this function again within my eventlistener so each time the event was fired, the animation will stop and run again.

but cancellAnimationFrame()function requires the target animation timeID, and there is no way to track this timeID inside my animate()function since if I am calling var timeID = requestionAnimationFrame(animate)it will come to huge lag spikes on my browser

just the more I want to modify to more I become to loss with this, so my questions are:

1, is this wise to use cancelAnimationFrame here as the first step to reset my animation?

2, is there any other good way to achieve this "reset" purpose?

Could someone please help me with this? thanks in advance.

Body:
There is no need to use cancelAnimationFrame() function at all in this case scenario.

You could just simply change / reset the value  (position) of x and y variable accordingly on window resize and that will reset the rectangle's starting position / point.

Since, the animate function is running in a recursive manner hence, changes to any variable's (used inside animate function) value will take effect immediately.

/*from basic setup*/
canvas = document.getElementById("myCanvas");
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
ctx = canvas.getContext("2d");

/*drawing the rectangle*/
var x = 0,
   y = canvas.height - 100,
   w = 100,
   h = 100,
   dx = 1;

/*the "resize" event and the reset function should be triggered */
window.addEventListener("resize", function() {
   canvas.height = window.innerHeight;
   canvas.width = window.innerWidth;
   x = 0; //reset starting point (x-axis)
   y = canvas.height - 100; //reset starting point (y-axis)
});

function theRect() {
   ctx.fillStyle = "lightblue";
   ctx.fillRect(x, y, w, h);
   x += dx;
   if (x + w > canvas.width / 2 || x < 0) {
      dx = -dx;
   }
}

/*start animation*/
function animate() {
   ctx.clearRect(0, 0, canvas.width, canvas.height);
   theRect();
   requestAnimationFrame(animate);
}
animate();

body{margin:0;overflow:hidden}

<canvas id="myCanvas"></canvas>

also, see a demo on JSBin


问:
How can we take the sum of each columns in SQL Server without using ;with cte?
How can I take sum of each rows by two row sum in 3rd column?

Here's a screenshot to illustrate:

You can see for id 1 sum is 10 but for id 2 sum is 10+50 = 60
and third sum is 60+100 = 160 and so on.

With Cte it is working fine for me. I need with out ;with cte means though code I need the sum

Example will as shown below

```<code>DECLARE @t TABLE(ColumnA INT, ColumnB VARCHAR(50));

INSERT INTO @t
VALUES (10,'1'), (50,'2'), (100,'3'), (5,'4'), (45,'5');

;WITH cte AS
(
   SELECT ColumnB, SUM(ColumnA) asum
   FROM @t
   GROUP BY ColumnB
), cteRanked AS
(
   SELECT asum, ColumnB, ROW_NUMBER() OVER(ORDER BY ColumnB) rownum
   FROM cte
)
SELECT
    (SELECT SUM(asum)
     FROM cteRanked c2
     WHERE c2.rownum <= c1.rownum) AS ColumnA,
    ColumnB
FROM
    cteRanked c1;
</code>```

答:
One option, which doesn't require explicit analytic functions, would be to use a correlated subquery to calculate the running total:

```<code>SELECT
    t1.ID,
    t1.Currency,
    (SELECT SUM(t2.Currency) FROM yourTable t2 WHERE t2.ID <= t1.ID) AS Sum
FROM yourTable t1
</code>```

Output:

Demo here:

Rextester

Body:
How can I take sum of each rows by two row sum in 3rd column?

Here's a screenshot to illustrate:

You can see for id 1 sum is 10 but for id 2 sum is 10+50 = 60
and third sum is 60+100 = 160 and so on.

With Cte it is working fine for me. I need with out ;with cte means though code I need the sum

Example will as shown below

DECLARE @t TABLE(ColumnA INT, ColumnB VARCHAR(50));

INSERT INTO @t
VALUES (10,'1'), (50,'2'), (100,'3'), (5,'4'), (45,'5');

;WITH cte AS
(
   SELECT ColumnB, SUM(ColumnA) asum
   FROM @t
   GROUP BY ColumnB
), cteRanked AS
(
   SELECT asum, ColumnB, ROW_NUMBER() OVER(ORDER BY ColumnB) rownum
   FROM cte
)
SELECT
    (SELECT SUM(asum)
     FROM cteRanked c2
     WHERE c2.rownum <= c1.rownum) AS ColumnA,
    ColumnB
FROM
    cteRanked c1;

Body:
One option, which doesn't require explicit analytic functions, would be to use a correlated subquery to calculate the running total:

SELECT
    t1.ID,
    t1.Currency,
    (SELECT SUM(t2.Currency) FROM yourTable t2 WHERE t2.ID <= t1.ID) AS Sum
FROM yourTable t1

Output:

Demo here:

Rextester


问:
React const keyword and creating component
I am working on a React App, which seems to be creating a react components in the following manner:

```<code>const VariableName = () => {
<div>
<p>SomeText</p>
</div>
</code>```

However, the materials available online show that the manner to create a React Component is

```<code>const VariableName = React.createClass({
  render() {
    return (
      <div>
       <p>SomeText</p>
      </div>
    );
  }
});
</code>```

What is the difference and how is the ReactApp that I am working on rendering the component?

答: The stateless components introduced in react 0.14 allows as don’t declare class and pass props to the component. Basically it's just a ES6 arrow function sintaksis  </p>

Body:
I am working on a React App, which seems to be creating a react components in the following manner:

const VariableName = () => {

SomeText

However, the materials available online show that the manner to create a React Component is

const VariableName = React.createClass({
  render() {
    return (

SomeText

    );
  }
});

What is the difference and how is the ReactApp that I am working on rendering the component?