问:
Initialize Bootstrap colorpicker with mongoDB data
I have a meteor application and I added the plugin colorpicker as a component.
But I want to initialize it with a value take in a MongoDB collection.
So I initialize the input text (something like #32a214) but I don't know how to initialize the color in the small square in the right.

In my html file I have :

```<code><div class="form-group"><label class="col-sm-2 control-label">Color text image<br/></label>
    <div class="col-sm-10">
         <div id="colorText" class="input-group colorpicker-component">
            <input type="text" value={{textImageColor}} id="textImageColor" placeholder="Choose a color" class="form-control" />
            <span class="input-group-addon"><i></i></span>
        </div>
    </div>
</div>
</code>```

In my javascript file, I have :

```<code>Template.yourTile.rendered = function(){

    $('#colorText').colorpicker({
        color: "#32a214"
    });
}
</code>```

So I want to replace "#32a214" with a value from the database.
I would like to do something like that :

```<code>color: {{textImageColor}}
</code>```

But it doesn't work.
So, do you know how I can do it ?

EDIT :

I have a javascript code on the server side :

```<code>Meteor.publish('tiles', function(){
  return tiles.find();
});
</code>```

And I get the data with a helper :

```<code>Template.yourTile.helpers({
    'textImageColor': function(){
        var userID = Meteor.userId();
        var doc = tiles.findOne({createBy: userID });
        var textImageColor = doc && doc.textImageColor;
        if(textImageColor == ""){
            return "";
        }else{
            return textImageColor;
        }
    }
}
</code>```

So if I call {{textImageColor}} in a html file, it works, but not in the javascript file.
I think it's maybe because the loading. The color is initialized in the rendered, so if I replace the color with {{textImageColor}} it doesn't work because the value is not yet load from the mongoDB collection. So maybe I need to wait to have the value but I don't know how to do it.

答:
to do a successful pub/sub, you need all of the following:

collection with data in db

a collection definition common to the client and server code

a publisher on the server

a subscriber on the client

a find() on the client

it looks like you're missing #2.

in some common code (e.g. /collections/tiles.js), you need to define the collection. e.g.

```<code>tiles = new Mongo.Collection('tiles');
</code>```

when run on the server, it will ensure that collection exists in the db. on the client, it will create a mini-mongo instance for that collection against which the client-side find() runs. it will also create a reference, "tiles", to those collections.

Body:
I have a meteor application and I added the plugin colorpicker as a component.
But I want to initialize it with a value take in a MongoDB collection.
So I initialize the input text (something like #32a214) but I don't know how to initialize the color in the small square in the right.

In my html file I have :

Color text image

            <input type="text" value={{textImageColor}} id="textImageColor" placeholder="Choose a color" class="form-control" />

In my javascript file, I have :

Template.yourTile.rendered = function(){

    $('#colorText').colorpicker({
        color: "#32a214"
    });
}

So I want to replace "#32a214" with a value from the database.
I would like to do something like that :

color: {{textImageColor}}

But it doesn't work.
So, do you know how I can do it ?

EDIT :

I have a javascript code on the server side :

Meteor.publish('tiles', function(){
  return tiles.find();
});

And I get the data with a helper :

Template.yourTile.helpers({
    'textImageColor': function(){
        var userID = Meteor.userId();
        var doc = tiles.findOne({createBy: userID });
        var textImageColor = doc && doc.textImageColor;
        if(textImageColor == ""){
            return "";
        }else{
            return textImageColor;
        }
    }
}

So if I call {{textImageColor}} in a html file, it works, but not in the javascript file.
I think it's maybe because the loading. The color is initialized in the rendered, so if I replace the color with {{textImageColor}} it doesn't work because the value is not yet load from the mongoDB collection. So maybe I need to wait to have the value but I don't know how to do it.

Body:
to do a successful pub/sub, you need all of the following:

collection with data in db

a collection definition common to the client and server code

a publisher on the server

a subscriber on the client

a find() on the client

it looks like you're missing #2.

in some common code (e.g. /collections/tiles.js), you need to define the collection. e.g.

tiles = new Mongo.Collection('tiles');

when run on the server, it will ensure that collection exists in the db. on the client, it will create a mini-mongo instance for that collection against which the client-side find() runs. it will also create a reference, "tiles", to those collections.


来源: stackexchange

问:
Setting an ACPI field in Linux
I've a netbook that is running the fan a bit to early for my liking. I've found a Windows-only solution to reducing the fan noise but I'm using Ubuntu on this computer.

In the Windows solution the guy is using a program called Notebook Hardware Control (NHC) which, from what I can make out, is reading and setting ACPI values. (http://hpmini110c.siteboard.eu/f3t31-lueftersteuerung-fuer-den-mini.html, relevant source in the 7z-file, the .cs-file in there is a C#-file with the logic for setting the fan on)

The part I would like to find a way to replicate in a Linux environment is:

```<code># Where the value is being set
write = ACPI.FIELD.Write("_SP.PCIO.SBRG.ECO.CTPM", 40);
# Reading the temperature
int temp1 = 0;
bool _tmp = APCI.FIELD.Read("_SB.PCIO.SBRG.ECO.TPM1", ref temp1)
</code>```

I'll be honest that I'm over my head on this, but if someone could nudge me in the right direction I'd be very grateful!

答:
Reflector says that NHC.exe is a managed assembly, and it contains the classes that provide ACPI.FIELD.Write() and ACPI.FIELD.Read() and so on.  The author of NHC has described, in the chm file, how to author your own classes that include calls to those things, for specific hardware types, something like a plugin model.

Rather than dropping in a .DLL, though, you drop in the actual C# code into a special folder; apparently nhc.exe dynamically compiles and runs this code when nhc.exe starts.  If all of that is true, you should be able to write your own app that uses ACPI.FIELD.Read and Write calls, compile it into an exe, specifying the nhc.exe as a reference.

The kicker though, is that nhc.exe is obfuscated, and all those classes are not visible. So you cannot simply run csc.exe and reference nhc.exe.  I don't know for sure, but it seems to me that It's only possible to run that code within the context of nhc.exe, which does a special compile to handle it.

The other bad news is that NHC development seems to have ceased; the forum website is dead, and the last update was from 2007.

ContentLicense: CC BY-SA 2.5

Title: Setting an ACPI field in Linux

Body:
I've a netbook that is running the fan a bit to early for my liking. I've found a Windows-only solution to reducing the fan noise but I'm using Ubuntu on this computer.

In the Windows solution the guy is using a program called Notebook Hardware Control (NHC) which, from what I can make out, is reading and setting ACPI values. (http://hpmini110c.siteboard.eu/f3t31-lueftersteuerung-fuer-den-mini.html, relevant source in the 7z-file, the .cs-file in there is a C#-file with the logic for setting the fan on)

The part I would like to find a way to replicate in a Linux environment is:

# Where the value is being set
write = ACPI.FIELD.Write("_SP.PCIO.SBRG.ECO.CTPM", 40);
# Reading the temperature
int temp1 = 0;
bool _tmp = APCI.FIELD.Read("_SB.PCIO.SBRG.ECO.TPM1", ref temp1)

I'll be honest that I'm over my head on this, but if someone could nudge me in the right direction I'd be very grateful!


问:
Spring oAuth2 with JWT using different authorization and resource servers
So I currently have this POC that I'm tinkering right now. I was thinking if it was possible that I can implement a Spring oAuth2 with JWT with a Authorization Server and a Resource Server both in different projects? </p>

<p>Flow goes like this User gets a token or passes through the Authorization Server and as long as he has the token and it's not expired he can make requests on the resource server. </p>

答:
I think that is the usual way to implement that. You have one authorization service providing tokens, either itself is backed by a database containing user information or maybe is  asking another user service if the credentials are valid. The returned tokens can be used to make authorized request against the resource service(s).

Maybe take a look at the grant flow here.

ContentLicense: CC BY-SA 3.0

Body:
So I currently have this POC that I'm tinkering right now. I was thinking if it was possible that I can implement a Spring oAuth2 with JWT with a Authorization Server and a Resource Server both in different projects?

Flow goes like this User gets a token or passes through the Authorization Server and as long as he has the token and it's not expired he can make requests on the resource server.


问:
Converting a List to pandas dataframe
I have the following list where the values are appended inside a loop like:

```<code>appended_data.append({'A': var.FIRST, 'B':VAR.SECOND})
</code>```

when printed:

```<code>appended_data[:1]
</code>```

Output:

```<code>[{'A':
904 23
945   65
965   36
Name: FIRST, dtype: float64,'B': 932    54
945 66
987 45
936 90
Name: SECOND, dtype: float64}]
</code>```

All I want to do is convert this to a pandas dataframe like so:

```<code>keys = ['FIRST','SECOND']
data_pol=pd.DataFrame(appended_data,columns = keys)
</code>```

But after printing data_pol.head() the dataframe is empty?

Title: Converting a List to pandas dataframe

Body:
I have the following list where the values are appended inside a loop like:

appended_data.append({'A': var.FIRST, 'B':VAR.SECOND})

when printed:

appended_data[:1]

Output:

[{'A':
904 23
945   65
965   36
Name: FIRST, dtype: float64,'B': 932    54
945 66
987 45
936 90
Name: SECOND, dtype: float64}]

All I want to do is convert this to a pandas dataframe like so:

keys = ['FIRST','SECOND']
data_pol=pd.DataFrame(appended_data,columns = keys)

But after printing data_pol.head() the dataframe is empty?

Body:
you want to call pd.DataFrame on the first element of appended_data.  You are calling it on a list.

appended_data[:1] is not the same as appended_data[0]

pd.DataFrame(appended_data[0])

        A     B
904  23.0   NaN
936   NaN  90.0
945  65.0  66.0
965  36.0   NaN
987   NaN  45.0

Consider the list of dictionaries of series appended_data

appended_data = [
    dict(
        A=pd.Series([23, 65, 36], [704, 745, 765]),
        B=pd.Series([66, 45, 90], [745, 787, 736])
    ),
    dict(
        A=pd.Series([23, 65, 36], [804, 845, 865]),
        B=pd.Series([66, 45, 90], [845, 887, 836])
    ),
    dict(
        A=pd.Series([23, 65, 36], [904, 945, 965]),
        B=pd.Series([66, 45, 90], [945, 987, 936])
    ),
]

Then we could use pd.concat

pd.concat([pd.DataFrame(i) for i in appended_data])

        A     B
704  23.0   NaN
736   NaN  90.0
745  65.0  66.0
765  36.0   NaN
787   NaN  45.0
804  23.0   NaN
836   NaN  90.0
845  65.0  66.0
865  36.0   NaN
887   NaN  45.0
904  23.0   NaN
936   NaN  90.0
945  65.0  66.0
965  36.0   NaN
987   NaN  45.0


问:
How to encrypt in Node.js?
I'm attempting to perform encryption in Node.js 7.5.0 using the 'des-cbc' algorithm. According to RFC 1423, this algorithm requires a 64-bit cryptographic key, and a 64-bit initialization vector.

I'm trying to use a key and iv composed of 8 Latin-1 characters; however, Node is saying, "Error: Invalid IV length". Here's some example code:

```<code>let crypto = require('crypto');

let key = '\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8',
     iv = '\xb8\xb7\xb6\xb5\xb4\xb3\xb2\xb1';

let cipher = crypto.createCipheriv('des-cbc', Buffer.from(key), Buffer.from(iv));
</code>```

If I change the iv to 8 ASCII characters, then Node is saying, "Error: Invalid key length":

```<code>let crypto = require('crypto');

let key = '\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8',
     iv = 'abcdefgh';

let cipher = crypto.createCipheriv('des-cbc', Buffer.from(key), Buffer.from(iv));
</code>```

But if both the key and iv are 8 ASCII characters, it works:

```<code>let crypto = require('crypto');

let key = 'hgfedcba',
     iv = 'abcdefgh';

let cipher = crypto.createCipheriv('des-cbc', Buffer.from(key), Buffer.from(iv));
</code>```

Why can't the Latin-1 characters be used for key and iv?

答:
Solution

You should either use

```<code>Buffer.from('\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8', 'binary')
</code>```

or even more cleaner as Maarten Bodewes points out

```<code>Buffer.from([0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8'])
</code>```

The same goes for your IV.

Reason

Buffer.from('\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8').length results in 16 which is not a valid length for a DES key. DES expects exactly 64 bits or 8 bytes as a key. That is also why DES is very insecure. The key size is simply too small.

The reason the above Buffer has a size of 16 bytes instead of 8 bytes is that the default encoding is UTF-8. If a code point is larger than 127 (decimal) or 0x7F (hexadecimal) it will encode into at least two bytes instead of one. Each and every code point (character) of your key is larger than 0x7F. So, each of them is encoded into two bytes.

Things to think about

Don't use DES nowadays. It only provides 56 bit of security. AES would be a much better, because it's more secure with the lowest key size of 128 bit. There is also a practical limit on the maximum ciphertext size with DES. See Security comparison of 3DES and AES.

The IV must be unpredictable (read: random). Don't use a static IV, because that makes the cipher deterministic and therefore not semantically secure. An attacker who observes ciphertexts can determine when the same message prefix was sent before. The IV is not secret, so you can send it along with the ciphertext. Usually, it is simply prepended to the ciphertext and sliced off before decryption.

The key is supposed to be indistinguishable from random noise. It is best to just generate it randomly and use it in your code in encoded form.

It is better to authenticate your ciphertexts so that attacks like a padding oracle attack are not possible. This can be done with authenticated modes like GCM or EAX, or with an encrypt-then-MAC scheme.

Title: How to encrypt in Node.js?

Body:
I'm attempting to perform encryption in Node.js 7.5.0 using the 'des-cbc' algorithm. According to RFC 1423, this algorithm requires a 64-bit cryptographic key, and a 64-bit initialization vector.

I'm trying to use a key and iv composed of 8 Latin-1 characters; however, Node is saying, "Error: Invalid IV length". Here's some example code:

let crypto = require('crypto');

let key = '\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8',
     iv = '\xb8\xb7\xb6\xb5\xb4\xb3\xb2\xb1';

let cipher = crypto.createCipheriv('des-cbc', Buffer.from(key), Buffer.from(iv));

If I change the iv to 8 ASCII characters, then Node is saying, "Error: Invalid key length":

let crypto = require('crypto');

let key = '\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8',
     iv = 'abcdefgh';

let cipher = crypto.createCipheriv('des-cbc', Buffer.from(key), Buffer.from(iv));

But if both the key and iv are 8 ASCII characters, it works:

let crypto = require('crypto');

let key = 'hgfedcba',
     iv = 'abcdefgh';

let cipher = crypto.createCipheriv('des-cbc', Buffer.from(key), Buffer.from(iv));

Why can't the Latin-1 characters be used for key and iv?

Body:
Solution

You should either use

Buffer.from('\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8', 'binary')

or even more cleaner as Maarten Bodewes points out

Buffer.from([0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8'])

The same goes for your IV.

Reason

Buffer.from('\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8').length results in 16 which is not a valid length for a DES key. DES expects exactly 64 bits or 8 bytes as a key. That is also why DES is very insecure. The key size is simply too small.

The reason the above Buffer has a size of 16 bytes instead of 8 bytes is that the default encoding is UTF-8. If a code point is larger than 127 (decimal) or 0x7F (hexadecimal) it will encode into at least two bytes instead of one. Each and every code point (character) of your key is larger than 0x7F. So, each of them is encoded into two bytes.

Things to think about

Don't use DES nowadays. It only provides 56 bit of security. AES would be a much better, because it's more secure with the lowest key size of 128 bit. There is also a practical limit on the maximum ciphertext size with DES. See Security comparison of 3DES and AES.

The IV must be unpredictable (read: random). Don't use a static IV, because that makes the cipher deterministic and therefore not semantically secure. An attacker who observes ciphertexts can determine when the same message prefix was sent before. The IV is not secret, so you can send it along with the ciphertext. Usually, it is simply prepended to the ciphertext and sliced off before decryption.

The key is supposed to be indistinguishable from random noise. It is best to just generate it randomly and use it in your code in encoded form.

It is better to authenticate your ciphertexts so that attacks like a padding oracle attack are not possible. This can be done with authenticated modes like GCM or EAX, or with an encrypt-then-MAC scheme.


问:
How to show no result found from a AngularJS search?
I am fetching data from an api and I am using it to search something. When the json returns no result how to show NO RESULT FOUND.

Html code

```<code>        <div class="item item-input-inset">
    <label class="item-input-wrapper">
      <input type="text" placeholder="Search" ng-model="search">
    </label>
    <button class="button button-small" ng-click="load(search)">
      Submit
    </button>
  </div>
  <section class="list">
       <article ng-repeat="object in news">
        <div class="item">

         <div ng-repeat="item in object.news">
        <p class="noWhiteSpace"><b>Available Size</b> - {{item.size}}</p>

         </div>

         </div>
         <div ng-repeat="item in object.news" class="button-bar bar-dark" >
  <a  ng-click = openUrl(item.url); class="button">button</a>

        </div>
      </article>
        </section>
        </ion-content>
      </ion-view>
    </script>
</code>```

This is JS Code where I am fetching data from an api and also searching it.

```<code> $http({

    method: "GET",
    url: https://news.com/json?limit=50"
  })
  .then(function(newsData){
   $scope.news= newsData.data.data.articles;
   $scope.hide();
    console.log(data);

  })

      $scope.load = function(search) {
     $scope.show();
  $http({
    method: "GET",
    url: "https://news.com/json?query_term=" + encodeURIComponent(search)
  })
  .then(function(newsData){
   $scope.newsto= newsData.data.data.article;
   $scope.hide();
    console.log(data);

  });
}

})
</code>```

答:
You haven't written code to catch service call failure.
By any chance, if such case is getting a failure response, then you haven't written code to handle that situation.</p>

```<code>$http({
    method: 'GET',
    url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
}, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
});
</code>```

Body:
I am fetching data from an api and I am using it to search something. When the json returns no result how to show NO RESULT FOUND.

Html code

      <input type="text" placeholder="Search" ng-model="search">

    <button class="button button-small" ng-click="load(search)">
      Submit
    </button>

Available Size - {{item.size}}

  button

        </ion-content>
      </ion-view>
    </script>

This is JS Code where I am fetching data from an api and also searching it.

 $http({

    method: "GET",
    url: https://news.com/json?limit=50"
  })
  .then(function(newsData){
   $scope.news= newsData.data.data.articles;
   $scope.hide();
    console.log(data);

  })

      $scope.load = function(search) {
     $scope.show();
  $http({
    method: "GET",
    url: "https://news.com/json?query_term=" + encodeURIComponent(search)
  })
  .then(function(newsData){
   $scope.newsto= newsData.data.data.article;
   $scope.hide();
    console.log(data);

  });
}

})

Body:
You haven't written code to catch service call failure.
By any chance, if such case is getting a failure response, then you haven't written code to handle that situation.

$http({
    method: 'GET',
    url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
}, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
});


问:
How to convert unordered list into nicely styled <select> dropdown using jquery?
How do I convert an unordered list in this format

```<code><ul class="selectdropdown">
    <li><a href="one.html" target="_blank">one</a></li>
    <li><a href="two.html" target="_blank">two</a></li>
    <li><a href="three.html" target="_blank">three</a></li>
    <li><a href="four.html" target="_blank">four</a></li>
    <li><a href="five.html" target="_blank">five</a></li>
    <li><a href="six.html" target="_blank">six</a></li>
    <li><a href="seven.html" target="_blank">seven</a></li>
</ul>
</code>```

into a dropdown in this format

```<code><select>
    <option value="one.html" target="_blank">one</option>
    <option value="two.html" target="_blank">two</option>
    <option value="three.html" target="_blank">three</option>
    <option value="four.html" target="_blank">four</option>
    <option value="five.html" target="_blank">five</option>
    <option value="six.html" target="_blank">six</option>
    <option value="seven.html" target="_blank">seven</option>
</select>
</code>```

using jQuery?

Edit: When selecting an entry from the select/dropdown the link should open in a new window or tab automatically. I also want to able to style it like: http://www.dfc-e.com/metiers/multimedia/opensource/jqtransform/

答:
I have recently created a solution where the ul transformed, mimics nearly completely the select.

It has in adition a search for the options of the select and supports the active state. Just add a class with name active and that option will be selected.

It handles the keyboard navigation.

Take a look at the code here: GitHub Code

And a live example here: Code Example

The unordered list must be in the form:

```<code><ul id="...">
  <li><a href="...">...</a></li>
  <li><a href="...">...</a></li>
  <li><a class="active" href="...">...</a></li>
  ...
</ul>
</code>```

To convert the ul to select just call:

```<code>$(window).on("load resize", function() {
  ulToSelect($("ul#id"), 767);
});
</code>```

Where #id is an id for the unordered list and 767 is the minimum width of the window for the convertion to take place. This is very useful if you want the convertion to take place only for mobile or tablet.

Body:
How do I convert an unordered list in this format

one

two

three

four

five

six

seven

into a dropdown in this format

<select>
    <option value="one.html" target="_blank">one</option>
    <option value="two.html" target="_blank">two</option>
    <option value="three.html" target="_blank">three</option>
    <option value="four.html" target="_blank">four</option>
    <option value="five.html" target="_blank">five</option>
    <option value="six.html" target="_blank">six</option>
    <option value="seven.html" target="_blank">seven</option>
</select>

using jQuery?

Edit: When selecting an entry from the select/dropdown the link should open in a new window or tab automatically. I also want to able to style it like: http://www.dfc-e.com/metiers/multimedia/opensource/jqtransform/

Body:
I have recently created a solution where the ul transformed, mimics nearly completely the select.

It has in adition a search for the options of the select and supports the active state. Just add a class with name active and that option will be selected.

It handles the keyboard navigation.

Take a look at the code here: GitHub Code

And a live example here: Code Example

The unordered list must be in the form:

<ul id="...">
  <li><a href="...">...</a></li>
  <li><a href="...">...</a></li>
  <li><a class="active" href="...">...</a></li>
  ...
</ul>

To convert the ul to select just call:

$(window).on("load resize", function() {
  ulToSelect($("ul#id"), 767);
});

Where #id is an id for the unordered list and 767 is the minimum width of the window for the convertion to take place. This is very useful if you want the convertion to take place only for mobile or tablet.


问:
What opengl library should i use with an nvidia graphics card
I'm trying to compile an SDL2 and OpenGL game on linux, but the error that shows up is always

/usr/bin/ld: cannot find -lGL
  collect2: error: ld returned 1 exit status

Which led me to find out which opengl version I have. But it shows this:

OpenGL version string: 4.5.0 NVIDIA 375.39

But I don't know which parameter or library to use with nvidia opengl.

Does anyone know?

答:
Fixed it easily by just swapping out -lGL with -l:libGL.so.1.
But find out what library you have using

ls /usr/lib/

and then look for libGL.so.version_number_here

Works for me until I need to add it to my linker.


问:
Angular JS Uncaught Error: [$injector:modulerr]
I am having a problem with Angular JS receiving an error : Uncaught Error: [$injector:modulerr].
My JS-file looks

angular.module('MyApp', ['ngRoute']);
angular.module('MyApp',['ngResource']);
function TwitterCtrl($scope,$resource){
}
```
<p>I also included angular-route-js</p>
<pre class="lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-route.min.js">
</code>```

Angular documentation says the problem is http://docs.angularjs.org/api/ngRoute

答:
I had the same problem. You should type your Angular js code outside of any function like this:</p>

```<code>$( document ).ready(function() {});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am having a problem with Angular JS receiving an error : Uncaught Error: [$injector:modulerr].
My JS-file looks

angular.module('MyApp', ['ngRoute']);
angular.module('MyApp',['ngResource']);
function TwitterCtrl($scope,$resource){
}

I also included angular-route-js

Body:
I had the same problem. You should type your Angular js code outside of any function like this:

$( document ).ready(function() {});


问:
bestpractises for big react projects
I want to develop my first reactjs project. It will be a big project with lots of views and components.

what would be a good best practise to get structure in it? ReactJS ist just for frontend stuff and the communication over REST with a Play framework backend.

答:
I would say start from router. Make sure your router works if url is hit directly, for that you need fallback backend routes that will render React as well as it would render on / route. Or else, use something like Next.js that does it for you automatically.

If you are going to use cookies, it's good to implement them in early stage too.

I do not know what kind of app you are building, but I would suggest using Redux for global states. Some global state usage examples:

Data from API that is used by multiple components

Data from components that is used by other multiple components

Shared states (loading, disables, for example if one button is clicked and loading and you want to disable other fields that are from different components, its good to have reducer for global loaders)

Since you are going to have a lot of views and components, create 3 directories, components, containers, views.

Use components directory for dumb (stateless) components.  Use containers directory for components with state. Each component may be a file or a folder that includes CSS and image files as well, and then include these directly within your component JS file. And finally views directory for each page.

As for build and other stuff, if you are not comfortable with webpack configurations, you could use create-react-app or again nextjs2 starters.

I do not know what is your app about and what it should do, so I am unable to provide more hints. Hope this helped a bit.

In the future, consider using Stackoverflow for specific problem questions, and for questions such as this use reddit, facebook react group or other forums that allow generic questions.

Title: bestpractises for big react projects


问:
Omitting the datatype (e.g. "unsigned" instead of "unsigned int")
I know that if the data type declaration is omitted in C/C++ code in such way: unsigned test=5;, the compiler automatically makes this variable an int (an unsigned int in this case). I've heard that it's a C standard and it will work in all compilers.

But I've also heard that doing this is considered a bad practice.

What do you think? Should I really type unsigned int instead of just unsigned?

Are short, long and long long also datatypes?

答:
unsigned is a data type! And it happens to alias to unsigned int.

When you’re writing unsigned x; you are not omitting any data type.

This is completely different from “default int” which exists in C (but not in C++!) where you really omit the type on a declaration and C automatically infers that type to be int.

As for style, I personally prefer to be explicit and thus to write unsigned int. On the other hand, I’m currently involved in a library where it’s convention to just write unsigned, so I do that instead.


问:
Unable to execute Perl script unless Perl is inserted before script name
Running Lubuntu -
Beginner Perl programmer

Script is XXX.pl located at ~/projects/XXX/XXX.pl

First line is the shebang

```<code>#!/usr/bin/perl
</code>```

Permission to run is set to Anyone.

In directory ~/projects/XXX, the command

```<code>~/projects/XXX$ perl XXX.pl
</code>```

works as desired, but the command

```<code>~/projects/XXX$ XXX.pl
</code>```

Fails with XXX.pl: command not found

What am I missing ?

答:
The two usual options to execute your Perl script are:

```<code>perl XXX.pl
</code>```

or

```<code>./XXX.pl
</code>```

Both ways assume that your current working directory contains the script XXX.pl, otherwise it won't work.

As already pointed out by jm666 in the comments, you can usually not execute a program or script from your current working directory without prepending ./, primarily because of security reasons. Now, you may wonder why it's necessary.

Explanation:

Your shell uses the contents of an environment variable called $PATH to find out about where external commands (non-builtin programs) are located in your filesystem. If you want to see what's in $PATH, just type the following in your shell:

```<code>echo $PATH
</code>```

Now you can see that the $PATH variable does NOT contain your current working directory. The consequence is that your shell is not able to find the program XXX.pl. By prepending ./ you instruct the shell to execute the program which comes after.
But there are two requirements if you want to execute your Perl script with ./script.pl:

The script has to be executable (check with ls -l)

The first line (shebang line) has to be #!/path/to/your/perl because your shell needs that information to find the perl interpreter in order to run your script

However, #1 and #2 are NOT required when you execute your script with

```<code>perl XXX.pl
</code>```

because it invokes the perl interpreter directly with your script.

See how to make Perl scripts executable on Linux and make the script itself directly executable with chmod for some more details.

Body:
Running Lubuntu -
Beginner Perl programmer

Script is XXX.pl located at ~/projects/XXX/XXX.pl

First line is the shebang

#!/usr/bin/perl

Permission to run is set to Anyone.

In directory ~/projects/XXX, the command

~/projects/XXX$ perl XXX.pl

works as desired, but the command

~/projects/XXX$ XXX.pl

Fails with XXX.pl: command not found

What am I missing ?

Body:
The two usual options to execute your Perl script are:

perl XXX.pl

or

./XXX.pl

Both ways assume that your current working directory contains the script XXX.pl, otherwise it won't work.

As already pointed out by jm666 in the comments, you can usually not execute a program or script from your current working directory without prepending ./, primarily because of security reasons. Now, you may wonder why it's necessary.

Explanation:

Your shell uses the contents of an environment variable called $PATH to find out about where external commands (non-builtin programs) are located in your filesystem. If you want to see what's in $PATH, just type the following in your shell:

echo $PATH

Now you can see that the $PATH variable does NOT contain your current working directory. The consequence is that your shell is not able to find the program XXX.pl. By prepending ./ you instruct the shell to execute the program which comes after.
But there are two requirements if you want to execute your Perl script with ./script.pl:

The script has to be executable (check with ls -l)

The first line (shebang line) has to be #!/path/to/your/perl because your shell needs that information to find the perl interpreter in order to run your script

However, #1 and #2 are NOT required when you execute your script with

perl XXX.pl

because it invokes the perl interpreter directly with your script.

See how to make Perl scripts executable on Linux and make the script itself directly executable with chmod for some more details.


问:
Save a MySQL binary field to disk with PHP
I'm trying to retrieve the content of a MySQL Binary field with PHP and save it to the disk, but when I try to open my image file, I get this error : "The file “a.jpg” could not be opened. It may be damaged or use a file format that Preview doesn’t recognize."

Note : I'm using Mac OS X.

Here is the code I started :

```<code>function extractImages(){

    global $co;
    $query = $co->query("SELECT id, singleSRC FROM tl_events");

    while ($row = mysqli_fetch_object($query)){

        $file = $row->id;

        // Save it to the Images folder
        $path = "images/".$file;
        $ressource = fopen($path, "wb") or die("Unable to open ".$path."<br>");
        fwrite($ressource, $row->singleSRC) or die("Unable to write in the file");

    }
}
</code>```

Thanks a lot for your help !

答:
I retrieve the file extension, but still can't open the generated file ("The file “a.jpg” could not be opened. It may be damaged or use a file format that Preview doesn’t recognize.")

Note : I'm using Mac Os X

Anyone has a solution ?

Thanks

Body:
I'm trying to retrieve the content of a MySQL Binary field with PHP and save it to the disk, but when I try to open my image file, I get this error : "The file “a.jpg” could not be opened. It may be damaged or use a file format that Preview doesn’t recognize."

Note : I'm using Mac OS X.

Here is the code I started :

function extractImages(){

    global $co;
    $query = $co->query("SELECT id, singleSRC FROM tl_events");

    while ($row = mysqli_fetch_object($query)){

        $file = $row->id;

        // Save it to the Images folder
        $path = "images/".$file;
        $ressource = fopen($path, "wb") or die("Unable to open ".$path."
");
        fwrite($ressource, $row->singleSRC) or die("Unable to write in the file");

    }
}

Thanks a lot for your help !


问:
Models load() usage
Can someone enligthen me ,what is the real usage of load method if setting post params can  be directly set to models attributes? Thanks

$model->load(Yii::$app->request->post());

vs

$model->attributes = Yii::$app->request->post();

答:
As you can easy see in  http://www.yiiframework.com/doc-2.0/yii-base-model.html#load()-detail

load  Populates the model with input data.  load() gets the 'FormName'
  from the model's formName() method (which you may override), unless
  the $formName parameter is given.

the data being populated is subject to the safety check by setAttributes().

see also http://www.yiiframework.com/doc-2.0/guide-structure-models.html

Title: Models load() usage


问:
Use colorbar for non type object
I currently try to modify a plot in a python2.7 code. This plot come from a radiative transfert code (what I can't modify), and the output is a class type with a method :

```<code>plot_image(wavelength0, overplot=False, inclination=None, cmap=None,
          ax=None, axes_units='AU', polarization=False, polfrac=False,
          psf_fwhm=None, vmin=None, vmax=None, dynamic_range=1000000.0)
</code>```

more informations here

So, when I put a plt.title() or plt.savefig() just after that, I call the respective method and the title of the plot changes and the plot is saved, as expected!

However, there is two things that I didn't find a way to do it :

Add a colorbar

trace the surface in log-scale

because no arguments in the method allow to do it.

When I try something like plt.colorbar(fig) with fig=res.plot_image(...) (with res the class, output of radiative transfert code) the error said that fig is not a mappable object (seems logic).

Any ideas that could help me ? hope I gave you enough informations.

Sorry for my English

Lo_du

答:
If res.plot_image(...) only plots one image to one axes, the solution to obtain a colorbar might be pretty easy.

```<code>import numpy as np
import matplotlib.pyplot as plt

#.... some code

res.plot_image(...)

im, = plt.gca().get_images()

plt.colorbar(im)

plt.show()
</code>```

Title: Use colorbar for non type object

Body:
I currently try to modify a plot in a python2.7 code. This plot come from a radiative transfert code (what I can't modify), and the output is a class type with a method :

plot_image(wavelength0, overplot=False, inclination=None, cmap=None,
          ax=None, axes_units='AU', polarization=False, polfrac=False,
          psf_fwhm=None, vmin=None, vmax=None, dynamic_range=1000000.0)

more informations here

So, when I put a plt.title() or plt.savefig() just after that, I call the respective method and the title of the plot changes and the plot is saved, as expected!

However, there is two things that I didn't find a way to do it :

Add a colorbar

trace the surface in log-scale

because no arguments in the method allow to do it.

When I try something like plt.colorbar(fig) with fig=res.plot_image(...) (with res the class, output of radiative transfert code) the error said that fig is not a mappable object (seems logic).

Any ideas that could help me ? hope I gave you enough informations.

Sorry for my English

Lo_du

Body:
If res.plot_image(...) only plots one image to one axes, the solution to obtain a colorbar might be pretty easy.

import numpy as np
import matplotlib.pyplot as plt

#.... some code

res.plot_image(...)

im, = plt.gca().get_images()

plt.colorbar(im)

plt.show()


问:
Select Where With Multiple of the same
I have a table called 'matches' where I associate a items in the table "numbers" with an item in the table "letters" via there id.

So it looks like

```<code>number_id, letter_id
1,10
2,10
3,10
5,11
4,23
7,19
1,19
3,64
</code>```

now the user inputs an array of numbers, say 1,2,3
and I have to find the letter where all of it's numbers are 1,2,3, which would be 10. If they gave 1,7 it would give them 19, if they gave 3 it would give them and 64.

How can I do that?

I've been trying to write a recursive function for this but it always breaks.
is there some sort of:

```<code>SELECT letter_id WHERE **number_id***s* = 1,2,3. That would be perfect. :)
</code>```

答:
Since the previous comments made the problem more than what the OP was, here's another answer...

You may be able to work it out by having temporary tables:

```<code>create temporary table r_sum as
    select letter_id, count(*) as total
    from r
    group by letter_id;
create temporary table r_count as
    select letter_id, count(*) as total
    from r
    where number_id in (1,2,3,7)
    group by letter_id;
select letter_id
from r_sum
    inner join r_count using (letter_id, total);</code>```

I think if this does not answer your question, I am not getting what you want and how to help you. If table is huge, you will have to create indexes on the temporary tables to help go faster. r is your original table in OP.

Title: Select Where With Multiple of the same

Body:
I have a table called 'matches' where I associate a items in the table "numbers" with an item in the table "letters" via there id.

So it looks like

number_id, letter_id
1,10
2,10
3,10
5,11
4,23
7,19
1,19
3,64

now the user inputs an array of numbers, say 1,2,3
and I have to find the letter where all of it's numbers are 1,2,3, which would be 10. If they gave 1,7 it would give them 19, if they gave 3 it would give them and 64.

How can I do that?

I've been trying to write a recursive function for this but it always breaks.
is there some sort of:

SELECT letter_id WHERE **number_id***s* = 1,2,3. That would be perfect. :)

Body:
Since the previous comments made the problem more than what the OP was, here's another answer...

You may be able to work it out by having temporary tables:

create temporary table r_sum as
    select letter_id, count(*) as total
    from r
    group by letter_id;
create temporary table r_count as
    select letter_id, count(*) as total
    from r
    where number_id in (1,2,3,7)
    group by letter_id;
select letter_id
from r_sum
    inner join r_count using (letter_id, total);

I think if this does not answer your question, I am not getting what you want and how to help you. If table is huge, you will have to create indexes on the temporary tables to help go faster. r is your original table in OP.


问:
Display of Multiple JavaScript Countdowns
I found a way to display multiple countdowns, using javascript.
Having multiple countdown timer events intervals in javascript

I am trying to create a "warmer" display, in a grid.  I opted for an HTML table.  I have a draft here

I can't get the countdowns to display in the table cells, with separated time components. I just have the entire SPAN tag in the "Days" column.

答:
If you are ok to use any javascript library why not check FlipClock.js out.

As per the text provided on their site, the following are the logical requirements that were considered when creating the API.

Use as a clock

Use as a timer

Use as a countdown

Themeable using pure CSS

Clean & Dry Syntax

Abstract everything into reusable objects

Full-Featured Developer API to create custom “Clock Faces”

And if you are not ok to use any library here is what you can learn from about how to create a countdown timer using javascript

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_countdown


问:
Firebase LIKE button and counter
In a structure of Firebase like this:

```<code>Pictures
-pictureID
-- name
-- date

Like
-pictureID
-- userID: true
-- userID: true

likePerUser
-userID
--pictureID: true
--pictureID: true

Users
-userID
-- name
-- lastname
</code>```

I have implemented a like system where user can likes images. (swift3)

I'm able to get the number of users that liked a specific picture by doing this:

```<code>ref.child("Like").child(pictureID!).observeSingleEvent(of: .value, with: { (snapshot) in

            print(snapshot.childrenCount)

        })
</code>```

how can i find if a user (which i know his userID) has liked a picture (i know also it's pictureID)?

So i edit the structure and code, now i need to check if under the node likeperuser, under child currentUser is there a pictureId equal to true
but this code doesn't work...

```<code>ref.child("likePerUser").child(FIRAuth.auth()!.currentUser!.uid).queryOrdered(byChild: pictureId).queryEqual(toValue: true).observe(FIRDataEventType.value, with:{(snap)in
</code>```

答:
In NoSQL you often model your data for the use-cases that your app needs. So if your app has a use-case where you want to know what pictures the user has liked, store a list of the pictures each user has liked:

```<code>LikesPerUser
- userID
-- pictureID: true
-- pictureID: true
</code>```

With this (additional) structure, looking up the likes-for-a-user is as simple as looking up the likes-for-a-picture is in your current structure.

For a good introduction to this topic, read NoSQL data modeling and watch Firebase for SQL developers.

Title: Firebase LIKE button and counter

Body:
In a structure of Firebase like this:

Pictures
-pictureID
-- name
-- date

Like
-pictureID
-- userID: true
-- userID: true

likePerUser
-userID
--pictureID: true
--pictureID: true

Users
-userID
-- name
-- lastname

I have implemented a like system where user can likes images. (swift3)

I'm able to get the number of users that liked a specific picture by doing this:

ref.child("Like").child(pictureID!).observeSingleEvent(of: .value, with: { (snapshot) in

            print(snapshot.childrenCount)

        })

how can i find if a user (which i know his userID) has liked a picture (i know also it's pictureID)?

So i edit the structure and code, now i need to check if under the node likeperuser, under child currentUser is there a pictureId equal to true
but this code doesn't work...

ref.child("likePerUser").child(FIRAuth.auth()!.currentUser!.uid).queryOrdered(byChild: pictureId).queryEqual(toValue: true).observe(FIRDataEventType.value, with:{(snap)in

Body:
In NoSQL you often model your data for the use-cases that your app needs. So if your app has a use-case where you want to know what pictures the user has liked, store a list of the pictures each user has liked:

LikesPerUser
- userID
-- pictureID: true
-- pictureID: true

With this (additional) structure, looking up the likes-for-a-user is as simple as looking up the likes-for-a-picture is in your current structure.

For a good introduction to this topic, read NoSQL data modeling and watch Firebase for SQL developers.


问:
Swapping using 2d arrays in C++
I want to sort an array which contains names according to their length, but the following program gives a compiler error when I try to swap them using a function. Please help me identify my mistake.</p>

```<code>void sort(char name1[][50])
{
    for (int i = 0; i < 5; i++)
    {
        if (strlen(name1[i])>strlen(name1[i+1]))
        {
            char temp[50];
            temp=name1[i];
            name1[i]=name1[i+1];
            name1[i+1]=temp;
        }
    }
}
</code>```

答:
Use strcpy to copy c-string. First copy the first string into the temp string, then copy the second into the first, and finally the temp into the second string.

```<code>strcpy(temp,name1[i]);

strcpy(name1[i],name1[i+1]);

strcpy(name1[i+1],temp);
</code>```

Title: Swapping using 2d arrays in C++

Body:
I want to sort an array which contains names according to their length, but the following program gives a compiler error when I try to swap them using a function. Please help me identify my mistake.

void sort(char name1[][50])
{
    for (int i = 0; i < 5; i++)
    {
        if (strlen(name1[i])>strlen(name1[i+1]))
        {
            char temp[50];
            temp=name1[i];
            name1[i]=name1[i+1];
            name1[i+1]=temp;
        }
    }
}

Body:
Use strcpy to copy c-string. First copy the first string into the temp string, then copy the second into the first, and finally the temp into the second string.

strcpy(temp,name1[i]);

strcpy(name1[i],name1[i+1]);

strcpy(name1[i+1],temp);


问:
docker: Is it possible to start native windows sibling containers from within another?
Is it possible to start a native windows sibling container from within a native windows container? So I don't mean docker-in-docker.

Like on linux:

```<code>docker run -v /var/run/docker.sock:/var/run/docker.sock ...
</code>```

答:
UPDATE: The latest Docker EE preview releases for Windows support bind-mounting the Docker API. Details here: https://blog.docker.com/2017/09/docker-windows-server-1709/

Yeah, there's a couple of steps though and it's not very elegant nor secure. You have to change the Windows Daemon config to listen on a public interface:

```<code>net stop docker
dockerd.exe --unregister-service
dockerd.exe -H npipe:////./pipe/docker_engine -H 0.0.0.0:2375 --register-service
net start docker
</code>```

Now when starting containers, the Docker API will be available on the default gateway ip (you can find it with ipconfig) of the container, on port 2375.

Body:
Is it possible to start a native windows sibling container from within a native windows container? So I don't mean docker-in-docker.

Like on linux:

docker run -v /var/run/docker.sock:/var/run/docker.sock ...

Body:
UPDATE: The latest Docker EE preview releases for Windows support bind-mounting the Docker API. Details here: https://blog.docker.com/2017/09/docker-windows-server-1709/

Yeah, there's a couple of steps though and it's not very elegant nor secure. You have to change the Windows Daemon config to listen on a public interface:

net stop docker
dockerd.exe --unregister-service
dockerd.exe -H npipe:////./pipe/docker_engine -H 0.0.0.0:2375 --register-service
net start docker

Now when starting containers, the Docker API will be available on the default gateway ip (you can find it with ipconfig) of the container, on port 2375.


问:
Address a text field created in Flash from an external class
How can I address a text field created in Flash (lets say its instance name is mytextfield) from an external class?</p>

答:
you could make it a static public var. That might work.

access it by using myClassName.myTextfield

If not you could also try registering it so you can retrieve it in another class. This 100% works.

AS3: How to access children of children of children?


问:
Unity3D C#: How to resize an inputfield according the content which is set dynamic
I've got an InputField where the text is filled in upon getting a string back from the server. We can debug the entire text so we receive it correctly. However the text is too long to fit in our InputField.
What I basicly need is the idea of the content size fitter provided by unity (Content size fitter isn't supported for InputFields by design)
At the moment we are trying to update the size of the InputField with the following snippet of code.</p>

```<code>var x = new GUIStyle();
var rectTransform = pvText.GetComponent<RectTransform>();
var words = pvText.text.Split(' ');
var currentWidth = 0f;
var currentHeight = 0f;
foreach (var word in words)
{
     var size = x.CalcSize(new GUIContent(word + "A"));
     var height = x.CalcHeight(new GUIContent(word), size.x);
     currentWidth += size.x;
     if (currentWidth >= rectTransform.sizeDelta.x)
     {
        currentWidth = size.x;
        currentHeight += height + pvText.textComponent.lineSpacing;
     }
 }
 rectTransform.sizeDelta = new Vector2(rectTransform.sizeDelta.x, currentHeight);
</code>```

答:
Add Content Size Fitter to your InputField, they's PlaceHolder and Text (all children)
In InputField set On Change Value to ContentSizeFitter.SetLayoutVertical from yout Input Field

Body:
I've got an InputField where the text is filled in upon getting a string back from the server. We can debug the entire text so we receive it correctly. However the text is too long to fit in our InputField.
What I basicly need is the idea of the content size fitter provided by unity (Content size fitter isn't supported for InputFields by design)
At the moment we are trying to update the size of the InputField with the following snippet of code.

var x = new GUIStyle();
var rectTransform = pvText.GetComponent<RectTransform>();
var words = pvText.text.Split(' ');
var currentWidth = 0f;
var currentHeight = 0f;
foreach (var word in words)
{
     var size = x.CalcSize(new GUIContent(word + "A"));
     var height = x.CalcHeight(new GUIContent(word), size.x);
     currentWidth += size.x;
     if (currentWidth >= rectTransform.sizeDelta.x)
     {
        currentWidth = size.x;
        currentHeight += height + pvText.textComponent.lineSpacing;
     }
 }
 rectTransform.sizeDelta = new Vector2(rectTransform.sizeDelta.x, currentHeight);


问:
Javascript addEventListener function gets invoked without the Event being triggered
I may be overlooking something obvious but this just doesn't seem to go right.

I have this little code block in which an addEventListener method should trigger a function and meanwhile pass a parameter through so I can work with different functions while creating all EventListeners with one loop.
It does work, but the function gets invoked immediately when the site finishes loading.

Why doesn't the function wait until it gets triggered, but runs immediately?

```<code>var html = document.getElementsByTagName('html');
var pics = document.getElementsByClassName('pics');
var functions = [];

for(h=0;h<pics.length;h++){
    array[h] = show(h);
}

for(p=0;p<pics.length;p++){
    pics[p].addEventListener('click',array[p]);
}

function show(index){
    html[0].style.backgroundColor = "black";
}
</code>```

答:
In the script

```<code>for (h = 0; h < pics.length; h++) {
    array[h] = show(h);
  }
</code>```

you are calling the function show with value of h.

Its invoked at that time.So,background get setup with given color.

Its not because of addEventListener you are adding in the second for loop

You can write in this way.

```<code>for (h = 0; h < pics.length; h++) {
    array[h] = show; // don't  call,store the function reference
  }

  for (p = 0; p < pics.length; p++) {
    pics[p].addEventListener('click', array[p].bind(this,p));
  }
</code>```

You can shorten two for loop into one

```<code>  for (p = 0; p < pics.length; p++) {
    pics[p].addEventListener('click', show.bind(this,p));
  }
</code>```

Note :

addEventListener expect callback and not an function call.

Body:
I may be overlooking something obvious but this just doesn't seem to go right.

I have this little code block in which an addEventListener method should trigger a function and meanwhile pass a parameter through so I can work with different functions while creating all EventListeners with one loop.
It does work, but the function gets invoked immediately when the site finishes loading.

Why doesn't the function wait until it gets triggered, but runs immediately?

var html = document.getElementsByTagName('html');
var pics = document.getElementsByClassName('pics');
var functions = [];

for(h=0;h<pics.length;h++){
    array[h] = show(h);
}

for(p=0;p<pics.length;p++){
    pics[p].addEventListener('click',array[p]);
}

function show(index){
    html[0].style.backgroundColor = "black";
}

Body:
In the script

for (h = 0; h < pics.length; h++) {
    array[h] = show(h);
  }

you are calling the function show with value of h.

Its invoked at that time.So,background get setup with given color.

Its not because of addEventListener you are adding in the second for loop

You can write in this way.

for (h = 0; h < pics.length; h++) {
    array[h] = show; // don't  call,store the function reference
  }

  for (p = 0; p < pics.length; p++) {
    pics[p].addEventListener('click', array[p].bind(this,p));
  }

You can shorten two for loop into one

  for (p = 0; p < pics.length; p++) {
    pics[p].addEventListener('click', show.bind(this,p));
  }

Note :

addEventListener expect callback and not an function call.


问:
Limiting WCF Data Members in Linq to SQL's DBML Serialization?
I understand that you can set the Serialization Mode = Unidirectional to allow data contracts to your dbml auto-generated entities.  However, is there a way to only expose certain entities and ALSO limit the entities exposed to only expose certain properties of that entity as well?

答:
I Googled and found it so I'm posting here for prosperity's sake:

Credit:
http://blogs.msdn.com/b/wriju/archive/2007/11/27/linq-to-sql-enabling-dbml-file-for-wcf.aspx

Basically you just set the DBML's Serializable Mode = Unidirectional and then you set the "Access" for each entity you don't want exposed to the Service equal to Friend instead of Public.  Access = Friend


问:
Wrong float division result in c
```<code>void four_corners(float A[rows][columns]){
int up,down,right,left;
int x=2;
A[0][0]=(float)(up+left)/(float)(x);
A[0][19]=(float)(up+right)/(float)(x);
A[9][0]=(float)(down+left)/(float)(x);
A[9][19]=(float)(down+right)/(float)(x);}
</code>```

When i insert the four values in an array i do not get the correct value of them. What's wrong with my code?

答:
Try this one:

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

#define W 10
#define H 20

void four_corners(float A[W][H], int up, int down, int right, int left) {
    int x = 2;
    A[0][0] = (float)(up + left) / (float)(x);
    A[0][19] = (float)(up + right) / (float)(x);
    A[9][0] = (float)(down + left) / (float)(x);
    A[9][19] = (float)(down + right) / (float)(x);
}

void print_board(float A[W][H]) {
    for (int i = 0; i < W; i++) {
        for (int j = 0; j < H; j++) {
            printf("%.1f ", A[i][j]);
        }
    }
}
int main(int argc, char *argv[]) {
    float A[W][H];
    memset(A, 0, W * H * sizeof(float));
    four_corners(A, 1, 2, 3, 4);
    print_board(A);
    getch();
}
</code>```

Basically the problem you're having in your code is up, down, right, left are all of them local variables and they're just visible to the four_corners functions. You think they're been initialized properly when doing scanf in another scope but they're actually not. If you want them to be visible to the scanf's scope and four_corners scope either you pass them as arguments to the function or you make them global. I'd suggest you read more about C scopes and this will become cristal clear to you. Happy coding!

Title: Wrong float division result in c

Body:
void four_corners(float A[rows][columns]){
int up,down,right,left;
int x=2;
A[0][0]=(float)(up+left)/(float)(x);
A[0][19]=(float)(up+right)/(float)(x);
A[9][0]=(float)(down+left)/(float)(x);
A[9][19]=(float)(down+right)/(float)(x);}

When i insert the four values in an array i do not get the correct value of them. What's wrong with my code?

Body:
Try this one:

#include <stdio.h>
#include <conio.h>
#include <string.h>

#define W 10
#define H 20

void four_corners(float A[W][H], int up, int down, int right, int left) {
    int x = 2;
    A[0][0] = (float)(up + left) / (float)(x);
    A[0][19] = (float)(up + right) / (float)(x);
    A[9][0] = (float)(down + left) / (float)(x);
    A[9][19] = (float)(down + right) / (float)(x);
}

void print_board(float A[W][H]) {
    for (int i = 0; i < W; i++) {
        for (int j = 0; j < H; j++) {
            printf("%.1f ", A[i][j]);
        }
    }
}
int main(int argc, char *argv[]) {
    float A[W][H];
    memset(A, 0, W * H * sizeof(float));
    four_corners(A, 1, 2, 3, 4);
    print_board(A);
    getch();
}

Basically the problem you're having in your code is up, down, right, left are all of them local variables and they're just visible to the four_corners functions. You think they're been initialized properly when doing scanf in another scope but they're actually not. If you want them to be visible to the scanf's scope and four_corners scope either you pass them as arguments to the function or you make them global. I'd suggest you read more about C scopes and this will become cristal clear to you. Happy coding!


问:
Servlet 3.0 without a WAR file?
Is it possible to launch a webapp altogether with:

1) No war file:

http://stephenh.github.io/2009/01/10/war-less-dev-with-jetty.html
http://www.jamesward.com/2011/08/23/war-less-java-web-apps

2) No web.xml (i.e., Servlet-3.0)

3) From an embedded web container (e.g., Tomcat or Jetty...)

答:
It's possible to  achieve an embedded server with Jetty that doesn't require a WAR or any XML. You just have to specify where your annotated classes will be, adding an extra class path.

This method should be called from a main you can name Server.java:

```<code>private static void startServer() throws Exception {
    final org.eclipse.jetty.server.Server server = new org.eclipse.jetty.server.Server(7070);
    final WebAppContext context = new WebAppContext("/", "/");
    context.setConfigurations(new Configuration[] { new AnnotationConfiguration(), new WebInfConfiguration() });
    context.setExtraClasspath("build/classes/main/com/example/servlet");
    server.setHandler(context);
    server.start();
    server.join();
}
</code>```

My src structure was:

```<code>-main
  -java
    -com.example
      -json
      -servlet
      -filter
      -util
      Server.java
</code>```

I would like to see a similar solution with Tomcat.

Title: Servlet 3.0 without a WAR file?

Body:
It's possible to  achieve an embedded server with Jetty that doesn't require a WAR or any XML. You just have to specify where your annotated classes will be, adding an extra class path.

This method should be called from a main you can name Server.java:

private static void startServer() throws Exception {
    final org.eclipse.jetty.server.Server server = new org.eclipse.jetty.server.Server(7070);
    final WebAppContext context = new WebAppContext("/", "/");
    context.setConfigurations(new Configuration[] { new AnnotationConfiguration(), new WebInfConfiguration() });
    context.setExtraClasspath("build/classes/main/com/example/servlet");
    server.setHandler(context);
    server.start();
    server.join();
}

My src structure was:

-main
  -java
    -com.example
      -json
      -servlet
      -filter
      -util
      Server.java

I would like to see a similar solution with Tomcat.


问:
Scss not working
So I have my navbar scss working perfectly fine but for some reason I cant get any scss to work on my posts. I have no clue why its not working. Here is some of my code.

Here is my _posts.html.erb

```<code><div class="col-sm-6 col-lg-4">
 <div class="card">
   <div class="card-topper" style="background-image: url();"></div>
    <div class="card-block">
        <h4 class="card-title"><%= link_to post.title, post %></h4>
        <p class="published-date">Published Today</p>
        <p class="card-text"><%= truncate(post.description, length: 130) %></p>
        <%= link_to "Read", post, class: "btn btn-read" %>
    </div>
</div>
</code>```

Im calling this in my posts index.html.erb

```<code><div class="row">
 <%=render @posts %>
</div>
</code>```

This is my _posts.scss

```<code>.posts.index {
 .card {
    border: none;
    border-radius: 0;
    border-bottom: 1px solid #181818;
    height: 400px;
    margin-bottom: 20px;
    .card-topper {
        height: 200px;
        width: 100%;
        background-size: cover;
        background-position: center;
    }
    .card-block {
        padding: 10px;
        .btn-read {
            background-color: #e8e8e8;
            font-weight: 300;
            border-radius: 0;
            color: black;
            &:hover {
                background-color: #d8d8d8;
            }
        }
        .card-title {
            font-size: 1.3rem;
            margin-bottom: 0.5rem;
            a {
                color: black;
                text-decoration: none;
            }
        }
        .published-date {
            font-size: 0.8rem;
            color: #787878;
            font-weight: 300;
            margin-top: 0.3rem;
            margin-bottom: 0.3rem;
        }
        .card-text {
            font-size: 0.9rem;
        }
    }
}
}
</code>```

This is my application.scss

```<code>@import "bootstrap";
@import "navbar";
@import "posts";
</code>```

Im importing the _posts.scss to my application.scsss just like I am with my _navbar.scss. Just dont understand why it seems to have no impact on my posts. Im using rails 5 and bootstrap 4.0.0.alpha3

答:
Actually, the problem is not with underscore. The problem is .posts.index and since you have no element with both posts and index rules, the style is not applied. Also, you miss a closing div tag in your _posts.html.erb file. you have three options:

Option 1) Change the _posts.html.erb file to something like this this (closing div is added):

```<code><div class="col-sm-6 col-lg-4">
    <div class="posts index">
        <div class="card">
            <div class="card-topper" style="background-image: url();"></div>
            <div class="card-block">
                <h4 class="card-title"><%= link_to post.title, post %></h4>
                <p class="published-date">Published Today</p>
                <p class="card-text"><%= truncate(post.description, length: 130) %></p>
                <%= link_to "Read", post, class: "btn btn-read" %>
            </div>
        </div>
    </div>
</div>
</code>```

Option 2) Change index.html.erb to something like this (make sure you added closing div to _posts.html.erb):

```<code><div class="row">
    <div class="posts index">
        <%=render @posts %>
    </div>
</div>
</code>```

Option 3) Remove .posts.index from your _posts.scss file like following:

```<code> .card {
    border: none;
    border-radius: 0;
    border-bottom: 1px solid #181818;
    height: 400px;
    margin-bottom: 20px;
    .card-topper {
        height: 200px;
        width: 100%;
        background-size: cover;
        background-position: center;
    }
    .card-block {
        padding: 10px;
        .btn-read {
            background-color: #e8e8e8;
            font-weight: 300;
            border-radius: 0;
            color: black;
            &:hover {
                background-color: #d8d8d8;
            }
        }
        .card-title {
            font-size: 1.3rem;
            margin-bottom: 0.5rem;
            a {
                color: black;
                text-decoration: none;
            }
        }
        .published-date {
            font-size: 0.8rem;
            color: #787878;
            font-weight: 300;
            margin-top: 0.3rem;
            margin-bottom: 0.3rem;
        }
        .card-text {
            font-size: 0.9rem;
        }
    }
}
</code>```

Title: Scss not working

Body:
So I have my navbar scss working perfectly fine but for some reason I cant get any scss to work on my posts. I have no clue why its not working. Here is some of my code.

Here is my _posts.html.erb

<%= link_to post.title, post %>

Published Today

<%= truncate(post.description, length: 130) %>

        <%= link_to "Read", post, class: "btn btn-read" %>

Im calling this in my posts index.html.erb

 <%=render @posts %>

This is my _posts.scss

.posts.index {
 .card {
    border: none;
    border-radius: 0;
    border-bottom: 1px solid #181818;
    height: 400px;
    margin-bottom: 20px;
    .card-topper {
        height: 200px;
        width: 100%;
        background-size: cover;
        background-position: center;
    }
    .card-block {
        padding: 10px;
        .btn-read {
            background-color: #e8e8e8;
            font-weight: 300;
            border-radius: 0;
            color: black;
            &:hover {
                background-color: #d8d8d8;
            }
        }
        .card-title {
            font-size: 1.3rem;
            margin-bottom: 0.5rem;
            a {
                color: black;
                text-decoration: none;
            }
        }
        .published-date {
            font-size: 0.8rem;
            color: #787878;
            font-weight: 300;
            margin-top: 0.3rem;
            margin-bottom: 0.3rem;
        }
        .card-text {
            font-size: 0.9rem;
        }
    }
}
}

This is my application.scss

@import "bootstrap";
@import "navbar";
@import "posts";

Im importing the _posts.scss to my application.scsss just like I am with my _navbar.scss. Just dont understand why it seems to have no impact on my posts. Im using rails 5 and bootstrap 4.0.0.alpha3

Body:
Actually, the problem is not with underscore. The problem is .posts.index and since you have no element with both posts and index rules, the style is not applied. Also, you miss a closing div tag in your _posts.html.erb file. you have three options:

Option 1) Change the _posts.html.erb file to something like this this (closing div is added):

<div class="col-sm-6 col-lg-4">
    <div class="posts index">
        <div class="card">
            <div class="card-topper" style="background-image: url();"></div>
            <div class="card-block">
                <h4 class="card-title"><%= link_to post.title, post %></h4>
                <p class="published-date">Published Today</p>
                <p class="card-text"><%= truncate(post.description, length: 130) %></p>
                <%= link_to "Read", post, class: "btn btn-read" %>
            </div>
        </div>
    </div>
</div>

Option 2) Change index.html.erb to something like this (make sure you added closing div to _posts.html.erb):

<div class="row">
    <div class="posts index">
        <%=render @posts %>
    </div>
</div>

Option 3) Remove .posts.index from your _posts.scss file like following:

 .card {
    border: none;
    border-radius: 0;
    border-bottom: 1px solid #181818;
    height: 400px;
    margin-bottom: 20px;
    .card-topper {
        height: 200px;
        width: 100%;
        background-size: cover;
        background-position: center;
    }
    .card-block {
        padding: 10px;
        .btn-read {
            background-color: #e8e8e8;
            font-weight: 300;
            border-radius: 0;
            color: black;
            &:hover {
                background-color: #d8d8d8;
            }
        }
        .card-title {
            font-size: 1.3rem;
            margin-bottom: 0.5rem;
            a {
                color: black;
                text-decoration: none;
            }
        }
        .published-date {
            font-size: 0.8rem;
            color: #787878;
            font-weight: 300;
            margin-top: 0.3rem;
            margin-bottom: 0.3rem;
        }
        .card-text {
            font-size: 0.9rem;
        }
    }
}


问:
Array of structures passed as parameter is not reflecting changes
Today I was working with my lab assignment of finding closest pair of points in C language.
I know pretty well how to send array of structures to function but for some reason the array is not reflecting its changes in main() function.
Since my code was quite messy I created a smaller code to understand the fault.
Following is the code :

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

struct node {
    int x;
    int y;
};

void fun(struct node *);

int main()
{
    struct node *arr = (struct node *)malloc(2 * sizeof(struct node));
    arr[0].x = 1;
    arr[0].y = 2;
    printf("%d %d\n", arr[0].x, arr[0].y);
    fun(arr);
    printf("%d %d\n", arr[0].x, arr[0].y);

    return 0;
}

struct node *fun2()
{
    struct node *tmp = (struct node *)malloc(2 * sizeof(struct node));
    tmp[0].x = 3;
    tmp[0].y = 4;

    return tmp;
}

void fun(struct node *arr)
{
    arr = fun2();
}
</code>```

Output

```<code>1 2
1 2
</code>```

but for the following code arr array reflects changes

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

struct node {
    int x;
    int y;
};

void fun(struct node *);

int main()
{
    struct node *arr = (struct node *)malloc(2 * sizeof(struct node));
    arr[0].x = 1;
    arr[0].y = 2;
    printf("%d %d\n", arr[0].x, arr[0].y);
    fun(arr);
    printf("%d %d\n", arr[0].x, arr[0].y);

    return 0;
}

struct node *fun2()
{
    struct node *tmp = (struct node *)malloc(2 * sizeof(struct node));
    tmp[0].x = 3;
    tmp[0].y = 4;

    return tmp;
}

void fun(struct node *arr)
{
//    arr = fun2();
    arr[0].x = 3;
    arr[0].y = 4;
}
</code>```

Output

```<code>1 2
3 4
</code>```

Could anyone help me with that?

答: In your first version, fun is assigning to the parameter arr, which doesn't change the argument arr in main.  In your second, you are making changes to what arr points to: the structures you wish to change.

Body:
Today I was working with my lab assignment of finding closest pair of points in C language.
I know pretty well how to send array of structures to function but for some reason the array is not reflecting its changes in main() function.
Since my code was quite messy I created a smaller code to understand the fault.
Following is the code :

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

struct node {
    int x;
    int y;
};

void fun(struct node *);

int main()
{
    struct node *arr = (struct node *)malloc(2 * sizeof(struct node));
    arr[0].x = 1;
    arr[0].y = 2;
    printf("%d %d\n", arr[0].x, arr[0].y);
    fun(arr);
    printf("%d %d\n", arr[0].x, arr[0].y);

    return 0;
}

struct node *fun2()
{
    struct node *tmp = (struct node *)malloc(2 * sizeof(struct node));
    tmp[0].x = 3;
    tmp[0].y = 4;

    return tmp;
}

void fun(struct node *arr)
{
    arr = fun2();
}

Output

1 2
1 2

but for the following code arr array reflects changes

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

struct node {
    int x;
    int y;
};

void fun(struct node *);

int main()
{
    struct node *arr = (struct node *)malloc(2 * sizeof(struct node));
    arr[0].x = 1;
    arr[0].y = 2;
    printf("%d %d\n", arr[0].x, arr[0].y);
    fun(arr);
    printf("%d %d\n", arr[0].x, arr[0].y);

    return 0;
}

struct node *fun2()
{
    struct node *tmp = (struct node *)malloc(2 * sizeof(struct node));
    tmp[0].x = 3;
    tmp[0].y = 4;

    return tmp;
}

void fun(struct node *arr)
{
//    arr = fun2();
    arr[0].x = 3;
    arr[0].y = 4;
}

Output

1 2
3 4

Could anyone help me with that?


问:
Subclasses with generics of subclasses
I have some issues with generics. I have a BaseObject with multiple sub-classes as well as a BaseContainer<T extends BaseObject> with sub-classes that correspond with BaseObject sub-classes.

```<code>public class TestClass extends BaseClass<BaseContainer<BaseObject>> {

    // method signature tied to BaseClass generic
    @Override
    private BaseContainer<BaseObject> createContainer() {
        BaseContainer<BaseObject> container;

        // example logic here to determine which container to use
        if (Math.random() < 0.5) {
            container = new Parent1Container(); // incompatible types
        } else {
            container = new Parent2Container(); // incompatible types
        }

        return container;
    }

    abstract static class BaseObject {}
    static class Parent1Object extends BaseObject {}
    static class Parent2Object extends BaseObject {}

    abstract static class BaseContainer<T extends BaseObject> {
        public abstract void foo(T object);
    }
    static class Parent1Container extends BaseContainer<Parent1Object> {
        public void foo(Parent1Object object) {}
    }
    static class Parent2Container extends BaseContainer<Parent2Object> {
        public void foo(Parent2Object object) {}
    }

}
</code>```

```<code>public class BaseClass<T extends BaseContainer> {
    public abstract T createContainer();
}
</code>```

I have a method that returns BaseContainer<BaseObject>. Unfortunately, instantiating sub-classes of BaseContainer results in incompatible types error.

I have tried adding casts to the container instantiation, but it leaves ugly unchecked warnings that make me feel like I'm just missing something. I'd like to avoid those and suppress warnings.

If possible, how can I re-write the any of the classes to make the createContainer() method work?

答:
Since Parent1Container and Parent2Container are not exactly BaseContainer<BaseObject> but BaseContainer<? extends BaseObject>
you need to change the signatures accordingly:

```<code>public class TestClass extends BaseClass<BaseContainer<? extends BaseObject>> {
    ...
    public BaseContainer<? extends BaseObject> createConstructor() {
        if (Math.random() < 0.5) {
           return new Parent1Container();
        } else {
           return new Parent2Container();
        }
    }
    ...
}
</code>```

BaseContainer<BaseObject> makes reference to all those BaseContainer (including extending classes) instances that are able to "handle" any BaseObject, where handle is a blanket-term for all the operations it may do with that type-argument.

In contrast BaseContainer<? extends BaseObject> refer to those BaseContainer instances that are meant to handle a subset of all BaseObject where the top parent class is unknown (thus the ?). It that ? happens to be BaseObject then these two sets would be equivalent.

If your case ? can be either Parent1Object or Parent2Object and so you cannot do better than just leave it as ?.

Title: Subclasses with generics of subclasses

Body:
I have some issues with generics. I have a BaseObject with multiple sub-classes as well as a BaseContainer<T extends BaseObject> with sub-classes that correspond with BaseObject sub-classes.

public class TestClass extends BaseClass<BaseContainer<BaseObject>> {

    // method signature tied to BaseClass generic
    @Override
    private BaseContainer<BaseObject> createContainer() {
        BaseContainer<BaseObject> container;

        // example logic here to determine which container to use
        if (Math.random() < 0.5) {
            container = new Parent1Container(); // incompatible types
        } else {
            container = new Parent2Container(); // incompatible types
        }

        return container;
    }

    abstract static class BaseObject {}
    static class Parent1Object extends BaseObject {}
    static class Parent2Object extends BaseObject {}

    abstract static class BaseContainer<T extends BaseObject> {
        public abstract void foo(T object);
    }
    static class Parent1Container extends BaseContainer<Parent1Object> {
        public void foo(Parent1Object object) {}
    }
    static class Parent2Container extends BaseContainer<Parent2Object> {
        public void foo(Parent2Object object) {}
    }

}

public class BaseClass<T extends BaseContainer> {
    public abstract T createContainer();
}

I have a method that returns BaseContainer<BaseObject>. Unfortunately, instantiating sub-classes of BaseContainer results in incompatible types error.

I have tried adding casts to the container instantiation, but it leaves ugly unchecked warnings that make me feel like I'm just missing something. I'd like to avoid those and suppress warnings.

If possible, how can I re-write the any of the classes to make the createContainer() method work?

Body:
Since Parent1Container and Parent2Container are not exactly BaseContainer<BaseObject> but BaseContainer<? extends BaseObject>
you need to change the signatures accordingly:

public class TestClass extends BaseClass<BaseContainer<? extends BaseObject>> {
    ...
    public BaseContainer<? extends BaseObject> createConstructor() {
        if (Math.random() < 0.5) {
           return new Parent1Container();
        } else {
           return new Parent2Container();
        }
    }
    ...
}

BaseContainer<BaseObject> makes reference to all those BaseContainer (including extending classes) instances that are able to "handle" any BaseObject, where handle is a blanket-term for all the operations it may do with that type-argument.

In contrast BaseContainer<? extends BaseObject> refer to those BaseContainer instances that are meant to handle a subset of all BaseObject where the top parent class is unknown (thus the ?). It that ? happens to be BaseObject then these two sets would be equivalent.

If your case ? can be either Parent1Object or Parent2Object and so you cannot do better than just leave it as ?.


问:
How to efficient perform column wise multiply?
I am trying to apply multiple multiplication columns wise in data.table. Example:

```<code>require(data.table)
DT <- data.table(a=1:5,b=2:6,c=3:7,
                 d=rep(1,5),e=rep(0,5),f=rep(-1,5))
</code>```

I want the results of a * d, b * e, and c * f, because I have 400 columns multiply another 400 column,
I wonder if there are some efficient solution. Thanks!

答:
Multiply one set of columns by the other:

```<code>> DT[,1:3]*DT[,4:6]
   a b  c
1: 1 0 -3
2: 2 0 -4
3: 3 0 -5
4: 4 0 -6
5: 5 0 -7
</code>```

For your larger problem, with 800 columns, it should just be:

```<code>> DT[,1:400]*DT[,401:800]
</code>```

Body:
I am trying to apply multiple multiplication columns wise in data.table. Example:

require(data.table)
DT <- data.table(a=1:5,b=2:6,c=3:7,
                 d=rep(1,5),e=rep(0,5),f=rep(-1,5))

I want the results of a * d, b * e, and c * f, because I have 400 columns multiply another 400 column,
I wonder if there are some efficient solution. Thanks!

Body:
Multiply one set of columns by the other:

> DT[,1:3]*DT[,4:6]
   a b  c
1: 1 0 -3
2: 2 0 -4
3: 3 0 -5
4: 4 0 -6
5: 5 0 -7

For your larger problem, with 800 columns, it should just be:

> DT[,1:400]*DT[,401:800]


问:
Date time base filter in dynamodb with node js
I am working on a DynamoDB project with node js and I want to fetch some data between two dates. So what i can do for date base filter please provide any code sample in nodejs for this problem. You can assume that we have to fetch student admission between two dates.</p>

答:
You can use BETWEEN to filter the items between two dates.

BETWEEN : Greater than or equal to the first value, and less than or
  equal to the second value.

Example params of Query API:-

```<code>var params = {
    TableName : table,
    KeyConditionExpression : 'yearkey = :hkey and title = :rkey',
    FilterExpression : 'createdate between :val1 and :val2',
    ExpressionAttributeValues : {
        ':hkey' : year_val,
        ':rkey' : title,
        ":val1" : "2010-12-21T16:42:31",
        ":val2" : "2010-12-21T17:42:35"
    }
};
</code>```

Database Item:-

```<code>GetItem succeeded: {
  "Items": [
    {
      "createdate": "2010-12-21T17:42:34Z",
      "title": "The Big New Movie 2010",
      "yearkey": 2010,
      "info": {
        "rating": 0,
        "plot": "Nothing happens at all."
      }
    }
  ],
  "Count": 1,
  "ScannedCount": 1
}
</code>```

Body:
You can use BETWEEN to filter the items between two dates.

BETWEEN : Greater than or equal to the first value, and less than or
  equal to the second value.

Example params of Query API:-

var params = {
    TableName : table,
    KeyConditionExpression : 'yearkey = :hkey and title = :rkey',
    FilterExpression : 'createdate between :val1 and :val2',
    ExpressionAttributeValues : {
        ':hkey' : year_val,
        ':rkey' : title,
        ":val1" : "2010-12-21T16:42:31",
        ":val2" : "2010-12-21T17:42:35"
    }
};

Database Item:-

GetItem succeeded: {
  "Items": [
    {
      "createdate": "2010-12-21T17:42:34Z",
      "title": "The Big New Movie 2010",
      "yearkey": 2010,
      "info": {
        "rating": 0,
        "plot": "Nothing happens at all."
      }
    }
  ],
  "Count": 1,
  "ScannedCount": 1
}


问:
display a mysql db table into datagridview in vb.net
I am working on this project and I want to display the content of a MySQL table in a datagridview in VB.NET.

The query for the retrieving the table works fine but when I run the program it doesn't display any data in the table shown.

The code I am using:

```<code>Private Sub Products_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    SearchTextBox.Enabled = False
    Label1.Enabled = False

    SqlConn = New MySqlConnection
    SqlConn.ConnectionString = "Server=localhost;userid=root;password=;database=osap"
    Dim data As MySqlDataAdapter

    Try
        SqlConn.Open()
        data = New MySqlDataAdapter("SELECT products.id, inventory, description, products.name, categories.name as category, price FROM products INNER JOIN branches ON products.branch_id = branches.id INNER JOIN categories ON products.category_id = categories.id WHERE branch_id ='" & LoginForm.BranchIDTextBox.Text & "' ", SqlConn)
        productstable = New DataTable
        data.Fill(productstable)

        ProductsDataGridView.DataSource = productstable
        ProductsDataGridView.ReadOnly = True
        SqlConn.Close()

    Catch ex As Exception
        MessageBox.Show(ex.Message)

    Finally
        SqlConn.Dispose()
    End Try

End Sub
</code>```

Why am I not getting any results in the DataGridView?

答:
Not sure how I didn't see this - you're not binding your data:</p>

```<code>ProductsDataGridView.DataSource = productstable
ProductsDataGridView.DataBind()
</code>```

Body:
I am working on this project and I want to display the content of a MySQL table in a datagridview in VB.NET.

The query for the retrieving the table works fine but when I run the program it doesn't display any data in the table shown.

The code I am using:

Private Sub Products_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    SearchTextBox.Enabled = False
    Label1.Enabled = False

    SqlConn = New MySqlConnection
    SqlConn.ConnectionString = "Server=localhost;userid=root;password=;database=osap"
    Dim data As MySqlDataAdapter

    Try
        SqlConn.Open()
        data = New MySqlDataAdapter("SELECT products.id, inventory, description, products.name, categories.name as category, price FROM products INNER JOIN branches ON products.branch_id = branches.id INNER JOIN categories ON products.category_id = categories.id WHERE branch_id ='" & LoginForm.BranchIDTextBox.Text & "' ", SqlConn)
        productstable = New DataTable
        data.Fill(productstable)

        ProductsDataGridView.DataSource = productstable
        ProductsDataGridView.ReadOnly = True
        SqlConn.Close()

    Catch ex As Exception
        MessageBox.Show(ex.Message)

    Finally
        SqlConn.Dispose()
    End Try

End Sub

Why am I not getting any results in the DataGridView?

Body:
Not sure how I didn't see this - you're not binding your data:

ProductsDataGridView.DataSource = productstable
ProductsDataGridView.DataBind()


问:
The UAC prompt shows a temporary random Program Name for msi, can the correct name be displayed?
I'm building an MSI installer for windows and sign the installer using signtool. When I run the .msi to test it, the UAC (User Account Control) prompt shows up to ask me if I want to allow the installation to proceed. That's fine, but the prompt shows a number of fields, and for the Program Name field it displays something like "403b3.msi". This is not the name of the msi I'm running.

How can I get the correct Program Name to be displayed?

答:
Use the /d command line argument with the required program name when executing signtool to sign the msi.

It appears that the windows installer creates a temporary copy of the msi file and assigns it a generated name before running it. If you don't use /d with signtool, you get to see the temporary filename which isn't very useful for your users.


问:
Convert array of objects into object
This is my object:

```<code>initialState:any = [{'checked':true}, {'checked':false}, {'checked':true}, {'checked':false}, {'checked':true}, {'checked':false}];
</code>```

This is the output that I expect:

```<code>var params = {
    "device0":"true",
    "device1":"true",
    "device2":"false",
    "device3":"true",
    "device4":"false",
    "device5":"true",
    "device6":"false",
    "device7":"true"
}
</code>```

I have an array of objects. I want to take value from an object and want to build single object as mentioned above.

答:
I would use reduce

var initialState = [{'checked':true},{'checked':false},{'checked':true},{'checked':false},{'checked':true},{'checked':false}],
   params = initialState.reduce( function( o, item, index ) {
       o["device" + index] = item.checked
       return o;
   }, {})

console.log(params);```

Title: Convert array of objects into object

Body:
This is my object:

initialState:any = [{'checked':true}, {'checked':false}, {'checked':true}, {'checked':false}, {'checked':true}, {'checked':false}];

This is the output that I expect:

var params = {
    "device0":"true",
    "device1":"true",
    "device2":"false",
    "device3":"true",
    "device4":"false",
    "device5":"true",
    "device6":"false",
    "device7":"true"
}

I have an array of objects. I want to take value from an object and want to build single object as mentioned above.


问:
Accessing command line (cmd) from RStudio
In my work under R I need to make the call to another software (ANSYS)
For that I am looking for a command under R which allows access to the command line windows (cmd).
For example under matlab the character (!) Allows to do it
thank you</p>

答:
thank you
Yes, it is this command that I seek but once I place my command in it, an error is displayed and indicates that R does not accept the santax

the command is
 system(paste('"C:\Program Files\ANSYS Inc\v150\ANSYS\bin\winx64\ansys150.exe"  -p ane3fl -dir "C:\Users\hamdani\Documents" -j "hamid" -s read -l en-us -b -i "C:\Users\hamdani\Documents\Plane Stress Bracket.txt" -o "C:\Users\hamdani\Documents\fichier.out"'), wait = FALSE)

the error is
Error: '\P' is an unrecognized escape in character string starting "'"C:\P"

When I place the command directly in the System Command, it works very well

OwnerDisplayName: Hamid Hamdani


问:
excel: how to determine if date is within a range of dates
I have following data in my Excel worksheet:

```<code>A1: dec. 25, 2017
A2: feb. 25, 2018
A3: jan. 27, 2018
A4: 1
A5: 2
A6: (this is where result should be)
</code>```

My current formula for A6 is:

```<code>if(and(datevalue(text(A2,"mm/dd/yy")) >= datevalue(text(A1,"mm/dd/yy")), datevalue(text(A2,"mm/dd/yy")) <= datevalue(text(A3,"mm/dd/yy"))), A4/A5, 0)
</code>```

And it genereates 0 with the data provided above which is wrong.

The equation works in dates with the same year but it doesn't work with different year like the example above. I'm working on my scheduling work and I really appreciate if you can help me. thanks

答:
If A1:A3 are properly formatted to date(time) value, it should not be so difficult to manipulate them. =if(and(a2>=a1, a2<=a3), ...) is enough.

If not, first format them properly. For example, if A1 is string 'dec. 25, 2017', next formula will convert A1 to a valid date value.

```<code>=DATE(RIGHT(A1,4), MONTH(1&LEFT(A1,3)), MID(A1,6,2))
</code>```

Getting a month number from a month string is from this article.

Body:
I have following data in my Excel worksheet:

A1: dec. 25, 2017
A2: feb. 25, 2018
A3: jan. 27, 2018
A4: 1
A5: 2
A6: (this is where result should be)

My current formula for A6 is:

if(and(datevalue(text(A2,"mm/dd/yy")) >= datevalue(text(A1,"mm/dd/yy")), datevalue(text(A2,"mm/dd/yy")) <= datevalue(text(A3,"mm/dd/yy"))), A4/A5, 0)

And it genereates 0 with the data provided above which is wrong.

The equation works in dates with the same year but it doesn't work with different year like the example above. I'm working on my scheduling work and I really appreciate if you can help me. thanks

Body:
If A1:A3 are properly formatted to date(time) value, it should not be so difficult to manipulate them. =if(and(a2>=a1, a2<=a3), ...) is enough.

If not, first format them properly. For example, if A1 is string 'dec. 25, 2017', next formula will convert A1 to a valid date value.

=DATE(RIGHT(A1,4), MONTH(1&LEFT(A1,3)), MID(A1,6,2))

Getting a month number from a month string is from this article.


问:
Do..end loop just returning main array
Can anyone help me to find problem here?

```<code>    @deals.each.with_index(1) do |deal, i|
  binding.pry
  puts "#{deal.title} - #{deal.price} - Rating: #{deal.deal_rating}"
  # puts "Available for #{deal.price}"
  # puts "Rating: #{deal.deal_rating}"
  # puts "#{deal.title}"
  # puts "Available at "
end
</code>```

If I do binding.pry, and try to check the value of deal here, it is returning me complete @deals array rather than one deal.

Thank you so much in advance for your help.

答:
Use just each_with_index which will give you the object and the index inside the total of elements being iterated:

```<code><% @deals.each_with_index do |deal, i| %>
  <% binding.pry %>
  <%= "#{deal.title} - #{deal.price} - Rating: #{deal.deal_rating}" %>
<% end %>
</code>```

This way inspecting with pry you take the first element from @deals:

```<code>[1] pry(#<#<Class:0x007fe0cd161ee8>>)> @deals.first
=> #<Deal:0x007fe0cb2751d8
 id: 1,
 title: "Deal-0",
 price: 764,
 deal_rating: 93,
 created_at: Sat, 01 Apr 2017 15:00:29 UTC +00:00,
 updated_at: Sat, 01 Apr 2017 15:00:29 UTC +00:00>
</code>```

If you want to do it in your views then use unless to check for the first element using the index:

```<code><% @deals.each_with_index do |deal, i| %>
  <% unless !i.zero? %>
    <%= "#{deal.title} - #{deal.price} - Rating: #{deal.deal_rating}" %>
  <% end %>
<% end %>
</code>```

The difference is that with with_index you can use an optional parameter to offset the starting index, so you're specifying the index from where to start with with_index(1) not trying to get the first element, see this:

```<code><% @deals.each.with_index(2) do |deal, index| %>
  <%= "#{index}: #{deal}" %><br>
<% end %>

2: #<Deal:0x007fe0cb55ca90>
3: #<Deal:0x007fe0cb55c950>
4: #<Deal:0x007fe0cb55c810>
...
</code>```

This starts from the index 2, and the other one from 0.

```<code><% @deals.each_with_index do |deal, index| %>
  <%= "#{index}: #{deal}" %><br>
<% end %>
0: #<Deal:0x007fe0cb55ca90>
1: #<Deal:0x007fe0cb55c950>
2: #<Deal:0x007fe0cb55c810>
3: #<Deal:0x007fe0cb55c6d0>
4: #<Deal:0x007fe0cb55c590>
</code>```

Title: Do..end loop just returning main array

Body:
Can anyone help me to find problem here?

    @deals.each.with_index(1) do |deal, i|
  binding.pry
  puts "#{deal.title} - #{deal.price} - Rating: #{deal.deal_rating}"
  # puts "Available for #{deal.price}"
  # puts "Rating: #{deal.deal_rating}"
  # puts "#{deal.title}"
  # puts "Available at "
end

If I do binding.pry, and try to check the value of deal here, it is returning me complete @deals array rather than one deal.

Thank you so much in advance for your help.

Body:
Use just each_with_index which will give you the object and the index inside the total of elements being iterated:

<% @deals.each_with_index do |deal, i| %>
  <% binding.pry %>
  <%= "#{deal.title} - #{deal.price} - Rating: #{deal.deal_rating}" %>
<% end %>

This way inspecting with pry you take the first element from @deals:

[1] pry(#<#<Class:0x007fe0cd161ee8>>)> @deals.first
=> #<Deal:0x007fe0cb2751d8
 id: 1,
 title: "Deal-0",
 price: 764,
 deal_rating: 93,
 created_at: Sat, 01 Apr 2017 15:00:29 UTC +00:00,
 updated_at: Sat, 01 Apr 2017 15:00:29 UTC +00:00>

If you want to do it in your views then use unless to check for the first element using the index:

<% @deals.each_with_index do |deal, i| %>
  <% unless !i.zero? %>
    <%= "#{deal.title} - #{deal.price} - Rating: #{deal.deal_rating}" %>
  <% end %>
<% end %>

The difference is that with with_index you can use an optional parameter to offset the starting index, so you're specifying the index from where to start with with_index(1) not trying to get the first element, see this:

<% @deals.each.with_index(2) do |deal, index| %>
  <%= "#{index}: #{deal}" %><br>
<% end %>

2: #<Deal:0x007fe0cb55ca90>
3: #<Deal:0x007fe0cb55c950>
4: #<Deal:0x007fe0cb55c810>
...

This starts from the index 2, and the other one from 0.

<% @deals.each_with_index do |deal, index| %>
  <%= "#{index}: #{deal}" %><br>
<% end %>
0: #<Deal:0x007fe0cb55ca90>
1: #<Deal:0x007fe0cb55c950>
2: #<Deal:0x007fe0cb55c810>
3: #<Deal:0x007fe0cb55c6d0>
4: #<Deal:0x007fe0cb55c590>


问:
Tomcat and Database references
Is there a proper way to set in tomcat database ip, user and password to open a connection toward DB?

My situation is: I have some Servlets running on tomcat, and almost all of them open a connection to mySQL DB and execute queries. Database ip, username and password of the connection are always the same, so what I want is a single point to store those info that let me change those info easly, for example editing a simple txt file or xml one.

答:
YES, JNDI is the solution. When asked for this problem, I have already read about jndi, but I had errors, so I thought the solution was not that. After a lot of search it comes out that the error is that when I specify 'url' for the resource it needs TWO BACKSLASHES after 'mysql:', NOT ONE, as a lot of online tutorials said. I report the correct procedure to solve the problem I asked for:

1)context.xml has to be like

```<code><Context>
<Resource name="jdbc/DB_NAME"
auth="Container"
type="javax.sql.DataSource"
username="db_user_to_interact_with_db"
password="password_of_username"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://db_IP:3306/DB_NAME?useSSL=true"
maxActive="100"
maxIdle="3"/>
</Context>
</code>```

2)you can obtain db connection as follow

```<code>Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
// Look up our data source
DataSource ds = (DataSource)envCtx.lookup("jdbc/DB_NAME");
// Allocate and use a connection from the pool
Connection conn = ds.getConnection();
</code>```

Title: Tomcat and Database references

Body:
YES, JNDI is the solution. When asked for this problem, I have already read about jndi, but I had errors, so I thought the solution was not that. After a lot of search it comes out that the error is that when I specify 'url' for the resource it needs TWO BACKSLASHES after 'mysql:', NOT ONE, as a lot of online tutorials said. I report the correct procedure to solve the problem I asked for:

1)context.xml has to be like

<Context>
<Resource name="jdbc/DB_NAME"
auth="Container"
type="javax.sql.DataSource"
username="db_user_to_interact_with_db"
password="password_of_username"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://db_IP:3306/DB_NAME?useSSL=true"
maxActive="100"
maxIdle="3"/>
</Context>

2)you can obtain db connection as follow

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
// Look up our data source
DataSource ds = (DataSource)envCtx.lookup("jdbc/DB_NAME");
// Allocate and use a connection from the pool
Connection conn = ds.getConnection();


问:
jQuery: if string matches one of these href's
I have this var in my code:

```<code>var href = $(this).attr('href'),
str = href.split('/').slice(-2,-1)[0];
</code>```

How do I check if 'images', 'images-2' or 'images-3'
matches the 'href' string, then do something..

答:
Take a look at this:
http://api.jquery.com/category/selectors/

You can have something like:
$('[href^="images"]')

Edit:
You can also make your own selectors if you want to.
http://dpatrickcaldwell.blogspot.com/2010/03/custom-jquery-selector-for-external-and.html

James Padolsey has already written one that could work for you.
http://james.padolsey.com/javascript/regex-selector-for-jquery/

Body:
I have this var in my code:

var href = $(this).attr('href'),
str = href.split('/').slice(-2,-1)[0];

How do I check if 'images', 'images-2' or 'images-3'
matches the 'href' string, then do something..