问:
Ansible: Register variable when JSON value equals
I'm calling a webservice and returning some JSON. I want to conditionally run a subsequent task, based on whether a particular name value is found.

For example, set a value nameExists if and only if the values array contains a name field of myDemo. So in this case, nameExists would be defined:

```<code>...
"failed": false,
"json": {
  "values": [{
    "id": "1234",
    "name": "myDemo"
  },
  {
    "id": "6789",
    "name": "myDemo2"
  }]
},
"msg": "OK (100 bytes)"
...
</code>```

Here's what I'm currently trying:

```<code># Call API
- name: Call API
  uri:
    url: myURL
    method: POST
  register: apiCheckResult

- name: Debug Auto tags
  debug:
    msg: "{{ item.name }}"
  loop: "{{ apiCheckResult.json['values'] }}"
  when: item.name == "myDemo"
  register: tagExists
</code>```

This works, in a way, but it gives me the full JSON output, all I need is a true / false.

Am I on the right track or is there a better way to achieve this?

答:
You don't (normally) use a debug task to set variables. You probably want to use set_fact. If I understand your question correctly, you want to set a boolean tagExists to true if one of the items in the values list of the API response contains the name myDemo.  That might look like this:

```<code>- set_fact:
    tagExists: "{{ apiCheckResult.json|json_query('values[?name == `myDemo`]') }}"
</code>```

"But wait!", you say, "that's not a boolean!".  While you are correct, you can treat it like on.  For example, after having set tagExists using that task, you could do this:

```<code>- debug:
    msg: "The tag exists!"
  when: tagExists
</code>```

This works because a non-empty list evaluates as a true value in a boolean context (and an empty list evaluates as false).  The json_query expression above returns a non-empty list when there is a match, and an empty list otherwise.

If you really want a boolean, you could do this instead:

```<code>- set_fact:
    tagExists: "{{ true if apiCheckResult.json|json_query('values[?name == `myDemo`]') else false }}"
</code>```

Body:
I'm calling a webservice and returning some JSON. I want to conditionally run a subsequent task, based on whether a particular name value is found.

For example, set a value nameExists if and only if the values array contains a name field of myDemo. So in this case, nameExists would be defined:

...
"failed": false,
"json": {
  "values": [{
    "id": "1234",
    "name": "myDemo"
  },
  {
    "id": "6789",
    "name": "myDemo2"
  }]
},
"msg": "OK (100 bytes)"
...

Here's what I'm currently trying:

# Call API
- name: Call API
  uri:
    url: myURL
    method: POST
  register: apiCheckResult

- name: Debug Auto tags
  debug:
    msg: "{{ item.name }}"
  loop: "{{ apiCheckResult.json['values'] }}"
  when: item.name == "myDemo"
  register: tagExists

This works, in a way, but it gives me the full JSON output, all I need is a true / false.

Am I on the right track or is there a better way to achieve this?

Body:
You don't (normally) use a debug task to set variables. You probably want to use set_fact. If I understand your question correctly, you want to set a boolean tagExists to true if one of the items in the values list of the API response contains the name myDemo.  That might look like this:

- set_fact:
    tagExists: "{{ apiCheckResult.json|json_query('values[?name == `myDemo`]') }}"

"But wait!", you say, "that's not a boolean!".  While you are correct, you can treat it like on.  For example, after having set tagExists using that task, you could do this:

- debug:
    msg: "The tag exists!"
  when: tagExists

This works because a non-empty list evaluates as a true value in a boolean context (and an empty list evaluates as false).  The json_query expression above returns a non-empty list when there is a match, and an empty list otherwise.

If you really want a boolean, you could do this instead:

- set_fact:
    tagExists: "{{ true if apiCheckResult.json|json_query('values[?name == `myDemo`]') else false }}"


来源: stackexchange

问:
Count with group by on Postgresql
I have a postgresql type and a table

CREATE TYPE mem_status AS ENUM('waiting', 'active', 'expired');

CREATE TABLE mems (
  id BIGSERIAL PRIMARY KEY,
  status mem_status NOT NULL
);
```

<p>dataset</p>

<pre class="lang-sql prettyprint-override"><code>INSERT INTO mems(id, status) VALUES
  (1, 'active'), (2, 'active'), (3, 'expired');
</code>```

I want to query counts that grouped by statuses. So I treid the query below.

WITH mem_statuses AS (
  SELECT unnest(enum_range(NULL::mem_status)) AS status
)
SELECT m.status, count(1)
  FROM mems m
  RIGHT JOIN mem_statuses ms ON ms.status = m.status
  GROUP BY m.status;
```

<p>But if there is no <code>waiting</code> mems, the result looks like below.</p>

```status     |  count
================
NULL       |  1      <- problem
'active'   |  2
'expired'  |  1
```

<p>I want to get result like this.</p>

```status     |  count
================
'waiting'  |  0
'active'   |  2
'expired'  |  1
```

How can I do that?

答:
You need to modify the join and aggregate a bit -</p>

```<code>select ms.status, count(m.status)
from (select unnest(enum_range(null::mem_status))) as ms(status)
left join mems as m
  on ms.status = m.status
group by ms.status;
</code>```

ContentLicense: CC BY-SA 4.0

Title: Count with group by on Postgresql

Body:
I have a postgresql type and a table

CREATE TYPE mem_status AS ENUM('waiting', 'active', 'expired');

CREATE TABLE mems (
  id BIGSERIAL PRIMARY KEY,
  status mem_status NOT NULL
);

dataset

INSERT INTO mems(id, status) VALUES
  (1, 'active'), (2, 'active'), (3, 'expired');

I want to query counts that grouped by statuses. So I treid the query below.

WITH mem_statuses AS (
  SELECT unnest(enum_range(NULL::mem_status)) AS status
)
SELECT m.status, count(1)
  FROM mems m
  RIGHT JOIN mem_statuses ms ON ms.status = m.status
  GROUP BY m.status;

But if there is no waiting mems, the result looks like below.

status     |  count
================
NULL       |  1      <- problem
'active'   |  2
'expired'  |  1

I want to get result like this.

status     |  count
================
'waiting'  |  0
'active'   |  2
'expired'  |  1

How can I do that?

Body:
You need to modify the join and aggregate a bit -

select ms.status, count(m.status)
from (select unnest(enum_range(null::mem_status))) as ms(status)
left join mems as m
  on ms.status = m.status
group by ms.status;


问:
Using Javascript to get list items, can I change item order?
I am using JavaScript to get list items and customize the look via html and CSS, however they are sorting automatically by ID number and I need it sorted by a custom field, 'EventDate'.

I haven't been able to figure find anything via search. I've tried changing the default list view sort order and such but nothing has worked thus far.

```<code><script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
<script type="text/javascript" src="_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="_layouts/15/sp.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

<script type="text/javascript">
$(function() {
    GetProducts();
    GetNews();
});

function GetProducts() {
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('HRKPI');
    this.collListItem = oList.getItems("");
    clientContext.load(collListItem);
    clientContext.executeQueryAsync(
        Function.createDelegate(this, this.onQuerySucceeded),
        Function.createDelegate(this, this.onQueryFailed)
    );
}

function GetNews() {
    var nclientContext = new SP.ClientContext.get_current();
    var nList = nclientContext.get_web().get_lists().getByTitle('NewsInfo');
    this.ncollListItem = nList.getItems("");
    nclientContext.load(ncollListItem);
    nclientContext.executeQueryAsync(
        Function.createDelegate(this, this.onQuerySucceeded),
        Function.createDelegate(this, this.onQueryFailed)
    );
}

function onQuerySucceeded(sender, args) {
    var listItemEnum = collListItem.getEnumerator();
    var nlistItemEnum = ncollListItem.getEnumerator();
    var ProductInfo = '<div>';
    var NewsInfoHTML = '<div>';

    while (listItemEnum.moveNext()) {
        var oListItem = listItemEnum.get_current();
        ProductInfo += '<div id="pParentSquareKPI"> <p id="pKPIName">' +
            oListItem.get_item('Name') + '</p>' +
            '<p id="pKPIValue">' + oListItem.get_item('Value') + '</p> </div>';
    }

    while (nlistItemEnum.moveNext()) {
        var nListItem = nlistItemEnum.get_current();
        NewsInfoHTML += '<table style="width:97%;text-align:center;color:#3C4F66;border: 1px solid #b1b8c1;margin-bottom:15px;"> <col width="95"> <tr style="margin-bottom:20px;"> <td style="background-color:#3C4F66;color:white;border-right: 1px solid #b1b8c1;font-size:20px;">' +
            nListItem.get_item('EventMonth') +
            '</td> <td rowspan="3" style="text-align:left;padding:10px;background-color:#f1f1f1;">' +
            nListItem.get_item('News') +
            '</td> </tr> <tr> <td style="border-right: 1px solid #b1b8c1;font-size:38px;">' +
            nListItem.get_item('EventDay') +
            '</td> </tr> <tr> <td style="background-color:#f2f2f2;border-right: 1px solid #b1b8c1;">' +
            nListItem.get_item('EventYear') + '</td> </tr> </table>';
    }

    ProductInfo += '</div>';
    $('#products').html(ProductInfo);

    NewsInfoHTML += '</div>';
    $('#news').html(NewsInfoHTML);
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>
</code>```

It outputs the items as needed but they are sorted by ID, which is not editable. I need it sorted by a custom column, 'EventDate'.

答:
Try set caml query to sort your data.

Sample script.

```<code>var nList = nclientContext.get_web().get_lists().getByTitle('NewsInfo');
    var query = new SP.CamlQuery();
    query.set_viewXml('<View><Query><OrderBy><FieldRef Name="EventDate" Ascending="FALSE"/></OrderBy></Query></View>');
    this.ncollListItem = nList.getItems(query);
</code>```

Body:
I am using JavaScript to get list items and customize the look via html and CSS, however they are sorting automatically by ID number and I need it sorted by a custom field, 'EventDate'.

I haven't been able to figure find anything via search. I've tried changing the default list view sort order and such but nothing has worked thus far.

It outputs the items as needed but they are sorted by ID, which is not editable. I need it sorted by a custom column, 'EventDate'.

Body:
Try set caml query to sort your data.

Sample script.

var nList = nclientContext.get_web().get_lists().getByTitle('NewsInfo');
    var query = new SP.CamlQuery();
    query.set_viewXml('<View><Query><OrderBy><FieldRef Name="EventDate" Ascending="FALSE"/></OrderBy></Query></View>');
    this.ncollListItem = nList.getItems(query);


问:
How can I know the output and input tensor names in a saved model
I know how to load a saved TensorFlow model but how will I know the input and output tensor names.

I can load a protobuf file using tf.import_graph_def and then load the tensors using function get_tensor_by_name but how will I know the tensor names of any pre-trained model. Do I need to check their documentation or is there any other way.

答:
Solution only for inputs:</p>

```<code># read pb into graph_def
with tf.gfile.GFile(input_model_filepath, "rb") as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())

# import graph_def
with tf.Graph().as_default() as graph:
    tf.import_graph_def(graph_def)

# print operations
for op in graph.get_operations():
    if op.type == "Placeholder":
        print(op.name)
</code>```

Body:
Solution only for inputs:

# read pb into graph_def
with tf.gfile.GFile(input_model_filepath, "rb") as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())

# import graph_def
with tf.Graph().as_default() as graph:
    tf.import_graph_def(graph_def)

# print operations
for op in graph.get_operations():
    if op.type == "Placeholder":
        print(op.name)


问:
Can't get Facebook ID and email
I faced with the following problem: I need to get FB id and email after authorization. Here's my code:

```<code>@Override
            public void onSuccess(LoginResult loginResult) {

                final String[] email = new String[1];
                final String[] id = new String[1];

                GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        (object, response) -> {
                            try {
                                email[0] = object.getString(FB_EMAIL_PERMISSION);
                                id[0] = object.getString(FB_ID_PERMISSION);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            response.getRawResponse();
                        });

                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,email");
                request.setParameters(parameters);
                request.executeAsync();

                Bundle bundle = new Bundle();
                bundle.putString(EXTRA_TOKEN, loginResult.getAccessToken().getToken());
                bundle.putString(EXTRA_EMAIL, email[0]);
                bundle.putString(EXTRA_ID, id[0]);

                mPresenter.saveUserData(bundle);
            }
</code>```

But when I run my app, I don't get this fields. I checked in debugger and part

```<code>GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        (object, response) -> {
                            try {
                                email[0] = object.getString(FB_EMAIL_PERMISSION);
                                id[0] = object.getString(FB_ID_PERMISSION);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            response.getRawResponse();
                        });
</code>```

isn't called at all. I don't understand why it happens. So, what's the matter and how can I solve it?

UPD

Probably, maybe it would help, here's whole fb logic:

```<code>mCallbackManager = CallbackManager.Factory.create();
        mFacebookButton.setReadPermissions(Collections.singletonList(FB_EMAIL_PERMISSION));
        mFacebookButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {

                final String[] email = new String[1];
                final String[] id = new String[1];

                GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        (object, response) -> {
                            try {
                                email[0] = object.getString(FB_EMAIL_PERMISSION);
                                id[0] = object.getString(FB_ID_PERMISSION);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            response.getRawResponse();
                        });

                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,email");
                request.setParameters(parameters);
                request.executeAsync();

                Bundle bundle = new Bundle();
                bundle.putString(EXTRA_TOKEN, loginResult.getAccessToken().getToken());
                bundle.putString(EXTRA_EMAIL, email[0]);
                bundle.putString(EXTRA_ID, id[0]);

                mPresenter.saveUserData(bundle);
            }
</code>```

UPD 2

I have one think about this problem, that request is asynchronous and when I put a breakpoint on line mPresenter.saveUserData(bundle); information isn't loaded yet, but how can I make it synchronous? Or maybe I am wrong?

UPD 3

I changed my request in the following way, but it still doesn't work and breakpoints are skipped in this part.

```<code>GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        (object, response) -> {
                            try {
                                if (response.getJSONObject() != null) {
                                    JSONObject data = response.getJSONObject();
                                    if (data.has(FB_EMAIL_PERMISSION)) {
                                        email[0] = response.getJSONObject().getString(FB_EMAIL_PERMISSION);
                                    }
                                    if (data.has(FB_ID_PERMISSION)) {
                                        id[0] = response.getJSONObject().getString(FB_ID_PERMISSION);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            response.getRawResponse();
                        });
</code>```

And here's the values of permissions:

```<code>private static final String FB_EMAIL_PERMISSION = "email";
private static final String FB_ID_PERMISSION = "id";
</code>```

答:
this is how i am using it
i am not sure of the value of FB_EMAIL_PERMISSION FB_ID_PERMISSION

```<code> final GraphRequest request = GraphRequest.newMeRequest(
                AccessToken.getCurrentAccessToken(),
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(
                            JSONObject object,
                            GraphResponse response) {
                        try {
                            String id = "", user_email = "", name = "";
                            Log.d("EHREIUIU", String.valueOf(object));
                            if (response.getJSONObject() != null) {
                                JSONObject data = response.getJSONObject();
                                if (data.has("id"))
                                    id = data.getString("id");
                                if (data.has("email"))
                                    user_email = data.getString("email");
                            }
                            getOneSignalToken();
                            socialLogin(user_email, name, null, id, "facebook");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
</code>```

Title: Can't get Facebook ID and email

Body:
I faced with the following problem: I need to get FB id and email after authorization. Here's my code:

@Override
            public void onSuccess(LoginResult loginResult) {

                final String[] email = new String[1];
                final String[] id = new String[1];

                GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        (object, response) -> {
                            try {
                                email[0] = object.getString(FB_EMAIL_PERMISSION);
                                id[0] = object.getString(FB_ID_PERMISSION);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            response.getRawResponse();
                        });

                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,email");
                request.setParameters(parameters);
                request.executeAsync();

                Bundle bundle = new Bundle();
                bundle.putString(EXTRA_TOKEN, loginResult.getAccessToken().getToken());
                bundle.putString(EXTRA_EMAIL, email[0]);
                bundle.putString(EXTRA_ID, id[0]);

                mPresenter.saveUserData(bundle);
            }

But when I run my app, I don't get this fields. I checked in debugger and part

GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        (object, response) -> {
                            try {
                                email[0] = object.getString(FB_EMAIL_PERMISSION);
                                id[0] = object.getString(FB_ID_PERMISSION);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            response.getRawResponse();
                        });

isn't called at all. I don't understand why it happens. So, what's the matter and how can I solve it?

UPD

Probably, maybe it would help, here's whole fb logic:

mCallbackManager = CallbackManager.Factory.create();
        mFacebookButton.setReadPermissions(Collections.singletonList(FB_EMAIL_PERMISSION));
        mFacebookButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {

                final String[] email = new String[1];
                final String[] id = new String[1];

                GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        (object, response) -> {
                            try {
                                email[0] = object.getString(FB_EMAIL_PERMISSION);
                                id[0] = object.getString(FB_ID_PERMISSION);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            response.getRawResponse();
                        });

                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,email");
                request.setParameters(parameters);
                request.executeAsync();

                Bundle bundle = new Bundle();
                bundle.putString(EXTRA_TOKEN, loginResult.getAccessToken().getToken());
                bundle.putString(EXTRA_EMAIL, email[0]);
                bundle.putString(EXTRA_ID, id[0]);

                mPresenter.saveUserData(bundle);
            }

UPD 2

I have one think about this problem, that request is asynchronous and when I put a breakpoint on line mPresenter.saveUserData(bundle); information isn't loaded yet, but how can I make it synchronous? Or maybe I am wrong?

UPD 3

I changed my request in the following way, but it still doesn't work and breakpoints are skipped in this part.

GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        (object, response) -> {
                            try {
                                if (response.getJSONObject() != null) {
                                    JSONObject data = response.getJSONObject();
                                    if (data.has(FB_EMAIL_PERMISSION)) {
                                        email[0] = response.getJSONObject().getString(FB_EMAIL_PERMISSION);
                                    }
                                    if (data.has(FB_ID_PERMISSION)) {
                                        id[0] = response.getJSONObject().getString(FB_ID_PERMISSION);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            response.getRawResponse();
                        });

And here's the values of permissions:

private static final String FB_EMAIL_PERMISSION = "email";
private static final String FB_ID_PERMISSION = "id";

Body:
this is how i am using it
i am not sure of the value of FB_EMAIL_PERMISSION FB_ID_PERMISSION

 final GraphRequest request = GraphRequest.newMeRequest(
                AccessToken.getCurrentAccessToken(),
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(
                            JSONObject object,
                            GraphResponse response) {
                        try {
                            String id = "", user_email = "", name = "";
                            Log.d("EHREIUIU", String.valueOf(object));
                            if (response.getJSONObject() != null) {
                                JSONObject data = response.getJSONObject();
                                if (data.has("id"))
                                    id = data.getString("id");
                                if (data.has("email"))
                                    user_email = data.getString("email");
                            }
                            getOneSignalToken();
                            socialLogin(user_email, name, null, id, "facebook");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });


问:
macos switching application between multiple displays
I am coming in from a windows background where I used to work with multiple displays.  One of the most frequently used shortcuts on Windows was win+left or win+right to move windows between multiple displays.  Is there a similar shortcut on macos.  I have seen some documentation on installing third party apps and then configuring them, but I would prefer something native on macos, since third party apps could slow down the system.</p>

答:
You can just drag and drop the window to the display on left or right. </p>

<p>Also, take a look here </p>

Body:
You can just drag and drop the window to the display on left or right.

Also, take a look here


问:
Function that takes an array of chars and returns a concatenated string. Haskell
Ugh... Struggling with haskell. Trying to implement Conway's GOL and create a random game board. Here is where I am at.

I have a function to randomize each square in an array, and a function to create an array of characters using the randomization function to represent my game board.

I am trying to now create a function: showBoard, which iterates through the array and concatenates each char to a string which I can print out in my main.

```<code>import System.Random
import Control.Monad
import Data.Array
import Data.List

randomBoard = do
    f1 <- randomIO :: IO Int
    if(f1 `mod` 2) == 0
        then return  '*'
        else return  ' '

boardArray :: IO (Array Int Char)
boardArray = listArray (0, 99) <$> replicateM 100 randomBoard

showBoard :: IO (Array Int Char) -> Int -> String -> String
showBoard arr i str = do
    if i > 0
       then showBoard arr (i-1) (str ++ (arr ! i))
       else return str

main :: IO ()
main =
let board = showBoard boardArray 100 ""
    in
        do
            putStr board
</code>```

I have spent an hour trying to tweak this out and keep getting type issues. I cant even get this board to print x.x please help.

答:
A few problems:

It's not possible to write a function that takes an IO of something and uses it to return something that isn't in IO. Change showBoard to take an Array Int Char without the IO wrapper, and remove do and return from it.

Since your array is zero-based, change arr ! i to arr ! (i - 1).

arr contains Chars, not Strings, so use [] instead of () around the indexing of it to make it into a String.

Since we made showBoard take a value without IO, use <- in main to get at the inner value we need.

Here's the result of all of those changes:

```<code>import System.Random
import Control.Monad
import Data.Array
import Data.List

randomBoard = do
    f1 <- randomIO :: IO Int
    if(f1 `mod` 2) == 0
        then return  '*'
        else return  ' '

boardArray :: IO (Array Int Char)
boardArray = listArray (0, 99) <$> replicateM 100 randomBoard

showBoard :: Array Int Char -> Int -> String -> String
showBoard arr i str =
    if i > 0
       then showBoard arr (i-1) (str ++ [arr ! (i - 1)])
       else str

main :: IO ()
main = do
    randomArray <- boardArray
    let board = showBoard randomArray 100 ""
    putStr board
</code>```

As an aside, the way showBoard is implemented, although it works, is particularly inefficient. You should avoid doing things that look like x ++ [y] recursively, as it's quadratically slow. Also, it looks like your function prints the elements starting at the end and going down to 0, rather than starting at 0 and going up to the end. Here's a new version of it that fixes both of those things at once:

```<code>showBoard :: Array Int Char -> Int -> String -> String
showBoard arr i str =
    if i > 0
       then showBoard arr (i-1) ((arr ! (i - 1)) : str)
       else str
</code>```

Using : where possible is much more efficient than always using ++.

You can simplify even further by not having showBoard at all, and using elems (from Data.Array) instead:

```<code>main :: IO ()
main = do
    randomArray <- boardArray
    let board = elems randomArray
    putStr board
</code>```

Body:
Ugh... Struggling with haskell. Trying to implement Conway's GOL and create a random game board. Here is where I am at.

I have a function to randomize each square in an array, and a function to create an array of characters using the randomization function to represent my game board.

I am trying to now create a function: showBoard, which iterates through the array and concatenates each char to a string which I can print out in my main.

import System.Random
import Control.Monad
import Data.Array
import Data.List

randomBoard = do
    f1 <- randomIO :: IO Int
    if(f1 `mod` 2) == 0
        then return  '*'
        else return  ' '

boardArray :: IO (Array Int Char)
boardArray = listArray (0, 99) <$> replicateM 100 randomBoard

showBoard :: IO (Array Int Char) -> Int -> String -> String
showBoard arr i str = do
    if i > 0
       then showBoard arr (i-1) (str ++ (arr ! i))
       else return str

main :: IO ()
main =
let board = showBoard boardArray 100 ""
    in
        do
            putStr board

I have spent an hour trying to tweak this out and keep getting type issues. I cant even get this board to print x.x please help.

Body:
A few problems:

It's not possible to write a function that takes an IO of something and uses it to return something that isn't in IO. Change showBoard to take an Array Int Char without the IO wrapper, and remove do and return from it.

Since your array is zero-based, change arr ! i to arr ! (i - 1).

arr contains Chars, not Strings, so use [] instead of () around the indexing of it to make it into a String.

Since we made showBoard take a value without IO, use <- in main to get at the inner value we need.

Here's the result of all of those changes:

import System.Random
import Control.Monad
import Data.Array
import Data.List

randomBoard = do
    f1 <- randomIO :: IO Int
    if(f1 `mod` 2) == 0
        then return  '*'
        else return  ' '

boardArray :: IO (Array Int Char)
boardArray = listArray (0, 99) <$> replicateM 100 randomBoard

showBoard :: Array Int Char -> Int -> String -> String
showBoard arr i str =
    if i > 0
       then showBoard arr (i-1) (str ++ [arr ! (i - 1)])
       else str

main :: IO ()
main = do
    randomArray <- boardArray
    let board = showBoard randomArray 100 ""
    putStr board

As an aside, the way showBoard is implemented, although it works, is particularly inefficient. You should avoid doing things that look like x ++ [y] recursively, as it's quadratically slow. Also, it looks like your function prints the elements starting at the end and going down to 0, rather than starting at 0 and going up to the end. Here's a new version of it that fixes both of those things at once:

showBoard :: Array Int Char -> Int -> String -> String
showBoard arr i str =
    if i > 0
       then showBoard arr (i-1) ((arr ! (i - 1)) : str)
       else str

Using : where possible is much more efficient than always using ++.

You can simplify even further by not having showBoard at all, and using elems (from Data.Array) instead:

main :: IO ()
main = do
    randomArray <- boardArray
    let board = elems randomArray
    putStr board


问:
Develop game AI with Tensorflow.js
I've made a game in my github repository ("Lil Square of Eight") and created some code to play against machine. Now, for study and joy purposes, I would like to create some AI with Tensorflow.js that can play the game and even win.

The game is simple, each turn a player click a square side and it's marked with player color. The player who closes the square do a score and can keep going with his turn.

I've done some tests with Tensorflow.js and I didn't understood it at all. All I could do was verify if one square has a side that can be clicked and don't give the oportunity to the other player score, or do a score itself.

```<code>const model = tf.sequential();

model.add(tf.layers.dense({ units: 16, inputShape: [8] }));
model.add(tf.layers.dense({ units: 16, inputShape: [16], activation: 'sigmoid' }));
model.add(tf.layers.dense({ units: 1, inputShape: [16] }));
model.compile({ optimizer: tf.train.adam(0.1), loss: 'meanSquaredError', lr: 0.3 });

const xs1 = tf.tensor2d([
                [0, 1, 1, 1, 2, 0, 3, 0], [0, 1, 1, 0, 2, 1, 3, 0], [0, 1, 1, 0, 2, 0, 3, 1], [0, 0, 1, 1, 2, 1, 3, 0], [0, 0, 1, 1, 2, 0, 3, 1], [0, 0, 1, 0, 2, 1, 3, 1],
                [0, 1, 1, 1, 2, 1, 3, 1],
                [0, 0, 1, 0, 2, 0, 3, 0], [0, 1, 1, 0, 2, 0, 3, 0], [0, 0, 1, 1, 2, 0, 3, 0], [0, 0, 1, 0, 2, 1, 3, 0], [0, 0, 1, 0, 2, 0, 3, 1],
                [0, 0, 1, 1, 2, 1, 3, 1], [0, 1, 1, 0, 2, 1, 3, 1], [0, 1, 1, 1, 2, 0, 3, 1], [0, 1, 1, 1, 2, 1, 3, 0]]);

await model.fit(xs1, tf.tensor2d([[0], [0], [0], [0], [0], [0], [0], [1], [1], [1], [1], [1], [2], [2], [2], [2]]), {epochs: 550});

console.log(model.predict(tf.tensor2d([[0, 1, 1, 0, 2, 0, 3, 0]])));
</code>```

EDIT

As asked, I would like help in how I can create an AI with Tensorflow.js that can think and play my game in a smart way. It can learn with previuos games and start to play the game.

答:
What you're looking for is called Reinforcement learning.   It's not as popular as most Tensorflow methods for ML.  TFJS examples generally orbit around supervised learning methods.

In this case, here's my recommendation.   The most popular (to me) method of game play on ML reinforcement learning, is called Q Learning.  Firstly, you can research Q Learning in regular old Tensorflow and Python, then you can convert it over to TFJS once you deeply understanding the concepts.  You'll be one of the first!

Here's a great series on Tensorflow AND Q Learning:  https://medium.com/emergent-future/simple-reinforcement-learning-with-tensorflow-part-0-q-learning-with-tables-and-neural-networks-d195264329d0

I hope this gives you some direction!

Title: Develop game AI with Tensorflow.js

Body:
I've made a game in my github repository ("Lil Square of Eight") and created some code to play against machine. Now, for study and joy purposes, I would like to create some AI with Tensorflow.js that can play the game and even win.

The game is simple, each turn a player click a square side and it's marked with player color. The player who closes the square do a score and can keep going with his turn.

I've done some tests with Tensorflow.js and I didn't understood it at all. All I could do was verify if one square has a side that can be clicked and don't give the oportunity to the other player score, or do a score itself.

const model = tf.sequential();

model.add(tf.layers.dense({ units: 16, inputShape: [8] }));
model.add(tf.layers.dense({ units: 16, inputShape: [16], activation: 'sigmoid' }));
model.add(tf.layers.dense({ units: 1, inputShape: [16] }));
model.compile({ optimizer: tf.train.adam(0.1), loss: 'meanSquaredError', lr: 0.3 });

const xs1 = tf.tensor2d([
                [0, 1, 1, 1, 2, 0, 3, 0], [0, 1, 1, 0, 2, 1, 3, 0], [0, 1, 1, 0, 2, 0, 3, 1], [0, 0, 1, 1, 2, 1, 3, 0], [0, 0, 1, 1, 2, 0, 3, 1], [0, 0, 1, 0, 2, 1, 3, 1],
                [0, 1, 1, 1, 2, 1, 3, 1],
                [0, 0, 1, 0, 2, 0, 3, 0], [0, 1, 1, 0, 2, 0, 3, 0], [0, 0, 1, 1, 2, 0, 3, 0], [0, 0, 1, 0, 2, 1, 3, 0], [0, 0, 1, 0, 2, 0, 3, 1],
                [0, 0, 1, 1, 2, 1, 3, 1], [0, 1, 1, 0, 2, 1, 3, 1], [0, 1, 1, 1, 2, 0, 3, 1], [0, 1, 1, 1, 2, 1, 3, 0]]);

await model.fit(xs1, tf.tensor2d([[0], [0], [0], [0], [0], [0], [0], [1], [1], [1], [1], [1], [2], [2], [2], [2]]), {epochs: 550});

console.log(model.predict(tf.tensor2d([[0, 1, 1, 0, 2, 0, 3, 0]])));

EDIT

As asked, I would like help in how I can create an AI with Tensorflow.js that can think and play my game in a smart way. It can learn with previuos games and start to play the game.


问:
Align the text vertically
How can I align this text vertically in the middle of the divs?

I've already tried to change the position using relative/absolute, and changing the top and left of the paragraph, but it doesn't work at all.

 div.roxo{
      background-color: purple;
      padding: 40px;
    }
    div.amarelo{
      background-color: yellow;
      height: 300px;
      width: 25%;
      float: left;
    }
    div.vermelho{
      background-color: red;
      height: 300px;
      width: 50%;
      float: left;
    }
    div.verde{
      background-color: green;
      height: 300px;
      width: 25%;
      float: left;
    }
    div.azul{
      background-color: blue;
      padding: 40px;
    }
    p{
       margin: 0;
       text-align: center;
       vertical-align: middle;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
   <html>
    <head>
    <title>Page Title</title>

    </head>
    <body>
      <div class="roxo">
       <p>roxo</p>
      </div>
      <div class="amarelo">
       <p>amarelo</p>
      </div>
      <div class="vermelho">
       <p>vermelho</p>
      </div>
      <div class="verde">
       <p>verde</p>
      </div>
      <div class="azul">
       <p>azul</p>
      </div>
    </body>
   </html></code>```

答:
You can do it using flexbox.

div.roxo{
      background-color: purple;
      padding: 40px;
    }
    div.amarelo{
      display:flex;
       justify-content:center;
      align-items:center;
      background-color: yellow;
      height: 300px;
      width: 25%;
      float: left;
    }
    div.vermelho{
      display:flex;
       justify-content:center;
      align-items:center;
      background-color: red;
      height: 300px;
      width: 50%;
      float: left;
    }
    div.verde{
      display:flex;
       justify-content:center;
      align-items:center;
      background-color: green;
      height: 300px;
      width: 25%;
      float: left;
    }
    div.azul{
      display:flex;
       justify-content:center;
      align-items:center;
      background-color: blue;
      padding: 40px;
    }
    p{
       margin: 0;
       text-align: center;
       vertical-align: middle;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
  <html>
    <head>
    <title>Page Title</title>

    </head>
    <body>
      <div class="roxo">
       <p>roxo</p>
      </div>
      <div class="amarelo">
       <p>amarelo</p>
      </div>
      <div class="vermelho">
       <p>vermelho</p>
      </div>
      <div class="verde">
       <p>verde</p>
      </div>
      <div class="azul">
       <p>azul</p>
      </div>
    </body>
  </html></code>```

Just add:

```<code>display:flex;
justify-content:center;
align-items:center;
</code>```

to your div CSS.

You can learn more about flexbox here at https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Title: Align the text vertically

Body:
How can I align this text vertically in the middle of the divs?

I've already tried to change the position using relative/absolute, and changing the top and left of the paragraph, but it doesn't work at all.

 div.roxo{
      background-color: purple;
      padding: 40px;
    }
    div.amarelo{
      background-color: yellow;
      height: 300px;
      width: 25%;
      float: left;
    }
    div.vermelho{
      background-color: red;
      height: 300px;
      width: 50%;
      float: left;
    }
    div.verde{
      background-color: green;
      height: 300px;
      width: 25%;
      float: left;
    }
    div.azul{
      background-color: blue;
      padding: 40px;
    }
    p{
       margin: 0;
       text-align: center;
       vertical-align: middle;
    }

<!DOCTYPE html>

    <title>Page Title</title>

roxo

amarelo

vermelho

verde

azul

Body:
You can do it using flexbox.

div.roxo{
      background-color: purple;
      padding: 40px;
    }
    div.amarelo{
      display:flex;
       justify-content:center;
      align-items:center;
      background-color: yellow;
      height: 300px;
      width: 25%;
      float: left;
    }
    div.vermelho{
      display:flex;
       justify-content:center;
      align-items:center;
      background-color: red;
      height: 300px;
      width: 50%;
      float: left;
    }
    div.verde{
      display:flex;
       justify-content:center;
      align-items:center;
      background-color: green;
      height: 300px;
      width: 25%;
      float: left;
    }
    div.azul{
      display:flex;
       justify-content:center;
      align-items:center;
      background-color: blue;
      padding: 40px;
    }
    p{
       margin: 0;
       text-align: center;
       vertical-align: middle;
    }

<!DOCTYPE html>
  <html>
    <head>
    <title>Page Title</title>

    </head>
    <body>
      <div class="roxo">
       <p>roxo</p>
      </div>
      <div class="amarelo">
       <p>amarelo</p>
      </div>
      <div class="vermelho">
       <p>vermelho</p>
      </div>
      <div class="verde">
       <p>verde</p>
      </div>
      <div class="azul">
       <p>azul</p>
      </div>
    </body>
  </html>

Just add:

display:flex;
justify-content:center;
align-items:center;

to your div CSS.

You can learn more about flexbox here at https://css-tricks.com/snippets/css/a-guide-to-flexbox/


问:
Git Autocompletion: syntax error near unexpected token `newline'
I have looked at different questions regarding this issue and none seem identical to mine: new git installation on Mac 10.10.2

I have used the below to install auto-completion:

```<code>curl -OL https://github.com/git/git/blob/master/contrib/completion/git-completion.bash
</code>```

I have also tried the above with: -O.

I have added a . to the file that was downloaded:

```<code>mv ~/git-completion.bash ~/.git-completion.bash
</code>```

Then I edit my bash_profile and inserted the line to get an auto load when terminal loads:

```<code>if [ -f ~/.git-completion.bash ]; then
  source ~/.git-completion.bash
fi
</code>```

Up on restarting terminal:

```<code>Users/user/.git-completion.bash: line 4: syntax error near unexpected token `newline'
</code>```

Is there an issue with the file that was download or my OS?

答: The problem is caused by the newline characters in the downloaded file. So you can press the 'raw' button on the github page and copy the raw content of the script. Then replace the content of git-completion.bash with the raw content using your text editor, save it and good to go.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have looked at different questions regarding this issue and none seem identical to mine: new git installation on Mac 10.10.2

I have used the below to install auto-completion:

curl -OL https://github.com/git/git/blob/master/contrib/completion/git-completion.bash

I have also tried the above with: -O.

I have added a . to the file that was downloaded:

mv ~/git-completion.bash ~/.git-completion.bash

Then I edit my bash_profile and inserted the line to get an auto load when terminal loads:

if [ -f ~/.git-completion.bash ]; then
  source ~/.git-completion.bash
fi

Up on restarting terminal:

Users/user/.git-completion.bash: line 4: syntax error near unexpected token `newline'

Is there an issue with the file that was download or my OS?


问:
Conditional compilation in Python
How to do conditional compilation in Python ?

Is it using DEF ?

答:
Python compiles a module automatically when you import it, so the only way to avoid compiling it is to not import it. You can write something like:

```<code>if some_condition:
  import some_module
</code>```

But that would only work for complete modules. In C and C++ you typically use a preprocessor for conditional compilation. There is nothing stopping you from using a preprocessor on your Python code, so you could write something like:

```<code>#ifdef SOME_CONDITION
def some_function():
  pass
#endif
</code>```

Run that through a C preprocessor and you'd have real conditional compilation and some_function will only be defined if SOME_CONDITION is defined.

BUT (and this is important): Conditional compilation is probably not what you want. Remember that when you import a module, Python simply executes the code in it. The def and class statements in the module are actually executed when you import the module. So the typical way of implementing what other languages would use conditional compilation for is just a normal if statement, like:

```<code>if some_condition:
  def some_function():
    pass
</code>```

This will only define some_function if some_condition is true.

It's stuff like this that makes dynamic languages so powerful while remaining conceptually simple.

ContentLicense: CC BY-SA 2.5

Title: Conditional compilation in Python

LastEditorDisplayName: David Segonds

Body:
Python compiles a module automatically when you import it, so the only way to avoid compiling it is to not import it. You can write something like:

if some_condition:
  import some_module

But that would only work for complete modules. In C and C++ you typically use a preprocessor for conditional compilation. There is nothing stopping you from using a preprocessor on your Python code, so you could write something like:

#ifdef SOME_CONDITION
def some_function():
  pass
#endif

Run that through a C preprocessor and you'd have real conditional compilation and some_function will only be defined if SOME_CONDITION is defined.

BUT (and this is important): Conditional compilation is probably not what you want. Remember that when you import a module, Python simply executes the code in it. The def and class statements in the module are actually executed when you import the module. So the typical way of implementing what other languages would use conditional compilation for is just a normal if statement, like:

if some_condition:
  def some_function():
    pass

This will only define some_function if some_condition is true.

It's stuff like this that makes dynamic languages so powerful while remaining conceptually simple.

OwnerDisplayName: Martin Vilcans


问:
std::is_same - Use-case of inherited functions from integral_constant
Looking at the implementation of std::is_same we can see a few internal functions (inherited from integral_constant). Let me copy the g++ code for convenience:

  template<typename _Tp, _Tp __v>
  struct integral_constant {
      static constexpr _Tp                value = __v;
      typedef _Tp                         value_type;
      typedef integral_constant<_Tp, __v> type;
      constexpr operator value_type()   const noexcept { return value; }
      constexpr value_type operator()() const noexcept { return value; }
  };

  template<typename, typename>
  struct is_same : public integral_constant<bool, false> { };

  template<typename _Tp>
  struct is_same<_Tp, _Tp> : public integral_constant<bool, true> { };
```

<p>This gives us a couple options on how to use it:</p>

<pre class="lang-cpp prettyprint-override"><code>  bool a1 = is_same<int, int>{};               // instantiate & then cast implicitly
  bool a2 = is_same<int, int>();               // instantiate & then cast implicitly
  bool a3 = is_same<int, int>::value;          // use static member
  bool a4 = is_same<int, int>{}();             // instantiate & then use operator()
  bool a5 = is_same<int, int>{}.operator()();  // instantiate & then use operator()
</code>```

I am wondering what use-cases there are for these extra functions, and why would e.g. a short implementation like

  template<class, class> constexpr bool is_same = false;
  template<class T> constexpr bool is_same<T,T> = true;
```

not suffice? Then we could just write bool a = is_same<int,int> without {} or () or ::value.

Any thoughts appreciated.

答:
The answer to this is largely historic. The type traits predated variable templates by a decade, so the option you're proposing is an anachronism. The rest were added piecemeal for usability reasons.

std::integral_constant was introduced way back in 2003, via N1424. So it's very old tech, C++03 tech. At the time, it looked like this:

```<code>template <class T, T v>
struct integral_constant
{
   static  const T                value = v;
   typedef T                      value_type;
   typedef integral_constant<T,v> type;
};
</code>```

None of the additional member functions you see, and note that value was also just static const, not static constexpr. There was no constexpr yet, after all.

Many years later, during development of C++0x, there was a library issue opened (LWG1019) which, given the novel addition of constexpr, extended this out to:

```<code>template <class T, T v>
struct integral_constant {
  static constexpr T value = v;
  typedef T value_type;
  typedef integral_constant<T,v> type;
  constexpr operator value_type() { return value; }
};
</code>```

This issue was resolved by N2976.

The motivation for the conversion function is that it lets you use objects of type integral_constant as those values. For certain styles of metaprogramming, if you have a function that returns, say, true_type directly, you can use it directy:

```<code>std::true_type foo();
if (foo()) { ... }
</code>```

Rather than having to write if (foo().value) or something else weird like that. However, for non-boolean constants, the only way to get the value out given an object is either to access the value member or to do an explicit cast (the latter of which requires you to know the type):

```<code>constant.value
static_cast<???>(constant)
</code>```

which led to N3545, in 2013, adding in the call operator allowing you to write constant() to pull the value back out. Is this last addition really useful? I dunno.

Notably, all of this predates variable templates - the first revision of which was N3615. The option you suggest of having is_same just being a variable bool template wasn't an option until later. And even with variable templates, it's quite convenient to have different types, so I'm not sure that we would go that route even if it were possible. Hard to say in retrospect.

Body:
Looking at the implementation of std::is_same we can see a few internal functions (inherited from integral_constant). Let me copy the g++ code for convenience:

  template<typename _Tp, _Tp __v>
  struct integral_constant {
      static constexpr _Tp                value = __v;
      typedef _Tp                         value_type;
      typedef integral_constant<_Tp, __v> type;
      constexpr operator value_type()   const noexcept { return value; }
      constexpr value_type operator()() const noexcept { return value; }
  };

  template<typename, typename>
  struct is_same : public integral_constant<bool, false> { };

  template<typename _Tp>
  struct is_same<_Tp, _Tp> : public integral_constant<bool, true> { };

This gives us a couple options on how to use it:

  bool a1 = is_same<int, int>{};               // instantiate & then cast implicitly
  bool a2 = is_same<int, int>();               // instantiate & then cast implicitly
  bool a3 = is_same<int, int>::value;          // use static member
  bool a4 = is_same<int, int>{}();             // instantiate & then use operator()
  bool a5 = is_same<int, int>{}.operator()();  // instantiate & then use operator()

I am wondering what use-cases there are for these extra functions, and why would e.g. a short implementation like

  template<class, class> constexpr bool is_same = false;
  template<class T> constexpr bool is_same<T,T> = true;

not suffice? Then we could just write bool a = is_same<int,int> without {} or () or ::value.

Any thoughts appreciated.

Body:
The answer to this is largely historic. The type traits predated variable templates by a decade, so the option you're proposing is an anachronism. The rest were added piecemeal for usability reasons.

std::integral_constant was introduced way back in 2003, via N1424. So it's very old tech, C++03 tech. At the time, it looked like this:

template <class T, T v>
struct integral_constant
{
   static  const T                value = v;
   typedef T                      value_type;
   typedef integral_constant<T,v> type;
};

None of the additional member functions you see, and note that value was also just static const, not static constexpr. There was no constexpr yet, after all.

Many years later, during development of C++0x, there was a library issue opened (LWG1019) which, given the novel addition of constexpr, extended this out to:

template <class T, T v>
struct integral_constant {
  static constexpr T value = v;
  typedef T value_type;
  typedef integral_constant<T,v> type;
  constexpr operator value_type() { return value; }
};

This issue was resolved by N2976.

The motivation for the conversion function is that it lets you use objects of type integral_constant as those values. For certain styles of metaprogramming, if you have a function that returns, say, true_type directly, you can use it directy:

std::true_type foo();
if (foo()) { ... }

Rather than having to write if (foo().value) or something else weird like that. However, for non-boolean constants, the only way to get the value out given an object is either to access the value member or to do an explicit cast (the latter of which requires you to know the type):

constant.value
static_cast<???>(constant)

which led to N3545, in 2013, adding in the call operator allowing you to write constant() to pull the value back out. Is this last addition really useful? I dunno.

Notably, all of this predates variable templates - the first revision of which was N3615. The option you suggest of having is_same just being a variable bool template wasn't an option until later. And even with variable templates, it's quite convenient to have different types, so I'm not sure that we would go that route even if it were possible. Hard to say in retrospect.


问:
how to make for-loop order to rbind all excel files in the same directory
i want to rbind all excel files (regardless the total amount of files) in a directory and make a new column that is filled with the name of files, so then i could identify where the data came from. For example, i have template of file like this

```<code>promo  stock
  a     200
  b     200
  c     200
</code>```

to be like this

```<code>store  promo  stock
file1    a     200
file1    b     200
file1    c     200
file2    a     200
file2    b     200
file2    c     200
file3    a     200
file3    b     200
file3    c     200
</code>```

how to make a for-loop order for this case? thanx in advance

答:
We could find the full path name to the files and then use lapply to read each file with readxl::read_excel and add a new column store with the name of the file

```<code>file_paths <- list.files("/path/to/files", pattern = ".xlsx$", full.names = TRUE)

do.call(rbind, lapply(file_paths, function(x)
    transform(readxl::read_excel(x), store = sub(".xlsx$", "", basename(x)))))

#  promo stock store
#1     a   200 file1
#2     b   200 file1
#3     c   200 file1
#4     a   200 file2
#5     b   200 file2
#6     c   200 file2
</code>```

We can also use purrr::map_df

```<code>purrr::map_df(file_paths, ~transform(readxl::read_excel(.),
                            store = sub(".xlsx$", "", basename(.))))
</code>```

Body:
i want to rbind all excel files (regardless the total amount of files) in a directory and make a new column that is filled with the name of files, so then i could identify where the data came from. For example, i have template of file like this

promo  stock
  a     200
  b     200
  c     200

to be like this

store  promo  stock
file1    a     200
file1    b     200
file1    c     200
file2    a     200
file2    b     200
file2    c     200
file3    a     200
file3    b     200
file3    c     200

how to make a for-loop order for this case? thanx in advance

Body:
We could find the full path name to the files and then use lapply to read each file with readxl::read_excel and add a new column store with the name of the file

file_paths <- list.files("/path/to/files", pattern = ".xlsx$", full.names = TRUE)

do.call(rbind, lapply(file_paths, function(x)
    transform(readxl::read_excel(x), store = sub(".xlsx$", "", basename(x)))))

#  promo stock store
#1     a   200 file1
#2     b   200 file1
#3     c   200 file1
#4     a   200 file2
#5     b   200 file2
#6     c   200 file2

We can also use purrr::map_df

purrr::map_df(file_paths, ~transform(readxl::read_excel(.),
                            store = sub(".xlsx$", "", basename(.))))


问:
Looking for R Studi function/code to cross-reference variables
I would appreciate if anyone could advise me on how to establish a relationship between 2 variables. It might be super easy, but I'm new to R. I cannot attach photos of what my dataset (X2015_11_metropolitan_stop_and_search) looks like, but here's a dput on the two variables that I'm interested in:

```<code>dput(X2015_11_metropolitan_stop_and_search$Object of search)
c("Offensive weapons", "Controlled drugs", "Controlled drugs", "Fireworks", "Controlled drugs", "Stolen goods", "Controlled drugs", "Controlled drugs", "Offensive weapons", "Controlled drugs", "Fireworks", "Controlled drugs", "Controlled drugs", "Evidence of offences under the Act", "Controlled drugs", "Controlled drugs", "Controlled drugs", "Controlled drugs", "Controlled drugs", "Controlled drugs", "Controlled drugs", "Controlled drugs", "Controlled drugs", "Controlled drugs", "Controlled drugs", "Controlled drugs", "Offensive weapons", "Stolen goods", "Controlled drugs", "Controlled drugs", "Offensive weapons", "Offensive weapons", "Controlled drugs", "Controlled drugs", "Controlled drugs", "Controlled drugs", "Controlled drugs" )
</code>```

```<code>dput(X2015_11_metropolitan_stop_and_search$Outcome)
c("Suspect arrested", "Nothing found - no further action", "Suspect arrested",
"Nothing found - no further action", "Nothing found - no further action",
"Nothing found - no further action", "Offender given drugs possession warning",
"Nothing found - no further action", "Offender given drugs possession warning",
"Nothing found - no further action", "Nothing found - no further action",
"Suspect arrested", "Suspect arrested", "Offender given drugs possession warning",
"Suspect arrested", "Suspect arrested", "Nothing found - no further action",
"Nothing found - no further action", "Suspect arrested", "Nothing found - no further action",
"Nothing found - no further action", "Suspect arrested", "Suspect arrested",
"Nothing found - no further action", "Nothing found - no further action",
"Nothing found - no further action", "Nothing found - no further action",
"Suspect arrested", "Nothing found - no further action", "Nothing found - no further action",
"Nothing found - no further action", "Nothing found - no further action",
"Nothing found - no further action", "Nothing found - no further action",
"Nothing found - no further action", "Nothing found - no further action",
"Suspect arrested", "Nothing found - no further action", "Nothing found - no further action",
"Suspect arrested", "Nothing found - no further action", "Nothing found - no further action",
"Nothing found - no further action", "Suspect arrested", "Suspect arrested",
"Nothing found - no further action", "Nothing found - no further action",
"Nothing found - no further action", "Offender given drugs possession warning",
"Suspect arrested", "Offender given penalty notice", "Nothing found - no further action")
</code>```

There is a small number of possible values for the variables 'Object of search' and 'Outcome'. I'd like to be able to see the 'Object of search' value for those individual incidents where the 'Outcome' value was 'Suspect arrested'. Is that possible?

In case I need to include more information, please let me know.

答:
You could try something like:

```<code>X2015_11_metropolitan_stop_and_search$Object of search[X2015_11_metropolitan_stop_and_search$Outcome == "Suspect arrested"]
</code>```

Which would return all the values of 'Object of search' that have the outcome "suspect arrested". A generic version of this would be:

```<code>data$column1[data$column2 == "dataValue"]
</code>```

Also check out the which() function to return the index number of data that fit the parameters you specify in the function.

Body:
I would appreciate if anyone could advise me on how to establish a relationship between 2 variables. It might be super easy, but I'm new to R. I cannot attach photos of what my dataset (X2015_11_metropolitan_stop_and_search) looks like, but here's a dput on the two variables that I'm interested in:

dput(X2015_11_metropolitan_stop_and_search$Object of search)
c("Offensive weapons", "Controlled drugs", "Controlled drugs", "Fireworks", "Controlled drugs", "Stolen goods", "Controlled drugs", "Controlled drugs", "Offensive weapons", "Controlled drugs", "Fireworks", "Controlled drugs", "Controlled drugs", "Evidence of offences under the Act", "Controlled drugs", "Controlled drugs", "Controlled drugs", "Controlled drugs", "Controlled drugs", "Controlled drugs", "Controlled drugs", "Controlled drugs", "Controlled drugs", "Controlled drugs", "Controlled drugs", "Controlled drugs", "Offensive weapons", "Stolen goods", "Controlled drugs", "Controlled drugs", "Offensive weapons", "Offensive weapons", "Controlled drugs", "Controlled drugs", "Controlled drugs", "Controlled drugs", "Controlled drugs" )

dput(X2015_11_metropolitan_stop_and_search$Outcome)
c("Suspect arrested", "Nothing found - no further action", "Suspect arrested",
"Nothing found - no further action", "Nothing found - no further action",
"Nothing found - no further action", "Offender given drugs possession warning",
"Nothing found - no further action", "Offender given drugs possession warning",
"Nothing found - no further action", "Nothing found - no further action",
"Suspect arrested", "Suspect arrested", "Offender given drugs possession warning",
"Suspect arrested", "Suspect arrested", "Nothing found - no further action",
"Nothing found - no further action", "Suspect arrested", "Nothing found - no further action",
"Nothing found - no further action", "Suspect arrested", "Suspect arrested",
"Nothing found - no further action", "Nothing found - no further action",
"Nothing found - no further action", "Nothing found - no further action",
"Suspect arrested", "Nothing found - no further action", "Nothing found - no further action",
"Nothing found - no further action", "Nothing found - no further action",
"Nothing found - no further action", "Nothing found - no further action",
"Nothing found - no further action", "Nothing found - no further action",
"Suspect arrested", "Nothing found - no further action", "Nothing found - no further action",
"Suspect arrested", "Nothing found - no further action", "Nothing found - no further action",
"Nothing found - no further action", "Suspect arrested", "Suspect arrested",
"Nothing found - no further action", "Nothing found - no further action",
"Nothing found - no further action", "Offender given drugs possession warning",
"Suspect arrested", "Offender given penalty notice", "Nothing found - no further action")

There is a small number of possible values for the variables 'Object of search' and 'Outcome'. I'd like to be able to see the 'Object of search' value for those individual incidents where the 'Outcome' value was 'Suspect arrested'. Is that possible?

In case I need to include more information, please let me know.

Body:
You could try something like:

X2015_11_metropolitan_stop_and_search$Object of search[X2015_11_metropolitan_stop_and_search$Outcome == "Suspect arrested"]

Which would return all the values of 'Object of search' that have the outcome "suspect arrested". A generic version of this would be:

data$column1[data$column2 == "dataValue"]

Also check out the which() function to return the index number of data that fit the parameters you specify in the function.


问:
How to get the number of Firestore documents in flutter?
I am building a flutter app and using Cloud Firestore. I want to get the number of documents in the database.

I tried

```<code>Firestore.instance.collection('products').toString().length
</code>```

but it didn't work.

答: Above suggestions will cause the client to download all of the documents in the collection to get the count. As a workaround, if your write operations are not frequently happening, you can put the length of the documents to firebase remote config and change it whenever you add/delete documents from the Firestore collection. Then you can fetch the length from firebase remote configs when you need it.</p>

Body:
I am building a flutter app and using Cloud Firestore. I want to get the number of documents in the database.

I tried

Firestore.instance.collection('products').toString().length

but it didn't work.


问:
select_related returns value None when querying
I'm trying to get the name field of my Model Category but it returns None. I can confirm that there is a value by running print(post.categories.values()) .
which returns

QuerySet [{'id': 3, 'name': 'Tasks'}]>

Model:

```<code>from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=30)

class Post(models.Model):
    title = models.SlugField(max_length = 250, null = True, blank = True)
    body = models.TextField()
    created_on = models.DateTimeField(null=True)
    last_modified = models.DateTimeField(null=True)
    categories = models.ManyToManyField('Category', related_name='posts')

class Comment(models.Model):
    author = models.CharField(max_length=60)
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    post = models.ForeignKey('Post', on_delete=models.CASCADE)
</code>```

View:

```<code>def blog_index(request):
    posts = Post.objects.all().order_by('-created_on')
    context = {
        "posts": posts,
    }
    return render(request, "blog_index.html", context)

def blog_category(request, category):
    posts = Post.objects.filter(
        categories__name__contains=category
    ).order_by(
        '-created_on'
    )
    if not posts:
        return HttpResponse(status=404)

    context = {
        "category": category,
        "posts": posts
    }
    return render(request, "blog_category.html", context)

def blog_detail(request, pk):
    post = Post.objects.select_related().get(pk=pk)
    print(post.categories.name) # Returns None!!
    form = CommentForm()
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = Comment(
                author=form.cleaned_data["author"],
                body=form.cleaned_data["body"],
                post=post
            )
            comment.save()

    comments = Comment.objects.filter(post=post)
    context = {
        "post": post,
        "comments": comments,
        "form": form,
    }
    return render(request, "blog_detail.html", context)
</code>```

答:
select_related is only a performance booster, that follows foreign-key relationships. In you case you have no models.Foreignkey in Post object so this is not doing any optimizations at all.

You are having models.ManyToManyField between post and category, that means that you can have more than one category for post. To get names of categories you should iterate through post.categories list

```<code>print([category.name for category in post.categories.all()])
</code>```

Also if you are wondering there is an optimization for this type of relationship with prefetch_related

Body:
I'm trying to get the name field of my Model Category but it returns None. I can confirm that there is a value by running print(post.categories.values()) .
which returns

QuerySet [{'id': 3, 'name': 'Tasks'}]>

Model:

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=30)

class Post(models.Model):
    title = models.SlugField(max_length = 250, null = True, blank = True)
    body = models.TextField()
    created_on = models.DateTimeField(null=True)
    last_modified = models.DateTimeField(null=True)
    categories = models.ManyToManyField('Category', related_name='posts')

class Comment(models.Model):
    author = models.CharField(max_length=60)
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    post = models.ForeignKey('Post', on_delete=models.CASCADE)

View:

def blog_index(request):
    posts = Post.objects.all().order_by('-created_on')
    context = {
        "posts": posts,
    }
    return render(request, "blog_index.html", context)

def blog_category(request, category):
    posts = Post.objects.filter(
        categories__name__contains=category
    ).order_by(
        '-created_on'
    )
    if not posts:
        return HttpResponse(status=404)

    context = {
        "category": category,
        "posts": posts
    }
    return render(request, "blog_category.html", context)

def blog_detail(request, pk):
    post = Post.objects.select_related().get(pk=pk)
    print(post.categories.name) # Returns None!!
    form = CommentForm()
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = Comment(
                author=form.cleaned_data["author"],
                body=form.cleaned_data["body"],
                post=post
            )
            comment.save()

    comments = Comment.objects.filter(post=post)
    context = {
        "post": post,
        "comments": comments,
        "form": form,
    }
    return render(request, "blog_detail.html", context)

Body:
select_related is only a performance booster, that follows foreign-key relationships. In you case you have no models.Foreignkey in Post object so this is not doing any optimizations at all.

You are having models.ManyToManyField between post and category, that means that you can have more than one category for post. To get names of categories you should iterate through post.categories list

print([category.name for category in post.categories.all()])

Also if you are wondering there is an optimization for this type of relationship with prefetch_related


问:
Rails image upload won't display
```<code>add_column :issues, :data, :binary, :limit => 1.megabyte
</code>```

```<code>get '/issues/:id/show_image' => 'issues#show_image', as: 'show_image_issue'
</code>```

```<code>def show_image
    @issue = Issue.find(params[:id])
    send_data @issue.data, :type => 'image/png', :disposition => 'inline'
end
</code>```

```<code><%= f.file_field :data, as: :file %>
</code>```

```<code><%= image_tag show_image_issue_path(@issue) %>
</code>```

The page loads and no errors, but there's no image.

答:
I recommend for you to use PaperClip or CarrierWave for storing images, storing binary data has many disadvantages.

PaperClip: https://github.com/thoughtbot/paperclip

CarrierWave: https://github.com/carrierwaveuploader/carrierwave

why? read here : Storing Images in DB - Yea or Nay?

if you insist to do this then you can try:-

<img src="<%= @issue.data %>" />

Title: Rails image upload won't display

Body:
add_column :issues, :data, :binary, :limit => 1.megabyte

get '/issues/:id/show_image' => 'issues#show_image', as: 'show_image_issue'

def show_image
    @issue = Issue.find(params[:id])
    send_data @issue.data, :type => 'image/png', :disposition => 'inline'
end

<%= f.file_field :data, as: :file %>

<%= image_tag show_image_issue_path(@issue) %>

The page loads and no errors, but there's no image.


问:
CSS::before pushes text to the right, how to avoid/override?
I want to use the css property ::before to add a tag before a paragraph.
I manage to render the tag correctly, but it pushes the text in the paragraph to the right. I want to avoid this as the tag will be placed in the top-left corner of the paragraph and the text should come under the tag.

I looked at w3schools to try to find out how it is done.

I also tried looking at the website I saw the design, but couldn't figure out how it worked. Heres the website link: Fetch API

The thing I'm tried to do is done under section 2.1 URL on that website.

.note {
    background-color: #C7FDBC;
    padding: 0.6em;
    margin-left:1em;
    margin-top: 2em;
    margin-bottom: 1.5em;
}

.note::before {
    content: "Note";
    background-color: green;
    color: white;
    font-weight: bold;
    padding: 0.4em;
    position: relative;
    top: -1.6em;
    left: -1.3em;
}
```

<pre class="lang-html prettyprint-override"><code><p class="note">The note</p>
</code>```

Expected result is something looking like the notes in the fetch api.
My result looked similar, just that the paragraph text is pushed to the right by the same amount as the width of the ::before content.

答:
If you don't want your ::before pseudo-element to affect the flow of other elements, then give it position: absolute. In order to make this absolute positioning relative to the
, you must give the
 a position other than static: I'll use relative here.

This works because the ::before pseudo-element is treated as a child of your
:

body
{
  padding: 1em;
}

.note {
    background-color: #C7FDBC;
    padding: 0.6em;
    margin-top: 2em;
    margin-bottom: 1.5em;
    position: relative;
}

.note::before {
    content: "Note";
    background-color: green;
    color: white;
    font-weight: bold;
    padding: 0.2em;
    position: absolute;
    top: -1.4em;
    left: -1.1em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>This is text before the note. See how the left edge of this text is aligned with the left edge of the note?</p>
<p class="note">This is the note.</p>
<p>This is text after the note. See how the left edge of this text is aligned with the left edge of the note?</p></code>```

Note: (see what I did there?)

Since this approach prevents the overlay from affecting the layout of the elements, the overlay will get clipped by the edge of the page unless it is padded (which is why I added some padding to the ).

Body:
I want to use the css property ::before to add a tag before a paragraph.
I manage to render the tag correctly, but it pushes the text in the paragraph to the right. I want to avoid this as the tag will be placed in the top-left corner of the paragraph and the text should come under the tag.

I looked at w3schools to try to find out how it is done.

I also tried looking at the website I saw the design, but couldn't figure out how it worked. Heres the website link: Fetch API

The thing I'm tried to do is done under section 2.1 URL on that website.

.note {
    background-color: #C7FDBC;
    padding: 0.6em;
    margin-left:1em;
    margin-top: 2em;
    margin-bottom: 1.5em;
}

.note::before {
    content: "Note";
    background-color: green;
    color: white;
    font-weight: bold;
    padding: 0.4em;
    position: relative;
    top: -1.6em;
    left: -1.3em;
}

The note

Expected result is something looking like the notes in the fetch api.
My result looked similar, just that the paragraph text is pushed to the right by the same amount as the width of the ::before content.

Body:
If you don't want your ::before pseudo-element to affect the flow of other elements, then give it position: absolute. In order to make this absolute positioning relative to the <p>, you must give the <p> a position other than static: I'll use relative here.

This works because the ::before pseudo-element is treated as a child of your <p>:

body
{
  padding: 1em;
}

.note {
    background-color: #C7FDBC;
    padding: 0.6em;
    margin-top: 2em;
    margin-bottom: 1.5em;
    position: relative;
}

.note::before {
    content: "Note";
    background-color: green;
    color: white;
    font-weight: bold;
    padding: 0.2em;
    position: absolute;
    top: -1.4em;
    left: -1.1em;
}

<p>This is text before the note. See how the left edge of this text is aligned with the left edge of the note?</p>
<p class="note">This is the note.</p>
<p>This is text after the note. See how the left edge of this text is aligned with the left edge of the note?</p>

Note: (see what I did there?)

Since this approach prevents the overlay from affecting the layout of the elements, the overlay will get clipped by the edge of the page unless it is padded (which is why I added some padding to the <body>).


问:
Copying a range from one sheet to a specific range in another sheet
The data from the form response sheet "EFS" needs to be copied into the "QE" sheet. The range for the destination sheet does not start in Column A Row1, instead, it should start in Column C of row 3. As this is an active form when a new entry is made that entry needs to be copied to the last row on the destination sheet "QE"  This is what I have so far. I am getting an error,

The number of rows in the data does not match the number of rows in the range. The data has 26751 but the range has 20. (line 15, file "QETaskList")

I've tried to change the range but I get other errors.

```<code>function CopyGradesToQETaskList() {

var sss = SpreadsheetApp.openById("1PK-nMvqIoXaL1nrYPRIWr72I5IQ3wd9sjeztMtR9J1M");
var ss = sss.getSheetByName('EFS');

var lastRowSource = ss.getLastRow();
var source = sss.getRange("A2:p2" + lastRowSource);
values = source.getValues();

var TargetSource = SpreadsheetApp.getActiveSpreadsheet();
var TargetSheet = TargetSource.getSheetByName('QE');
var last_row = TargetSheet.getLastRow();
TargetSheet.insertRowAfter(last_row)
var tsRange = TargetSheet.getRange("C2:R2"+last_row);
tsRange.setValues(values);

}
</code>```

答:
Part of the problem is that lastRowSource and last_row hasn't the same value.

Another problem is that the expressions  "A2:p2" + lastRowSource and "C2:R2"+last_row are wrong

Let say that both sheets have the same number of rows. The problem is that if the last row on both sheets where 10, the result of the above expressions are A2:p210 and C2:R210 respectively while it's very likely that you expect A2:p10 and C2:R10.

Body:
The data from the form response sheet "EFS" needs to be copied into the "QE" sheet. The range for the destination sheet does not start in Column A Row1, instead, it should start in Column C of row 3. As this is an active form when a new entry is made that entry needs to be copied to the last row on the destination sheet "QE"  This is what I have so far. I am getting an error,

The number of rows in the data does not match the number of rows in the range. The data has 26751 but the range has 20. (line 15, file "QETaskList")

I've tried to change the range but I get other errors.

function CopyGradesToQETaskList() {

var sss = SpreadsheetApp.openById("1PK-nMvqIoXaL1nrYPRIWr72I5IQ3wd9sjeztMtR9J1M");
var ss = sss.getSheetByName('EFS');

var lastRowSource = ss.getLastRow();
var source = sss.getRange("A2:p2" + lastRowSource);
values = source.getValues();

var TargetSource = SpreadsheetApp.getActiveSpreadsheet();
var TargetSheet = TargetSource.getSheetByName('QE');
var last_row = TargetSheet.getLastRow();
TargetSheet.insertRowAfter(last_row)
var tsRange = TargetSheet.getRange("C2:R2"+last_row);
tsRange.setValues(values);

}


问:
How to change the OS on an existing Service Fabric cluster?
I'm trying to change my VMSS from:

```<code>    "imageReference": {
      "publisher": "MicrosoftWindowsServer",
      "offer": "WindowsServer",
      "sku": "2016-Datacenter-with-Containers",
      "version": "latest"
    }
</code>```

To:

```<code>    "imageReference": {
      "publisher": "MicrosoftWindowsServer",
      "offer": "WindowsServerSemiAnnual",
      "sku": "Datacenter-Core-1803-with-Containers-smalldisk",
      "version": "latest"
    }
</code>```

The first thing I tried was:

Update-AzureRmVmss -ResourceGroupName "DevServiceFabric" -VMScaleSetName "HTTP" -ImageReferenceSku Datacenter-Core-1803-with-Containers-smalldisk -ImageReferenceOffer WindowsServerSemiAnnual

Which gives me the error:

Update-AzureRmVmss : Changing property 'imageReference.offer' is not allowed.
  ErrorCode: PropertyChangeNotAllowed

This is confirmed in the docs; you can only set the offer when the scaleset is created.

Next I tried Add-AzureRmServiceFabricNodeType to add a new node type, thinking I could just delete the old one after.  However, this command doesn't seem to allow you to set the OS image.  You can only set the VM SKU (In other words, all VMs on your cluster have to have the same OS).

Is there a way to change this without deleting the entire cluster and starting from scratch?

答:
Here's another (simpler) answer for those who want to switch to another OS, but can switch to an OS image in the same publisher/Offer.  You can get the list of available OS SKUs with the following command:

```<code>Get-AzureRmVMImageSku -Location 'westus2' -PublisherName MicrosoftWindowsServer -Offer WindowsServer
</code>```

Then, you can upgrade your cluster to use that image with:

```<code>Update-AzureRmVmss -ResourceGroupName "DevServiceFabric" -VMScaleSetName "HTTP" -ImageReferenceSku 2019-Datacenter-Core-with-Containers-smalldisk
</code>```

The command will take an hour or more to run.

I've also run into a few SKUs that error out with an "Image Not Found" error, even though they appear on the list.  Not sure what the cause of that is.  However, in this case I was able to find out that works for me.

Body:
I'm trying to change my VMSS from:

    "imageReference": {
      "publisher": "MicrosoftWindowsServer",
      "offer": "WindowsServer",
      "sku": "2016-Datacenter-with-Containers",
      "version": "latest"
    }

To:

    "imageReference": {
      "publisher": "MicrosoftWindowsServer",
      "offer": "WindowsServerSemiAnnual",
      "sku": "Datacenter-Core-1803-with-Containers-smalldisk",
      "version": "latest"
    }

The first thing I tried was:

Update-AzureRmVmss -ResourceGroupName "DevServiceFabric" -VMScaleSetName "HTTP" -ImageReferenceSku Datacenter-Core-1803-with-Containers-smalldisk -ImageReferenceOffer WindowsServerSemiAnnual

Which gives me the error:

Update-AzureRmVmss : Changing property 'imageReference.offer' is not allowed.
  ErrorCode: PropertyChangeNotAllowed

This is confirmed in the docs; you can only set the offer when the scaleset is created.

Next I tried Add-AzureRmServiceFabricNodeType to add a new node type, thinking I could just delete the old one after.  However, this command doesn't seem to allow you to set the OS image.  You can only set the VM SKU (In other words, all VMs on your cluster have to have the same OS).

Is there a way to change this without deleting the entire cluster and starting from scratch?

Body:
Here's another (simpler) answer for those who want to switch to another OS, but can switch to an OS image in the same publisher/Offer.  You can get the list of available OS SKUs with the following command:

Get-AzureRmVMImageSku -Location 'westus2' -PublisherName MicrosoftWindowsServer -Offer WindowsServer

Then, you can upgrade your cluster to use that image with:

Update-AzureRmVmss -ResourceGroupName "DevServiceFabric" -VMScaleSetName "HTTP" -ImageReferenceSku 2019-Datacenter-Core-with-Containers-smalldisk

The command will take an hour or more to run.

I've also run into a few SKUs that error out with an "Image Not Found" error, even though they appear on the list.  Not sure what the cause of that is.  However, in this case I was able to find out that works for me.


问:
Rails ActiveRecord group by time but pad dates with nil values?
So I'm using activerecord to get the count of items for a certain day:

```<code>Item.group("date(created_at)").count.values
</code>```

But this doesn't give me 0 if there are no records for a given day, how can I fix this? Or is there are more "Rails" way do to something like this?

Any help is hugely appreciated, thanks again!

答:
Using a GROUP BY query, you are going to get groups based on the records that exist, so if there are no records with a given value in the grouping column, there will be no groups for that value.  The database does not psychically know to add in other date values that you might be interested in.

What I would do to get what you want is create a new Hash with a default value of 0 and then merge the result of your query into that.  When you subsequently try to retrieve any value from that Hash for which there is no entry, you'll get 0 as the result.

Edit: Remove .values

```<code>date_counts = Hash.new(0)
date_counts.merge! Item.group("date(created_at)").count
</code>```

Alternatively, if you want to make sure there are entries in the Hash for every date in a range, so you can iterate over those, ...

```<code>date_counts = {}
(Date.civil(2010,1,1)...Date.civil(2010,2,1)).each do |date|
  date_counts[date]=0
end
date_counts.merge! Item.group("date(created_at)").count
</code>```

Update

Here is some output when I pass my date range and model into here, oddly enough it gets different length hashes:

```<code>{Sun, 01 May 2011=>0, Mon, 02 May 2011=>0, Tue, 03 May 2011=>0, Wed, 04 May 2011=>0, Thu, 05 May 2011=>0, Fri, 06 May 2011=>0, Sat, 07 May 2011=>0, Sun, 08 May 2011=>0, Mon, 09 May 2011=>0, Tue, 10 May 2011=>0, Wed, 11 May 2011=>0, Thu, 31 Mar 2011=>2, Sun, 03 Apr 2011=>1, Fri, 08 Apr 2011=>643, Sat, 09 Apr 2011=>2360, Sun, 10 Apr 2011=>705, Mon, 11 Apr 2011=>34}
{Sun, 01 May 2011=>0, Mon, 02 May 2011=>0, Tue, 03 May 2011=>0, Wed, 04 May 2011=>0, Thu, 05 May 2011=>0, Fri, 06 May 2011=>0, Sat, 07 May 2011=>0, Sun, 08 May 2011=>0, Mon, 09 May 2011=>0, Tue, 10 May 2011=>0, Wed, 11 May 2011=>0, Sat, 02 Apr 2011=>1, Fri, 08 Apr 2011=>4158, Sat, 09 Apr 2011=>12206, Sun, 10 Apr 2011=>4279, Mon, 11 Apr 2011=>169}
{Sun, 01 May 2011=>0, Mon, 02 May 2011=>0, Tue, 03 May 2011=>0, Wed, 04 May 2011=>0, Thu, 05 May 2011=>0, Fri, 06 May 2011=>0, Sat, 07 May 2011=>0, Sun, 08 May 2011=>0, Mon, 09 May 2011=>0, Tue, 10 May 2011=>0, Wed, 11 May 2011=>0}
</code>```

Not sure whats causing it... hmm.

Body:
So I'm using activerecord to get the count of items for a certain day:

Item.group("date(created_at)").count.values

But this doesn't give me 0 if there are no records for a given day, how can I fix this? Or is there are more "Rails" way do to something like this?

Any help is hugely appreciated, thanks again!

Body:
Using a GROUP BY query, you are going to get groups based on the records that exist, so if there are no records with a given value in the grouping column, there will be no groups for that value.  The database does not psychically know to add in other date values that you might be interested in.

What I would do to get what you want is create a new Hash with a default value of 0 and then merge the result of your query into that.  When you subsequently try to retrieve any value from that Hash for which there is no entry, you'll get 0 as the result.

Edit: Remove .values

date_counts = Hash.new(0)
date_counts.merge! Item.group("date(created_at)").count

Alternatively, if you want to make sure there are entries in the Hash for every date in a range, so you can iterate over those, ...

date_counts = {}
(Date.civil(2010,1,1)...Date.civil(2010,2,1)).each do |date|
  date_counts[date]=0
end
date_counts.merge! Item.group("date(created_at)").count

Update

Here is some output when I pass my date range and model into here, oddly enough it gets different length hashes:

{Sun, 01 May 2011=>0, Mon, 02 May 2011=>0, Tue, 03 May 2011=>0, Wed, 04 May 2011=>0, Thu, 05 May 2011=>0, Fri, 06 May 2011=>0, Sat, 07 May 2011=>0, Sun, 08 May 2011=>0, Mon, 09 May 2011=>0, Tue, 10 May 2011=>0, Wed, 11 May 2011=>0, Thu, 31 Mar 2011=>2, Sun, 03 Apr 2011=>1, Fri, 08 Apr 2011=>643, Sat, 09 Apr 2011=>2360, Sun, 10 Apr 2011=>705, Mon, 11 Apr 2011=>34}
{Sun, 01 May 2011=>0, Mon, 02 May 2011=>0, Tue, 03 May 2011=>0, Wed, 04 May 2011=>0, Thu, 05 May 2011=>0, Fri, 06 May 2011=>0, Sat, 07 May 2011=>0, Sun, 08 May 2011=>0, Mon, 09 May 2011=>0, Tue, 10 May 2011=>0, Wed, 11 May 2011=>0, Sat, 02 Apr 2011=>1, Fri, 08 Apr 2011=>4158, Sat, 09 Apr 2011=>12206, Sun, 10 Apr 2011=>4279, Mon, 11 Apr 2011=>169}
{Sun, 01 May 2011=>0, Mon, 02 May 2011=>0, Tue, 03 May 2011=>0, Wed, 04 May 2011=>0, Thu, 05 May 2011=>0, Fri, 06 May 2011=>0, Sat, 07 May 2011=>0, Sun, 08 May 2011=>0, Mon, 09 May 2011=>0, Tue, 10 May 2011=>0, Wed, 11 May 2011=>0}

Not sure whats causing it... hmm.


答:
The ::before pseudo element is functionally a child element of whatever element it is applied to. In your case, this would be something like
<::before>Note</::before>The note

The solution is to establish .note as a positioning context with position: relative and then position the before pseudo-element where you want it with position: absolute.

Title: CSS::before pushes text to the right, how to avoid/override?

Body:
The ::before pseudo element is functionally a child element of whatever element it is applied to. In your case, this would be something like <p class="note"><::before>Note</::before>The note</p>

The solution is to establish .note as a positioning context with position: relative and then position the before pseudo-element where you want it with position: absolute.


问:
How to group timelines by hrs
Lets say I have array of JSON data with timeStarted and timeEnded values in Date format. I am struggling to group timeSpent by hours.
For example,

```<code>[{timeStarted: '00:10:30', timeEnded: '00:14:02'},
{timeStarted: '00:48:08', timeEnded: '02:33:33'}, ...]
</code>```

I am trying to group them so I get array like

```<code>[{hrs: '0', timeSpent: '16'},
{hrs: '1', timeSpent: '60'},
{hrs: '2', timeSpent: '34'}, ...]
</code>```

I have tried like billion times to group them but I cant figure out how: I always get values like 95 mins in hour. At least I need a right way to think. Thanks.

答:
If your times are always strings in the format hh:mm:ss, then a simple string split with some math could work:

```<code>const times = [
  { timeStarted: '00:10:30', timeEnded: '00:14:02' },
  { timeStarted: '00:48:08', timeEnded: '02:33:33' },
];
const withHours = times.map(time => {
  // Split on colon to get the components of the timestamp
  var start = time.timeStarted.split(':');
  var end = time.timeEnded.split(':');

  // Convert to seconds by multiplying each component by how many seconds it's worth
  var startSeconds = (+start[0]) * 60 * 60 + (+start[1]) * 60 + (+start[2]);
  var endSeconds = (+end[0]) * 60 * 60 + (+end[1]) * 60 + (+end[2]);

  // Find the difference in seconds and convert back to hours
  // We'll also floor this cause it looks like you want ints rounded down
  var hrs = Math.floor((endSeconds - startSeconds) / (60 * 60));

  return {
    timeStarted: time.timeStarted,
    timeEnded: time.timeEnded,
    hrs,
  };
});
</code>```

EDIT

Just noticed you have an additional field there called timeSpent.  Not sure what that is supposed to be.

Title: How to group timelines by hrs

Body:
Lets say I have array of JSON data with timeStarted and timeEnded values in Date format. I am struggling to group timeSpent by hours.
For example,

[{timeStarted: '00:10:30', timeEnded: '00:14:02'},
{timeStarted: '00:48:08', timeEnded: '02:33:33'}, ...]

I am trying to group them so I get array like

[{hrs: '0', timeSpent: '16'},
{hrs: '1', timeSpent: '60'},
{hrs: '2', timeSpent: '34'}, ...]

I have tried like billion times to group them but I cant figure out how: I always get values like 95 mins in hour. At least I need a right way to think. Thanks.

Body:
If your times are always strings in the format hh:mm:ss, then a simple string split with some math could work:

const times = [
  { timeStarted: '00:10:30', timeEnded: '00:14:02' },
  { timeStarted: '00:48:08', timeEnded: '02:33:33' },
];
const withHours = times.map(time => {
  // Split on colon to get the components of the timestamp
  var start = time.timeStarted.split(':');
  var end = time.timeEnded.split(':');

  // Convert to seconds by multiplying each component by how many seconds it's worth
  var startSeconds = (+start[0]) * 60 * 60 + (+start[1]) * 60 + (+start[2]);
  var endSeconds = (+end[0]) * 60 * 60 + (+end[1]) * 60 + (+end[2]);

  // Find the difference in seconds and convert back to hours
  // We'll also floor this cause it looks like you want ints rounded down
  var hrs = Math.floor((endSeconds - startSeconds) / (60 * 60));

  return {
    timeStarted: time.timeStarted,
    timeEnded: time.timeEnded,
    hrs,
  };
});

EDIT

Just noticed you have an additional field there called timeSpent.  Not sure what that is supposed to be.


问:
How to import candidate-requisition with match operation in tcc?
I want to import a candidate-requisition using match operation, but I don't know how, couldn't find match operation guidance. anyone have any idea?</p>

答:
Please use the Import > Candidate and select match option.
You will need three parameter the CSUser reference which is your Candidate ID, Requisition reference which is your Requisition ID and SendRMI if you want to send the matching details/application to Candidate (TRUE/FALSE).

Hope this helps you.


问:
Django Rest JWT login using username or email?
I am using django-rest-jwt for authentication in my app.

By default it user username field to autenticate a user but I want let the users login using email or username.

Is there any mean supported by django-rest-jwt to accomplish this.
I know the last option would be write my own login method.

答:
Building on top of Shikhar's answer and for anyone coming here looking for a solution for rest_framework_simplejwt (since django-rest-framework-jwt seems to be dead, it's last commit was 2 years ago) like me, here's a general solution that tries to alter as little as possible the original validation from TokenObtainPairSerializer:

```<code>from rest_framework_simplejwt.serializers import TokenObtainPairSerializer

class CustomJWTSerializer(TokenObtainPairSerializer):
    def validate(self, attrs):
        credentials = {
            'username': '',
            'password': attrs.get("password")
        }

        # This is answering the original question, but do whatever you need here.
        # For example in my case I had to check a different model that stores more user info
        # But in the end, you should obtain the username to continue.
        user_obj = User.objects.filter(email=attrs.get("username")).first() or User.objects.filter(username=attrs.get("username")).first()
        if user_obj:
            credentials['username'] = user_obj.username

        return super().validate(credentials)
</code>```

And in urls.py:

url(r'^token/$', TokenObtainPairView.as_view(serializer_class=CustomJWTSerializer)),

Body:
Building on top of Shikhar's answer and for anyone coming here looking for a solution for rest_framework_simplejwt (since django-rest-framework-jwt seems to be dead, it's last commit was 2 years ago) like me, here's a general solution that tries to alter as little as possible the original validation from TokenObtainPairSerializer:

from rest_framework_simplejwt.serializers import TokenObtainPairSerializer

class CustomJWTSerializer(TokenObtainPairSerializer):
    def validate(self, attrs):
        credentials = {
            'username': '',
            'password': attrs.get("password")
        }

        # This is answering the original question, but do whatever you need here.
        # For example in my case I had to check a different model that stores more user info
        # But in the end, you should obtain the username to continue.
        user_obj = User.objects.filter(email=attrs.get("username")).first() or User.objects.filter(username=attrs.get("username")).first()
        if user_obj:
            credentials['username'] = user_obj.username

        return super().validate(credentials)

And in urls.py:

url(r'^token/$', TokenObtainPairView.as_view(serializer_class=CustomJWTSerializer)),