问:
Combine two lists of different lengths in python
I have 2 lists of different length.
A gift is selected and assigned to a name, then the next gift will be given to the next name, and so on, in the circle, until the gifts are finished.

```<code>gifts = ['pencil', 'pen', 'book', 'notebook', 'pencil_box', 'schoolbag', 'stick']
name = ['John', 'Marcus', 'Marie']
</code>```

Expected Output:

```<code>John: pencil notebook stick
Marcus: pen pencil_box
Marie: book schoolbag
</code>```

Another example:

```<code>gifts  = ['car', 'house', 'phone']
name = ['RichieRich']
</code>```

Expected Output:

```<code>RichieRich: car house phone
</code>```

Some help?

答:
This is possible using for loops:

count = 0
kids = [yourkids]
gifts = [yourgifts]
outputKids = kids
for gift in gifts:
    if count > kids.length:
        count = 0;
    outputKids[count].push(gift)
    count = count + 1
```

Then just map your "kids' array to your "outputKids" (index-wise) and you have the gifts for each kid.

Body:
I have 2 lists of different length.
A gift is selected and assigned to a name, then the next gift will be given to the next name, and so on, in the circle, until the gifts are finished.

gifts = ['pencil', 'pen', 'book', 'notebook', 'pencil_box', 'schoolbag', 'stick']
name = ['John', 'Marcus', 'Marie']

Expected Output:

John: pencil notebook stick
Marcus: pen pencil_box
Marie: book schoolbag

Another example:

gifts  = ['car', 'house', 'phone']
name = ['RichieRich']

Expected Output:

RichieRich: car house phone

Some help?

Body:
This is possible using for loops:

count = 0
kids = [yourkids]
gifts = [yourgifts]
outputKids = kids
for gift in gifts:
    if count > kids.length:
        count = 0;
    outputKids[count].push(gift)
    count = count + 1

Then just map your "kids' array to your "outputKids" (index-wise) and you have the gifts for each kid.


来源: stackexchange

问:
How to authorise a role to perform "execute-api:Invoke"?
I'm attempting to move a suite of end-to-end tests so that they are fully contained within AWS. I've done this through code build and gotten everything running up to the point of running the tests, which invoke an API to reset the database before every test run. I keep running into this error message when the first test attempts to run.

StatusCodeError: 403 - "{\"Message\":\"User: anonymous is not authorized to perform: execute-api:Invoke on resource: arn:aws:execute-api:eu-west-2:*:*"}"
```

<p>At first, I thought the error was being caused by a lack of permissions on the role that was being used to build everything. I tried adding the correct permissions to IAM Role being used, eventual making them more open than I would like. </p>

```"Effect": "Allow",
"Action": [
    "execute-api:Invoke",
    "execute-api:ManageConnections"
],
"Resource": "arn:aws:execute-api:*:*:*"
```

<p>Obviously didn't fix things but I did notice that the access advisor shows that the particular policy isn't being accessed.</p>

<p>Next, I went into the resource policy in API Gateway to see if there was something there. I removed some Ip Address conditions that were set up to restrict access to the office's Ip Addresses. </p>

<p>I've look inside of WAF and Shield and can't see anything that would be related to invoking the API. At this point I am at a lost on where my next investigation should start.</p>

<p><strong><em>Edit</em></strong></p>

<p>Here's the responce I'm getting back.</p>

```"requestId": "********-82f8-11e9-a732-0b550cf3fcd6",
"ip": "*.*.*.*",
"caller": "-",
"user": "-",
"requestTime": "30/May/2019:16:32:50 +0000",
"httpMethod": "GET",
"resourcePath": "/*/ref-data/{proxy+}", "status": "403", "protocol": "HTTP/1.1", "responseLength": "185"
```

答:
Your role's policy which allows execute-api:Invoke appears to be correct, but the error message you provided says User: anonymous is not authorized to perform.... If you're expecting your role to be attempting this action, then something is wrong because your attempting the action with a user named anonymous.

The role that you use to build your stack isn't necessarily the role that is used to execute functions on that stack. I recommend you double check all of your IAM entities throughout and clearly identify and understand what each one is attempting to do. Make sure that whatever is invoking your function is actually the role you want with the correct policy attached.

Hope this helps!

ContentLicense: CC BY-SA 4.0

Body:
I'm attempting to move a suite of end-to-end tests so that they are fully contained within AWS. I've done this through code build and gotten everything running up to the point of running the tests, which invoke an API to reset the database before every test run. I keep running into this error message when the first test attempts to run.

StatusCodeError: 403 - "{\"Message\":\"User: anonymous is not authorized to perform: execute-api:Invoke on resource: arn:aws:execute-api:eu-west-2:*:*"}"

At first, I thought the error was being caused by a lack of permissions on the role that was being used to build everything. I tried adding the correct permissions to IAM Role being used, eventual making them more open than I would like.

"Effect": "Allow",
"Action": [
    "execute-api:Invoke",
    "execute-api:ManageConnections"
],
"Resource": "arn:aws:execute-api:*:*:*"

Obviously didn't fix things but I did notice that the access advisor shows that the particular policy isn't being accessed.

Next, I went into the resource policy in API Gateway to see if there was something there. I removed some Ip Address conditions that were set up to restrict access to the office's Ip Addresses.

I've look inside of WAF and Shield and can't see anything that would be related to invoking the API. At this point I am at a lost on where my next investigation should start.

Edit

Here's the responce I'm getting back.

"requestId": "********-82f8-11e9-a732-0b550cf3fcd6",
"ip": "*.*.*.*",
"caller": "-",
"user": "-",
"requestTime": "30/May/2019:16:32:50 +0000",
"httpMethod": "GET",
"resourcePath": "/*/ref-data/{proxy+}", "status": "403", "protocol": "HTTP/1.1", "responseLength": "185"


问:
Creating an editable HTML table from 2D array
So I am trying to make a flashcards website, where users can add, edit, and delete flashcards. There are two cards - front and back. The user can already add words, but cannot edit or delete them. For the purposes of this question I will use an example array:

```<code>var flashcards = [["Uomo", "Man"],["Donna", "Woman"],["Ragazzo", "Boy"]]
</code>```

But I would like a more user-friendly way to edit the flashcards, preferably using a table like this:

```<code><table>
  <tr>
    <th>Front</th>
    <th>Back</th>
  </tr>
  <tr>
    <td><input type="text" name="flashcard" value="Uomo"> </td>
    <td><input type="text" name="flashcard" value="Man"></td>
  </tr>
    <tr>
    <td><input type="text" name="flashcard" value="Donna"></td>
    <td><input type="text" name="flashcard" value="Woman"></td>
  </tr>
      <tr>
    <td><input type="text" name="flashcard" value="Ragazzo"></td>
    <td><input type="text" name="flashcard" value="Boy"></td>
  </tr>
</table>

<button type="button">Add more</button>
<br>
<button type="button">Save changes</button>
</code>```

So they can update their flashcards editing the input fields, or clicking "add more" and it creating a new row. Clicking "save changes" updates the array to the content of the table.

I don't mind it not being a HTML table per se, but something that is easy to edit for the user.

I just cannot figure out the best way to approach this. Any advice?

答:
I've put together a working sample using pure native javascript with a data-driven approach. You can have a look and understand the way how data should be manipulated and worked with in large Js application.

The point here is to isolate the data and logic as much as possible.

Hope this help.

Codepen: https://codepen.io/DieByMacro/pen/rgQBPZ

(function() {
  /**
   * Default value for Front and Back
   */
  const DEFAULT = {
    front: '',
    back: '',
  }

  /**
   * Class Card: using for holding value of front and back.
   * As well as having `update` method to handle new value
   * from input itself.
   */
  class Card {
    constructor({front, back, id} = {}) {
      this.front = front || DEFAULT.front;
      this.back = back || DEFAULT.back;
      this.id = id;
    }

    update = (side, value) => this[side] = value;
  }

  /**
   * Table Class: handle rendering data and update new value
   * according to the instance of Card.
   */
  class Table {
    constructor() {
      this.init();
    }

    /** Render basic table and heading of table */
    init = () => {
      const table = document.querySelector('#table');
      const thead = document.createElement('tr');
      const theadContent = this.renderRow('th', thead, { front: 'Front', back: 'Back' })
      const tbody = document.createElement('tbody');

      table.appendChild(theadContent);
      table.appendChild(tbody);
    }

    /** Handling add event from Clicking on Add button
     * Note the `update: updateFnc` line, this means we will refer
     * `.update()` method of Card instance with `updateFnc()`, this is
     * used for update value Card instance itself.
     */
    add = ({front, back, id, update: updateFnc }) => {
      const tbody = document.querySelector('#table tbody');
      const row = document.createElement('tr');
      const rowWithInput = this.renderRow('td', row, {front, back, id, updateFnc});
      tbody.appendChild(rowWithInput);
    }

    renderInput = (side, id, fnc) => {
      const input = document.createElement('input');
      input.setAttribute('type','text');
      input.setAttribute('name',`${side}-value-${id}`)
      input.addEventListener('change', e => this.onInputChangeHandler(e, side, fnc));

      return input;
    }

    renderRow = ( tag, parent, { front, back, id, updateFnc }) => {
      const frontColumn = document.createElement( tag );
      const backColumn = document.createElement( tag );

      /** Conditionally rendering based on `tag` type */
      if ( tag === 'th') {
        frontColumn.innerText = front;
        backColumn.innerText = back;
      }else {
        /** Create two new inputs for each Card instance. Each handle
         * each side (front, back)
         */
        const inputFront = this.renderInput('front', id, updateFnc);
        const inputBack = this.renderInput('back', id, updateFnc);

        frontColumn.appendChild(inputFront);
        backColumn.appendChild(inputBack);
      }

      parent.appendChild(frontColumn)
      parent.appendChild(backColumn)

      return parent;
    }

    /** Getting new value and run `.update()` method of Card, now referred as `fnc` */
    onInputChangeHandler = (event, side, fnc) => {
      fnc(side, event.target.value);
    }
  }

  class App {
    /**
     * Holding cards data
     * Notice this is an object, not an array
     * Working with react for a while, I see most of the times data as an object works best when it comes to cRUD, this means we don't have to iterate through the array to find the specific element/item to do the work. This saves a lot of time
     */
    cards = {};

    constructor(){
      this.domTable = new Table();
      this.domAdd = document.querySelector('#btn-add');
      this.domResult = document.querySelector('#btn-result');

      this.domAdd.addEventListener('click', this.onClickAddHandler );
      this.domResult.addEventListener('click', this.onClickResultHandler );
    }

    onClickAddHandler = () => {
      const id = uuid();
      const newCard = new Card({id});
      this.cards[id] = newCard;
      this.domTable.add(newCard)
    }

    onClickResultHandler = () => {
      /**
       * Using `for ... in ` with object. Or you can use 3rd party like lodash for iteration
       */
      for (const id in this.cards) {
        console.log({
          front: this.cards[id].front,
          back: this.cards[id].back,
          id: this.cards[id].id
        });
      }
    };
  }

  // Start the application
  const app = new App();
})();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/node-uuid/1.4.8/uuid.min.js"></script>
<div id="table"></div>
<button id="btn-add">Add</button>
<button id="btn-result">Result</button></code>```

Body:
So I am trying to make a flashcards website, where users can add, edit, and delete flashcards. There are two cards - front and back. The user can already add words, but cannot edit or delete them. For the purposes of this question I will use an example array:

var flashcards = [["Uomo", "Man"],["Donna", "Woman"],["Ragazzo", "Boy"]]

But I would like a more user-friendly way to edit the flashcards, preferably using a table like this:

    Front
    Back

    <input type="text" name="flashcard" value="Uomo">
    <input type="text" name="flashcard" value="Man">

    <input type="text" name="flashcard" value="Donna">
    <input type="text" name="flashcard" value="Woman">

    <input type="text" name="flashcard" value="Ragazzo">
    <input type="text" name="flashcard" value="Boy">

<button type="button">Add more</button>

<button type="button">Save changes</button>

So they can update their flashcards editing the input fields, or clicking "add more" and it creating a new row. Clicking "save changes" updates the array to the content of the table.

I don't mind it not being a HTML table per se, but something that is easy to edit for the user.

I just cannot figure out the best way to approach this. Any advice?

Body:
I've put together a working sample using pure native javascript with a data-driven approach. You can have a look and understand the way how data should be manipulated and worked with in large Js application.

The point here is to isolate the data and logic as much as possible.

Hope this help.

Codepen: https://codepen.io/DieByMacro/pen/rgQBPZ

(function() {
  /**
   * Default value for Front and Back
   */
  const DEFAULT = {
    front: '',
    back: '',
  }

  /**
   * Class Card: using for holding value of front and back.
   * As well as having `update` method to handle new value
   * from input itself.
   */
  class Card {
    constructor({front, back, id} = {}) {
      this.front = front || DEFAULT.front;
      this.back = back || DEFAULT.back;
      this.id = id;
    }

    update = (side, value) => this[side] = value;
  }

  /**
   * Table Class: handle rendering data and update new value
   * according to the instance of Card.
   */
  class Table {
    constructor() {
      this.init();
    }

    /** Render basic table and heading of table */
    init = () => {
      const table = document.querySelector('#table');
      const thead = document.createElement('tr');
      const theadContent = this.renderRow('th', thead, { front: 'Front', back: 'Back' })
      const tbody = document.createElement('tbody');

      table.appendChild(theadContent);
      table.appendChild(tbody);
    }

    /** Handling add event from Clicking on Add button
     * Note the `update: updateFnc` line, this means we will refer
     * `.update()` method of Card instance with `updateFnc()`, this is
     * used for update value Card instance itself.
     */
    add = ({front, back, id, update: updateFnc }) => {
      const tbody = document.querySelector('#table tbody');
      const row = document.createElement('tr');
      const rowWithInput = this.renderRow('td', row, {front, back, id, updateFnc});
      tbody.appendChild(rowWithInput);
    }

    renderInput = (side, id, fnc) => {
      const input = document.createElement('input');
      input.setAttribute('type','text');
      input.setAttribute('name',`${side}-value-${id}`)
      input.addEventListener('change', e => this.onInputChangeHandler(e, side, fnc));

      return input;
    }

    renderRow = ( tag, parent, { front, back, id, updateFnc }) => {
      const frontColumn = document.createElement( tag );
      const backColumn = document.createElement( tag );

      /** Conditionally rendering based on `tag` type */
      if ( tag === 'th') {
        frontColumn.innerText = front;
        backColumn.innerText = back;
      }else {
        /** Create two new inputs for each Card instance. Each handle
         * each side (front, back)
         */
        const inputFront = this.renderInput('front', id, updateFnc);
        const inputBack = this.renderInput('back', id, updateFnc);

        frontColumn.appendChild(inputFront);
        backColumn.appendChild(inputBack);
      }

      parent.appendChild(frontColumn)
      parent.appendChild(backColumn)

      return parent;
    }

    /** Getting new value and run `.update()` method of Card, now referred as `fnc` */
    onInputChangeHandler = (event, side, fnc) => {
      fnc(side, event.target.value);
    }
  }

  class App {
    /**
     * Holding cards data
     * Notice this is an object, not an array
     * Working with react for a while, I see most of the times data as an object works best when it comes to cRUD, this means we don't have to iterate through the array to find the specific element/item to do the work. This saves a lot of time
     */
    cards = {};

    constructor(){
      this.domTable = new Table();
      this.domAdd = document.querySelector('#btn-add');
      this.domResult = document.querySelector('#btn-result');

      this.domAdd.addEventListener('click', this.onClickAddHandler );
      this.domResult.addEventListener('click', this.onClickResultHandler );
    }

    onClickAddHandler = () => {
      const id = uuid();
      const newCard = new Card({id});
      this.cards[id] = newCard;
      this.domTable.add(newCard)
    }

    onClickResultHandler = () => {
      /**
       * Using `for ... in ` with object. Or you can use 3rd party like lodash for iteration
       */
      for (const id in this.cards) {
        console.log({
          front: this.cards[id].front,
          back: this.cards[id].back,
          id: this.cards[id].id
        });
      }
    };
  }

  // Start the application
  const app = new App();
})();

<script src="https://cdnjs.cloudflare.com/ajax/libs/node-uuid/1.4.8/uuid.min.js"></script>
<div id="table"></div>
<button id="btn-add">Add</button>
<button id="btn-result">Result</button>


问:
Compile throws a "User-defined type not defined" error but does not go to the offending line of code

Symptoms

This is a symptom specifically when compiling an Excel VBA project. The following error occurs:

User-defined type not defined

However, the code that produces this error is not highlighted by the compiler and so I cannot identify the issue.

What I already know and have tried

This is a "User-defined type not defined" error that I have seen before with simple issues such as naming something As Strig instead of As String. However, this particular error is only popping up during the Debug > Compile VBAProject menu option and when the error message box pops up it does not highlight the line of code that the error is occurring in.

After a lot of research I have found that this bug can be related to missing references and I have ruled this out as I have included all needed references and Toolbox objects.

To ensure I wasn't missing any obvious missing Dim statements I have added Option Explicit to all code pages (forms included) to make sure nothing was missing. The error still shows when running a compile.

There is also this known bug that states the issue has been known to happen because of the VB6 projects using binary compatibility:

Turn off Binary Compatibility and compile the project. Visual Basic
  will highlight the line of code that contains the User Defined Type
  that is not defined. After resolving the problem, Binary Compatibility
  can be turned back on.

I found this article via this Question and Answer, however, I cannot find this option in the standard Excel VBA editor.

Help save mine and others' sanity!

I know from Google searches and other questions that I am not the only one who has had this issue.

I have tried going through the code manually but there are simply too many lines to feasibly do so.

Is there a way of turning off Binary Compatibility in Excel VBA projects? How do people find this offending line of code if they can't debug to what they need to change? Any help would be lovely!

Thank you in advance.

Edit: I have found the offending line of code and so my particular issue is solved The problem is still here after removing that particular line - it was a misspelt control name on a form being referenced in its code. This still does not solve the particular issue of how you would go about finding this offending code was the issue. Are we able to find a good way of finding the offending code when this bug happens so others in the future can avoid this agony?

答:
I had this same problem when I inherited another analyst's workbook. He assigned macros to each button on his worksheet. When I changed the name of the module (not the procedure name), it kicked up this error.
  The fix was easy. Have the button run an _OnClick() event procedure in the worksheet and have that procedure explicitly Call MyProcedureName().


问:
Error: Schema validation failed with the following errors: Data path "" should NOT have additional properties(project)
After migrating application from angular 5 to 6, on running ng serve the following errors pop up.

Schema validation failed with the following errors:
    Data path "" should NOT have additional properties(project).
  Error: Schema validation failed with the following errors:
    Data path "" should NOT have additional properties(project).
      at MergeMapSubscriber._registry.compile.pipe.operators_1.concatMap.validatorResult [as project] (.../TemplateApp/me-cmf-web-template-angular/node_modules/@angular-devkit/core/src/workspace/workspace.js:210:42)
      at MergeMapSubscriber._tryNext (/.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/mergeMap.js:65:27)
      at MergeMapSubscriber._next (.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/mergeMap.js:55:18)
      at MergeMapSubscriber.Subscriber.next (/home/training/Attinad_Projects/TemplateApp/me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:64:18)
      at MergeMapSubscriber.notifyNext (.../TemplateApp/me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/mergeMap.js:84:26)
      at InnerSubscriber._next (.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/InnerSubscriber.js:25:21)
      at InnerSubscriber.Subscriber.next (/.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:64:18)
      at MapSubscriber._next (.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/map.js:52:26)
      at MapSubscriber.Subscriber.next (/.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:64:18)
      at SwitchMapSubscriber.notifyNext (.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:77:26)

I assume that the error is with .angular.json file which I re-named from .angular-cli.json .

My .angular.json file is as follows :

```<code>{
    "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
    "project": {
        "name": "mediaweb"
    },
    "apps": [{
            "root": "src",
            "outDir": "dist/browser",
            "assets": [
                "assets",
                "favicon.ico"
            ],
            "index": "index.html",
            "main": "main.ts",
            "polyfills": "polyfills.ts",
            "test": "test.ts",
            "tsconfig": "tsconfig.app.json",
            "testTsconfig": "tsconfig.spec.json",
            "prefix": "app",
            "styles": [
                "styles.scss",
                "../node_modules/owl.carousel/dist/assets/owl.carousel.css",
                "../node_modules/owl.carousel/dist/assets/owl.theme.default.css",
                "../node_modules/video.js/dist/video-js.css"
            ],
            "scripts": [
                "../node_modules/jquery/dist/jquery.js",
                "../node_modules/owl.carousel/dist/owl.carousel.js",
                "../node_modules/video.js/dist/ie8/videojs-ie8.js",
                "../node_modules/video.js/dist/video.js"
            ],
            "environmentSource": "environments/environment.ts",
            "environments": {
                "dev": "environments/environment.dev.ts",
                "prod": "environments/environment.prod.ts"
            }
        },
        {
            "platform": "server",
            "root": "src",
            "outDir": "dist/server",
            "assets": [
                "assets",
                "favicon.ico"
            ],
            "index": "index.html",
            "main": "main.server.ts",
            "test": "test.ts",
            "tsconfig": "tsconfig.server.json",
            "testTsconfig": "tsconfig.spec.json",
            "prefix": "app",
            "styles": [
                "styles.scss"
            ],
            "scripts": [],
            "environmentSource": "environments/environment.ts",
            "environments": {
                "dev": "environments/environment.dev.ts",
                "prod": "environments/environment.prod.ts"
            }
        }
    ],
    "e2e": {
        "protractor": {
            "config": "./protractor.conf.js"
        }
    },
    "lint": [{
            "project": "src/tsconfig.app.json",
            "exclude": ["**/node_modules/**", "**/UI/**"]
        },
        {
            "project": "src/tsconfig.spec.json",
            "exclude": "**/node_modules/**"
        },
        {
            "project": "e2e/tsconfig.e2e.json",
            "exclude": "**/node_modules/**"
        }
    ],
    "test": {
        "karma": {
            "config": "./karma.conf.js"
        }
    },
    "defaults": {
        "styleExt": "scss",
        "component": {}
    }
}
</code>```

Should I re-structure the json file, if so how?.

Any help would be great.

答:
Updating npm and angular fixed mine:

Assuming you use npm

```<code>npm update
</code>```

then run:

```<code>ng update
</code>```

NB: You might be prompted to update individual dependencies. In my case, I was prompted to run:

ng update @angular/cli and ng update @angular/core.

Body:
After migrating application from angular 5 to 6, on running ng serve the following errors pop up.

Schema validation failed with the following errors:
    Data path "" should NOT have additional properties(project).
  Error: Schema validation failed with the following errors:
    Data path "" should NOT have additional properties(project).
      at MergeMapSubscriber._registry.compile.pipe.operators_1.concatMap.validatorResult [as project] (.../TemplateApp/me-cmf-web-template-angular/node_modules/@angular-devkit/core/src/workspace/workspace.js:210:42)
      at MergeMapSubscriber._tryNext (/.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/mergeMap.js:65:27)
      at MergeMapSubscriber._next (.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/mergeMap.js:55:18)
      at MergeMapSubscriber.Subscriber.next (/home/training/Attinad_Projects/TemplateApp/me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:64:18)
      at MergeMapSubscriber.notifyNext (.../TemplateApp/me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/mergeMap.js:84:26)
      at InnerSubscriber._next (.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/InnerSubscriber.js:25:21)
      at InnerSubscriber.Subscriber.next (/.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:64:18)
      at MapSubscriber._next (.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/map.js:52:26)
      at MapSubscriber.Subscriber.next (/.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:64:18)
      at SwitchMapSubscriber.notifyNext (.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:77:26)

I assume that the error is with .angular.json file which I re-named from .angular-cli.json .

My .angular.json file is as follows :

{
    "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
    "project": {
        "name": "mediaweb"
    },
    "apps": [{
            "root": "src",
            "outDir": "dist/browser",
            "assets": [
                "assets",
                "favicon.ico"
            ],
            "index": "index.html",
            "main": "main.ts",
            "polyfills": "polyfills.ts",
            "test": "test.ts",
            "tsconfig": "tsconfig.app.json",
            "testTsconfig": "tsconfig.spec.json",
            "prefix": "app",
            "styles": [
                "styles.scss",
                "../node_modules/owl.carousel/dist/assets/owl.carousel.css",
                "../node_modules/owl.carousel/dist/assets/owl.theme.default.css",
                "../node_modules/video.js/dist/video-js.css"
            ],
            "scripts": [
                "../node_modules/jquery/dist/jquery.js",
                "../node_modules/owl.carousel/dist/owl.carousel.js",
                "../node_modules/video.js/dist/ie8/videojs-ie8.js",
                "../node_modules/video.js/dist/video.js"
            ],
            "environmentSource": "environments/environment.ts",
            "environments": {
                "dev": "environments/environment.dev.ts",
                "prod": "environments/environment.prod.ts"
            }
        },
        {
            "platform": "server",
            "root": "src",
            "outDir": "dist/server",
            "assets": [
                "assets",
                "favicon.ico"
            ],
            "index": "index.html",
            "main": "main.server.ts",
            "test": "test.ts",
            "tsconfig": "tsconfig.server.json",
            "testTsconfig": "tsconfig.spec.json",
            "prefix": "app",
            "styles": [
                "styles.scss"
            ],
            "scripts": [],
            "environmentSource": "environments/environment.ts",
            "environments": {
                "dev": "environments/environment.dev.ts",
                "prod": "environments/environment.prod.ts"
            }
        }
    ],
    "e2e": {
        "protractor": {
            "config": "./protractor.conf.js"
        }
    },
    "lint": [{
            "project": "src/tsconfig.app.json",
            "exclude": ["**/node_modules/**", "**/UI/**"]
        },
        {
            "project": "src/tsconfig.spec.json",
            "exclude": "**/node_modules/**"
        },
        {
            "project": "e2e/tsconfig.e2e.json",
            "exclude": "**/node_modules/**"
        }
    ],
    "test": {
        "karma": {
            "config": "./karma.conf.js"
        }
    },
    "defaults": {
        "styleExt": "scss",
        "component": {}
    }
}

Should I re-structure the json file, if so how?.

Any help would be great.

Body:
Updating npm and angular fixed mine:

Assuming you use npm

npm update

then run:

ng update

NB: You might be prompted to update individual dependencies. In my case, I was prompted to run:

ng update @angular/cli and ng update @angular/core.


问:
How to start mapping a nested json from a certain index and map it back to that index-1 value

I want to map my nested json from a certain index

For example if my json is the following:

```<code>{"data":[{id:1,name:"NAV"},{id:2,name:"Rick"},{id:3,name:"Ceil"}]}
</code>```

I want to start mapping this json from 1st index i.e. id =1 name :rick
and map it till nav so the mapping is in the following order:

{id:2,name:"Rick"}

{id:3,name:"Ceil"}

{id:1,name:"NAV"}

Something like a circular array or queue
I have no idea how to implement this mapping in react native or js.

How I am currently mapping my json

```<code>renderArtciles=()=>{

  return this.state.dataSource.map((item,i)=>{
    <Animated.View key={item._id} >
      <View style={styles.Imagebody}>
        <Image source={{ uri:item.img.data }} style{styles.image}/>
      </View>

      <View  style={styles.inner}>
        <ShareItem id={item._id} />
        <View style={styles.inner}>
          <Text style={styles.titleArrtibute}>Trending</Text>
          <Text style={styles.titleText} >{item.title}</Text>
          <View>
            <Text style={styles.body}>{item.body}</Text>
          </View>
        </View>
      </View >
    </Animated.View>
  });
}
</code>```

答:
I don't know if there's a way to do it with .map (my instinct is no) but you could do something like the below with a for loop:

```<code>    let index = 1; //whatever index you want to start from
    for (let i = 0; i < data.length; i++) {
        //do all of your stuff referencing data[index] not data[i]
        //at the end of whatever do:
        index === data.length - 1 ? index = 0 : index++;
    }
</code>```

Give it a go, something along these lines should work.

Note: This uses the array index, and not your object id.

Body:
I want to map my nested json from a certain index

For example if my json is the following:

{"data":[{id:1,name:"NAV"},{id:2,name:"Rick"},{id:3,name:"Ceil"}]}

I want to start mapping this json from 1st index i.e. id =1 name :rick
and map it till nav so the mapping is in the following order:

{id:2,name:"Rick"}

{id:3,name:"Ceil"}

{id:1,name:"NAV"}

Something like a circular array or queue
I have no idea how to implement this mapping in react native or js.

How I am currently mapping my json

renderArtciles=()=>{

  return this.state.dataSource.map((item,i)=>{
    <Animated.View key={item._id} >
      <View style={styles.Imagebody}>
        <Image source={{ uri:item.img.data }} style{styles.image}/>
      </View>

      <View  style={styles.inner}>
        <ShareItem id={item._id} />
        <View style={styles.inner}>
          <Text style={styles.titleArrtibute}>Trending</Text>
          <Text style={styles.titleText} >{item.title}</Text>
          <View>
            <Text style={styles.body}>{item.body}</Text>
          </View>
        </View>
      </View >
    </Animated.View>
  });
}

Body:
I don't know if there's a way to do it with .map (my instinct is no) but you could do something like the below with a for loop:

    let index = 1; //whatever index you want to start from
    for (let i = 0; i < data.length; i++) {
        //do all of your stuff referencing data[index] not data[i]
        //at the end of whatever do:
        index === data.length - 1 ? index = 0 : index++;
    }

Give it a go, something along these lines should work.

Note: This uses the array index, and not your object id.


问:
DRF ImageField Inconsistent behavior
I'm creating a Django API with DRF. I have a custom User Model like this :

models.py :

from typing import Type, List
from uuid import uuid4
from django.db import models
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from django.utils.translation import ugettext_lazy as _
from django_extensions.db.models import TimeStampedModel

from main.apps.user.managers import UserManager

def to_profile_picture(instance: "User", filename: str) -> str:
    return f"profile_pictures/{instance.email}/{uuid4()}_{filename}"

class User(AbstractBaseUser, TimeStampedModel, PermissionsMixin):
    email = models.EmailField(_("Email Address"), unique=True)
    first_name = models.CharField(
        _("First Name"), max_length=128, blank=True, null=True
    )
    last_name = models.CharField(_("Last Name"), max_length=128, blank=True, null=True)
    display_name = models.CharField(_("Display Name"), max_length=128)
    is_active = models.BooleanField(_("Active"), default=True)
    is_staff = models.BooleanField(_("Is staff"), default=False)
    profile_picture = models.ImageField(
        upload_to=to_profile_picture, null=True, blank=True
    )

    objects: Type[UserManager] = UserManager()

    USERNAME_FIELD: str = "email"
    REQUIRED_FIELDS: List[str] = []

    class Meta:
        verbose_name: str = _("User")
        verbose_name_plural: str = _("Users")

    @property
    def get_full_name(self) -> str:
        return f"{self.first_name} {self.last_name}"
```

<p><strong>managers.py :</strong></p>

<pre class="lang-py prettyprint-override"><code>from django.contrib.auth.base_user import BaseUserManager

class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        """
        Creates and saves a User with the given email and password.
        """
        if not email:
            raise ValueError("The given email must be set")
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email: str, password: str = None, **extra_fields):
        extra_fields.setdefault("is_superuser", False)
        extra_fields.setdefault("is_staff", False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault("is_superuser", True)
        extra_fields.setdefault("is_staff", True)

        if extra_fields.get("is_superuser") is not True:
            raise ValueError("Superuser must have is_superuser=True.")

        return self._create_user(email, password, **extra_fields)
</code>```

viewsets.py :

from typing import Type
from rest_framework import viewsets, status
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.response import Response
from rest_framework.request import Request
from rest_framework.decorators import action

from main.apps.user.models import User
from main.apps.user.serializers import UserSerializer

class UsersViewset(viewsets.ModelViewSet):
    def get_permissions(self):
        """
        Instantiates and returns the list of permissions that this view requires.
        """
        if self.action == "create":
            permission_classes = [AllowAny]
        else:
            permission_classes = [IsAuthenticated]
        return [permission() for permission in permission_classes]

    queryset = User.objects.all()
    serializer_class: Type[UserSerializer] = UserSerializer

    def create(self, request, *args, **kwargs):
        serializer: UserSerializer = UserSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = User.objects.create_user(
            serializer.validated_data.pop("email"),
            serializer.validated_data.pop("password"),
            **serializer.validated_data,
        )
        return Response(status=status.HTTP_201_CREATED, data=UserSerializer(user).data)

    @action(detail=False)
    def me(self, request: Request):
        return Response(
            status=status.HTTP_200_OK, data=UserSerializer(request.user).data
        )
```

<p>serializers.py :</p>

<pre class="lang-py prettyprint-override"><code>from typing import Type, Tuple, Dict, Any

from rest_framework import serializers

from main.apps.user.models import User

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model: Type[User] = User
        fields: Tuple[str] = (
            "id",
            "email",
            "password",
            "display_name",
            "first_name",
            "last_name",
            "profile_picture",
        )
        extra_kwargs: Dict[str, Any] = {"password": {"write_only": True}}
</code>```

My issue here is that when I go to the route I defined for the UserViewset and trigger the list action, it returns the full URL with the http://domain/ in front of the file path, which is actually exactly what I want. But on the /me route or the create route, only the path is returned, without the domain.

I'm thinking it might have something to do with the context that is not passed to the serializer in custom routes, but might be in the default ModelViewset routes.

If anyone knows how I can replicate the list action behavior on my other routes, I'll be glad !

答:
Okay, found out that it was what I thought, I just needed to pass the request as context to my serializer.

Change the method me in file viewsets.py from that :

@action(detail=False)
    def me(self, request: Request):
        return Response(
            status=status.HTTP_200_OK, data=UserSerializer(request.user).data
        )
```

<p>to this :</p>

<pre class="lang-py prettyprint-override"><code>@action(detail=False)
    def me(self, request: Request):
        return Response(
            status=status.HTTP_200_OK,
            data=UserSerializer(request.user, context={"request": request}).data,
        )
</code>```

Title: DRF ImageField Inconsistent behavior

Body:
I'm creating a Django API with DRF. I have a custom User Model like this :

models.py :

from typing import Type, List
from uuid import uuid4
from django.db import models
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from django.utils.translation import ugettext_lazy as _
from django_extensions.db.models import TimeStampedModel

from main.apps.user.managers import UserManager

def to_profile_picture(instance: "User", filename: str) -> str:
    return f"profile_pictures/{instance.email}/{uuid4()}_{filename}"

class User(AbstractBaseUser, TimeStampedModel, PermissionsMixin):
    email = models.EmailField(_("Email Address"), unique=True)
    first_name = models.CharField(
        _("First Name"), max_length=128, blank=True, null=True
    )
    last_name = models.CharField(_("Last Name"), max_length=128, blank=True, null=True)
    display_name = models.CharField(_("Display Name"), max_length=128)
    is_active = models.BooleanField(_("Active"), default=True)
    is_staff = models.BooleanField(_("Is staff"), default=False)
    profile_picture = models.ImageField(
        upload_to=to_profile_picture, null=True, blank=True
    )

    objects: Type[UserManager] = UserManager()

    USERNAME_FIELD: str = "email"
    REQUIRED_FIELDS: List[str] = []

    class Meta:
        verbose_name: str = _("User")
        verbose_name_plural: str = _("Users")

    @property
    def get_full_name(self) -> str:
        return f"{self.first_name} {self.last_name}"

managers.py :

from django.contrib.auth.base_user import BaseUserManager

class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        """
        Creates and saves a User with the given email and password.
        """
        if not email:
            raise ValueError("The given email must be set")
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email: str, password: str = None, **extra_fields):
        extra_fields.setdefault("is_superuser", False)
        extra_fields.setdefault("is_staff", False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault("is_superuser", True)
        extra_fields.setdefault("is_staff", True)

        if extra_fields.get("is_superuser") is not True:
            raise ValueError("Superuser must have is_superuser=True.")

        return self._create_user(email, password, **extra_fields)

viewsets.py :

from typing import Type
from rest_framework import viewsets, status
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.response import Response
from rest_framework.request import Request
from rest_framework.decorators import action

from main.apps.user.models import User
from main.apps.user.serializers import UserSerializer

class UsersViewset(viewsets.ModelViewSet):
    def get_permissions(self):
        """
        Instantiates and returns the list of permissions that this view requires.
        """
        if self.action == "create":
            permission_classes = [AllowAny]
        else:
            permission_classes = [IsAuthenticated]
        return [permission() for permission in permission_classes]

    queryset = User.objects.all()
    serializer_class: Type[UserSerializer] = UserSerializer

    def create(self, request, *args, **kwargs):
        serializer: UserSerializer = UserSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = User.objects.create_user(
            serializer.validated_data.pop("email"),
            serializer.validated_data.pop("password"),
            **serializer.validated_data,
        )
        return Response(status=status.HTTP_201_CREATED, data=UserSerializer(user).data)

    @action(detail=False)
    def me(self, request: Request):
        return Response(
            status=status.HTTP_200_OK, data=UserSerializer(request.user).data
        )

serializers.py :

from typing import Type, Tuple, Dict, Any

from rest_framework import serializers

from main.apps.user.models import User

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model: Type[User] = User
        fields: Tuple[str] = (
            "id",
            "email",
            "password",
            "display_name",
            "first_name",
            "last_name",
            "profile_picture",
        )
        extra_kwargs: Dict[str, Any] = {"password": {"write_only": True}}

My issue here is that when I go to the route I defined for the UserViewset and trigger the list action, it returns the full URL with the http://domain/ in front of the file path, which is actually exactly what I want. But on the /me route or the create route, only the path is returned, without the domain.

I'm thinking it might have something to do with the context that is not passed to the serializer in custom routes, but might be in the default ModelViewset routes.

If anyone knows how I can replicate the list action behavior on my other routes, I'll be glad !

Body:
Okay, found out that it was what I thought, I just needed to pass the request as context to my serializer.

Change the method me in file viewsets.py from that :

@action(detail=False)
    def me(self, request: Request):
        return Response(
            status=status.HTTP_200_OK, data=UserSerializer(request.user).data
        )

to this :

@action(detail=False)
    def me(self, request: Request):
        return Response(
            status=status.HTTP_200_OK,
            data=UserSerializer(request.user, context={"request": request}).data,
        )


问:
how to find out all properties of an object in lua?
Is there any way of getting all the non-nil parameters / properties
of an object? I found this: getmetadata(self.xxxx) and i am looking for something like: getalldata(self).

I'm currently working on a project where lua is involved. Unfortunately, there is no complete reference and i have to use precompiled stuff.

I hope you are able to understand what I am trying to say.

答:
I believe objects are just a table, so you should be able to iterate over the properties as any other table:</p>

```<code>for i,v in ipairs(your_object) do body end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I believe objects are just a table, so you should be able to iterate over the properties as any other table:

for i,v in ipairs(your_object) do body end


问:
Is there a way find values associated with Lat/Long points that fall within radius of other Lat/Long Points?
I have over 1000 rows of lat/long data for different communities across the US in data table. Some of these communities are competitors and others are our own. Each of these communities has a number of units (apartments). There are many instances where multiple communities fall within 3 miles of each other. I am looking to find a way to do the following: 1)determine if each of the sites falls within a 3 mile radius of ALL other sites THEN 2) sum the "units" column of the sites that fall within that 3 mile radius. I would like two columns added to the data table... first column called "number of sites" and second is "number of units"

I already had written code to check to see if any other lat/lon fell within a 3 mile radius of each other but that is as far as I have gotten.

the main_df has over 400 columns. To simplify this I redid to show only the required columns..

colnames(main_df)
Result: Lat, Lon, Units

So the code to use in this question would be

main_df<-cbind(main_df, X=((X=rowSums(distm (main_df[,2:1],
     fun = distHaversine) / 1000<= 4.828032)/3)-1))
```

<p>As mentioned before, I expect the result to add two additional columns to main_df.
colnames(main_df)
Result: Lat, Lon, Units, number of sites, number of units</p>

<p>So kinda like this...</p>

```Lat         Lon      Units  #of Sites   #of Units
40.06127    -86.05604   80    2           184
41.15241    -85.12709   123   3           262
42.91640    -83.62937   125   1           200
39.67114    -86.07211   59    0           0
41.24905    -81.83060   200   4           387
```

答:
As per my earlier comment:

"My suggestion is the save the output from the distm function as variable.
Then you can search for rows where the rowSums > 1 and then use the which function to find the columns (thus the rows of your original data frame) of the nearby units."

```<code>#Last rows added for testing
main_df<-read.table(header=TRUE, text="Lat    Lon  Units
40.06127    -86.05604   80
41.15241    -85.12709   123
42.91640    -83.62937   125
39.67114    -86.07211   59
41.24905    -81.83060   200
40.061    -86.056   100
40.060    -86.0561   300")

library(geosphere)

#create and store distance matrix
#this will be a square matrix the length and width of as the number of rows in main_df.
# be aware of memory use.
distmat<-distm (main_df[,2:1], fun = distHaversine)/1000
# convert to logical matrix of units nearby, exclude same location.
distmat<-(distmat >0 & distmat <= 4.828032)

main_df$nearbysites <- rowSums(distmat)

#find rows where there is at least one other nearby sites
rowsnearby<-which(main_df$nearby >0)

#add place holding columns
main_df$sumunits<-0

#loop through all of the rows with more than 1 nearby site
for (i in rowsnearby){
  #find columns which are nearby, the column number is the same as the rows of main df that are close by
  targetrows<-which(distmat[i,]==TRUE)
  #find sum
  main_df$sumunits[i]<-sum(main_df$Units[targetrows])
}
print(main_df)
</code>```

Body:
I have over 1000 rows of lat/long data for different communities across the US in data table. Some of these communities are competitors and others are our own. Each of these communities has a number of units (apartments). There are many instances where multiple communities fall within 3 miles of each other. I am looking to find a way to do the following: 1)determine if each of the sites falls within a 3 mile radius of ALL other sites THEN 2) sum the "units" column of the sites that fall within that 3 mile radius. I would like two columns added to the data table... first column called "number of sites" and second is "number of units"

I already had written code to check to see if any other lat/lon fell within a 3 mile radius of each other but that is as far as I have gotten.

the main_df has over 400 columns. To simplify this I redid to show only the required columns..

colnames(main_df)
Result: Lat, Lon, Units

So the code to use in this question would be

main_df<-cbind(main_df, X=((X=rowSums(distm (main_df[,2:1],
     fun = distHaversine) / 1000<= 4.828032)/3)-1))

As mentioned before, I expect the result to add two additional columns to main_df.
colnames(main_df)
Result: Lat, Lon, Units, number of sites, number of units

So kinda like this...

Lat         Lon      Units  #of Sites   #of Units
40.06127    -86.05604   80    2           184
41.15241    -85.12709   123   3           262
42.91640    -83.62937   125   1           200
39.67114    -86.07211   59    0           0
41.24905    -81.83060   200   4           387

Body:
As per my earlier comment:

"My suggestion is the save the output from the distm function as variable.
Then you can search for rows where the rowSums > 1 and then use the which function to find the columns (thus the rows of your original data frame) of the nearby units."

#Last rows added for testing
main_df<-read.table(header=TRUE, text="Lat    Lon  Units
40.06127    -86.05604   80
41.15241    -85.12709   123
42.91640    -83.62937   125
39.67114    -86.07211   59
41.24905    -81.83060   200
40.061    -86.056   100
40.060    -86.0561   300")

library(geosphere)

#create and store distance matrix
#this will be a square matrix the length and width of as the number of rows in main_df.
# be aware of memory use.
distmat<-distm (main_df[,2:1], fun = distHaversine)/1000
# convert to logical matrix of units nearby, exclude same location.
distmat<-(distmat >0 & distmat <= 4.828032)

main_df$nearbysites <- rowSums(distmat)

#find rows where there is at least one other nearby sites
rowsnearby<-which(main_df$nearby >0)

#add place holding columns
main_df$sumunits<-0

#loop through all of the rows with more than 1 nearby site
for (i in rowsnearby){
  #find columns which are nearby, the column number is the same as the rows of main df that are close by
  targetrows<-which(distmat[i,]==TRUE)
  #find sum
  main_df$sumunits[i]<-sum(main_df$Units[targetrows])
}
print(main_df)


问:
Problem with android:targetSdkVersion attribute
I have an application compiled in Android 1.6 (api level 4) but I need to add android:installLocation attribute. I have put this line in my AndroidManifest.xml:

```<code><uses-sdk android:minSdkVersion="4" android:targetSdkVersion="8"/>
</code>```

I have defined the android:targetSdkVersion as 8, but the android:installLocation doesn't work right.

答:
You need to compile against the Level 8 SDK.

Look for point number 3 in the Backwards Compatibility section here http://developer.android.com/guide/appendix/install-location.html

Body:
I have an application compiled in Android 1.6 (api level 4) but I need to add android:installLocation attribute. I have put this line in my AndroidManifest.xml:

<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="8"/>

I have defined the android:targetSdkVersion as 8, but the android:installLocation doesn't work right.


问:
Convert a model into tf lite for Coral Dev Board
I have developed a model for custom speech recognition by following this tutorial: https://www.tensorflow.org/tutorials/sequences/audio_recognition
I have customized the model with custom parameters and I have frozen my graph. Now, I would like to deploy this model on a Coral Dev Board. For these reasons, I have performed an 8-bit quantization aware training. However, I'm in trouble converting the frozen graph into Tensorflow Lite model, by using the tflite_convert tool. The command:

```<code> tflite_convert --output_file=model.tflite --graph_def_file=frozen.pb --input_arrays=wav_data --output_arrays=labels_softmax --inference_type=QUANTIZED_UINT8
</code>```

return the following error:

ValueError: Provide an input shape for input array 'wav_data'.

How can I find the correct values for the requested parameters? Any idea?
Thanks.

答:
I think that you might be using the wrong input node, 'wav_data' is a DecodeWav op that takes in the content of a .wav file, but you'll probably want to pass in raw sample data captured from a microphone, which will go in 'decoded_sample_data' instead. Here are the arguments I typically use to toco in this case:</p>

```<code>--input_shapes=16000,1:1 --input_arrays=decoded_sample_data,decoded_sample_data:1
</code>```

Body:
I have developed a model for custom speech recognition by following this tutorial: https://www.tensorflow.org/tutorials/sequences/audio_recognition
I have customized the model with custom parameters and I have frozen my graph. Now, I would like to deploy this model on a Coral Dev Board. For these reasons, I have performed an 8-bit quantization aware training. However, I'm in trouble converting the frozen graph into Tensorflow Lite model, by using the tflite_convert tool. The command:

 tflite_convert --output_file=model.tflite --graph_def_file=frozen.pb --input_arrays=wav_data --output_arrays=labels_softmax --inference_type=QUANTIZED_UINT8

return the following error:

ValueError: Provide an input shape for input array 'wav_data'.

How can I find the correct values for the requested parameters? Any idea?
Thanks.

Body:
I think that you might be using the wrong input node, 'wav_data' is a DecodeWav op that takes in the content of a .wav file, but you'll probably want to pass in raw sample data captured from a microphone, which will go in 'decoded_sample_data' instead. Here are the arguments I typically use to toco in this case:

--input_shapes=16000,1:1 --input_arrays=decoded_sample_data,decoded_sample_data:1


问:
Importing from a file in another folder which is at the same level of a project's structure
I've searched far and wide for how to do this, without success. Imagine I have a project structure like this:

```<code>my_proj
- notebooks
- - a_notebook_into_which_i_want_to_import_a_class.ipynb
- src
- - a_file_with_the_class_i_want_to_import.py
</code>```

How would I write the import statement?

I'm using python 3.7, but am also interested in the correct procedures for other python versions, if they differ.

答:
You essentially need to inform Python where it needs to look for that class you want to import. You can check the list of default locations by printing sys.path in a script. Usually, this is a couple of standard locations including the python install directory itself. It will also check in the directory that the currently running script is present in.

Since you can't move that other file into the same directory, you can either add it to the PYTHONPATH environment variable (which makes it accessible to all scripts on your machine) or use the following snippet in order to load it only for your particular script.

The snippet adds the path only for the duration of your script, and doesn't make any persistent changes.

```<code>import os
import sys
from pathlib import Path

# to get the path of currently running script
path = Path(os.path.realpath(__file__))
# path.parents[0] gets the immediate parent dir (notebooks/)
# path.parents[1] is 2 levels up, i.e. my_proj/
# use path.join to get abspath of src/, and then add it to sys.path
sys.path.append(os.path.join(path.parents[1], 'src'))

from a_file_with_the_class_i_want_to_import import DesiredClass

# You should be able to use it now
</code>```

Body:
I've searched far and wide for how to do this, without success. Imagine I have a project structure like this:

my_proj
- notebooks
- - a_notebook_into_which_i_want_to_import_a_class.ipynb
- src
- - a_file_with_the_class_i_want_to_import.py

How would I write the import statement?

I'm using python 3.7, but am also interested in the correct procedures for other python versions, if they differ.

Body:
You essentially need to inform Python where it needs to look for that class you want to import. You can check the list of default locations by printing sys.path in a script. Usually, this is a couple of standard locations including the python install directory itself. It will also check in the directory that the currently running script is present in.

Since you can't move that other file into the same directory, you can either add it to the PYTHONPATH environment variable (which makes it accessible to all scripts on your machine) or use the following snippet in order to load it only for your particular script.

The snippet adds the path only for the duration of your script, and doesn't make any persistent changes.

import os
import sys
from pathlib import Path

# to get the path of currently running script
path = Path(os.path.realpath(__file__))
# path.parents[0] gets the immediate parent dir (notebooks/)
# path.parents[1] is 2 levels up, i.e. my_proj/
# use path.join to get abspath of src/, and then add it to sys.path
sys.path.append(os.path.join(path.parents[1], 'src'))

from a_file_with_the_class_i_want_to_import import DesiredClass

# You should be able to use it now


问:
How can I create an EMR cluster resource that uses spot instances without hardcoding the bid_price variable?
I'm using Terraform to create an AWS EMR cluster that uses spot instances as core instances.

I know I can use the bid_price variable within the core_instance_group block on a aws_emr_cluster resource, but I don't want to hardcode prices as I'd have to change them manually every time the instance type changes.

Using the AWS Web UI, I'm able to choose the "Use on-demand as max price" option. That's exactly what I'm trying to reproduce, but in Terraform.

Right now I am trying to solve my problem using the aws_pricing_product data source. You can see what I have so far below:

```<code>data "aws_pricing_product" "m4_large_price" {
  service_code = "AmazonEC2"

  filters {
   field = "instanceType"
   value = "m4.large"
  }

  filters {
   field = "operatingSystem"
   value = "Linux"
  }

  filters {
   field = "tenancy"
   value = "Shared"
  }

  filters {
   field = "usagetype"
   value = "BoxUsage:m4.large"
  }

  filters {
   field = "preInstalledSw"
   value = "NA"
  }

  filters {
    field = "location"
    value = "US East (N. Virginia)"
  }
}
</code>```

data.aws_pricing_product.m4_large_price.result returns a json containing the details of a single product (you can check the response of the example here). The actual on-demand price is buried somewhere inside this json, but I don't know how can I get it (image generated with http://jsonviewer.stack.hu/):

I know I might be able solve this by using an external data source and piping the output of an aws cli call to something like jq, e.g:

aws pricing get-products --filters "Type=TERM_MATCH,Field=sku,Value=8VCNEHQMSCQS4P39" --format-version aws_v1 --service-code AmazonEC2 | jq [........]
```

But I'd like to know if there is any way to accomplish what I'm trying to do with pure Terraform. Thanks in advance!

答:
Unfortunately the aws_pricing_product data source docs don't expand on how it should be used effectively but the discussion in the pull request that added it adds some insight.

In Terraform 0.12 you should be able to use the jsondecode function to nicely get at what you want with the following given as an example in the linked pull request:

```<code>data "aws_pricing_product" "example" {
  service_code = "AmazonRedshift"

  filters = [
    {
      field = "instanceType"
      value = "ds1.xlarge"
    },
    {
      field = "location"
      value = "US East (N. Virginia)"
    },
  ]
}

# Potential Terraform 0.12 syntax - may change during implementation
# Also, not sure about the exact attribute reference architecture myself :)
output "example" {
  values = jsondecode(data.json_query.example.value).terms.OnDemand.*.priceDimensions.*.pricePerUnit.USD
}
</code>```

If you are stuck on Terraform <0.12 you might struggle to do this natively in Terraform other than the external data source approach you've already suggested.

Body:
I'm using Terraform to create an AWS EMR cluster that uses spot instances as core instances.

I know I can use the bid_price variable within the core_instance_group block on a aws_emr_cluster resource, but I don't want to hardcode prices as I'd have to change them manually every time the instance type changes.

Using the AWS Web UI, I'm able to choose the "Use on-demand as max price" option. That's exactly what I'm trying to reproduce, but in Terraform.

Right now I am trying to solve my problem using the aws_pricing_product data source. You can see what I have so far below:

data "aws_pricing_product" "m4_large_price" {
  service_code = "AmazonEC2"

  filters {
   field = "instanceType"
   value = "m4.large"
  }

  filters {
   field = "operatingSystem"
   value = "Linux"
  }

  filters {
   field = "tenancy"
   value = "Shared"
  }

  filters {
   field = "usagetype"
   value = "BoxUsage:m4.large"
  }

  filters {
   field = "preInstalledSw"
   value = "NA"
  }

  filters {
    field = "location"
    value = "US East (N. Virginia)"
  }
}

data.aws_pricing_product.m4_large_price.result returns a json containing the details of a single product (you can check the response of the example here). The actual on-demand price is buried somewhere inside this json, but I don't know how can I get it (image generated with http://jsonviewer.stack.hu/):

I know I might be able solve this by using an external data source and piping the output of an aws cli call to something like jq, e.g:

aws pricing get-products --filters "Type=TERM_MATCH,Field=sku,Value=8VCNEHQMSCQS4P39" --format-version aws_v1 --service-code AmazonEC2 | jq [........]

But I'd like to know if there is any way to accomplish what I'm trying to do with pure Terraform. Thanks in advance!

Body:
Unfortunately the aws_pricing_product data source docs don't expand on how it should be used effectively but the discussion in the pull request that added it adds some insight.

In Terraform 0.12 you should be able to use the jsondecode function to nicely get at what you want with the following given as an example in the linked pull request:

data "aws_pricing_product" "example" {
  service_code = "AmazonRedshift"

  filters = [
    {
      field = "instanceType"
      value = "ds1.xlarge"
    },
    {
      field = "location"
      value = "US East (N. Virginia)"
    },
  ]
}

# Potential Terraform 0.12 syntax - may change during implementation
# Also, not sure about the exact attribute reference architecture myself :)
output "example" {
  values = jsondecode(data.json_query.example.value).terms.OnDemand.*.priceDimensions.*.pricePerUnit.USD
}

If you are stuck on Terraform <0.12 you might struggle to do this natively in Terraform other than the external data source approach you've already suggested.


问:
How can I generate a requirements.txt file for a package not available on my development platform?
I'm trying to generate requirements/dev.txt and prod.txt files for my python project. I'm using pip-compile-multi to generate them from base.in dev.in and prod.in files. Everything works great until I add tensorflow-gpu==2.0.0a0 into the prod.in file. I get this error when I do: RuntimeError: Failed to pip-compile requirements/prod.in.

I believe this is because tensorflow-gpu is only available on Linux, and my dev machine is a Mac. (If I run pip install tensorflow-gpu==2.0.0a0 I am told there is no distribution for my platform.) Is there a way I can generate a requirements.txt file for pip for a package that is not available on my platform? To be clear, my goal is to generate a requirements.txt file using something like pip-compile-multi (because that will version dependencies) that will only install on Linux, but I want to be able to actually generate the file on any platform.

答:
I think you are looking for tensorflow-gpu==2.0.0a0 (remove the - before the a). I think this is the version you are looking for: https://pypi.org/project/tensorflow-gpu/2.0.0a0/
See the pip install command on the page. Hope this helps.


问:
Layout and formatting without Dynamic Controls in WPF
How do I format and throw my controls in a layout in WPF? I mean, I know about making dynamic controls and throwing them on a Grid or a Panel or something, but is there a better way? Like if this were a web app, I could just use some HTML and CSS and get what I want but is there something better than creating dynamic controls in WPF? I have database table full of stuff which I want displayed in my WPF application. Can I modify the DataGrid or ListView or something else for this purpose? I'm attaching images, which might make it easier for you guys to understand what I'm talking about.

images:

my data, inside the database table - http://i.stack.imgur.com/LnHCv.png

my data, formatted with HTML and CSS - http://i.stack.imgur.com/6PHBH.png

答:
The typical way to do this in WPF is via Data Templating.

In general, if you want to display a set of data formatted as per your second screenshot, you'd bind the dataset (usually contained in a collection such as ObservableCollection) to a ListBox or similar child of ItemsControl, and set the ItemsTemplate to a DataTemplate you've created to display the items in the format you desire.

For example, a very rough approximation of your HTML layout:

```<code><ListBox ItemsSource="{Binding}">
    <ListBox.ItemTemplate>
        <DataTemplate DataType="TypeOfYourDataObject">
            <StackPanel>
                <TextBlock FontSize="12" Foreground="Turquoise" Text="{Binding NickName}"/>
                <StackPanel Orientation="Horizontal">
                    <TextBlock FontSize="11" Foreground="Gray" Text="email / "/>
                    <TextBlock FontSize="11" Foreground="Turquoise" Text="{Binding EmailAddress}"/>
                </StackPanel>
                <StackPanel Orientation="Horizontal">
                    <TextBlock FontSize="11" Foreground="Gray" Text="web / "/>
                    <TextBlock FontSize="11" Foreground="Turquoise" Text="{Binding Url}"/>
                </StackPanel>
                <Separator/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
</code>```

Body:
The typical way to do this in WPF is via Data Templating.

In general, if you want to display a set of data formatted as per your second screenshot, you'd bind the dataset (usually contained in a collection such as ObservableCollection) to a ListBox or similar child of ItemsControl, and set the ItemsTemplate to a DataTemplate you've created to display the items in the format you desire.

For example, a very rough approximation of your HTML layout:

<ListBox ItemsSource="{Binding}">
    <ListBox.ItemTemplate>
        <DataTemplate DataType="TypeOfYourDataObject">
            <StackPanel>
                <TextBlock FontSize="12" Foreground="Turquoise" Text="{Binding NickName}"/>
                <StackPanel Orientation="Horizontal">
                    <TextBlock FontSize="11" Foreground="Gray" Text="email / "/>
                    <TextBlock FontSize="11" Foreground="Turquoise" Text="{Binding EmailAddress}"/>
                </StackPanel>
                <StackPanel Orientation="Horizontal">
                    <TextBlock FontSize="11" Foreground="Gray" Text="web / "/>
                    <TextBlock FontSize="11" Foreground="Turquoise" Text="{Binding Url}"/>
                </StackPanel>
                <Separator/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>


问:
How to append a path to every file to be stored in array?
suppose i have an array

```<code>$f_attachments = @()
</code>```

every file i have, i simply append to it

```<code>$f_attachments += $file
</code>```

however, i would like to include the directory as well for every file saved in this array

in other words, instead of having to do something like this:

```<code>$f_attachments += $currentFolder\$file1
$f_attachments += $currentFolder\$file2
etc...
</code>```

can i just append it at the array level?

```<code>$f_attachments = @($currentFolder)
</code>```

more explanation

i have a HUGE script. i am appending files (i.e. $f_attachments += $file1  $f_attachments += $file2, etc...) to $f_attachments array at random parts of the script. this array is defined at the VERY BEGINNING

```<code>$f_attachments = @()
</code>```

suppose my full script is like this:

```<code>$f_attachments = @()
if()
{
do something...
$f_attachments += $currentFolder\$file1
}
else
{
do something...
$f_attachments += $currentFolder\$file2
}
....
</code>```

as you can see, i added $currentFolder\ everytime i am adding a file to the array

i want something at the array definition level, here $f_attachments = @()

that will automatically append this $currentFolder\

in other words, an ideal solution would look like this:

```<code>$f_attachments = @($currentFolder\)
if()
{
do something...
$f_attachments += $file1
}
else
{
do something...
$f_attachments += $file2
}
....
</code>```

答:
You can loop the array with a foreach-object and add the folder name.

The | means pipe. It takes the data from the input object and sends it to the next command in the pipe. This case %{} which is a alias for Foreach-Object.
You then are storing the output from %{} back into variable $files

```<code>$files = @("abc.txt","efg.txt","hij.txt","lmn.txt")

$files = $a | %{
    "FolderName\$_"
}

$files
</code>```

EDIT : The post was updated with additional information.

So what you need here is a custom object that adds the folder to the name of each file added :

```<code>$Files = New-Object PSObject -Property @{
    Array = @()
    FolderName = ""
}
$Files | Add-Member -MemberType scriptmethod  -Name Files -Value {
    param([string]$File = "")
    if($File.Length -eq 0){
        return $this.Array
    }else{
        $this.Array += "$($this.FolderName)\$File"
    }
}

$Files.FolderName = "FolderHere"
$Files.Files("Test.txt")
$Files.Files("Test2.txt")
$Files.Files("Test3.txt")
$Files.Files("Test4.txt")
$Files.Files()
</code>```

This returns

```<code>FolderHere\Test.txt
FolderHere\Test2.txt
FolderHere\Test3.txt
FolderHere\Test4.txt
</code>```

We are creating a new-object PSObject with the properties FolderName which will store the folder name to add to the files. Array which will hold the final array object. Files which will be a ScriptMethod member that will add the folder to the name and if nothing is entered as a param will return the Array property

Body:
suppose i have an array

$f_attachments = @()

every file i have, i simply append to it

$f_attachments += $file

however, i would like to include the directory as well for every file saved in this array

in other words, instead of having to do something like this:

$f_attachments += $currentFolder\$file1
$f_attachments += $currentFolder\$file2
etc...

can i just append it at the array level?

$f_attachments = @($currentFolder)

more explanation

i have a HUGE script. i am appending files (i.e. $f_attachments += $file1  $f_attachments += $file2, etc...) to $f_attachments array at random parts of the script. this array is defined at the VERY BEGINNING

$f_attachments = @()

suppose my full script is like this:

$f_attachments = @()
if()
{
do something...
$f_attachments += $currentFolder\$file1
}
else
{
do something...
$f_attachments += $currentFolder\$file2
}
....

as you can see, i added $currentFolder\ everytime i am adding a file to the array

i want something at the array definition level, here $f_attachments = @()

that will automatically append this $currentFolder\

in other words, an ideal solution would look like this:

$f_attachments = @($currentFolder\)
if()
{
do something...
$f_attachments += $file1
}
else
{
do something...
$f_attachments += $file2
}
....

Body:
You can loop the array with a foreach-object and add the folder name.

The | means pipe. It takes the data from the input object and sends it to the next command in the pipe. This case %{} which is a alias for Foreach-Object.
You then are storing the output from %{} back into variable $files

$files = @("abc.txt","efg.txt","hij.txt","lmn.txt")

$files = $a | %{
    "FolderName\$_"
}

$files

EDIT : The post was updated with additional information.

So what you need here is a custom object that adds the folder to the name of each file added :

$Files = New-Object PSObject -Property @{
    Array = @()
    FolderName = ""
}
$Files | Add-Member -MemberType scriptmethod  -Name Files -Value {
    param([string]$File = "")
    if($File.Length -eq 0){
        return $this.Array
    }else{
        $this.Array += "$($this.FolderName)\$File"
    }
}

$Files.FolderName = "FolderHere"
$Files.Files("Test.txt")
$Files.Files("Test2.txt")
$Files.Files("Test3.txt")
$Files.Files("Test4.txt")
$Files.Files()

This returns

FolderHere\Test.txt
FolderHere\Test2.txt
FolderHere\Test3.txt
FolderHere\Test4.txt

We are creating a new-object PSObject with the properties FolderName which will store the folder name to add to the files. Array which will hold the final array object. Files which will be a ScriptMethod member that will add the folder to the name and if nothing is entered as a param will return the Array property


问:
Hide all rows in a DataGridView using VB
I am trying to filter data in a DataGridView and I need to hide all rows and columns. I try to do this using looping list LINQ & lambda expressions because if I use a foreach it is slow when I try to filter 3000 rows.

The following code executes without errors and works perfectly in c# but doesn't hide the rows in vb:

c# works perfectly

```<code>dataGridView1.Columns.OfType<DataGridViewColumn>().ToList().ForEach(col => col.Visible = false);
</code>```

vb doesnt works

```<code>datagrid.Rows.OfType(Of DataGridViewRow)().ToList().ForEach(Function(obj) obj.Visible = False)
</code>```

I'm looking for the equivalent code in vb.

答:
You should bind the data and do your operations on the data itself - not the user interface. You can do similar to the following:

```<code>Public Class Form1

    Private allData As IEnumerable(Of Data) ' all your data
    Private filtered As IEnumerable(Of Data) ' filtered for logical and display purposes

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        allData = Enumerable.Range(0, 32).Select(Function(i) New Data() With {.Value = i})
        updateFilteredNumbers(Function(d) True) ' filtered list initially identical to all
    End Sub
    Private Sub HideButton_Click(sender As Object, e As EventArgs) Handles HideButton.Click
        updateFilteredNumbers(Function(d) False)
    End Sub
    Private Sub ShowButton_Click(sender As Object, e As EventArgs) Handles ShowButton.Click
        updateFilteredNumbers(Function(d) True)
    End Sub
    Private Sub EvenButton_Click(sender As Object, e As EventArgs) Handles EvenButton.Click
        updateFilteredNumbers(Function(d) d.Value Mod 2 = 0)
    End Sub
    Private Sub OddButton_Click(sender As Object, e As EventArgs) Handles OddButton.Click
        updateFilteredNumbers(Function(d) d.Value Mod 2 = 1)
    End Sub
    Private Async Sub updateFilteredNumbers(predicate As Func(Of Data, Boolean))
        ' perform filtering asynchronously, then update datasource on UI thread
        filtered = Await Task.Factory.StartNew(Function() allData.Where(predicate).ToList())
        datagrid.DataSource = filtered
    End Sub

End Class

Public Structure Data ' Class to represent your data. Simple for this example
    Public Property Value As Integer
End Structure
</code>```

This example can hide all, show all, or show odd or even values only. You can update the "filtered" collection and just refresh the DataSource.

Body:
I am trying to filter data in a DataGridView and I need to hide all rows and columns. I try to do this using looping list LINQ & lambda expressions because if I use a foreach it is slow when I try to filter 3000 rows.

The following code executes without errors and works perfectly in c# but doesn't hide the rows in vb:

c# works perfectly

dataGridView1.Columns.OfType<DataGridViewColumn>().ToList().ForEach(col => col.Visible = false);

vb doesnt works

datagrid.Rows.OfType(Of DataGridViewRow)().ToList().ForEach(Function(obj) obj.Visible = False)

I'm looking for the equivalent code in vb.

Body:
You should bind the data and do your operations on the data itself - not the user interface. You can do similar to the following:

Public Class Form1

    Private allData As IEnumerable(Of Data) ' all your data
    Private filtered As IEnumerable(Of Data) ' filtered for logical and display purposes

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        allData = Enumerable.Range(0, 32).Select(Function(i) New Data() With {.Value = i})
        updateFilteredNumbers(Function(d) True) ' filtered list initially identical to all
    End Sub
    Private Sub HideButton_Click(sender As Object, e As EventArgs) Handles HideButton.Click
        updateFilteredNumbers(Function(d) False)
    End Sub
    Private Sub ShowButton_Click(sender As Object, e As EventArgs) Handles ShowButton.Click
        updateFilteredNumbers(Function(d) True)
    End Sub
    Private Sub EvenButton_Click(sender As Object, e As EventArgs) Handles EvenButton.Click
        updateFilteredNumbers(Function(d) d.Value Mod 2 = 0)
    End Sub
    Private Sub OddButton_Click(sender As Object, e As EventArgs) Handles OddButton.Click
        updateFilteredNumbers(Function(d) d.Value Mod 2 = 1)
    End Sub
    Private Async Sub updateFilteredNumbers(predicate As Func(Of Data, Boolean))
        ' perform filtering asynchronously, then update datasource on UI thread
        filtered = Await Task.Factory.StartNew(Function() allData.Where(predicate).ToList())
        datagrid.DataSource = filtered
    End Sub

End Class

Public Structure Data ' Class to represent your data. Simple for this example
    Public Property Value As Integer
End Structure

This example can hide all, show all, or show odd or even values only. You can update the "filtered" collection and just refresh the DataSource.


问:
Query a database and return a 'total' for each location based on a search parameter
I'm creating an API for a database, and I'm currently trying to make a search endpoint that takes the search parameter and returns all 'days' and a total of occurrences for that parameter. E.g. (Columns = degrees) (Rows = days in a year), if the parameter was 30 degrees I want to select the 30 degree column and return a total of occasions in which a day hit 30 degrees. So something like: Monday: 0:, Tuesday 10, Wednesday: 8, etc.

So far I've selected the data I want to use based on the parameter but I can't get it to sum each day. My attempts so far have either been a list of 365 days, or a sum of all the days. I understand that I would have to sum the Temp param but I can't work out how to do it so that I end up with each days total.

Current function:

```<code>router.get('/search/:Temp', func(req, res) {
    req.temps.from('days').select('weekDay', req.params.Temp)
    .then((columns)=> {
        res.json({'Search Result': rows)
    )
</code>```

答:
If I understand right, you have a table that looks something like this:

Id  Date        WeekDay     Temperature
----------------------------------------
1   2019-05-30  Thursday    25
2   2019-05-29  Wednesday   30
3   2019-05-28  Tuesday     30
4   2019-05-27  Monday      25
5   2019-05-26  Sunday      25
6   2019-05-25  Saturday    26
7   2019-05-24  Friday      27
8   2019-05-23  Thursday    25
9   2019-05-22  Wednesday   25
10  2019-05-21  Tuesday     30
11  2019-05-20  Monday      30
12  2019-05-19  Sunday      25
13  2019-05-18  Saturday    26
14  2019-05-17  Friday      25
15  2019-05-16  Thursday    25
```

<p>And you want to have a result that looks something like this, given a temperature:</p>

<pre class="lang-none prettyprint-override"><code>WeekDay     Occurences
-----------------------
Friday      1
Monday      1
Sunday      2
Thursday    3
Wednesday   1
</code>```

You have to use the GROUP BY. In raw SQL it can be written like this:

SELECT
      WeekDay
    , COUNT(Temperature) AS Occurences
FROM Temperatures
WHERE Temperature = 25
GROUP BY WeekDay
```

<p>The temperature here is 25. The <code>GROUP BY</code> clause groups all the weekdays together. When you group things together, you must also use aggregate functions that decides how the rows are grouped together. In this case, <code>COUNT()</code> is the aggregate function to use.</p>

<p>Using Knex, it should look something like this:</p>

```knex
  .select('WeekDay', knex.raw('COUNT(Temperature)'))
  .from('Temperatures')
  .where('Temperature', 25)
  .groupBy('WeekDay')
```

Body:
I'm creating an API for a database, and I'm currently trying to make a search endpoint that takes the search parameter and returns all 'days' and a total of occurrences for that parameter. E.g. (Columns = degrees) (Rows = days in a year), if the parameter was 30 degrees I want to select the 30 degree column and return a total of occasions in which a day hit 30 degrees. So something like: Monday: 0:, Tuesday 10, Wednesday: 8, etc.

So far I've selected the data I want to use based on the parameter but I can't get it to sum each day. My attempts so far have either been a list of 365 days, or a sum of all the days. I understand that I would have to sum the Temp param but I can't work out how to do it so that I end up with each days total.

Current function:

router.get('/search/:Temp', func(req, res) {
    req.temps.from('days').select('weekDay', req.params.Temp)
    .then((columns)=> {
        res.json({'Search Result': rows)
    )

Body:
If I understand right, you have a table that looks something like this:

Id  Date        WeekDay     Temperature
----------------------------------------
1   2019-05-30  Thursday    25
2   2019-05-29  Wednesday   30
3   2019-05-28  Tuesday     30
4   2019-05-27  Monday      25
5   2019-05-26  Sunday      25
6   2019-05-25  Saturday    26
7   2019-05-24  Friday      27
8   2019-05-23  Thursday    25
9   2019-05-22  Wednesday   25
10  2019-05-21  Tuesday     30
11  2019-05-20  Monday      30
12  2019-05-19  Sunday      25
13  2019-05-18  Saturday    26
14  2019-05-17  Friday      25
15  2019-05-16  Thursday    25

And you want to have a result that looks something like this, given a temperature:

WeekDay     Occurences
-----------------------
Friday      1
Monday      1
Sunday      2
Thursday    3
Wednesday   1

You have to use the GROUP BY. In raw SQL it can be written like this:

SELECT
      WeekDay
    , COUNT(Temperature) AS Occurences
FROM Temperatures
WHERE Temperature = 25
GROUP BY WeekDay

The temperature here is 25. The GROUP BY clause groups all the weekdays together. When you group things together, you must also use aggregate functions that decides how the rows are grouped together. In this case, COUNT() is the aggregate function to use.

Using Knex, it should look something like this:

knex
  .select('WeekDay', knex.raw('COUNT(Temperature)'))
  .from('Temperatures')
  .where('Temperature', 25)
  .groupBy('WeekDay')


问:
c# windows shutdown control
Please read - this is not a duplicate.

I have a Windows service that runs under the LocalSystem acct.  I am in need of restoring certain files prior to shutdown.  I am able to intercept the Shutdown action at which point I initiate my restore process but the shutdown happens before I am able to complete.
I have enabled Shutdown privileges, added calls to AbortShutdown (Win32) and several other (ie shutdown /a) options but they do not work.  I believe it is because the shutdown or restart has already been initiated and I have read that these functions only stop a shutdown while it is scheduled.

My goal is to intercept the shutdown, abort it, complete my tasks and then shutdown.  I just need more time and the amount of time is dependent on the number and size of files I have to restore.

I am open to any suggestion and appreciate your time and consideration.
Thanks!

答: This sounds more like something that can be done with windows batch files.</p>

Title: c# windows shutdown control


问:
How to Minimize Run Time: Value Replacement Iterations in Pandas
I have a dataframe called df_override that contains the "name", "Field", and "New Value" columns. The aim of this loop is to replace all "name" matches in the df dataframe's "Field" column to the "New Value". The if statement is to see if it's an integer, then it would match by the "id" column instead.

This loop works fine but with a large dataframe it gets unbelievably slow. I have several other for loops that run just like this later in the function. I am wondering if there is any other way to perform this function that's optimized for run time?

Thanks.

```<code>for index, row in df_override.iterrows():
    if(not str(row["name"]).isdigit()):
        df.loc[df["name"] == row["name"], row["Field"]] = row["New Value"]
    else:
        df.loc[df["id"] == row["name"], row["Field"]] = row["New Value"]

</code>```

```<code>df_override
"name"  "Field"  "New Value"
apple    color     red
100     is_number  True

df
"name" "id" "color"  "is_number"
apple   300   blue      False
apple   200   yellow    False
banana  100   green     False

df (after processing)
"name" "id" "color"  "is_number"
apple  300    red       False
apple  200    red       False
banana 100    green     True
</code>```

答:
Changing it to values instead of iterrow improved performance but it's still slow.

New Loop

```<code>for field, name, value in zip(df_override["Field"].values,df_override["name"].values,df_override["New Value"].values):
    if not str(name).isdigit():
        df[field] = np.where(df["name"]  == name, df[field], value)
    else:
        df[field] = np.where(df["id"]  == name, df[field], value)

</code>```

Body:
I have a dataframe called df_override that contains the "name", "Field", and "New Value" columns. The aim of this loop is to replace all "name" matches in the df dataframe's "Field" column to the "New Value". The if statement is to see if it's an integer, then it would match by the "id" column instead.

This loop works fine but with a large dataframe it gets unbelievably slow. I have several other for loops that run just like this later in the function. I am wondering if there is any other way to perform this function that's optimized for run time?

Thanks.

for index, row in df_override.iterrows():
    if(not str(row["name"]).isdigit()):
        df.loc[df["name"] == row["name"], row["Field"]] = row["New Value"]
    else:
        df.loc[df["id"] == row["name"], row["Field"]] = row["New Value"]

df_override
"name"  "Field"  "New Value"
apple    color     red
100     is_number  True

df
"name" "id" "color"  "is_number"
apple   300   blue      False
apple   200   yellow    False
banana  100   green     False

df (after processing)
"name" "id" "color"  "is_number"
apple  300    red       False
apple  200    red       False
banana 100    green     True

Body:
Changing it to values instead of iterrow improved performance but it's still slow.

New Loop

for field, name, value in zip(df_override["Field"].values,df_override["name"].values,df_override["New Value"].values):
    if not str(name).isdigit():
        df[field] = np.where(df["name"]  == name, df[field], value)
    else:
        df[field] = np.where(df["id"]  == name, df[field], value)


问:
Pyspark low performance for monthly frequency
There are two tables A , B in Hive A Table has the following columns and is Partitioned based upon Day. We need to extract data from 1st jan 2016 till    31st Dec 2016. I've just mentioned sample but these records are in millions for 1 year. Table A as follows

```<code>ID Day Name Description
 1   2016-09-01  Sam   Retail
 2   2016-01-28  Chris Retail
 3   2016-02-06  ChrisTY Retail
 4   2016-02-26  Christa Retail
 3   2016-12-06  ChrisTu Retail
 4   2016-12-31  Christi Retail

Table B

ID SkEY
1  1.1
2  1.2
3  1.3
</code>```

The following query is working but taking a long time as the number of columns are around 60(just used sample 3). performance isn't good at all as the result is taking 1 hour for 20 days partitions to process, Can you please figure out and optimise the query.

```<code>from pyspark.sql import sparksession
from pyspark.sql import functions as F
from pyspark import HiveContext
hiveContext= HiveContext(sc)

def UDF_df(i):
    print(i[0])
ABC2 = spark.sql(
    "select * From A where day ='{0}'".format(i[0])
)
Join = ABC2.join(
    Tab2,
     (
        ABC2.ID == Tab2.ID
    )
).select(
    Tab2.skey,
    ABC2.Day,
    ABC2.Name,
    ABC2.Description
)
Join.select(
    "Tab2.skey",
    "ABC2.Day",
    "ABC2.Name",
    "ABC2.Description"
).write.mode("append").format("parquet").insertinto("Table")

ABC=spark.sql(
    "select distinct day from A where day<= '2016-01-01' and day<='2016-12-31'"
)
Tab2=spark.sql("select * from B where day is not null")
for in in ABC.collect():
    UDF_df(i)
</code>```

Above is the pyspark code for a month that I've considered just to test the total time. A Join B with ID and output ID along with other columns of A.  It's taking 1 hour to complete. Is there any better way of optimising the query by taking either 1 month or 1 year of data. And also output table is partitioned on 2 columns where the data is getting inserted which is why hive contexts are used.

Body:
There are two tables A , B in Hive A Table has the following columns and is Partitioned based upon Day. We need to extract data from 1st jan 2016 till    31st Dec 2016. I've just mentioned sample but these records are in millions for 1 year. Table A as follows

ID Day Name Description
 1   2016-09-01  Sam   Retail
 2   2016-01-28  Chris Retail
 3   2016-02-06  ChrisTY Retail
 4   2016-02-26  Christa Retail
 3   2016-12-06  ChrisTu Retail
 4   2016-12-31  Christi Retail

Table B

ID SkEY
1  1.1
2  1.2
3  1.3

The following query is working but taking a long time as the number of columns are around 60(just used sample 3). performance isn't good at all as the result is taking 1 hour for 20 days partitions to process, Can you please figure out and optimise the query.

from pyspark.sql import sparksession
from pyspark.sql import functions as F
from pyspark import HiveContext
hiveContext= HiveContext(sc)

def UDF_df(i):
    print(i[0])
ABC2 = spark.sql(
    "select * From A where day ='{0}'".format(i[0])
)
Join = ABC2.join(
    Tab2,
     (
        ABC2.ID == Tab2.ID
    )
).select(
    Tab2.skey,
    ABC2.Day,
    ABC2.Name,
    ABC2.Description
)
Join.select(
    "Tab2.skey",
    "ABC2.Day",
    "ABC2.Name",
    "ABC2.Description"
).write.mode("append").format("parquet").insertinto("Table")

ABC=spark.sql(
    "select distinct day from A where day<= '2016-01-01' and day<='2016-12-31'"
)
Tab2=spark.sql("select * from B where day is not null")
for in in ABC.collect():
    UDF_df(i)

Above is the pyspark code for a month that I've considered just to test the total time. A Join B with ID and output ID along with other columns of A.  It's taking 1 hour to complete. Is there any better way of optimising the query by taking either 1 month or 1 year of data. And also output table is partitioned on 2 columns where the data is getting inserted which is why hive contexts are used.

Body:
I've build a third table C with three columns -
Start_Date  End_Date Month_No
2016-01-01 2016-01-31 1
2016-02-01 2016-02-28 2
2016-03-01 2016-03-31 3
2016-04-01 2016-04-30 4
2016-05-01 2016-05-31 5
2016-06-01 2016-06-30 6
2016-07-01 2016-07-31 7
2016-08-01 2016-08-31 8
2016-09-01 2016-09-30 9
2016-10-01 2016-10-30 10
2016-11-01 2016-11-31 11
2016-12-01 2016-12-31 12
,
Used a Range[1-12) & then "select * From A where day >=start_date & day<=End_Date & month_no='{0}'".format(i[0]). Called the loop which solved the code.


问:
How does comparing two chars (within a string) work in Python
I am starting to learn Python and looked at following website: https://www.w3resource.com/python-exercises/string/
I work on #4 which is "Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself."

```<code>str="restart"
char=str[0]
print(char)

strcpy=str
i=1
for i in range(len(strcpy)):
  print(strcpy[i], "\n")
  if strcpy[i] is char:
    strcpy=strcpy.replace(strcpy[i], '$')
print(strcpy)
</code>```

I would expect "resta$t" but the actual result is: $esta$t

Thank you for your help!

答:
There are some need of modification on your code.

Modify your code with as given in below.

```<code>strcpy="restart"

i=1
for i in range(len(strcpy)):
   strcpy=strcpy.replace(strcpy[0], '$')[:]
print(strcpy)
# $esta$t
</code>```

Also, the best practice to write code in Python is to use Function. You can modify your code as given below or You can use this function.

```<code>def charreplace(s):
   return s.replace(s[0],'$')[:]

charreplace("restart")
#'$esta$t'
</code>```

Hope this helpful.

Body:
I am starting to learn Python and looked at following website: https://www.w3resource.com/python-exercises/string/
I work on #4 which is "Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself."

str="restart"
char=str[0]
print(char)

strcpy=str
i=1
for i in range(len(strcpy)):
  print(strcpy[i], "\n")
  if strcpy[i] is char:
    strcpy=strcpy.replace(strcpy[i], '$')
print(strcpy)

I would expect "resta$t" but the actual result is: $esta$t

Thank you for your help!

Body:
There are some need of modification on your code.

Modify your code with as given in below.

strcpy="restart"

i=1
for i in range(len(strcpy)):
   strcpy=strcpy.replace(strcpy[0], '$')[:]
print(strcpy)
# $esta$t

Also, the best practice to write code in Python is to use Function. You can modify your code as given below or You can use this function.

def charreplace(s):
   return s.replace(s[0],'$')[:]

charreplace("restart")
#'$esta$t'

Hope this helpful.


问:
How to make use of the Cython modules in Apache Beam?
Beam has support for Cython, but there are no instructions how to make use of it in an application (https://beam.apache.org/get-started/quickstart-py/). Are there any extra dependencies that need to be installed?</p>

答:
You are correct that the Python SDK has some Cython optimizations.

To ensure that these are available to you when you install Beam, make sure to have Cython installed in your environment. If you have Cython installed, Beam will go ahead and compile its modules when possible.

In short, before running pip install apache-beam, you'd want to run pip install Cython first.

To add some more detail, check out Beam's setup.py. When Beam is installed, it will check for a Cython installation, and if it does find one, it will attempt to cythonize its modules.