问:
React, Formik, React-select & Firebase - isMulti array in a Formik form
I am trying to use React, Formik, react-select and Firebase (cloud firestore) to build a form in react.

It all works fine when I only use react-select once. There is only one state to update. When I try to use more than one drop down, I get an error that says:

```<code>Unhandled Rejection (FirebaseError): Function DocumentReference.set() called with invalid data. Unsupported field value: undefined (found in field fieldOfResearch)
</code>```

I don't know what this error message means. I've employed multiple code mentors and devs from upwork/codementor etc - and now the code is a shambles and untraceable back to the Formik documents - however, it works when I use react-select once. I think the problem might be something to do with how I name the fields to differentiate the state updates.

I have:

```<code>const initialValues = {
  fieldOfResearch: null,
  disclosureStatus: null,
}
</code>```

Both of these are react-select fields in my form.

Then I have:

```<code>class ProjectForm extends React.Component {
  state = {
    selectedValue1: null,
    selectedValue2: null,

  };

  handleSelectChange1 = selectedValue1 => {
    this.setState({ selectedValue1 });
  };

  handleSelectChange2 = selectedValue2 => {
    this.setState({ selectedValue2 });
  };
</code>```

SelectedValue1 is what I'm using for fieldOfResearch and SelectedValue2 is for disclosureStatus.

```<code>handleSubmit = (formState, { resetForm }) => {
    console.log("SUCCESS!! :-)\n\n", formState);
    fsDB
      .collection("project")
      .add(formState)
      .then(docRef => {
        console.log("docRef>>>", docRef);
        this.setState({ selectedValue1: null });
        this.setState({ selectedValue2: null });

        resetForm(initialValues);
      })
      .catch(error => {
        console.error("Error adding document: ", error);
      });
  };
</code>```

Then in my render method, I have:

```<code>render() {
    return (
      <Formik
        initialValues={initialValues}

onSubmit={this.handleSubmit}
        render={({ errors, status, touched, setFieldTouched, handleSubmit, values }) => {
          let fieldOfResearch;
          const handleChange1 = optionsObject => {
            fieldOfResearch = optionsObject;
            return (values.fieldOfResearch = optionsObject.value);
          };
          let disclosureStatus;
          const handleChange2 = confidentialityObject => {
            disclosureStatus = confidentialityObject;
            return (values.disclosureStatus = confidentialityObject.value);
          };
</code>```

The form group elements are:

```<code><div className="form-group">
                                <label htmlFor="fieldOfResearch">
                                Select your field(s) of research
                                </label>

                                <Select
                                key={`my_unique_select_key__${fieldOfResearch}`}
                                name="fieldOfResearch"
                                isMulti={true}
                                className={
                                    "react-select-container" +
                                    (errors.fieldOfResearch && touched.fieldOfResearch ? " is-invalid" : "")
                                }
                                classNamePrefix="react-select"
                                value={this.state.selectedValue1}
                                onChange={e => {
                                    handleChange1(e);
                                    this.handleSelectChange1(e);
                                }}
                                onBlur={setFieldTouched}
                                options={options}
                                />
                                {errors.fieldOfResearch && touched.fieldOfResearch &&
                                <ErrorMessage
                                name="fieldOfResearch"
                                component="div"
                                className="invalid-feedback d-block"
                                />}
                                </div>
</code>```

I was trying to use Yup for validation, with the following:

```<code>fieldOfResearch: Yup.array().required("What is your field of research?"),
</code>```

From the text of the error message, I think the part it doesn't like is the handle submit method:

```<code>this.setState({ selectedValue1: null });
</code>```

Does anyone know how to handle multiple fields that have a state in them with react-select, formik, firebase and react?

I took this whole form apart and started again. I think part of the problem may have something to do with the react-select isMulti option - which allows a field to have multiple values.

From the react-select documents, I think it is supposed to be used on the field as follows:

```<code>                      isMulti={true}
</code>```

When I try that, the form renders in local and allows multiple values to be selected, but saves them all as undefined. The error copied above throws when it tries to post to the database.

So - does anyone know how to use react-select with multiple input values on a select menu?

I have seen this question and the answer explaining how to use Formik with react-select, but I can't make any sense of it, or see how it could be integrated with the form structure that I am using.

I have also seen this Code Sandbox which shows a way this can be done in a language other than jsx. I can't figure out how to incorporate this approach into my form structure.

答:
Here is a codesandbox that I believe solves your issues. It doesn't include the add to firestore method in the handleSubmit function.

I made one field a multi-select and the other a plain select as examples.

https://codesandbox.io/s/formik-and-reactselect-example-i67l6

Body:
I am trying to use React, Formik, react-select and Firebase (cloud firestore) to build a form in react.

It all works fine when I only use react-select once. There is only one state to update. When I try to use more than one drop down, I get an error that says:

Unhandled Rejection (FirebaseError): Function DocumentReference.set() called with invalid data. Unsupported field value: undefined (found in field fieldOfResearch)

I don't know what this error message means. I've employed multiple code mentors and devs from upwork/codementor etc - and now the code is a shambles and untraceable back to the Formik documents - however, it works when I use react-select once. I think the problem might be something to do with how I name the fields to differentiate the state updates.

I have:

const initialValues = {
  fieldOfResearch: null,
  disclosureStatus: null,
}

Both of these are react-select fields in my form.

Then I have:

class ProjectForm extends React.Component {
  state = {
    selectedValue1: null,
    selectedValue2: null,

  };

  handleSelectChange1 = selectedValue1 => {
    this.setState({ selectedValue1 });
  };

  handleSelectChange2 = selectedValue2 => {
    this.setState({ selectedValue2 });
  };

SelectedValue1 is what I'm using for fieldOfResearch and SelectedValue2 is for disclosureStatus.

handleSubmit = (formState, { resetForm }) => {
    console.log("SUCCESS!! :-)\n\n", formState);
    fsDB
      .collection("project")
      .add(formState)
      .then(docRef => {
        console.log("docRef>>>", docRef);
        this.setState({ selectedValue1: null });
        this.setState({ selectedValue2: null });

        resetForm(initialValues);
      })
      .catch(error => {
        console.error("Error adding document: ", error);
      });
  };

Then in my render method, I have:

render() {
    return (
      <Formik
        initialValues={initialValues}

onSubmit={this.handleSubmit}
        render={({ errors, status, touched, setFieldTouched, handleSubmit, values }) => {
          let fieldOfResearch;
          const handleChange1 = optionsObject => {
            fieldOfResearch = optionsObject;
            return (values.fieldOfResearch = optionsObject.value);
          };
          let disclosureStatus;
          const handleChange2 = confidentialityObject => {
            disclosureStatus = confidentialityObject;
            return (values.disclosureStatus = confidentialityObject.value);
          };

The form group elements are:

                                Select your field(s) of research

                                <Select
                                key={`my_unique_select_key__${fieldOfResearch}`}
                                name="fieldOfResearch"
                                isMulti={true}
                                className={
                                    "react-select-container" +
                                    (errors.fieldOfResearch && touched.fieldOfResearch ? " is-invalid" : "")
                                }
                                classNamePrefix="react-select"
                                value={this.state.selectedValue1}
                                onChange={e => {
                                    handleChange1(e);
                                    this.handleSelectChange1(e);
                                }}
                                onBlur={setFieldTouched}
                                options={options}
                                />
                                {errors.fieldOfResearch && touched.fieldOfResearch &&
                                <ErrorMessage
                                name="fieldOfResearch"
                                component="div"
                                className="invalid-feedback d-block"
                                />}

I was trying to use Yup for validation, with the following:

fieldOfResearch: Yup.array().required("What is your field of research?"),

From the text of the error message, I think the part it doesn't like is the handle submit method:

this.setState({ selectedValue1: null });

Does anyone know how to handle multiple fields that have a state in them with react-select, formik, firebase and react?

I took this whole form apart and started again. I think part of the problem may have something to do with the react-select isMulti option - which allows a field to have multiple values.

From the react-select documents, I think it is supposed to be used on the field as follows:

                      isMulti={true}

When I try that, the form renders in local and allows multiple values to be selected, but saves them all as undefined. The error copied above throws when it tries to post to the database.

So - does anyone know how to use react-select with multiple input values on a select menu?

I have seen this question and the answer explaining how to use Formik with react-select, but I can't make any sense of it, or see how it could be integrated with the form structure that I am using.

I have also seen this Code Sandbox which shows a way this can be done in a language other than jsx. I can't figure out how to incorporate this approach into my form structure.


来源: stackexchange

问:
call to php file via ajax not working
This seems like a relatively simple question, and I am pretty new to using ajax, but I saw a post about being able to call a PHP script when an OnClick event has been triggered. I am trying to destroy a session upon a user clicking the "Log Out" link, so I want to call the logout.php file when the OnClick event has occurred. My problem is that nothing happens when the link is clicked.

Here's my code:

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

// Expand Panel
$("#open").click(function(){
    //when the user clicks the logout button
    $.ajax({
        url: "logout.php"
    )};
});
});

<div class="tab">
    <ul class="login">
        <li class="left"> </li>
        <li><?php if(isset($_SESSION['username'])){echo $_SESSION['username'];}else{echo 'Hello Guest!';}?></li>
        <li class="sep">|</li>
        <li id="toggle">
            <a id="open" class="open" href="#">Log Out</a>
        </li>
        <li class="right"> </li>
    </ul>
</div> <!-- / top -->
</code>```

答:
Using $.ajax isn't the same as clicking regular links. $.ajax doesn't "follow" the link, it loads the data from that link into the document without refreshing the page.

What you need to do is do what you want in your logout.php file and then you sent information on whether logout succeeded or not. You do that by outputting HTML, XML or JSON, which you check in your javascript code and take appropriate action (redirect user, lock down the UI or whatever).

ContentLicense: CC BY-SA 3.0

Title: call to php file via ajax not working

Body:
This seems like a relatively simple question, and I am pretty new to using ajax, but I saw a post about being able to call a PHP script when an OnClick event has been triggered. I am trying to destroy a session upon a user clicking the "Log Out" link, so I want to call the logout.php file when the OnClick event has occurred. My problem is that nothing happens when the link is clicked.

Here's my code:

$(document).ready(function() {

// Expand Panel
$("#open").click(function(){
    //when the user clicks the logout button
    $.ajax({
        url: "logout.php"
    )};
});
});

<?php if(isset($_SESSION['username'])){echo $_SESSION['username'];}else{echo 'Hello Guest!';}?>

|

            Log Out


问:
Integrating XAML apps in Unity projects
I've been developing a Unity3D project with Hololens using the Mixed Reality Toolkit, running smoothly with now problems. I'm trying now to create a Single-SignOn capability in the project - a Web Account Manager - by following this page, which uses XAML's to display and use the information of a AccountSettingsPane.

As a beginner of XAML and UWP development, I'm having a problem in how to integrate this with Unity. I tried turning the Account project into a plugin but no success because it doesn't seems to recognize the XAML code (and I've been able to create other UWP plugins previously). But I don't even know if this is the correct course of action.

I've search for resolutions but the only thing I find is XAML's running Unity apps and I'm looking for otherwise. I also tried to check if the plugin had any problem but I don't have a way to know since it doesn't returns errors, it simply doesn't do anything.

Did anyone tried to integrate a XAML project with Unity successfully or if it is possible at all? Or point me in the right direction since I feel a bit lost.

答:
Here's a blog post that describes a similar authentication process, where you jump out of the 3D Unity app to a browser to complete the authentication process and than go back to Unity: https://peted.azurewebsites.net/microsoft-graph-auth-on-hololens/

The sample linked at the bottom was changed to a different auth method which might not be available for your thing, but you can just go back to the old state of the repo by checking out an older commit: https://github.com/peted70/msal-hololens

ContentLicense: CC BY-SA 4.0

Title: Integrating XAML apps in Unity projects


问:
How to send data from adapter to activity and display it in a recyclerview?
I try to pass data from an adapter to an activity and display it in a recyclerview. I am getting the NullPointerException when I run the app. What am I doing wrong?

This is the activity where I want to display data:

```<code>public class ListOfChatsActivity extends AppCompatActivity {
Toolbar lToolbar;
RecyclerView lRV;
BottomNavigationView lBnv;
ListOfChatsAdapter adapter;
LinearLayoutManager layoutManager;
ArrayList<String> chatList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_of_chats);

    lToolbar = findViewById(R.id.lToolbar);
    lRV = findViewById(R.id.lRV);
    lBnv = findViewById(R.id.lBnv);
    Intent intent = this.getIntent();
    if(intent!=null){
    String string = intent.getStringExtra("username");
    chatList.add(string);}

    adapter = new ListOfChatsAdapter(chatList, getApplicationContext());
    layoutManager = new LinearLayoutManager(getApplicationContext());
    lRV.setAdapter(adapter);
    lRV.setLayoutManager(layoutManager);
}
</code>```

This is the adapter from where I want to send data:

```<code>public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.ViewHolder> {

ArrayList<User> friendsSearchedList = new ArrayList<>();
Context mContext;

public SearchAdapter(ArrayList<User> friendsSearchedList, Context mContext){
    this.friendsSearchedList = friendsSearchedList;
    this.mContext = mContext;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.search_user_item,
            parent, false);
    ViewHolder holder = new ViewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
    final User username = friendsSearchedList.get(position);
    holder.text.setText(username.getUsername());
   holder.button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String iUsername = holder.text.getText().toString();
            Intent intent = new Intent();
            intent.putExtra("username", iUsername);
        }
    });

}

@Override
public int getItemCount() {
    return friendsSearchedList == null ? 0:friendsSearchedList.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    TextView text;
    Button button;
    RelativeLayout relativeLayout;
    public ViewHolder(View itemView){
        super(itemView);

        text = itemView.findViewById(R.id.sText);
        button = itemView.findViewById(R.id.addFriend);
        relativeLayout = itemView.findViewById(R.id.relativeLayout);
    }
}
</code>```

}

I don't open the Activity from this Adapter. I just want to send extras. I tried more options, but I don't get it right.

答:
Change 1

adapter = new ListOfChatsAdapter(chatList, getApplicationContext());

Why is the ListOfChatsAdapter being used here? You have included SearchAdapter as the adapter to use in the RecyclerView.

Change 2

The ViewHolder object that is returned by onCreateViewHolder(), should be of type SearchAdapter.ViewHolder and not just ViewHolder. The same applies to the first arguement of onBindViewHolder().

Try these and check

Body:
I try to pass data from an adapter to an activity and display it in a recyclerview. I am getting the NullPointerException when I run the app. What am I doing wrong?

This is the activity where I want to display data:

public class ListOfChatsActivity extends AppCompatActivity {
Toolbar lToolbar;
RecyclerView lRV;
BottomNavigationView lBnv;
ListOfChatsAdapter adapter;
LinearLayoutManager layoutManager;
ArrayList<String> chatList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_of_chats);

    lToolbar = findViewById(R.id.lToolbar);
    lRV = findViewById(R.id.lRV);
    lBnv = findViewById(R.id.lBnv);
    Intent intent = this.getIntent();
    if(intent!=null){
    String string = intent.getStringExtra("username");
    chatList.add(string);}

    adapter = new ListOfChatsAdapter(chatList, getApplicationContext());
    layoutManager = new LinearLayoutManager(getApplicationContext());
    lRV.setAdapter(adapter);
    lRV.setLayoutManager(layoutManager);
}

This is the adapter from where I want to send data:

public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.ViewHolder> {

ArrayList<User> friendsSearchedList = new ArrayList<>();
Context mContext;

public SearchAdapter(ArrayList<User> friendsSearchedList, Context mContext){
    this.friendsSearchedList = friendsSearchedList;
    this.mContext = mContext;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.search_user_item,
            parent, false);
    ViewHolder holder = new ViewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
    final User username = friendsSearchedList.get(position);
    holder.text.setText(username.getUsername());
   holder.button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String iUsername = holder.text.getText().toString();
            Intent intent = new Intent();
            intent.putExtra("username", iUsername);
        }
    });

}

@Override
public int getItemCount() {
    return friendsSearchedList == null ? 0:friendsSearchedList.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    TextView text;
    Button button;
    RelativeLayout relativeLayout;
    public ViewHolder(View itemView){
        super(itemView);

        text = itemView.findViewById(R.id.sText);
        button = itemView.findViewById(R.id.addFriend);
        relativeLayout = itemView.findViewById(R.id.relativeLayout);
    }
}

}

I don't open the Activity from this Adapter. I just want to send extras. I tried more options, but I don't get it right.


问:
Generating a hierarchy view in angular with a list of json objects
I am currently in the process of trying to build out a hierarchy view of users. My end goal is to generate the view using this hierarchy view
or something similar.

The difficulty lies in how the JSON objects used to generate the hierarchy are given. This is a sample response (this response can be much bigger), where pid is the parent id and depth is the distance from the first parent.

```<code>response = [
    {uid: "abc", pid: null, depth: 1, parent: true},
    {uid: "def", pid: "abc", depth: 2, parent: false},
    {uid: "ghi", pid: "abc", depth: 2, parent: true},
    {uid: "jkl", pid: "ghi", depth: 3, parent: false},
    {uid: "mno", pid: "ghi", depth: 3, parent: false},
]
</code>```

To explain the above response better, here is the visual hierarchy view of it:
image

A lot of the answers and solutions I've seen so far utilize JSON with children nested in each one. Is it possible to generate the view using the json model above?

Any help or insight would be much appreciated! Thanks!

答:
First, you need to convert your self-reference table to a hierarchical table (tree). I suggest you use a custom pipe to do this since you will be able to reuse this pipe in other places.

You can use Reactgular's code, my code from the StackOverflow thread, or write your own code. I create my converter pipe with Reactgular's code:

converter.pipe.ts

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'converter'
})
export class ConverterPipe implements PipeTransform {
  transform(array: any[], id: string = 'uid', parentId: string = 'pid'): any[] {
    const map = array.reduce(
      (acc, node) => ((node.items = []), (acc[node[id]] = node), acc),
      {}
    );

    return Object.values(map)
      .map(
        node => (node[parentId] && map[node[parentId]].items.push(node), node)
      )
      .filter(node => node[parentId] === null);
  }
}
</code>```

Don't forget to add it to the declaration section of your module:

app.module.ts

```<code>import { ConverterPipe } from './converter.pipe';

@NgModule({
  declarations: [
    ConverterPipe
  ]
})
export class AppModule { }
</code>```

Now, you can create your component template and use the approach from the Hierarchy View CodePen. Since you need different markup for branches and leaves, it's handy to use NgTemplateOutlet's and NgIf structural directives. This's a good idea to move the level markup in a template and reuse it when you need to render a tree in Angular. The same idea is illustrated in my answer. Based on the provided CodePen code, your Angular markup may look as the following:

app.component.html

```<code><div class="hv-wrapper">
  <ng-template #Item let-item>
    <ng-container *ngIf="!item.items.length; else Component">
      <p>{{ item.uid }}</p>
    </ng-container>
    <ng-template #Component>
      <div class="hv-item">
        <div class="hv-item-parent">
          <p>{{ item.uid }}</p>
        </div>
        <div class="hv-item-children">
          <div class="hv-item-child" *ngFor="let child of item.items">
            <ng-container
              *ngTemplateOutlet="Item; context: { $implicit: child }"
            ></ng-container>
          </div>
        </div>
      </div>
    </ng-template>
  </ng-template>

  <ng-container *ngFor="let child of response | converter"
    ><ng-container
      *ngTemplateOutlet="Item; context: { $implicit: child }"
    ></ng-container
  ></ng-container>
</div>
</code>```

Here, response is your original array:

app.component.ts

```<code>export class AppComponent {
  response = [
    { uid: 'abc', pid: null, depth: 1, parent: true },
    { uid: 'def', pid: 'abc', depth: 2, parent: true },
    { uid: 'ghi', pid: 'abc', depth: 2, parent: false },
    { uid: 'jkl', pid: 'ghi', depth: 3, parent: false },
    { uid: 'mno', pid: 'ghi', depth: 3, parent: false }
  ];
}
</code>```

Don't forget to use the CodePen SASS styles in your project.

After this, you will a graph like:

This is a StackBlitz project that demonstrates this approach in action.

Body:
I am currently in the process of trying to build out a hierarchy view of users. My end goal is to generate the view using this hierarchy view
or something similar.

The difficulty lies in how the JSON objects used to generate the hierarchy are given. This is a sample response (this response can be much bigger), where pid is the parent id and depth is the distance from the first parent.

response = [
    {uid: "abc", pid: null, depth: 1, parent: true},
    {uid: "def", pid: "abc", depth: 2, parent: false},
    {uid: "ghi", pid: "abc", depth: 2, parent: true},
    {uid: "jkl", pid: "ghi", depth: 3, parent: false},
    {uid: "mno", pid: "ghi", depth: 3, parent: false},
]

To explain the above response better, here is the visual hierarchy view of it:
image

A lot of the answers and solutions I've seen so far utilize JSON with children nested in each one. Is it possible to generate the view using the json model above?

Any help or insight would be much appreciated! Thanks!

Body:
First, you need to convert your self-reference table to a hierarchical table (tree). I suggest you use a custom pipe to do this since you will be able to reuse this pipe in other places.

You can use Reactgular's code, my code from the StackOverflow thread, or write your own code. I create my converter pipe with Reactgular's code:

converter.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'converter'
})
export class ConverterPipe implements PipeTransform {
  transform(array: any[], id: string = 'uid', parentId: string = 'pid'): any[] {
    const map = array.reduce(
      (acc, node) => ((node.items = []), (acc[node[id]] = node), acc),
      {}
    );

    return Object.values(map)
      .map(
        node => (node[parentId] && map[node[parentId]].items.push(node), node)
      )
      .filter(node => node[parentId] === null);
  }
}

Don't forget to add it to the declaration section of your module:

app.module.ts

import { ConverterPipe } from './converter.pipe';

@NgModule({
  declarations: [
    ConverterPipe
  ]
})
export class AppModule { }

Now, you can create your component template and use the approach from the Hierarchy View CodePen. Since you need different markup for branches and leaves, it's handy to use NgTemplateOutlet's and NgIf structural directives. This's a good idea to move the level markup in a template and reuse it when you need to render a tree in Angular. The same idea is illustrated in my answer. Based on the provided CodePen code, your Angular markup may look as the following:

app.component.html

<div class="hv-wrapper">
  <ng-template #Item let-item>
    <ng-container *ngIf="!item.items.length; else Component">
      <p>{{ item.uid }}</p>
    </ng-container>
    <ng-template #Component>
      <div class="hv-item">
        <div class="hv-item-parent">
          <p>{{ item.uid }}</p>
        </div>
        <div class="hv-item-children">
          <div class="hv-item-child" *ngFor="let child of item.items">
            <ng-container
              *ngTemplateOutlet="Item; context: { $implicit: child }"
            ></ng-container>
          </div>
        </div>
      </div>
    </ng-template>
  </ng-template>

  <ng-container *ngFor="let child of response | converter"
    ><ng-container
      *ngTemplateOutlet="Item; context: { $implicit: child }"
    ></ng-container
  ></ng-container>
</div>

Here, response is your original array:

app.component.ts

export class AppComponent {
  response = [
    { uid: 'abc', pid: null, depth: 1, parent: true },
    { uid: 'def', pid: 'abc', depth: 2, parent: true },
    { uid: 'ghi', pid: 'abc', depth: 2, parent: false },
    { uid: 'jkl', pid: 'ghi', depth: 3, parent: false },
    { uid: 'mno', pid: 'ghi', depth: 3, parent: false }
  ];
}

Don't forget to use the CodePen SASS styles in your project.

After this, you will a graph like:

This is a StackBlitz project that demonstrates this approach in action.


问:
AVG function calculates correctly in a SELECT with GROUP BY but not with an UPDATE for some records
I have a simple detail table listing a customer number and a corresponding score in float format, when I do an average using AVG with Group By customer in a Select, it correctly calculates the score averages for each customer, but if want to update a master table with the customer number with its average score using the original Select, my Update query is calculating averages incorrectly for some of the customers, so I wonder where the error might lie.

Tried to use Cast to decimal with two decimal points in the Update query on the select part of it, as data has 17 decimal points, but issue remains.
This is just a test on 16 records but I have to nail down the issue before continuing.

```<code>--AVG used only in Select correctly does the average calculation from the detail (child) table SELECT sd.customer, AVG(score) AS avg_score_group from score_detail as sd
        JOIN score_master as sm ON sd.customer = sm.customer
        GROUP BY sd.customer
    -- Using AVG to actually update the master table with averages from child
    -- table has incorrect calculations for some grouped records
        UPDATE score_master
        SET avg_score = t.avg_score_group
        FROM (
        SELECT AVG(score) AS avg_score_group from score_detail as sd
        JOIN
        score_master as sm
        ON
        sd.customer = sm.customer
        GROUP BY sd.customer
        ) AS t
    --Let us explore master table
        SELECT * FROM  score_master;
--Table structures:
CREATE TABLE [dbo].[score_detail](
[customer] [float] NULL,
[score] [float] NULL
) ON [PRIMARY]

CREATE TABLE [dbo].[score_master](
[customer] [float] NULL,
[avg_score] [float] NULL
) ON [PRIMARY]
-- Data to calculate average has 17 Decimal points:
INSERT [dbo].[score_detail] ([customer], [score]) VALUES (2, -0.07216878364870323)
</code>```

I would expect the same results in the Select-only from detail table to appear in the Update query for the master table, but some are not correct, i.e. customers 4 and 7:

```<code>Cust No -   Avg in Detail table     - Avg in Master table
2           -0.0681                 -0.0681
4            0.0000                  0.1127
7            0.0184                 -0.0681
16           0.1127                  0.1127
</code>```

答:
I don't see a where clause in the sub query used in the update and this looks incorrect... there is no correlation and thus no guarantee which value is chosen from the results of the sub-query. Try rewriting your update query like so:

```<code>UPDATE score_master
SET avg_score = (
    SELECT AVG(score)
    FROM score_detail
    WHERE score_detail.customer = score_master.customer
)
</code>```

Having said that, I would recommend that you do not store values that can be calculated on demand. Create a view for the averages instead.

Body:
I have a simple detail table listing a customer number and a corresponding score in float format, when I do an average using AVG with Group By customer in a Select, it correctly calculates the score averages for each customer, but if want to update a master table with the customer number with its average score using the original Select, my Update query is calculating averages incorrectly for some of the customers, so I wonder where the error might lie.

Tried to use Cast to decimal with two decimal points in the Update query on the select part of it, as data has 17 decimal points, but issue remains.
This is just a test on 16 records but I have to nail down the issue before continuing.

--AVG used only in Select correctly does the average calculation from the detail (child) table SELECT sd.customer, AVG(score) AS avg_score_group from score_detail as sd
        JOIN score_master as sm ON sd.customer = sm.customer
        GROUP BY sd.customer
    -- Using AVG to actually update the master table with averages from child
    -- table has incorrect calculations for some grouped records
        UPDATE score_master
        SET avg_score = t.avg_score_group
        FROM (
        SELECT AVG(score) AS avg_score_group from score_detail as sd
        JOIN
        score_master as sm
        ON
        sd.customer = sm.customer
        GROUP BY sd.customer
        ) AS t
    --Let us explore master table
        SELECT * FROM  score_master;
--Table structures:
CREATE TABLE [dbo].[score_detail](
[customer] [float] NULL,
[score] [float] NULL
) ON [PRIMARY]

CREATE TABLE [dbo].[score_master](
[customer] [float] NULL,
[avg_score] [float] NULL
) ON [PRIMARY]
-- Data to calculate average has 17 Decimal points:
INSERT [dbo].[score_detail] ([customer], [score]) VALUES (2, -0.07216878364870323)

I would expect the same results in the Select-only from detail table to appear in the Update query for the master table, but some are not correct, i.e. customers 4 and 7:

Cust No -   Avg in Detail table     - Avg in Master table
2           -0.0681                 -0.0681
4            0.0000                  0.1127
7            0.0184                 -0.0681
16           0.1127                  0.1127

Body:
I don't see a where clause in the sub query used in the update and this looks incorrect... there is no correlation and thus no guarantee which value is chosen from the results of the sub-query. Try rewriting your update query like so:

UPDATE score_master
SET avg_score = (
    SELECT AVG(score)
    FROM score_detail
    WHERE score_detail.customer = score_master.customer
)

Having said that, I would recommend that you do not store values that can be calculated on demand. Create a view for the averages instead.


问:
How to Obtain Python Script Return Value to Use in Visual Studio Form?
I am currently using a DAQC2 PiPlate on my Raspberry Pi and testing Analog Inputs on it. To get the inputs, I call a python script to return them. My problem is that I am using Visual Studio to create a Form GUI so that when the program runs independently on the Pi, the form handles the GUI (running on a 7" touchscreen)

I've currently tried using a StreamReader that reads the script's output every time the timer ticks, which then updates the label afterward.

My PythonScript Class

```<code>    public PythonScript(string scriptName)
    {
        _scriptName = scriptName;
    }
    public string Run()
    {
        ProcessStartInfo psi = new ProcessStartInfo();
        psi.FileName = "python3";
        psi.Arguments = _scriptName;
        psi.UseShellExecute = false;
        psi.CreateNoWindow = true;
        psi.RedirectStandardOutput = false;
        psi.RedirectStandardError = true;

        Process process = new Process();
        process.StartInfo = psi;
        process.StartInfo.RedirectStandardOutput = true;
        process.Start();

        StreamReader myStreamReader = process.StandardOutput;
        string str = myStreamReader.ReadLine();
        process.WaitForExit();
        process.Close();
        return str;

    }
</code>```

My current work in the Form1.cs class that handles the form loading and the location of the timer

```<code>    private void Form1_Load(object sender, EventArgs e)
    {
        /**
        //Maximize form to fill screen
        WindowState = FormWindowState.Normal;
        FormBorderStyle = FormBorderStyle.None;
        Location = new Point(0, 0);
        TopMost = true;
        Screen currentScreen = Screen.FromHandle(this.Handle);
        this.Size = new System.Drawing.Size(currentScreen.Bounds.Width, currentScreen.Bounds.Height);
        **/

        //set up timer
        timer.Interval = (10);
        timer.Tick += new EventHandler(timer_tick);
        timer.Start();
    }

    private void timer_tick(object sender, EventArgs e)
    {
        string value = "";
        PythonScript getValue1 = new PythonScript("/home/pi/Desktop/DAQC2_Script.py");
        value = getValue1.Run();
        label1.Text = value;
    }
</code>```

My python script

```<code>    import piplates.DAQC2plate as x
    value = str(x.getADC(0, 1))
    return value
</code>```

Currently my form builds and runs properly, however it doesn't do anything. The label remains the default "00.0." I am sure my RaspberryPi and it's equipment are hooked up properly, because I can execute the script (without the return statement) and it reads the data and allows me to print to the console.

I simply want the value in the python script to be updated to the label1.Text every second. I'm new to not only c#, but to python as well so any help is greatly appreciated.

答: So after awhile of digging, I was drastically overlooking the possibility that my issue was within my python script. I finally got the idea to use process.RedirectStandardError, which led me to find that my 'return' statement was "out of function." Not only was my return statement not in any specific function, but I discovered it wasn't needed at all. The StreamReader handles the reading without any return statement from within the script. This was a learning experience for this noob. </p>

Body:
I am currently using a DAQC2 PiPlate on my Raspberry Pi and testing Analog Inputs on it. To get the inputs, I call a python script to return them. My problem is that I am using Visual Studio to create a Form GUI so that when the program runs independently on the Pi, the form handles the GUI (running on a 7" touchscreen)

I've currently tried using a StreamReader that reads the script's output every time the timer ticks, which then updates the label afterward.

My PythonScript Class

    public PythonScript(string scriptName)
    {
        _scriptName = scriptName;
    }
    public string Run()
    {
        ProcessStartInfo psi = new ProcessStartInfo();
        psi.FileName = "python3";
        psi.Arguments = _scriptName;
        psi.UseShellExecute = false;
        psi.CreateNoWindow = true;
        psi.RedirectStandardOutput = false;
        psi.RedirectStandardError = true;

        Process process = new Process();
        process.StartInfo = psi;
        process.StartInfo.RedirectStandardOutput = true;
        process.Start();

        StreamReader myStreamReader = process.StandardOutput;
        string str = myStreamReader.ReadLine();
        process.WaitForExit();
        process.Close();
        return str;

    }

My current work in the Form1.cs class that handles the form loading and the location of the timer

    private void Form1_Load(object sender, EventArgs e)
    {
        /**
        //Maximize form to fill screen
        WindowState = FormWindowState.Normal;
        FormBorderStyle = FormBorderStyle.None;
        Location = new Point(0, 0);
        TopMost = true;
        Screen currentScreen = Screen.FromHandle(this.Handle);
        this.Size = new System.Drawing.Size(currentScreen.Bounds.Width, currentScreen.Bounds.Height);
        **/

        //set up timer
        timer.Interval = (10);
        timer.Tick += new EventHandler(timer_tick);
        timer.Start();
    }

    private void timer_tick(object sender, EventArgs e)
    {
        string value = "";
        PythonScript getValue1 = new PythonScript("/home/pi/Desktop/DAQC2_Script.py");
        value = getValue1.Run();
        label1.Text = value;
    }

My python script

    import piplates.DAQC2plate as x
    value = str(x.getADC(0, 1))
    return value

Currently my form builds and runs properly, however it doesn't do anything. The label remains the default "00.0." I am sure my RaspberryPi and it's equipment are hooked up properly, because I can execute the script (without the return statement) and it reads the data and allows me to print to the console.

I simply want the value in the python script to be updated to the label1.Text every second. I'm new to not only c#, but to python as well so any help is greatly appreciated.


问:
Trying to print multiple variable under loop
Here is what I tried

```<code>f = open('names.txt')
for people in f:
    print('{0} and {1}'.format(people, people))
</code>```

Output:

```<code>john
and john

vlad
and vlad
</code>```

But my expected output is

```<code>john and john
vlad and vlad
</code>```

What is wrong here and how to fix it?

答:
How about this:</p>

```<code>people = people.rstrip()
print('{0} and {1}'.format(people, people))
</code>```

Body:
Here is what I tried

f = open('names.txt')
for people in f:
    print('{0} and {1}'.format(people, people))

Output:

john
and john

vlad
and vlad

But my expected output is

john and john
vlad and vlad

What is wrong here and how to fix it?

Body:
How about this:

people = people.rstrip()
print('{0} and {1}'.format(people, people))


问:
Digest Auth using axios
Has anyone performed 'digest auth' using the axios modules in nodejs? Unable to find the right configuration options to be set for the peforming the authentication.</p>

答:
Don't seem to be support for digest
https://github.com/axios/axios/issues/686

But there's another package
https://github.com/rearn/axios-digest

I haven't tried it though, and cant understans if it only support encrypted digestfile (not regular digest)

Title: Digest Auth using axios


问:
How can I implement a promise in my calculator function?
I've written a calculator-like application in JavaScript, mainly so that it will run in any browser. It has a number of input fields. When I press the calculate button, it gathers data from these fields, calls various functions on it, and displays the result. There's no asynchronous stuff to do, no web or disc fetches that could delay or fail, the user triggers an event and then has to wait until the answer has been produced.

The fragment below is more or less a Hello World for this sort of process.

```<code><script type="text/javascript">
function transformer(instring)
{
    var outstring = instring + instring;
    return outstring;
}

function calculate()
{
    var srcStr = document.mainform.src.value;
    var transformed = transformer(srcStr);
    document.mainform.dst.value = transformed;
}
</script>

<form name="mainform">
Input data <input type="text" name="src" value="abc"/><br>
<button type="button" onclick="javascript:calculate();">Calculate</button><br>
Output data <input type="text" name="dst"  />
</form>
</code>```

I would like to replace the transformer() function with a function from a library that returns a promise. What's the minimum change in code I need to make to accomplish this. I've searched a lot for promises, async functions, thens etc, but not found a simple 'here is how to use a promise in a simple event driven program', and I have not yet managed to write a working equivalent of the program above. Once I have a working hello world, I can build from there.

Assume that the promise will always resolve, reject never needs to be handled. By 'minimum change', I don't necessarily mean fewest characters, but easiest to understand, or with fewest new concepts.

答:
Here is your code using a promise. Note the result side.

function transformer(instring) {
  return new Promise((resolve, reject) => {
    const outstring = instring + instring;
    resolve(outstring);
  });
}

function calculate() {
  var srcStr = document.querySelector('#src').value;
  transformer(srcStr).then(result => document.querySelector('#dst').value = result);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="mainform">
  Input data <input type="text" id="src" value="abc" /><br>
  <button type="button" onclick="javascript:calculate();">Calculate</button><br> Output data <input type="text" id="dst" />
</form></code>```

Body:
I've written a calculator-like application in JavaScript, mainly so that it will run in any browser. It has a number of input fields. When I press the calculate button, it gathers data from these fields, calls various functions on it, and displays the result. There's no asynchronous stuff to do, no web or disc fetches that could delay or fail, the user triggers an event and then has to wait until the answer has been produced.

The fragment below is more or less a Hello World for this sort of process.

<form name="mainform">
Input data <input type="text" name="src" value="abc"/>

<button type="button" onclick="javascript:calculate();">Calculate</button>

Output data <input type="text" name="dst"  />
</form>

I would like to replace the transformer() function with a function from a library that returns a promise. What's the minimum change in code I need to make to accomplish this. I've searched a lot for promises, async functions, thens etc, but not found a simple 'here is how to use a promise in a simple event driven program', and I have not yet managed to write a working equivalent of the program above. Once I have a working hello world, I can build from there.

Assume that the promise will always resolve, reject never needs to be handled. By 'minimum change', I don't necessarily mean fewest characters, but easiest to understand, or with fewest new concepts.

Body:
Here is your code using a promise. Note the result side.

function transformer(instring) {
  return new Promise((resolve, reject) => {
    const outstring = instring + instring;
    resolve(outstring);
  });
}

function calculate() {
  var srcStr = document.querySelector('#src').value;
  transformer(srcStr).then(result => document.querySelector('#dst').value = result);
}

<form name="mainform">
  Input data <input type="text" id="src" value="abc" /><br>
  <button type="button" onclick="javascript:calculate();">Calculate</button><br> Output data <input type="text" id="dst" />
</form>


问:
Reactjs npm start causes error ELIFECYCLE/3221225477
I just installed React through the command npm init react-app client and tried to start it through npm start, but got the following error.
But some details before that, I've installed React globally through npm install -g create-react-app and I am using VS Code.

```<code>0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'start'
1 verbose cli ]
2 info using npm@6.9.0
3 info using node@v12.0.0
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle client@0.1.0~prestart: client@0.1.0
6 info lifecycle client@0.1.0~start: client@0.1.0
7 verbose lifecycle client@0.1.0~start: unsafe-perm in lifecycle true
8 verbose lifecycle client@0.1.0~start: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\Projeto\client\node_modules\.bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\110\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files\Microsoft SQL Server\120\DTS\Binn\;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\nodejs\;C:\Users\leopl\AppData\Local\Programs\Python\Python37\Scripts\;C:\Users\leopl\AppData\Local\Programs\Python\Python37\;C:\Users\leopl\AppData\Local\Microsoft\WindowsApps;;C:\Users\leopl\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\leopl\AppData\Roaming\npm
9 verbose lifecycle client@0.1.0~start: CWD: C:\Projeto\client
10 silly lifecycle client@0.1.0~start: Args: [ '/d /s /c', 'react-scripts start' ]
11 silly lifecycle client@0.1.0~start: Returned: code: 3221225477  signal: null
12 info lifecycle client@0.1.0~start: Failed to exec start script
13 verbose stack Error: client@0.1.0 start: `react-scripts start`
13 verbose stack Exit status 3221225477
13 verbose stack     at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:301:16)
13 verbose stack     at EventEmitter.emit (events.js:196:13)
13 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:196:13)
13 verbose stack     at maybeClose (internal/child_process.js:1000:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:267:5)
14 verbose pkgid client@0.1.0
15 verbose cwd C:\Projeto\client
16 verbose Windows_NT 10.0.17763
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
18 verbose node v12.0.0
19 verbose npm  v6.9.0
20 error code ELIFECYCLE
21 error errno 3221225477
22 error client@0.1.0 start: `react-scripts start`
22 error Exit status 3221225477
23 error Failed at the client@0.1.0 start script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 3221225477, true ]
</code>```

Package.json

```<code>{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-scripts": "3.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
</code>```

I have tried:

Clean cache

npm cache clean --force

delete node_modules folder

delete package-lock.json file

npm install

Just deleted everything

Delete everything in the folder

Install again with npm init react-app client (but I've tried create-react-app client as well)

Uninstall React and install again

Delete everything in the folder

npm -g uninstall create-react-app --save

Install everything again

Install 2 times (I saw that this worked for one person, so I tried it too)

npm init react-app client

npm install

One additional information, but that may be important, I can not run react-scripts start. I can not describe exactly what is the error in VS Code because it is in PT-BR, but it says the term react-scripts was not recognized and had a CommandNotFoundException error.

答: A simple thing solved this problem, I was using the latest version of Node.js (Latest - 12.0.0), I uninstalled it and installed the 10.15.3 LTS version, it is now normal. I did not even need to reinstall React again.</p>

Body:
I just installed React through the command npm init react-app client and tried to start it through npm start, but got the following error.
But some details before that, I've installed React globally through npm install -g create-react-app and I am using VS Code.

0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'start'
1 verbose cli ]
2 info using npm@6.9.0
3 info using node@v12.0.0
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle client@0.1.0~prestart: client@0.1.0
6 info lifecycle client@0.1.0~start: client@0.1.0
7 verbose lifecycle client@0.1.0~start: unsafe-perm in lifecycle true
8 verbose lifecycle client@0.1.0~start: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\Projeto\client\node_modules\.bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\110\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files\Microsoft SQL Server\120\DTS\Binn\;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\nodejs\;C:\Users\leopl\AppData\Local\Programs\Python\Python37\Scripts\;C:\Users\leopl\AppData\Local\Programs\Python\Python37\;C:\Users\leopl\AppData\Local\Microsoft\WindowsApps;;C:\Users\leopl\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\leopl\AppData\Roaming\npm
9 verbose lifecycle client@0.1.0~start: CWD: C:\Projeto\client
10 silly lifecycle client@0.1.0~start: Args: [ '/d /s /c', 'react-scripts start' ]
11 silly lifecycle client@0.1.0~start: Returned: code: 3221225477  signal: null
12 info lifecycle client@0.1.0~start: Failed to exec start script
13 verbose stack Error: client@0.1.0 start: `react-scripts start`
13 verbose stack Exit status 3221225477
13 verbose stack     at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:301:16)
13 verbose stack     at EventEmitter.emit (events.js:196:13)
13 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:196:13)
13 verbose stack     at maybeClose (internal/child_process.js:1000:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:267:5)
14 verbose pkgid client@0.1.0
15 verbose cwd C:\Projeto\client
16 verbose Windows_NT 10.0.17763
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
18 verbose node v12.0.0
19 verbose npm  v6.9.0
20 error code ELIFECYCLE
21 error errno 3221225477
22 error client@0.1.0 start: `react-scripts start`
22 error Exit status 3221225477
23 error Failed at the client@0.1.0 start script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 3221225477, true ]

Package.json

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-scripts": "3.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

I have tried:

Clean cache

npm cache clean --force

delete node_modules folder

delete package-lock.json file

npm install

Just deleted everything

Delete everything in the folder

Install again with npm init react-app client (but I've tried create-react-app client as well)

Uninstall React and install again

Delete everything in the folder

npm -g uninstall create-react-app --save

Install everything again

Install 2 times (I saw that this worked for one person, so I tried it too)

npm init react-app client

npm install

One additional information, but that may be important, I can not run react-scripts start. I can not describe exactly what is the error in VS Code because it is in PT-BR, but it says the term react-scripts was not recognized and had a CommandNotFoundException error.


问:
Remove white space between header and body
I've tried to remove the white space between the header and body but can't get it to work. I've included a snippet that shows my code. anyone knows how to sort this?

header {
    width: 100%;
    height: 10em;
    background-color: #345cd7;
    position: relative;
    margin: 0;
    padding: 0;
}

.top-box {
    background-color: #345cd7;
    margin: 0;
    padding: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <header>
    <img src="images/white.svg" id="logo" />
</header>
    <div class="top-box">
        <h1>Welcome to</h1>
        <h2>Welcome to the family. Download one of the apps and get making them calls!</h2>
    </div>
</body></code>```

答:
Just use the universal selector:

```<code>*{ margin: 0%; }
</code>```

source: https://css-tricks.com/almanac/selectors/u/universal/

Body:
I've tried to remove the white space between the header and body but can't get it to work. I've included a snippet that shows my code. anyone knows how to sort this?

header {
    width: 100%;
    height: 10em;
    background-color: #345cd7;
    position: relative;
    margin: 0;
    padding: 0;
}

.top-box {
    background-color: #345cd7;
    margin: 0;
    padding: 0;
}

Welcome to

Welcome to the family. Download one of the apps and get making them calls!

Body:
Just use the universal selector:

*{ margin: 0%; }

source: https://css-tricks.com/almanac/selectors/u/universal/


问:
How to merge a grouped and aggregated df?
I have grouped and aggregated transactions per account number (to calculate monthly statisitics) and now I want to merge the output with another dataframe on account numbers. The account numbers are however no longer in the index/columns.

Group transactions per account and month and perform aggregated calculations

```<code>df1 = df.groupby(['AcctNr','Month']).sum().groupby(level=0).agg({'Amount': 'mean', 'median', max, 'std', percentile(75), iqr]})

df1.columns = ["_".join(x) for x in df1.columns.ravel()]
</code>```

This results in the following results from

```<code>df1.columns:

Index(['Amount_mean', 'Amount_median', 'Amount_max', 'Amount_std',
       'Amount_percentile_75', 'Amount_iqr', 'UpperBP'],
      dtype='object')
</code>```

When I try to merge with another DF on AcctNr i get:

```<code>df3 = df1.merge(df2, on='AcctNr')

KeyError: 'AcctNr'
</code>```

答:
You need to keep account number in your df1 because without it you can not join.

If you don't need it in your final df you can drop it with

```<code>df3 = df3.drop("AcctNr", axis=1)
</code>```

Body:
I have grouped and aggregated transactions per account number (to calculate monthly statisitics) and now I want to merge the output with another dataframe on account numbers. The account numbers are however no longer in the index/columns.

Group transactions per account and month and perform aggregated calculations

df1 = df.groupby(['AcctNr','Month']).sum().groupby(level=0).agg({'Amount': 'mean', 'median', max, 'std', percentile(75), iqr]})

df1.columns = ["_".join(x) for x in df1.columns.ravel()]

This results in the following results from

df1.columns:

Index(['Amount_mean', 'Amount_median', 'Amount_max', 'Amount_std',
       'Amount_percentile_75', 'Amount_iqr', 'UpperBP'],
      dtype='object')

When I try to merge with another DF on AcctNr i get:

df3 = df1.merge(df2, on='AcctNr')

KeyError: 'AcctNr'

Body:
You need to keep account number in your df1 because without it you can not join.

If you don't need it in your final df you can drop it with

df3 = df3.drop("AcctNr", axis=1)


问:
Vuex Store Unknown Getters with Nuxt
I've almoust finished my app in Vuejs and now I decided to "rewrite" everything on Nuxt due to SSR :)
I almoust get everything but there is this getter thing I am not getting.. I can't make it around even though I tried so hard and I am not sure what I am missing.

I am using vuex module so my /store/categories.js looks like:

```<code>export const state = () =>  ({
  categories: [
    {
          name: 'category 1',
         id: '1'
         subcategories: [
        {
           name: 'Subcategory 1',
            id: '1.1'
        }
      ]
    },
    {
      name: 'category 2',
      id: '2',
      subcategories: [
        {
          name: 'Subcategory 2',
          id: '1.1'
        }
      ]
    }
  ]
})
export const getters = () => ({
filterCategory() {
    return state.categories
  },
})
</code>```

This is a simple getter above and I can't even make this work..

And here is my posts/test.vue page:

```<code><template>
  <div>
    <p>{{ filter }} </p>
    <p>{{ mainCategories }} </p>
  </div>
</template>
<script>

import { mapGetters } from 'vuex'

export default {
  name: 'test',
  layout: 'test',
  data () {
    return {
      search: '',
    }
  },
  computed: {
    ...mapGetters({
      filter: 'categories/filterCategory'
    }),
    mainCategories () {
      return this.$store.getters['categories/filterpazari']
    }
  },
}
</script>
</code>```

What am I missing ?

答:
Getters should be exported as objects not function.

As Bert already mentioned in the comment how to declare getters. But it was trouble some to find the solutions at first glance. So here is the formated answer.

```<code>const getters = {
  filterCategory: state => state.categories,
}

export default getters
</code>```

Credit to Bert

Title: Vuex Store Unknown Getters with Nuxt

Body:
I've almoust finished my app in Vuejs and now I decided to "rewrite" everything on Nuxt due to SSR :)
I almoust get everything but there is this getter thing I am not getting.. I can't make it around even though I tried so hard and I am not sure what I am missing.

I am using vuex module so my /store/categories.js looks like:

export const state = () =>  ({
  categories: [
    {
          name: 'category 1',
         id: '1'
         subcategories: [
        {
           name: 'Subcategory 1',
            id: '1.1'
        }
      ]
    },
    {
      name: 'category 2',
      id: '2',
      subcategories: [
        {
          name: 'Subcategory 2',
          id: '1.1'
        }
      ]
    }
  ]
})
export const getters = () => ({
filterCategory() {
    return state.categories
  },
})

This is a simple getter above and I can't even make this work..

And here is my posts/test.vue page:

<template>

{{ filter }}

{{ mainCategories }}

</template>

What am I missing ?

Body:
Getters should be exported as objects not function.

As Bert already mentioned in the comment how to declare getters. But it was trouble some to find the solutions at first glance. So here is the formated answer.

const getters = {
  filterCategory: state => state.categories,
}

export default getters

Credit to Bert


问:
AJAX php code inserting NULL and not input values to database
I am trying to insert 2 values interchangeably to my database - my Select element with name=toctquantsel and my Input element with name=toctquant. When my Select element is hidden, the value of my Input will be inserted to the database, and vise versa. I was able to achieve with my php code alone, however when doing this with AJAX, I get the error message, "Uncaught mysqli_sql_exception: Column 'toctquant' cannot be null". Again, I did not get this error when not using AJAX. How do I fix this so I can insert my values to the database without having to change my database columns to NULL?

答:
When you submit the form normally, the form fields will be put in $_POST['toctquantsel]and$_POST['toctquant']`. In your AJAX call, you have

```<code>data: {selectValueBox: selectValue, inputValueBox: inputValue},
</code>```

When you use AJAX, the parameter names sent to PHP come from the data: object, not the names of the form fields. So these fields will be in $_POST['selectValueBox'] and $_POST['inputValueBox']. To make your AJAX code work with the same PHP code on the server, you need to change that to:

```<code>data: {toctquantsel: selectValue, toctquant: inputValue},
</code>```

Body:
When you submit the form normally, the form fields will be put in $_POST['toctquantsel]and$_POST['toctquant']`. In your AJAX call, you have

data: {selectValueBox: selectValue, inputValueBox: inputValue},

When you use AJAX, the parameter names sent to PHP come from the data: object, not the names of the form fields. So these fields will be in $_POST['selectValueBox'] and $_POST['inputValueBox']. To make your AJAX code work with the same PHP code on the server, you need to change that to:

data: {toctquantsel: selectValue, toctquant: inputValue},


问:
Getting comma separated values from PHP array
I have an array thusly

```<code>$main_array = [

    ["image" => "james.jpg", "name" => "james", "tag" => "spacey, wavy"],
    ["image" => "ned.jpg", "name" => "ned", "tag" => "bright"]
    ["image" => "helen.jpg", "name" => "helen", "tag" => "wavy, bright"]

]
</code>```

I use a foreach to echo some HTML based on the value of tag. Something like this

```<code>    foreach($main_array as $key => $array) {
        if ($array['tag'] == "bright") {
            echo '<p>'.$array['name'].' '.$array['image'].' '.$array['tag'].'</p>';
        }
    }
</code>```

This only outputs "ned" as matching the tag "bright". But it should output "helen" too. Similarly:

```<code>    foreach($main_array as $key => $array) {
        if ($array['tag'] == "wavy") {
            echo '<p>'.$array['name'].' '.$array['image'].' '.$array['tag'].'</p>';
        }
    }
</code>```

Should output "james" and "helen". What kind of function do I need to achieve the desired result?

答:
You cant do it directly, because it return key with values in string. Below are the working code.</p>

```<code><?php
   $main_array = [

    ["image" => "james.jpg", "name" => "james", "tag" => "spacey, wavy"],
    ["image" => "ned.jpg", "name" => "ned", "tag" => "bright"],
    ["image" => "helen.jpg", "name" => "helen", "tag" => "wavy, bright"]

];

foreach($main_array as $key => $array) {
    $str_arr = explode (", ", $array['tag']);
    foreach ($str_arr as $key2 => $array2) {
        if ($array2 == "wavy") {
            echo '<p>'.$array['name'].' '.$array['image'].' '.$array['tag'].'</p>';
        }
    }
}
?>
</code>```

Body:
I have an array thusly

$main_array = [

    ["image" => "james.jpg", "name" => "james", "tag" => "spacey, wavy"],
    ["image" => "ned.jpg", "name" => "ned", "tag" => "bright"]
    ["image" => "helen.jpg", "name" => "helen", "tag" => "wavy, bright"]

]

I use a foreach to echo some HTML based on the value of tag. Something like this

    foreach($main_array as $key => $array) {
        if ($array['tag'] == "bright") {
            echo '
'.$array['name'].' '.$array['image'].' '.$array['tag'].'
';
        }
    }

This only outputs "ned" as matching the tag "bright". But it should output "helen" too. Similarly:

    foreach($main_array as $key => $array) {
        if ($array['tag'] == "wavy") {
            echo '
'.$array['name'].' '.$array['image'].' '.$array['tag'].'
';
        }
    }

Should output "james" and "helen". What kind of function do I need to achieve the desired result?

Body:
You cant do it directly, because it return key with values in string. Below are the working code.

<?php
   $main_array = [

    ["image" => "james.jpg", "name" => "james", "tag" => "spacey, wavy"],
    ["image" => "ned.jpg", "name" => "ned", "tag" => "bright"],
    ["image" => "helen.jpg", "name" => "helen", "tag" => "wavy, bright"]

];

foreach($main_array as $key => $array) {
    $str_arr = explode (", ", $array['tag']);
    foreach ($str_arr as $key2 => $array2) {
        if ($array2 == "wavy") {
            echo '<p>'.$array['name'].' '.$array['image'].' '.$array['tag'].'</p>';
        }
    }
}
?>


问:
How to group a dataframe by column and get number of repeating lines?
I want to get a number of sales for each day from my dataframe

I tried to call just df.groupby(['sale_date']).count() but it doesn't compute the numbers.

Source dataframe looks like:

```<code>sale_date, borough, building_class, ...
2003-01-01, ...
2003-01-01, ...
2003-01-02, ...
</code>```

And I want to have a new dataframe which will look like this:

```<code>sale_date, number_sales
2003-01-01, 2
2003-01-02, 1
</code>```

答:
You can groupby all the columns in the dataframe, then take the size to get the number of counts.

```<code>import pandas as pd

df = pd.DataFrame([['a'], ['a'], ['a'], ['b'], ['b'], ['a']],
              columns=['A'])

df['B'] = ['b', 'b', 'b', 'c', 'a', 'c']
print(df)
#    A  B
# 0  a  b
# 1  a  b
# 2  a  b
# 3  b  c
# 4  b  a
# 5  a  c

df = df.groupby(list(df.columns)).size().reset_index()

df.rename(columns = {0: 'number_sales'}, inplace = True)

print(df)

   A  B  number_sales
0  a  b             3
1  a  c             1
2  b  a             1
3  b  c             1
</code>```

Body:
I want to get a number of sales for each day from my dataframe

I tried to call just df.groupby(['sale_date']).count() but it doesn't compute the numbers.

Source dataframe looks like:

sale_date, borough, building_class, ...
2003-01-01, ...
2003-01-01, ...
2003-01-02, ...

And I want to have a new dataframe which will look like this:

sale_date, number_sales
2003-01-01, 2
2003-01-02, 1

Body:
You can groupby all the columns in the dataframe, then take the size to get the number of counts.

import pandas as pd

df = pd.DataFrame([['a'], ['a'], ['a'], ['b'], ['b'], ['a']],
              columns=['A'])

df['B'] = ['b', 'b', 'b', 'c', 'a', 'c']
print(df)
#    A  B
# 0  a  b
# 1  a  b
# 2  a  b
# 3  b  c
# 4  b  a
# 5  a  c

df = df.groupby(list(df.columns)).size().reset_index()

df.rename(columns = {0: 'number_sales'}, inplace = True)

print(df)

   A  B  number_sales
0  a  b             3
1  a  c             1
2  b  a             1
3  b  c             1


问:
How can I pass the current post taxonomy term using ajax?
I'm creating a filter for a wordpress custom post type.  I want to be able to dynamically display more posts using a dropdown.  This works fine.  The issue is that I'm only getting it to work if I hard code the taxonomy term.  I'd like to be able to pass the term dynamically with the number of posts per page that the use has selected.

I've already tried to pass it using a hidden input.  I was able to create the variable and add it to the name attribute but couldn't pull it out on the server side.  I also think that was a hacky way of doing it.

```<code>$args = array(
            'post_type' => 'products',
            'posts_per_page' => $_POST['ppp'],
            'tax_query' => array(
                array(
                    'taxonomy' => 'product-category',
                    'field'    => 'slug',
                    'terms'    => 'terminals'
                ),
            ),
        );
</code>```

```<code><form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
    <select name="ppp">
        <option value="1">Show 12 Per Page</option>
        <option value="2">Show 24 Per Page</option>
        <option value="3">Show 48 Per Page</option>
        <option value="-1">Show All</option>
    </select>
    <!-- <div id = "spinner"></div> -->
    <input type="hidden" name="action" value="myfilter">
</form>
</code>```

```<code>$('#filter').change(function() {
        var filter = $('#filter');
        $.ajax({
            url:filter.attr('action'),
            data:filter.serialize(),
            type:filter.attr('method'),
            beforeSend:function(xhr){
                //show the spinner
            },
            success:function(data){
                //hide the spinner
                $('#response').html(data);
            }
        });
        return false;
    });
</code>```

I'd like to be able to grab the taxonomy term from the current post and pass it to the function through ajax.

答:
I ended up digging into this a bit more based on Twisty's response and what I found I ended up adding the taxonomy term in as a hidden input value:</p>

```<code>$args = array(
            'post_type' => 'products',
            'posts_per_page' => $_POST['ppp'],
            'tax_query' => array(
                array(
                    'taxonomy' => 'product-category',
                    'field'    => 'slug',
                    'terms'    => $_POST['term']
                ),
            ),
        );
</code>```

```<code><form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="tax-filter">
                            <label>
                            <select name="ppp">
                                <option value="12">Show 12 Per Page</option>
                                <option value="24">Show 24 Per Page</option>
                                <option value="48">Show 48 Per Page</option>
                                <option value="-1">Show All</option>
                            </select>
                            <?php //get the post taxonomy term
                            $obj = get_queried_object(); ?>
                            <input type="hidden" name="term" value="<?php echo $obj->slug; ?>">
                            <input type="hidden" name="action" value="myfilter">
                        </form>
</code>```

```<code>$('#tax-filter').change(function() {
    var filter = $('#tax-filter');
    $.ajax({
        url:filter.attr('action'),
        data:filter.serialize(),
        type:filter.attr('method'),
        beforeSend:function(xhr){
            $('#spinner').toggle();
        },
        success:function(data){
            $('#spinner').toggle();
            $('#sortedPosts').html(data);
        }
    });
    //debugging
    //console.log(filter.attr('method'));
    return false;
});
</code>```

Body:
I'm creating a filter for a wordpress custom post type.  I want to be able to dynamically display more posts using a dropdown.  This works fine.  The issue is that I'm only getting it to work if I hard code the taxonomy term.  I'd like to be able to pass the term dynamically with the number of posts per page that the use has selected.

I've already tried to pass it using a hidden input.  I was able to create the variable and add it to the name attribute but couldn't pull it out on the server side.  I also think that was a hacky way of doing it.

$args = array(
            'post_type' => 'products',
            'posts_per_page' => $_POST['ppp'],
            'tax_query' => array(
                array(
                    'taxonomy' => 'product-category',
                    'field'    => 'slug',
                    'terms'    => 'terminals'
                ),
            ),
        );

<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
    <select name="ppp">
        <option value="1">Show 12 Per Page</option>
        <option value="2">Show 24 Per Page</option>
        <option value="3">Show 48 Per Page</option>
        <option value="-1">Show All</option>
    </select>

    <input type="hidden" name="action" value="myfilter">
</form>

$('#filter').change(function() {
        var filter = $('#filter');
        $.ajax({
            url:filter.attr('action'),
            data:filter.serialize(),
            type:filter.attr('method'),
            beforeSend:function(xhr){
                //show the spinner
            },
            success:function(data){
                //hide the spinner
                $('#response').html(data);
            }
        });
        return false;
    });

I'd like to be able to grab the taxonomy term from the current post and pass it to the function through ajax.

Body:
I ended up digging into this a bit more based on Twisty's response and what I found I ended up adding the taxonomy term in as a hidden input value:

$args = array(
            'post_type' => 'products',
            'posts_per_page' => $_POST['ppp'],
            'tax_query' => array(
                array(
                    'taxonomy' => 'product-category',
                    'field'    => 'slug',
                    'terms'    => $_POST['term']
                ),
            ),
        );

<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="tax-filter">
                            <label>
                            <select name="ppp">
                                <option value="12">Show 12 Per Page</option>
                                <option value="24">Show 24 Per Page</option>
                                <option value="48">Show 48 Per Page</option>
                                <option value="-1">Show All</option>
                            </select>
                            <?php //get the post taxonomy term
                            $obj = get_queried_object(); ?>
                            <input type="hidden" name="term" value="<?php echo $obj->slug; ?>">
                            <input type="hidden" name="action" value="myfilter">
                        </form>

$('#tax-filter').change(function() {
    var filter = $('#tax-filter');
    $.ajax({
        url:filter.attr('action'),
        data:filter.serialize(),
        type:filter.attr('method'),
        beforeSend:function(xhr){
            $('#spinner').toggle();
        },
        success:function(data){
            $('#spinner').toggle();
            $('#sortedPosts').html(data);
        }
    });
    //debugging
    //console.log(filter.attr('method'));
    return false;
});


问:
How to convert ablosution position returned from re.finditer to row.column needed for a tkinter Text Widget?
I am using re.finditer to search for words in a tkinter text widget. This returns absolution positions for found items in the string, not row.column.

Now I need to convert this to row.column, however there seems to be no method to do this. However, in researching documentation here, it shows this, which doesn't work and gives the below error, and this which I found no option to do what i need:

```<code>.index(i)

    For an index i, this method returns the equivalent position in the form 'line.char'.
</code>```

Error:

```<code>loc = text.index(11)
Python Debugger 2:02:16 PM
  File "C:\Programs\Python37\lib\tkinter\__init__.py", line 3268, in index
Python Debugger 2:02:16 PM
    return str(self.tk.call(self._w, 'index', index))
</code>```

So, how can I accomplish getting row.column from absolution position?

Background info:
I have config file's I'm trying to search and highlight found items using tags. I'm using the below code to find the start index of the found items as well as the item itself so I know the length (since this uses regex and found items will not necessarily be the same length). I then created an OrderedDict so I can loop through it and highlight all found items.

The problem is that adding a tag doesn't work without absolute position, it requires row.column which I have no way to get from re.finditer.

Relevant code. For testing I am simply passing in StrToFind, and assume this is a long bit of text rows, separated by a \n. I can make it work if it's a long string without any \n's, but then the config being searched is incredibly hard to read.

```<code>import tkinter as tk
import re
import itertools
from collections import OrderedDict

def findStr(strToFind, strBeingSearched):
    '''returns OrderedDict of start locations and the word found'''
    wordlst = re.findall(strToFind, strBeingSearched) #get words found so I can know the length
    lst = [m.start() for m in re.finditer(strToFind, strBeingSearched)] #get index position of each word
    d = OrderedDict(zip(lst, wordlst)) #create ordered dict from 2 lists.
    return d

def btnFindAllClick(event):
    global search, color
    search[color] = findStr('StrToFind', text.get("1.0", tk.END))
    for index, word in search[color].items():
        length = len(word)
        text.tag_add(color, index, index + length) #this is where it breaks because I don't have row.column!

search = {}
color = 'yellow'

root = tk.Tk()
text = tk.Text(root, height=10, wrap="word")
text.pack(fill="both", expand=True)
text.tag_configure(color, background="yellow", foreground="black")
text.tag_raise("sel")

btn = tk.Button(root, text="Find All", width=12)
btn.pack(side="right")
btn.bind("<Button-1>", btnFindAllClick)

root.mainloop()
</code>```

答:
The text widget has a search method which can be used to find the exact line and character position of a match. It would be more efficient than getting all the text, doing a search, and then converting the results to a text widget index.

However, if you want to use your method, and assuming the text widget contains only text, you can have tkinter do some math for you if all you have is a number that represents an offset from zero.

For example, if you have the value 100, and you want to convert that to a proper index, you can use 1.0 + 100 characters (or 1.0+100c).

Thus, in your case you could compute the starting and ending index of the match like this:

```<code>start_index = text.index("1.0+{}c".format(index))
end_index = text.index("{} + {}c".format(start_index, length))
</code>```

Body:
I am using re.finditer to search for words in a tkinter text widget. This returns absolution positions for found items in the string, not row.column.

Now I need to convert this to row.column, however there seems to be no method to do this. However, in researching documentation here, it shows this, which doesn't work and gives the below error, and this which I found no option to do what i need:

.index(i)

    For an index i, this method returns the equivalent position in the form 'line.char'.

Error:

loc = text.index(11)
Python Debugger 2:02:16 PM
  File "C:\Programs\Python37\lib\tkinter\__init__.py", line 3268, in index
Python Debugger 2:02:16 PM
    return str(self.tk.call(self._w, 'index', index))

So, how can I accomplish getting row.column from absolution position?

Background info:
I have config file's I'm trying to search and highlight found items using tags. I'm using the below code to find the start index of the found items as well as the item itself so I know the length (since this uses regex and found items will not necessarily be the same length). I then created an OrderedDict so I can loop through it and highlight all found items.

The problem is that adding a tag doesn't work without absolute position, it requires row.column which I have no way to get from re.finditer.

Relevant code. For testing I am simply passing in StrToFind, and assume this is a long bit of text rows, separated by a \n. I can make it work if it's a long string without any \n's, but then the config being searched is incredibly hard to read.

import tkinter as tk
import re
import itertools
from collections import OrderedDict

def findStr(strToFind, strBeingSearched):
    '''returns OrderedDict of start locations and the word found'''
    wordlst = re.findall(strToFind, strBeingSearched) #get words found so I can know the length
    lst = [m.start() for m in re.finditer(strToFind, strBeingSearched)] #get index position of each word
    d = OrderedDict(zip(lst, wordlst)) #create ordered dict from 2 lists.
    return d

def btnFindAllClick(event):
    global search, color
    search[color] = findStr('StrToFind', text.get("1.0", tk.END))
    for index, word in search[color].items():
        length = len(word)
        text.tag_add(color, index, index + length) #this is where it breaks because I don't have row.column!

search = {}
color = 'yellow'

root = tk.Tk()
text = tk.Text(root, height=10, wrap="word")
text.pack(fill="both", expand=True)
text.tag_configure(color, background="yellow", foreground="black")
text.tag_raise("sel")

btn = tk.Button(root, text="Find All", width=12)
btn.pack(side="right")
btn.bind("<Button-1>", btnFindAllClick)

root.mainloop()

Body:
The text widget has a search method which can be used to find the exact line and character position of a match. It would be more efficient than getting all the text, doing a search, and then converting the results to a text widget index.

However, if you want to use your method, and assuming the text widget contains only text, you can have tkinter do some math for you if all you have is a number that represents an offset from zero.

For example, if you have the value 100, and you want to convert that to a proper index, you can use 1.0 + 100 characters (or 1.0+100c).

Thus, in your case you could compute the starting and ending index of the match like this:

start_index = text.index("1.0+{}c".format(index))
end_index = text.index("{} + {}c".format(start_index, length))


答:
I believe rows you targeted for update in UPDATE statement don't get selected properly, you have to connect updated table and table with averages using INNER JOIN (or just JOIN, which is actually INNER JOIN):

```<code>    UPDATE score_master
    SET avg_score = t.avg_score_group
    FROM
    (
       SELECT AVG(score) AS avg_score_group , sd.customer AS customer
       FROM score_detail as sd
       JOIN score_master as sm
       ON
       sd.customer = sm.customer
       GROUP BY sd.customer
    ) AS t
    JOIN score_master ON score_master.customer = t.customer
</code>```

Here is SQL fiddle: http://sqlfiddle.com/#!18/50cf30/17

Title: AVG function calculates correctly in a SELECT with GROUP BY but not with an UPDATE for some records

Body:
I have a simple detail table listing a customer number and a corresponding score in float format, when I do an average using AVG with Group By customer in a Select, it correctly calculates the score averages for each customer, but if want to update a master table with the customer number with its average score using the original Select, my Update query is calculating averages incorrectly for some of the customers, so I wonder where the error might lie.

Tried to use Cast to decimal with two decimal points in the Update query on the select part of it, as data has 17 decimal points, but issue remains.
This is just a test on 16 records but I have to nail down the issue before continuing.

--AVG used only in Select correctly does the average calculation from the detail (child) table SELECT sd.customer, AVG(score) AS avg_score_group from score_detail as sd
        JOIN score_master as sm ON sd.customer = sm.customer
        GROUP BY sd.customer
    -- Using AVG to actually update the master table with averages from child
    -- table has incorrect calculations for some grouped records
        UPDATE score_master
        SET avg_score = t.avg_score_group
        FROM (
        SELECT AVG(score) AS avg_score_group from score_detail as sd
        JOIN
        score_master as sm
        ON
        sd.customer = sm.customer
        GROUP BY sd.customer
        ) AS t
    --Let us explore master table
        SELECT * FROM  score_master;
--Table structures:
CREATE TABLE [dbo].[score_detail](
[customer] [float] NULL,
[score] [float] NULL
) ON [PRIMARY]

CREATE TABLE [dbo].[score_master](
[customer] [float] NULL,
[avg_score] [float] NULL
) ON [PRIMARY]
-- Data to calculate average has 17 Decimal points:
INSERT [dbo].[score_detail] ([customer], [score]) VALUES (2, -0.07216878364870323)

I would expect the same results in the Select-only from detail table to appear in the Update query for the master table, but some are not correct, i.e. customers 4 and 7:

Cust No -   Avg in Detail table     - Avg in Master table
2           -0.0681                 -0.0681
4            0.0000                  0.1127
7            0.0184                 -0.0681
16           0.1127                  0.1127

Body:
I believe rows you targeted for update in UPDATE statement don't get selected properly, you have to connect updated table and table with averages using INNER JOIN (or just JOIN, which is actually INNER JOIN):

    UPDATE score_master
    SET avg_score = t.avg_score_group
    FROM
    (
       SELECT AVG(score) AS avg_score_group , sd.customer AS customer
       FROM score_detail as sd
       JOIN score_master as sm
       ON
       sd.customer = sm.customer
       GROUP BY sd.customer
    ) AS t
    JOIN score_master ON score_master.customer = t.customer

Here is SQL fiddle: http://sqlfiddle.com/#!18/50cf30/17


问:
Removing overlapping polygons, too many points
I have many points of data. In fact, too many points. None of the points are overlapping but some are quite near to each other. I'd like to have less points but without moving any of the locations.

I'd to end up with as many points as possible but only points which are at least ~5.7km apart from any other point. (if there is a little bit of overlap it's okay -- an error of 0.5km is acceptable)

I tried to write an algorithm in R to accomplish this but there are quite a few unexpected results. I have some data that is about 300,000 points covering the earth. I have some other data that is a few million. When I execute the algorithm I can segment the data by country which could reduce those numbers into the 20,000 to 100,000 range. If the location of the points didn't matter then I would probably just make an interpolated raster and call it good but for this problem I need to keep the specific location intact.

Another thing that I tried is to make a regular grid of 0.028 degrees and run NNJoin to find the nearest data point. This worked a bit better than my R code but the results are a bit funny as you can probably imagine.

Another idea I had was to Buffer the points the count how many of the points intersect with the Buffered layer. I'm still working on this one

Is there an already established method for arriving at this result? I am comfortable to work with PostGIS, QGIS, Python, R if there is a package or library that can do this.

tl;dr how do I reduce dense clusters of points but maintain coverage with a reduced set of points?

答:
Here is an approach.

Example data

```<code>x <- runif(10000, -180, 180)
y <- runif(10000, -90, 90)
pts <- cbind(x, y)
</code>```

Solution

```<code>library(raster)
# you will want a lower resolution than this
r <- raster(nrow=18, ncol=36, vals=1)
# get cell numbers
cells <- cellFromXY(r, pts)
# pick one point per cell
sel <- aggregate(pts, list(cells), function(i)i[1])  # or sample
</code>```

Let's see

```<code>plot(r)
points(pts, cex=.1)
points(sel[,2:3], pch=20, col="red")
</code>```

Note that this use lon/lat so the distances are not the same across latitudes. Not sure if that matters; but if so you could transform.

Later:

There are several ways to create shifted variations by changing the extent, or when creating the RasterLayer. See ?raster and ?extent for more. You can also use shift

```<code>#add a row and a column
r1 <- raster(nrow=19, ncol=37, xmx=190, ymn=-100)
r2 <- shift(r1, -.5*xres(r1), -.5*yres(r1))

plot(as(r1, "SpatialPolygons"))
lines(as(r2, "SpatialPolygons"), col="red")
</code>```

Body:
Here is an approach.

Example data

x <- runif(10000, -180, 180)
y <- runif(10000, -90, 90)
pts <- cbind(x, y)

Solution

library(raster)
# you will want a lower resolution than this
r <- raster(nrow=18, ncol=36, vals=1)
# get cell numbers
cells <- cellFromXY(r, pts)
# pick one point per cell
sel <- aggregate(pts, list(cells), function(i)i[1])  # or sample

Let's see

plot(r)
points(pts, cex=.1)
points(sel[,2:3], pch=20, col="red")

Note that this use lon/lat so the distances are not the same across latitudes. Not sure if that matters; but if so you could transform.

Later:

There are several ways to create shifted variations by changing the extent, or when creating the RasterLayer. See ?raster and ?extent for more. You can also use shift

#add a row and a column
r1 <- raster(nrow=19, ncol=37, xmx=190, ymn=-100)
r2 <- shift(r1, -.5*xres(r1), -.5*yres(r1))

plot(as(r1, "SpatialPolygons"))
lines(as(r2, "SpatialPolygons"), col="red")


问:
ImportError: cannot import name 'enums'
I am trying to use Google Speech API to recognize speech from mic input in real time. I have tried https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/speech/cloud-client/transcribe_streaming_mic.py
 but this error came out. Anybody knows how to solve this?

```<code>from google.cloud.speech import enums
ImportError: cannot import name 'enums'
</code>```

Update:
I have solved the problem by running the code in virtual environment as suggested by the official Cloud Speech API website. However, I still dont understand why we need to run that in virtual environment instead of my original environment as the virtual environment is not Linux or other OS.

答:
I am using cloud function to transcribe the audio to text.
I believe the documentation for google-cloud-speech has been updated, you may refer to the documentation. https://pypi.org/project/google-cloud-speech/. I believe the class is now called speech_v1, you can use the alias "as speech" to make the github sample codes work.

```<code>from google.cloud import speech_v1 as speech
from google.cloud.speech_v1 import enums
from google.cloud.speech_v1 import types
</code>```

HTH.

Title: ImportError: cannot import name 'enums'

Body:
I am trying to use Google Speech API to recognize speech from mic input in real time. I have tried https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/speech/cloud-client/transcribe_streaming_mic.py
 but this error came out. Anybody knows how to solve this?

from google.cloud.speech import enums
ImportError: cannot import name 'enums'

Update:
I have solved the problem by running the code in virtual environment as suggested by the official Cloud Speech API website. However, I still dont understand why we need to run that in virtual environment instead of my original environment as the virtual environment is not Linux or other OS.

Body:
I am using cloud function to transcribe the audio to text.
I believe the documentation for google-cloud-speech has been updated, you may refer to the documentation. https://pypi.org/project/google-cloud-speech/. I believe the class is now called speech_v1, you can use the alias "as speech" to make the github sample codes work.

from google.cloud import speech_v1 as speech
from google.cloud.speech_v1 import enums
from google.cloud.speech_v1 import types

HTH.