问:
LUIS chatbot integration with Power BI
Is there any way to get the graph from Power BI through API call? I find that there is embed URL returned by Power BI API call, but is there any way to send this embed URL and show the graph or report in chatbot (Skype or teams)?</p>

答:
You have a few options available to you, but each is limited in different ways. All are imperfect given your specific request (i.e. chart displayed in chat). You will need to decide which is best for you.

1) Send an adaptive card (or hero card) that contains a clickable link (via your bot) - This will open a separate tab/window displaying the linked content. The below includes an icon image next to the link, but you could include a full image indicating the graph/report. You can experiment with designing adaptive cards here.

async sendCardStep (stepContext) {
    const adaptiveCard = {
        "type": "AdaptiveCard",
        "version": "1.0",
        "body": [
            {
                "type": "TextBlock",
                "text": "Power BI Report",
                "size": "Large"
            },
            {
                "type": "TextBlock",
                "text": "Description of the report..."
            },
            {
                "type": "Container",
                "items": [
                    {
                        "type": "ColumnSet",
                        "columns": [
                            {
                                "type": "Column",
                                "width": "stretch",
                                "minHeight": "200px",
                                "id": "column1",
                                "items": [
                                    {
                                        "type": "Image",
                                        "altText": "",
                                        "url": "<<some link>>",
                                        "height": "200px",
                                        "width": "20px"
                                    }
                                ]
                            },
                            {
                                "type": "Column",
                                "width": "stretch",
                                "selectAction": {
                                    "type": "Action.OpenUrl",
                                    "id": "powerBIAction",
                                    "title": "Click to Open",
                                    "url": "<<some link>>"
                                },
                                "id": "colum2",
                                "style": "default",
                                "items": [
                                    {
                                        "type": "ActionSet",
                                        "actions": [
                                            {
                                                "type": "Action.OpenUrl",
                                                "title": "Click to Open",
                                                "url": "<<some link>>",
                                                "id": "openUrl"
                                            }
                                        ]
                                    }
                                ],
                                "verticalContentAlignment": "Center"
                            }
                        ],
                        "id": "columnSet",
                        "minHeight": "200px",
                        "horizontalAlignment": "Left"
                    }
                ]
            }
        ],
        "$schema": "http://adaptivecards.io/schemas/adaptive-card.json"
    }

    const adaptiveMessage = CardFactory.adaptiveCard(adaptiveCard);
    await context.sendActivity({attachments:[adaptiveMessage]});
}
```

<p><img src="https://i.stack.imgur.com/Esigl.png" alt="enter image description here"></p>

<p><strong>2) Create a static tab (via your Teams manifest)</strong> - This can display the linked content in the tab. However, this likely will require some level of authentication which I am lacking. Technically, this works in that the tab shows the sign-in button required to access the content. However, the sign-in button for me quickly opens and closes a browser window without allowing actual sign-in to occur for the tab. Unsure if this is specific to me or a larger issue (developer's console shows an error...may be a bug needing a proper fix). There is an open-in-browser button that, when clicked, <em>will</em> open the report in the user's browser. You can reference the custom tabs docs here.</p>

<pre class="lang-js prettyprint-override"><code>{
  [...],
  "staticTabs": [
    {
      "entityId": "powerBITab",
      "name": "Power BI Report Tab",
      "contentUrl": "<<some link>>",
      "websiteUrl": "<<some link>>",
      "scopes": [
        "personal"
      ]
    }
  ],
  [...]
}
</code>```

3) Create a task module (via your Teams manifest & bot) - This is similar to option #1. The difference is it becomes a function of your bot and Teams and not strictly your bot. In other words, it is accessible from your bot, but in response to some action taken in Teams (vs. a waterfall step or component dialog activity sent from your bot). You can reference the task modules docs here.

```<code>{
  [...],
  "composeExtensions": [
    {
      "botId": "613ed145-a6da-4412-9435-30ac5325c84e",
      "commands": [
        {
          "id": "openPowerBI",
          "type": "action",
          "context": [
            "compose"
          ],
          "description": "Command to run action to open Power BI graph",
          "title": "Open Power BI Report",
          "fetchTask": true,
          "taskInfo": {
            "title": "Card title",
            "width": "medium",
            "height": "medium",
            "url": "<<some link>>"
          }
        }
      ]
    }
  ],
  [...]
}
</code>```

const { TeamsActivityHandler, CardFactory, MessageFactory } = require('botbuilder');

class TeamsMessagingExtensionsActionBot extends TeamsActivityHandler {
    constructor() {
        super();
        // See https://aka.ms/about-bot-activity-message to learn more about the message and other activity types.
        this.onMessage(async (context, next) => {
            const heroCard = this.getHeroCardMenu();
            const heroMessage = MessageFactory.attachment(heroCard);
            await context.sendActivity(heroMessage);

            // By calling next() you ensure that the next BotHandler is run.
            await next();
        });

        this.onMembersAdded(async (context, next) => {
            const card = this.getGetHeroCardMenu();
            const message = MessageFactory.attachment(card);
            await context.sendActivity(message);

            // By calling next() you ensure that the next BotHandler is run.
            await next();
        });
    };

    getHeroCardMenu() {
        return CardFactory.heroCard('Open Power BI Report',
            'Description of the report...',
            null, // No images
            [{ type: 'invoke', title: 'Click to Open', value: { type: 'task/fetch', data: 'adaptivecard' } }]);
    }

    handleTeamsTaskModuleFetch(context, taskModuleRequest) {
        // taskModuleRequest.data can be checked to determine different paths.

        return {
            task: {
                type: 'continue',
                value: {
                    card: this.getTaskModuleAdaptiveCard(),
                    height: 220,
                    width: 400,
                    title: 'Adaptive Card: Inputs'
                }
            }
        };
    }

    getTaskModuleAdaptiveCard() {
        return CardFactory.adaptiveCard({
            version: '1.0.0',
            type: 'AdaptiveCard',
            "body": [
                {
                    "type": "TextBlock",
                    "text": "Power BI Report"
                },
                {
                    "type": "ActionSet",
                    "actions": [
                        {
                            "type": "Action.OpenUrl",
                            "title": "Click to Open",
                            "url": "<<some link>>",
                            "id": "powerBIAction",
                            "iconUrl": "<<some link>>"
                        }
                    ]
                }
            ]
        });
    }
}

module.exports.TeamsMessagingExtensionsActionBot = TeamsMessagingExtensionsActionBot;
```

<p><img src="https://i.stack.imgur.com/yBuBI.png" alt="enter image description here"></p>

<p><strong>4) Create an action messaging extension (via your Teams manifest)</strong> - This creates a modal with the report embedded within it. Presently, it suffers the same problem as the tab in that it displays the report sign-in button, but only flashes open a browser window which is immediately closed. Again, I'm unsure if this error is specific to me or not. There is no open-in-browser button option. You can reference the messaging extension docs here.</p>

<pre class="lang-js prettyprint-override"><code>const { TeamsActivityHandler } = require('botbuilder');

class TeamsMessagingExtensionsActionBot extends TeamsActivityHandler {
    handleTeamsMessagingExtensionFetchTask(context, action) {
        return {
            task: {
                type: 'continue',
                value: {
                    width: 500,
                    height: 450,
                    title: 'Open Power BI Report',
                    url: '<<some link>>',
                    fallbackUrl: 'https://powerbi.microsoft.com/en-us/'
                }
            }
        };
    }
}

module.exports.TeamsMessagingExtensionsActionBot = TeamsMessagingExtensionsActionBot;
</code>```

App manifests - Lastly, the app manifest will require certain properties to be included for your bot or messaging extensions to work fully with Teams. Look over the app manifest checklist, including the snippet at the bottom regarding Submission extras for bots. Always good to reference the manifest schema, as well.

Hope of help!

Title: LUIS chatbot integration with Power BI

Body:
You have a few options available to you, but each is limited in different ways. All are imperfect given your specific request (i.e. chart displayed in chat). You will need to decide which is best for you.

1) Send an adaptive card (or hero card) that contains a clickable link (via your bot) - This will open a separate tab/window displaying the linked content. The below includes an icon image next to the link, but you could include a full image indicating the graph/report. You can experiment with designing adaptive cards here.

async sendCardStep (stepContext) {
    const adaptiveCard = {
        "type": "AdaptiveCard",
        "version": "1.0",
        "body": [
            {
                "type": "TextBlock",
                "text": "Power BI Report",
                "size": "Large"
            },
            {
                "type": "TextBlock",
                "text": "Description of the report..."
            },
            {
                "type": "Container",
                "items": [
                    {
                        "type": "ColumnSet",
                        "columns": [
                            {
                                "type": "Column",
                                "width": "stretch",
                                "minHeight": "200px",
                                "id": "column1",
                                "items": [
                                    {
                                        "type": "Image",
                                        "altText": "",
                                        "url": "<<some link>>",
                                        "height": "200px",
                                        "width": "20px"
                                    }
                                ]
                            },
                            {
                                "type": "Column",
                                "width": "stretch",
                                "selectAction": {
                                    "type": "Action.OpenUrl",
                                    "id": "powerBIAction",
                                    "title": "Click to Open",
                                    "url": "<<some link>>"
                                },
                                "id": "colum2",
                                "style": "default",
                                "items": [
                                    {
                                        "type": "ActionSet",
                                        "actions": [
                                            {
                                                "type": "Action.OpenUrl",
                                                "title": "Click to Open",
                                                "url": "<<some link>>",
                                                "id": "openUrl"
                                            }
                                        ]
                                    }
                                ],
                                "verticalContentAlignment": "Center"
                            }
                        ],
                        "id": "columnSet",
                        "minHeight": "200px",
                        "horizontalAlignment": "Left"
                    }
                ]
            }
        ],
        "$schema": "http://adaptivecards.io/schemas/adaptive-card.json"
    }

    const adaptiveMessage = CardFactory.adaptiveCard(adaptiveCard);
    await context.sendActivity({attachments:[adaptiveMessage]});
}

2) Create a static tab (via your Teams manifest) - This can display the linked content in the tab. However, this likely will require some level of authentication which I am lacking. Technically, this works in that the tab shows the sign-in button required to access the content. However, the sign-in button for me quickly opens and closes a browser window without allowing actual sign-in to occur for the tab. Unsure if this is specific to me or a larger issue (developer's console shows an error...may be a bug needing a proper fix). There is an open-in-browser button that, when clicked, will open the report in the user's browser. You can reference the custom tabs docs here.

{
  [...],
  "staticTabs": [
    {
      "entityId": "powerBITab",
      "name": "Power BI Report Tab",
      "contentUrl": "<<some link>>",
      "websiteUrl": "<<some link>>",
      "scopes": [
        "personal"
      ]
    }
  ],
  [...]
}

3) Create a task module (via your Teams manifest & bot) - This is similar to option #1. The difference is it becomes a function of your bot and Teams and not strictly your bot. In other words, it is accessible from your bot, but in response to some action taken in Teams (vs. a waterfall step or component dialog activity sent from your bot). You can reference the task modules docs here.

{
  [...],
  "composeExtensions": [
    {
      "botId": "613ed145-a6da-4412-9435-30ac5325c84e",
      "commands": [
        {
          "id": "openPowerBI",
          "type": "action",
          "context": [
            "compose"
          ],
          "description": "Command to run action to open Power BI graph",
          "title": "Open Power BI Report",
          "fetchTask": true,
          "taskInfo": {
            "title": "Card title",
            "width": "medium",
            "height": "medium",
            "url": "<<some link>>"
          }
        }
      ]
    }
  ],
  [...]
}

const { TeamsActivityHandler, CardFactory, MessageFactory } = require('botbuilder');

class TeamsMessagingExtensionsActionBot extends TeamsActivityHandler {
    constructor() {
        super();
        // See https://aka.ms/about-bot-activity-message to learn more about the message and other activity types.
        this.onMessage(async (context, next) => {
            const heroCard = this.getHeroCardMenu();
            const heroMessage = MessageFactory.attachment(heroCard);
            await context.sendActivity(heroMessage);

            // By calling next() you ensure that the next BotHandler is run.
            await next();
        });

        this.onMembersAdded(async (context, next) => {
            const card = this.getGetHeroCardMenu();
            const message = MessageFactory.attachment(card);
            await context.sendActivity(message);

            // By calling next() you ensure that the next BotHandler is run.
            await next();
        });
    };

    getHeroCardMenu() {
        return CardFactory.heroCard('Open Power BI Report',
            'Description of the report...',
            null, // No images
            [{ type: 'invoke', title: 'Click to Open', value: { type: 'task/fetch', data: 'adaptivecard' } }]);
    }

    handleTeamsTaskModuleFetch(context, taskModuleRequest) {
        // taskModuleRequest.data can be checked to determine different paths.

        return {
            task: {
                type: 'continue',
                value: {
                    card: this.getTaskModuleAdaptiveCard(),
                    height: 220,
                    width: 400,
                    title: 'Adaptive Card: Inputs'
                }
            }
        };
    }

    getTaskModuleAdaptiveCard() {
        return CardFactory.adaptiveCard({
            version: '1.0.0',
            type: 'AdaptiveCard',
            "body": [
                {
                    "type": "TextBlock",
                    "text": "Power BI Report"
                },
                {
                    "type": "ActionSet",
                    "actions": [
                        {
                            "type": "Action.OpenUrl",
                            "title": "Click to Open",
                            "url": "<<some link>>",
                            "id": "powerBIAction",
                            "iconUrl": "<<some link>>"
                        }
                    ]
                }
            ]
        });
    }
}

module.exports.TeamsMessagingExtensionsActionBot = TeamsMessagingExtensionsActionBot;

4) Create an action messaging extension (via your Teams manifest) - This creates a modal with the report embedded within it. Presently, it suffers the same problem as the tab in that it displays the report sign-in button, but only flashes open a browser window which is immediately closed. Again, I'm unsure if this error is specific to me or not. There is no open-in-browser button option. You can reference the messaging extension docs here.

const { TeamsActivityHandler } = require('botbuilder');

class TeamsMessagingExtensionsActionBot extends TeamsActivityHandler {
    handleTeamsMessagingExtensionFetchTask(context, action) {
        return {
            task: {
                type: 'continue',
                value: {
                    width: 500,
                    height: 450,
                    title: 'Open Power BI Report',
                    url: '<<some link>>',
                    fallbackUrl: 'https://powerbi.microsoft.com/en-us/'
                }
            }
        };
    }
}

module.exports.TeamsMessagingExtensionsActionBot = TeamsMessagingExtensionsActionBot;

App manifests - Lastly, the app manifest will require certain properties to be included for your bot or messaging extensions to work fully with Teams. Look over the app manifest checklist, including the snippet at the bottom regarding Submission extras for bots. Always good to reference the manifest schema, as well.

Hope of help!


来源: stackexchange

问:
AudioKit iOS Setting Input and Output devices
Have an app that can record audio and play it with another audio simultaneously.

What I Want: To be able to switch Audio Input And Output devices. For example. Record Audio from iPhone build in mic and listen audio through wired or bluetooth headphones. and vice versa

What am I trying to do:

```<code>            do {
                print("Seted Input:\(String(describing: AudioKit.inputDevice))")
                if let inputs = AudioKit.inputDevices {
                    print("Selected Input:\(String(describing: [indexPath.row]))")
                    try AudioKit.setInputDevice(inputs[indexPath.row])
                    try PlayerManager.sharedInstance.mic.setDevice(inputs[indexPath.row])
                    print("Selected Input:\(String(describing: AudioKit.inputDevice))")
                }
            } catch let error as NSError{
                print(error)
            }
</code>```

Result:

```<code>Seted Input:Optional(<Device: Микрофон гарнитуры (Wired Microphone)>)
Selected Input:<Device: iPhone Микрофон (Built-In Microphone Снизу)>
Selscted Input:Optional(<Device: Микрофон гарнитуры (Wired Microphone)>)
Selected Output:Optional(<Device: Наушники (Wired Headphones)>)
</code>```

Question: How to properly set input device with AudioKit.

I'am using xCode 9.3 (9E145) and AudioKit (4.2.1)

P.S It would be great if some one help me with output setting too.
AudioKit.outputDevices always return 1 device to me, even if bluetooth and wired headphones connected

答:
```<code>do {
        try AudioKit.setInputDevice(AudioKit.inputDevices![0])
    } catch {
        AKLog("AudioKit setInputDevice failed")
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Have an app that can record audio and play it with another audio simultaneously.

What I Want: To be able to switch Audio Input And Output devices. For example. Record Audio from iPhone build in mic and listen audio through wired or bluetooth headphones. and vice versa

What am I trying to do:

            do {
                print("Seted Input:\(String(describing: AudioKit.inputDevice))")
                if let inputs = AudioKit.inputDevices {
                    print("Selected Input:\(String(describing: [indexPath.row]))")
                    try AudioKit.setInputDevice(inputs[indexPath.row])
                    try PlayerManager.sharedInstance.mic.setDevice(inputs[indexPath.row])
                    print("Selected Input:\(String(describing: AudioKit.inputDevice))")
                }
            } catch let error as NSError{
                print(error)
            }

Result:

Seted Input:Optional(<Device: Микрофон гарнитуры (Wired Microphone)>)
Selected Input:<Device: iPhone Микрофон (Built-In Microphone Снизу)>
Selscted Input:Optional(<Device: Микрофон гарнитуры (Wired Microphone)>)
Selected Output:Optional(<Device: Наушники (Wired Headphones)>)

Question: How to properly set input device with AudioKit.

I'am using xCode 9.3 (9E145) and AudioKit (4.2.1)

P.S It would be great if some one help me with output setting too.
AudioKit.outputDevices always return 1 device to me, even if bluetooth and wired headphones connected


问:
Absolute/outer and inner namespace confusion in C#
```<code>using Foo.Uber;

namespace MyStuff.Foo
{
    class SomeClass{
        void DoStuff(){
            // I want to reference the outer "absolute" Foo.Uber
            // but the compiler thinks I'm refering to MyStuff.Foo.Uber
            var x = Foo.Uber.Bar();
        }
    }
}
</code>```

How could I solve this? Just moving the using statement inside my namespace doesn't help.

答: You can assign an alias in your using directive as described on MSDN.</p>

ContentLicense: CC BY-SA 3.0

Body:
using Foo.Uber;

namespace MyStuff.Foo
{
    class SomeClass{
        void DoStuff(){
            // I want to reference the outer "absolute" Foo.Uber
            // but the compiler thinks I'm refering to MyStuff.Foo.Uber
            var x = Foo.Uber.Bar();
        }
    }
}

How could I solve this? Just moving the using statement inside my namespace doesn't help.


问:
Why does my JavaScript event listener condition not work?
This event listener is executed when I click anywhere in the document, I would like it to not execute when I click on this.dropdown or when I click on this.inputField. Now it executes even when i click on these two elements.

```<code>constructor(inputField, monthInput, previousMonth, nextMonth, dates, dropdown, document) {
        this.monthInput = monthInput;
        this.previousMonth = previousMonth;
        this.nextMonth = nextMonth;
        this.dates = dates;
        this.dropdown = dropdown;
        this.inputField = inputField;
        this.document = document;

this.document.addEventListener('click', (e) => {
            if (e.target.id !== this.dropdown.id && e.target.id !== this.inputField.id) {
                this.dropdown.style.display = 'none';
            }
        });
}
</code>```

Thank you for any suggestions!

答:
Capture the click event on those elements and stop the event propagation:

```<code>this.dropdown.addEventListener('click', (e) => {
  console.log('Element clicked');
  e.stopPropagation();
});
</code>```

https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation

Body:
This event listener is executed when I click anywhere in the document, I would like it to not execute when I click on this.dropdown or when I click on this.inputField. Now it executes even when i click on these two elements.

constructor(inputField, monthInput, previousMonth, nextMonth, dates, dropdown, document) {
        this.monthInput = monthInput;
        this.previousMonth = previousMonth;
        this.nextMonth = nextMonth;
        this.dates = dates;
        this.dropdown = dropdown;
        this.inputField = inputField;
        this.document = document;

this.document.addEventListener('click', (e) => {
            if (e.target.id !== this.dropdown.id && e.target.id !== this.inputField.id) {
                this.dropdown.style.display = 'none';
            }
        });
}

Thank you for any suggestions!

Body:
Capture the click event on those elements and stop the event propagation:

this.dropdown.addEventListener('click', (e) => {
  console.log('Element clicked');
  e.stopPropagation();
});

https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation


问:
Console.log of function returning object
So I have a function which is returning an object which has an object as value. I need to console.log the result of the function, however what I get is this:

```<code> testedDatalayer: {
    event: 'mkt_pageInformation',
    eventDetails: { page: [Object], pagePath: '/' }
  }
</code>```

I need to display the value as normal instead of [Object]. I know I can stringify it, however I really want to keep it as an object rather then string and make it look like this:

```<code> expectedDataLayer: {
    event: 'mkt_pageInformation',
    page: { type: 'xxx', category: 'xxxx' },
    pagePath: 'xxxxx'
  },
</code>```

Is there any way of keeping that structure and console logging the function without the need of strinfigy?

EDIT: doing it on node.js and logging to cmd

答:
You can format it as an object structure using JSON.stringify() third parameter to pretty print Object.

var objectToLog = {
    expectedDataLayer: {
        event: 'mkt_pageInformation',
        details: { page: { type: 'xxx', category: 'xxxx' } },
        pagePath: 'xxxxx'
    }
}

console.log(JSON.stringify(objectToLog,null,4));```

Body:
So I have a function which is returning an object which has an object as value. I need to console.log the result of the function, however what I get is this:

 testedDatalayer: {
    event: 'mkt_pageInformation',
    eventDetails: { page: [Object], pagePath: '/' }
  }

I need to display the value as normal instead of [Object]. I know I can stringify it, however I really want to keep it as an object rather then string and make it look like this:

 expectedDataLayer: {
    event: 'mkt_pageInformation',
    page: { type: 'xxx', category: 'xxxx' },
    pagePath: 'xxxxx'
  },

Is there any way of keeping that structure and console logging the function without the need of strinfigy?

EDIT: doing it on node.js and logging to cmd


问:
Scheduling a native alarm/timer
I'm using Ionic Framework to build an Android/iPhone cookbook app with Angular.

One of the features should be alarms/timers for each ingredient/step.

Ionic is based on a wrapper around Apache Cordova, I guess. So I've tried using a Cordova plugin, from an answer below... but it's older and it's not specifically for Ionic, and I've tried a few times but it just hasn't worked for me.  I haven't found any alternatives.

  doSomething() {

    let successCallback = () => window.confirm('success');
    let errorCallback = () => window.confirm('fail');

    // set wakeup timer
    (<any>window).plugins.wakeuptimer.wakeup(successCallback,
      errorCallback,
      // a list of alarms to set
      {
          alarms : [{
              type : 'onetime',
              time : { seconds  : 5 },
              extra : { message : 'json containing app-specific information to be posted when alarm triggers' },
              message : 'Alarm has expired!'
          }]
      }
    );
  }
```

Local notifications are kind of an option, but it's just a notification. It doesn't work like a native alarm clock. (It's like getting a text, but you miss it so your burgers burn.)

Can anyone give an example of an alarm or timer in a modern Ionic app? Maybe I'm just missing something to get the plugin to work?

Or is there any kind of alternative I'm missing?

I'm getting bummed that the app is almost done but I've been stuck on this. :(

答:
The plugin you are attempting to use is almost 5 years old. Older than Ionic 2
if you using Ionic v3 and you try to install the plugin will return this erore

so the best solution for you use Local Notifications

Good luck.

Title: Scheduling a native alarm/timer

Body:
I'm using Ionic Framework to build an Android/iPhone cookbook app with Angular.

One of the features should be alarms/timers for each ingredient/step.

Ionic is based on a wrapper around Apache Cordova, I guess. So I've tried using a Cordova plugin, from an answer below... but it's older and it's not specifically for Ionic, and I've tried a few times but it just hasn't worked for me.  I haven't found any alternatives.

  doSomething() {

    let successCallback = () => window.confirm('success');
    let errorCallback = () => window.confirm('fail');

    // set wakeup timer
    (<any>window).plugins.wakeuptimer.wakeup(successCallback,
      errorCallback,
      // a list of alarms to set
      {
          alarms : [{
              type : 'onetime',
              time : { seconds  : 5 },
              extra : { message : 'json containing app-specific information to be posted when alarm triggers' },
              message : 'Alarm has expired!'
          }]
      }
    );
  }

Local notifications are kind of an option, but it's just a notification. It doesn't work like a native alarm clock. (It's like getting a text, but you miss it so your burgers burn.)

Can anyone give an example of an alarm or timer in a modern Ionic app? Maybe I'm just missing something to get the plugin to work?

Or is there any kind of alternative I'm missing?

I'm getting bummed that the app is almost done but I've been stuck on this. :(


问:
Clunky/slow dragging functionality on my analog clock project
I just finished my first Python project, an analog clock. I managed to reach a state where I implemented everything I had in mind and fixed the issues that followed. The last thing I added in is a dragging capability for my clock and while it works it seems slow or at least just unsmooth. Right now I lack the knowledge and experience to understand why its happening and let alone fix it.. Any help or ideas would be appreciated, Thanks in advance. :)

Here is my code:

```<code># Imported tkinter for its methods
import tkinter as tk

# Imported turtle for drawing the clock's hands
import turtle

# Imported time to handle setting and updating the time
import time

# Declared and set the color used for transparency
transparent_clr = '#FB00FF'

# Setup a borderless window with transparent background
# and always on top flag
root = tk.Tk()
root.overrideredirect(True)
root.wm_attributes('-topmost', 1)
root.deiconify()
root.attributes('-transparentcolor', transparent_clr)

# Setup the clock's face using an image
Clock_bg = tk.PhotoImage(file='Clock_bg.png')
canvas = tk.Canvas(width=300, height=300, highlightthickness=0)
screen = turtle.TurtleScreen(canvas)
canvas.create_image(0, 0, image=Clock_bg)
canvas.pack()

screen.tracer(0)
screen.bgcolor(transparent_clr)

# Configure the pen used for the clock's hands
draw = turtle.RawTurtle(screen)
draw.hideturtle()
draw.speed(0)
draw.pensize(3)

# Retain Windows TaskBar visibility and function such as exiting
# the app
wn = tk.Toplevel(root)
wn.iconify()
wn.iconbitmap('Clock_icon.ico')
wn.attributes('-alpha', 0.0)

def wn_destroy():
    wn.protocol('WM_DELETE_WINDOW', exit_func)

def exit_func():
    root.destroy()

wn_destroy()

# Make the clock draggable

def draggable():
    root._offsetx = 0
    root._offsety = 0
    root.bind('<Button-1>', winclick)
    root.bind('<B1-Motion>', windrag)

def windrag(event):
    x = root.winfo_pointerx() - root._offsetx
    y = root.winfo_pointery() - root._offsety
    root.geometry('+{x}+{y}'.format(x=x, y=y))

def winclick(event):
    root._offsetx = event.x
    root._offsety = event.y

draggable()

# Draw the clock and its hands

def draw_clock(h, m, s, draw):

    # Draw the hours hand
    draw.penup()
    draw.goto(0, 0)
    draw.color('black')
    draw.setheading(90)
    angle = (h / 12) * 360 + (m / 60) * 30
    draw.rt(angle)
    draw.pendown()
    draw.fd(70)

    # Draw the minutes hand
    draw.penup()
    draw.goto(0, 0)
    draw.color('black')
    draw.setheading(90)
    angle = (m / 60) * 360 + (s / 60) * 6
    draw.rt(angle)
    draw.pendown()
    draw.fd(100)

    # Draw the seconds hand
    draw.penup()
    draw.goto(0, 0)
    draw.color('red')
    draw.setheading(90)
    angle = (s / 60) * 360
    draw.rt(angle)
    draw.pendown()
    draw.fd(60)

# Update the time in real time
while True:
    # Declared and set the hour, minutes and seconds
    h = int(time.strftime('%I'))
    m = int(time.strftime('%M'))
    s = int(time.strftime('%S'))

    draw_clock(h, m, s, draw)
    screen.update()

    time.sleep(1)

    draw.clear()
</code>```

答:
"You are using your own mainloop with time.sleep(1), therefore root.geometry( gets only called every second. –stovfl"

Thanks a billion, stovf1!

Body:
I just finished my first Python project, an analog clock. I managed to reach a state where I implemented everything I had in mind and fixed the issues that followed. The last thing I added in is a dragging capability for my clock and while it works it seems slow or at least just unsmooth. Right now I lack the knowledge and experience to understand why its happening and let alone fix it.. Any help or ideas would be appreciated, Thanks in advance. :)

Here is my code:

# Imported tkinter for its methods
import tkinter as tk

# Imported turtle for drawing the clock's hands
import turtle

# Imported time to handle setting and updating the time
import time

# Declared and set the color used for transparency
transparent_clr = '#FB00FF'

# Setup a borderless window with transparent background
# and always on top flag
root = tk.Tk()
root.overrideredirect(True)
root.wm_attributes('-topmost', 1)
root.deiconify()
root.attributes('-transparentcolor', transparent_clr)

# Setup the clock's face using an image
Clock_bg = tk.PhotoImage(file='Clock_bg.png')
canvas = tk.Canvas(width=300, height=300, highlightthickness=0)
screen = turtle.TurtleScreen(canvas)
canvas.create_image(0, 0, image=Clock_bg)
canvas.pack()

screen.tracer(0)
screen.bgcolor(transparent_clr)

# Configure the pen used for the clock's hands
draw = turtle.RawTurtle(screen)
draw.hideturtle()
draw.speed(0)
draw.pensize(3)

# Retain Windows TaskBar visibility and function such as exiting
# the app
wn = tk.Toplevel(root)
wn.iconify()
wn.iconbitmap('Clock_icon.ico')
wn.attributes('-alpha', 0.0)

def wn_destroy():
    wn.protocol('WM_DELETE_WINDOW', exit_func)

def exit_func():
    root.destroy()

wn_destroy()

# Make the clock draggable

def draggable():
    root._offsetx = 0
    root._offsety = 0
    root.bind('<Button-1>', winclick)
    root.bind('<B1-Motion>', windrag)

def windrag(event):
    x = root.winfo_pointerx() - root._offsetx
    y = root.winfo_pointery() - root._offsety
    root.geometry('+{x}+{y}'.format(x=x, y=y))

def winclick(event):
    root._offsetx = event.x
    root._offsety = event.y

draggable()

# Draw the clock and its hands

def draw_clock(h, m, s, draw):

    # Draw the hours hand
    draw.penup()
    draw.goto(0, 0)
    draw.color('black')
    draw.setheading(90)
    angle = (h / 12) * 360 + (m / 60) * 30
    draw.rt(angle)
    draw.pendown()
    draw.fd(70)

    # Draw the minutes hand
    draw.penup()
    draw.goto(0, 0)
    draw.color('black')
    draw.setheading(90)
    angle = (m / 60) * 360 + (s / 60) * 6
    draw.rt(angle)
    draw.pendown()
    draw.fd(100)

    # Draw the seconds hand
    draw.penup()
    draw.goto(0, 0)
    draw.color('red')
    draw.setheading(90)
    angle = (s / 60) * 360
    draw.rt(angle)
    draw.pendown()
    draw.fd(60)

# Update the time in real time
while True:
    # Declared and set the hour, minutes and seconds
    h = int(time.strftime('%I'))
    m = int(time.strftime('%M'))
    s = int(time.strftime('%S'))

    draw_clock(h, m, s, draw)
    screen.update()

    time.sleep(1)

    draw.clear()


问:
Automated importing/renaming of Flash assets
So I have an AS3 flash project with A LOT of assets, roughly 1000 at the time being but that may expand to several thousand later. They are all images but half of them are Animated GIFs so I can't import them at runtime. I considered simply dragging them into the flash project but I don't seem to have any control over the naming scheme. Basically, what I want to know is:

Is there a way to automate importing and renaming of flash assets, like "Import these 1000 files and export them for Actionscript with this name"?

Additionally, is there a better way for me to be doing this? I've tried http://code.google.com/p/as3gif/ AS3GIF but it struggles with larger animated gifs like the ones I'm working with (650x450). Any help would be appreciated.

答:
Jsfl is your friend. Jsfl is Flash IDE script language, you can automate a lot of thing, for example, rename all lib clip :

```<code>function main()
{
    var DOM = fl.getDocumentDOM();
    var lib = DOM.library.getSelectedItems();

    searchedClip = prompt("Search in clip name :");
    if(searchedClip == null) return;

    replaceClip = prompt("Replace by :");
    if(replaceClip == null) return;

    fl.outputPanel.clear();

    nbRes = 0;
    for(var i =0; i < lib.length; ++i)
    {
        name = lib[i].name.split("/");
        name = name[name.length-1];
        nIndex = name.toUpperCase().indexOf(searchedClip.toUpperCase());
        if(nIndex != -1)
        {
            ++nbRes;
            fl.trace(lib[i].name);
            lib[i].name = name.substring(0,nIndex) + replaceClip + name.substring(nIndex+searchedClip.length);
        }
    }
    if(nbRes) fl.trace("\n"+nbRes+" results");
    else fl.trace("no result");
}
main();
</code>```

Look Flash IDE doc (http://livedocs.adobe.com/flash/9.0/main/flash_cs3_extending.pdf for CS3 Flash IDE Version)

Body:
Jsfl is your friend. Jsfl is Flash IDE script language, you can automate a lot of thing, for example, rename all lib clip :

function main()
{
    var DOM = fl.getDocumentDOM();
    var lib = DOM.library.getSelectedItems();

    searchedClip = prompt("Search in clip name :");
    if(searchedClip == null) return;

    replaceClip = prompt("Replace by :");
    if(replaceClip == null) return;

    fl.outputPanel.clear();

    nbRes = 0;
    for(var i =0; i < lib.length; ++i)
    {
        name = lib[i].name.split("/");
        name = name[name.length-1];
        nIndex = name.toUpperCase().indexOf(searchedClip.toUpperCase());
        if(nIndex != -1)
        {
            ++nbRes;
            fl.trace(lib[i].name);
            lib[i].name = name.substring(0,nIndex) + replaceClip + name.substring(nIndex+searchedClip.length);
        }
    }
    if(nbRes) fl.trace("\n"+nbRes+" results");
    else fl.trace("no result");
}
main();

Look Flash IDE doc (http://livedocs.adobe.com/flash/9.0/main/flash_cs3_extending.pdf for CS3 Flash IDE Version)


问:
working with the collection of objects in laravel
Trying to work with the collection of objects.

the collection is NOT an Eloquent one but hand made Illuminate\Support\Collection

if i understood it right in the case of collection of objects i'm not able to use most of methods but only those which can use callback.

so, i have collection of objects:

and here is the code ($country = 'Russia'):

```<code>        dump($this->countries);
        $filtered = $this->countries->filter(function ($countryObj) use($country) {
            dump($countryObj->name == $country);
            return $countryObj->name == $country;
        });
        dd($filtered);
</code>```

i expect the $filtered contains only one element, the one which return true (in our case Russia)
but instead of it i have the same collection of 3 elements.

here is the rest of classes to be sure they are collection related

```<code>use App\Services\Taxes\DataSourceInterface;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

abstract class JsonModel extends Collection implements DataSourceInterface
{
    public function __construct()
    {
        parent::__construct($this->readDataFile(env('JSON_DATA_PATH')));
    }

    protected function readDataFile(string $path): array
    {
        $disk = Storage::disk('local');

        try {
            $dataObj = json_decode($disk->get($path), false, 10, JSON_THROW_ON_ERROR);
            return $this->loadData($dataObj);
        } catch (FileNotFoundException $e) {
            Log::error('Storage ' . $e->getMessage() . ' was not found');
        } catch (\JsonException $e) {
            Log::error('Json DataFile: ' . $e->getMessage());
        }

        return [];
    }

    abstract protected function loadData(object $dataObject): array;
}
</code>```

```<code>class JsonCountries extends JsonModel
{
    public function loadData(object $dataObject): array
    {
        $data = array_filter($dataObject->countries, function ($item){
            unset($item->states);
            return true;
        });

        return $data;
    }
}
</code>```

答:
problem was in new static which used inside laravel methods which return instance of collection and in fact that i dont expect array entry in my constructor.

choice between empty array and file reading fixes the problem

```<code>abstract class JsonModel extends Collection implements DataSourceInterface
{
    public function __construct($dataArr = [])
    {
        if(!is_array($dataArr))
           $dataArr = $this->readDataFile(env('JSON_DATA_PATH'));

        parent::__construct($dataArr);
    }
</code>```

Body:
Trying to work with the collection of objects.

the collection is NOT an Eloquent one but hand made Illuminate\Support\Collection

if i understood it right in the case of collection of objects i'm not able to use most of methods but only those which can use callback.

so, i have collection of objects:

and here is the code ($country = 'Russia'):

        dump($this->countries);
        $filtered = $this->countries->filter(function ($countryObj) use($country) {
            dump($countryObj->name == $country);
            return $countryObj->name == $country;
        });
        dd($filtered);

i expect the $filtered contains only one element, the one which return true (in our case Russia)
but instead of it i have the same collection of 3 elements.

here is the rest of classes to be sure they are collection related

use App\Services\Taxes\DataSourceInterface;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

abstract class JsonModel extends Collection implements DataSourceInterface
{
    public function __construct()
    {
        parent::__construct($this->readDataFile(env('JSON_DATA_PATH')));
    }

    protected function readDataFile(string $path): array
    {
        $disk = Storage::disk('local');

        try {
            $dataObj = json_decode($disk->get($path), false, 10, JSON_THROW_ON_ERROR);
            return $this->loadData($dataObj);
        } catch (FileNotFoundException $e) {
            Log::error('Storage ' . $e->getMessage() . ' was not found');
        } catch (\JsonException $e) {
            Log::error('Json DataFile: ' . $e->getMessage());
        }

        return [];
    }

    abstract protected function loadData(object $dataObject): array;
}

class JsonCountries extends JsonModel
{
    public function loadData(object $dataObject): array
    {
        $data = array_filter($dataObject->countries, function ($item){
            unset($item->states);
            return true;
        });

        return $data;
    }
}

Body:
problem was in new static which used inside laravel methods which return instance of collection and in fact that i dont expect array entry in my constructor.

choice between empty array and file reading fixes the problem

abstract class JsonModel extends Collection implements DataSourceInterface
{
    public function __construct($dataArr = [])
    {
        if(!is_array($dataArr))
           $dataArr = $this->readDataFile(env('JSON_DATA_PATH'));

        parent::__construct($dataArr);
    }


问:
JSON Array parsing where key is missing in the key-value pair
I am trying to parse a JSON Array which looks something like this

"data":["data1","data2","data3"]

If I write JSONArray arr = obj1.getJSONArray("data");, this will provide me with the JSON array but since the key name from key-value pair is missing, how will I retrieve "data1", "data2" and "data3"?

答:
Assuming this is your JSON,

{"data":["data1","data2","data3"]}

Use the following to retrieve the array,

```<code>JSONArray arrJson = jsonData.getJSONArray("data");
String[] arr = new String[arrJson.length()];
for(int i = 0; i < arrJson.length(); i++) {
    arr[i] = arrJson.getString(i);
}
</code>```

Body:
Assuming this is your JSON,

{"data":["data1","data2","data3"]}

Use the following to retrieve the array,

JSONArray arrJson = jsonData.getJSONArray("data");
String[] arr = new String[arrJson.length()];
for(int i = 0; i < arrJson.length(); i++) {
    arr[i] = arrJson.getString(i);
}


问:
How to update, rotate and display a ply file with python?
I tried using open3d, simpleRender and several other examples from the web but it was not good. SimpleRender is bugged and I can't start the python script at all. Open3d works but it has limited functionality. I am not able to display the ply file exactly as I want with open3d.

I have a stereo vision camera that generates new ply files every second. I need to display, rotate and update a ply file in a loop without closing the display window.

答:
Maybe you can try this:

convert your ply files to octree using PotreeConverter

Then you can use it's CLI in python using a subprocess.

It generates a HTML file that can be rendered.


问:
react function component inside class component, is a valid component ? What is the difference?
I'm trying to return a function component after the condition is checked within a class component. Here is my code:

```<code> class Page extends React.Component {
  constructor(props) {
    super(props);
    this.state = props.warn;
  }

   function WarningBanner() {
    if (this.state == false) {
      return null;
    }

    return (
      <div className="warning">
        Warning!
      </div>
    );
  }
  render() {
    return (
      <div>
        <WarningBanner />
      </div>
    );
  }
}

ReactDOM.render(
  <Page warn={true}/>,
  document.getElementById('root')
);
</code>```

Is a function component inside a class component considered a valid component ? Or is there a another way to define a function component inside a class component?

What is the difference between a function component inside class component or a function component outside a class component ?

I have also tried doing this:

```<code><WarningBanner warn = {this.state}/>
</code>```

And

```<code>function WarningBanner(warning) {
    if (warning.warn == false) {
      return null;
    }
    return (<div className="warning">Warning!</div>);
  }
</code>```

答:
You could do something like...

```<code>    class Page extends React.Component {
  constructor(props) {
    super(props);
    this.state = props.warn;
  }

  render() {
    return (
      <div>
        {this.props.warn && <div className="warning">Warning!</div>}
      </div>
    );
  }
}

ReactDOM.render(
  <Page warn={true}/>,
  document.getElementById('root')
);
</code>```

Where {this.props.warn &&
Warning!
} will evaluate if the condition is true and, if so, render the component.

If you wanted to make a more complex functional component, I would suggest creating it outside of your stateful component like this...

```<code>const Warning = () => {
  return (<div className="warning">Warning!</div>);
}

class Page extends React.Component {
  constructor(props) {
    super(props);
    this.state = props.warn;
  }

  render() {
    return (
      <div>
        {this.props.warn && <Warning />}
      </div>
    );
  }
}

ReactDOM.render(
  <Page warn={true}/>,
  document.getElementById('root')
);
</code>```

I would recommend this method to comply with React best practices, as outside of codepen you would have different files for different components.

Here's a pen to illustrate: https://codepen.io/paulmartin91/pen/zYGKRNa

hope this helps!

Body:
I'm trying to return a function component after the condition is checked within a class component. Here is my code:

 class Page extends React.Component {
  constructor(props) {
    super(props);
    this.state = props.warn;
  }

   function WarningBanner() {
    if (this.state == false) {
      return null;
    }

    return (

        Warning!

    );
  }
  render() {
    return (

        <WarningBanner />

    );
  }
}

ReactDOM.render(
  <Page warn={true}/>,
  document.getElementById('root')
);

Is a function component inside a class component considered a valid component ? Or is there a another way to define a function component inside a class component?

What is the difference between a function component inside class component or a function component outside a class component ?

I have also tried doing this:

<WarningBanner warn = {this.state}/>

And

function WarningBanner(warning) {
    if (warning.warn == false) {
      return null;
    }
    return (
Warning!
);
  }

Body:
You could do something like...

    class Page extends React.Component {
  constructor(props) {
    super(props);
    this.state = props.warn;
  }

  render() {
    return (
      <div>
        {this.props.warn && <div className="warning">Warning!</div>}
      </div>
    );
  }
}

ReactDOM.render(
  <Page warn={true}/>,
  document.getElementById('root')
);

Where {this.props.warn && <div className="warning">Warning!</div>} will evaluate if the condition is true and, if so, render the component.

If you wanted to make a more complex functional component, I would suggest creating it outside of your stateful component like this...

const Warning = () => {
  return (<div className="warning">Warning!</div>);
}

class Page extends React.Component {
  constructor(props) {
    super(props);
    this.state = props.warn;
  }

  render() {
    return (
      <div>
        {this.props.warn && <Warning />}
      </div>
    );
  }
}

ReactDOM.render(
  <Page warn={true}/>,
  document.getElementById('root')
);

I would recommend this method to comply with React best practices, as outside of codepen you would have different files for different components.

Here's a pen to illustrate: https://codepen.io/paulmartin91/pen/zYGKRNa

hope this helps!


问:
Table without a identity column but this column can't have repeated values
I'm creating a table that needs to have 2 columns. The first column can't be repeated. The thing is, I will insert the value of the first column. How do I create this column?
SQLServer 2005</p>

答: Make the first column the primary key of the table.</p>


问:
How do I 'lift up' a setState function in a react component using hooks?
I have a component with shared state that needs to be in sync.

One piece of state sets the current musical scale type, which should support every possible scale, but I'm starting out with minor and major. The second piece of state sets the correct notes for the chosen note name, based upon the scale type chosen. I have it mostly working, but I need to synchronize the state better so that one can react to the other.

It has been recommended by a few people in the react community to 'lift the state up', which I am trying to figure out how to do properly, especially using hooks.

So, I have been able to figure out how to lift up the state of the musical scale notes that was being set on the components into some objects full of arrays, but now I need to figure out how to lift up the onClick function in the following code, and there are 12 of these note name components, and each one is setting different musical scales to the notes state:

<NoteInput
  id="c"
  scale={scale}
  type="radio"
  name="notes"
  label="c"
  value="c"
  onClick={
    () => setNotes(
      scale === 'minor' ? scalePatterns['c-minor'] :
      scale === 'major' ? scalePatterns['c-major'] :
      ''
    )
  }
/>
<NoteLabel
  whileHover={{ scale: 1 }}
  whileTap={{ scale: 0.9 }}
  scale={scale}
  htmlFor="c"
>
  {
    scale === 'major' ? 'C' :
    scale === 'minor' ? 'C' :
    'C'
  }
</NoteLabel>
```

<p>So now I need to figure out how to 'lift up' the arrow function in the onClick prop into it's own function, but I don't know how to go about it, as the requirement is that I need to pass different state to each instance of the function, but keep that state in sync with another piece of state, which is setting the scale type that the note buttons then react to.</p>

<p>UPDATE:</p>

<p>Upon closer inspection, I believe the state functions as follows:</p>

```Scale Type
  |     \
  |      \
  |    Root Note
  |      /
  |     /
Scale Notes
```

...where the scale type will affect both which root note is chosen (C# or Db, for example) as well as the notes for the scale itself. Then the scale notes ALSO need to know the root note in combination with the scale type.

答:
Based on what I understood from your question, you have the following dependencies in your state -

```<code>Root Note       Scale
        \       /
         \     /
          Notes
</code>```

The notes state variable only changes when there is either a change in root note name (c/d/e etc) or scale (major/minor etc). You can abstract away all of the scale related state into a context and use it in the respective component as shown below. You can use the useEffect hook's 2nd arg to listen to state variable changes and perform side-effects.

ScalesContext.js

...

const SCALE_PATTERNS = {
  "c-major": ["c", "d", "e", "f", "g", "a", "b"],
  "c-minor": ["c", "d", "eflat", "f", "g", "aflat", "bflat"]
};

const ScalesContext = createContext(null);

export const ScalesContextProvider = ({ children }) => {
  const [rootNote, setRootNote] = useState(""); // 'c'
  const [scale, setScale] = useState(""); // 'major'
  const [notes, setNotes] = useState([]); // ['c', 'd', ...]

  // On scale/rootNote state change -> update notes
  useEffect(() => {
    const key = `${rootNote}-${scale}`;
    setNotes(SCALE_PATTERNS[key]);
  }, [scale, rootNote]);

  return (
    <ScalesContext.Provider
      value={{ rootNote, scale, notes, setScale, setRootNote }}
    >
      {children}
    </ScalesContext.Provider>
  );
};

export const useScalesContext = () => useContext(ScalesContext);
```

<p><strong>App.js</strong></p>

<pre class="lang-js prettyprint-override"><code>...

export default function App() {
  return (
    <div className="App">
      // Hook up Provider around ScaleSelect component
      <ScalesContextProvider>
        <ScaleSelect />
      </ScalesContextProvider>
    </div>
  );
}
</code>```

ScaleSelect.js

...

export const ScaleSelect = () => {
  const state = useScalesContext();
  const { rootNote, scale, notes, setScale, setRootNote } = state;

  return (

Root Note: {rootNote}

Scale: {scale}

      <input
        type="text"
        value={rootNote}
        placeholder="Root Note (try 'c')"
        onChange={e => setRootNote(e.target.value)}
      />
      <input
        type="text"
        placeholder="Scale (try 'major')"
        value={scale}
        onChange={e => setScale(e.target.value)}
      />

Notes: {JSON.stringify(notes)}

  );
};
```

I have a working example here - https://codesandbox.io/s/scales-notes-d8o18?fontsize=14&hidenavigation=1&theme=dark

Body:
I have a component with shared state that needs to be in sync.

One piece of state sets the current musical scale type, which should support every possible scale, but I'm starting out with minor and major. The second piece of state sets the correct notes for the chosen note name, based upon the scale type chosen. I have it mostly working, but I need to synchronize the state better so that one can react to the other.

It has been recommended by a few people in the react community to 'lift the state up', which I am trying to figure out how to do properly, especially using hooks.

So, I have been able to figure out how to lift up the state of the musical scale notes that was being set on the components into some objects full of arrays, but now I need to figure out how to lift up the onClick function in the following code, and there are 12 of these note name components, and each one is setting different musical scales to the notes state:

<NoteInput
  id="c"
  scale={scale}
  type="radio"
  name="notes"
  label="c"
  value="c"
  onClick={
    () => setNotes(
      scale === 'minor' ? scalePatterns['c-minor'] :
      scale === 'major' ? scalePatterns['c-major'] :
      ''
    )
  }
/>
<NoteLabel
  whileHover={{ scale: 1 }}
  whileTap={{ scale: 0.9 }}
  scale={scale}
  htmlFor="c"
>
  {
    scale === 'major' ? 'C' :
    scale === 'minor' ? 'C' :
    'C'
  }
</NoteLabel>

So now I need to figure out how to 'lift up' the arrow function in the onClick prop into it's own function, but I don't know how to go about it, as the requirement is that I need to pass different state to each instance of the function, but keep that state in sync with another piece of state, which is setting the scale type that the note buttons then react to.

UPDATE:

Upon closer inspection, I believe the state functions as follows:

Scale Type
  |     \
  |      \
  |    Root Note
  |      /
  |     /
Scale Notes

...where the scale type will affect both which root note is chosen (C# or Db, for example) as well as the notes for the scale itself. Then the scale notes ALSO need to know the root note in combination with the scale type.

Body:
Based on what I understood from your question, you have the following dependencies in your state -

Root Note       Scale
        \       /
         \     /
          Notes

The notes state variable only changes when there is either a change in root note name (c/d/e etc) or scale (major/minor etc). You can abstract away all of the scale related state into a context and use it in the respective component as shown below. You can use the useEffect hook's 2nd arg to listen to state variable changes and perform side-effects.

ScalesContext.js

...

const SCALE_PATTERNS = {
  "c-major": ["c", "d", "e", "f", "g", "a", "b"],
  "c-minor": ["c", "d", "eflat", "f", "g", "aflat", "bflat"]
};

const ScalesContext = createContext(null);

export const ScalesContextProvider = ({ children }) => {
  const [rootNote, setRootNote] = useState(""); // 'c'
  const [scale, setScale] = useState(""); // 'major'
  const [notes, setNotes] = useState([]); // ['c', 'd', ...]

  // On scale/rootNote state change -> update notes
  useEffect(() => {
    const key = `${rootNote}-${scale}`;
    setNotes(SCALE_PATTERNS[key]);
  }, [scale, rootNote]);

  return (
    <ScalesContext.Provider
      value={{ rootNote, scale, notes, setScale, setRootNote }}
    >
      {children}
    </ScalesContext.Provider>
  );
};

export const useScalesContext = () => useContext(ScalesContext);

App.js

...

export default function App() {
  return (
    <div className="App">
      // Hook up Provider around ScaleSelect component
      <ScalesContextProvider>
        <ScaleSelect />
      </ScalesContextProvider>
    </div>
  );
}

ScaleSelect.js

...

export const ScaleSelect = () => {
  const state = useScalesContext();
  const { rootNote, scale, notes, setScale, setRootNote } = state;

  return (
    <div>
      <p>Root Note: {rootNote}</p>
      <p>Scale: {scale}</p>
      <input
        type="text"
        value={rootNote}
        placeholder="Root Note (try 'c')"
        onChange={e => setRootNote(e.target.value)}
      />
      <input
        type="text"
        placeholder="Scale (try 'major')"
        value={scale}
        onChange={e => setScale(e.target.value)}
      />
      <p>Notes: {JSON.stringify(notes)}</p>
    </div>
  );
};

I have a working example here - https://codesandbox.io/s/scales-notes-d8o18?fontsize=14&hidenavigation=1&theme=dark


问:
Get Control or Recrdset Value on Continous Form
I have a continuous form with a button for each record and would like to pass the ID of the record passed to another form when a button is clicked. I know how to pass the value. My problem is that regardless of which button is clicked I get the ID of the first record using Forms![Form name]!Text19.Value.

Even in the image below a different record is selected but I get the Id of the first record.

The Id value is in the recordset and also in a hidden field if that helps.

答:
You can use the recordset to retrieve the corresponding data:

```<code>Dim r As DAO.Recordset
Set r = Forms![Form name].RecordsetClone 'Clone the recordset
r.Bookmark = Forms![Form name].Bookmark 'Navigate to the active record
MyValue = r!SomeField.Value
</code>```

Note that if the form is inactive, Bookmark might not refer to the record you think is selected. To avoid this, cache the bookmark (save it on Form_Current)

Body:
You can use the recordset to retrieve the corresponding data:

Dim r As DAO.Recordset
Set r = Forms![Form name].RecordsetClone 'Clone the recordset
r.Bookmark = Forms![Form name].Bookmark 'Navigate to the active record
MyValue = r!SomeField.Value

Note that if the form is inactive, Bookmark might not refer to the record you think is selected. To avoid this, cache the bookmark (save it on Form_Current)


问:
How to loop through a HTMLCollection in an angular app using typescript
I'm new to angular, and I'm trying to loop through a html collection so that I can get properties such as id for each element but it does not seem to be working even after get a array representation of the collection as seen on the code below. I'm using typescript to build an angular app. Any work around this? or anything I'm doing wrong?</p>

```<code>this.customElements = Array.from(
      document.getElementsByClassName('custom-elem')
    );

    this.customElements.forEach(element => {
      console.log(element);
    });
</code>```

答:
You don't have to create a new array from the HTMLCollection. getElementsByClassName() function by default returns an array-like object of all child elements. So the following should work:

```<code>this.customElements = document.getElementsByClassName('custom-elem');

for (const element in this.customElements) {
  console.log(element);
}
</code>```

Working example: Stackblitz

Body:
I'm new to angular, and I'm trying to loop through a html collection so that I can get properties such as id for each element but it does not seem to be working even after get a array representation of the collection as seen on the code below. I'm using typescript to build an angular app. Any work around this? or anything I'm doing wrong?

this.customElements = Array.from(
      document.getElementsByClassName('custom-elem')
    );

    this.customElements.forEach(element => {
      console.log(element);
    });

Body:
You don't have to create a new array from the HTMLCollection. getElementsByClassName() function by default returns an array-like object of all child elements. So the following should work:

this.customElements = document.getElementsByClassName('custom-elem');

for (const element in this.customElements) {
  console.log(element);
}

Working example: Stackblitz


问:
Why I can't install React and uninstall create-react-app in my system?
I have tried so many ways. But I can't find any solution. The problem is I can't install ReactJS in my system. Here is the message I get when complete my installation process.

A template was not provided. This is likely because you're using an
  outdated version of create-react-app. Please note that global installs
  of create-react-app are no longer supported.

I cleaned the cache. I also saw it with a fresh node even wanted to try uninstalling the create-react-app. But if I do, I get this message.

I manually deleted this log and it didn't work.

Can anyone suggest me any solution?

Update: Actually these two problems are solved when I manually deleted
  the cache from the AppData\Roaming\npm (temp) directory.

Thanks Everyone

答:
So, I know this has been answered several times, but after attempting each of the suggested solutions I've only found this one to work for me. First, I uninstalled the global create-react-app.

```<code>npm uninstall -g create-react-app
</code>```

And then removed the cache. Yet, it still was not working. Turns out, I had a non-global install of create-react-app in the directory that I keep my projects.

```<code>npm uninstall create-react-app
</code>```

After running the command without the -g all was well. If nothing else works, this may be someone's solution if they're experiencing the same issue.

Body:
So, I know this has been answered several times, but after attempting each of the suggested solutions I've only found this one to work for me. First, I uninstalled the global create-react-app.

npm uninstall -g create-react-app

And then removed the cache. Yet, it still was not working. Turns out, I had a non-global install of create-react-app in the directory that I keep my projects.

npm uninstall create-react-app

After running the command without the -g all was well. If nothing else works, this may be someone's solution if they're experiencing the same issue.


问:
UISwitch Throwing Fault Swift
All.

I have had a look through, struggling to find an answer. For the life of me I know I can figure it out, however, I am struggling.

The below code executes and pushes changeURL to another view controller. This changeURL variable is set to an 'if' statement where true appends one string to the URL and false appends another.

The API works fine. Everything works as it should.

However, When I load the initial view below the UISwitch is already on. I hit enter and I get the return table view populated with content.

```<code>import UIKit

class DashboardViewController: UIViewController {

    @IBOutlet weak var warningLabel: UILabel!
    @IBOutlet weak var clickToEnterButton: UIButton!
    @IBOutlet weak var explicitSwitch: UISwitch!

    //    @IBAction func urlSwitch(_ sender: UISwitch) {
    //        performSegue(withIdentifier: "goToTableView", sender: explicitSwitch)
    //    }
    @IBAction func enterButton(_ sender: UIButton) {
        performSegue(withIdentifier: "goToTableView", sender: clickToEnterButton)

    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.destination is JokesTableViewController {
            let vc = segue.destination as? JokesTableViewController
            vc?.changeURL = explicitSwitch.isOn
        }
    }
}
</code>```

If I then switch the UISwitch to the 'off' position it throws a fault.

```<code>'invalid mode 'kCFRunLoopCommonModes' provided to CFRunLoopRunSpecific - break on _CFRunLoopError_RunCalledWithInvalidMode to debug. This message will only appear once per execution.'
</code>```

I know the switch is working because if I set the switch to false after accessing the view and then clicking enter again it presents me with the second API - code below.

```<code>import UIKit

class DashboardViewController: UIViewController {

    @IBOutlet weak var warningLabel: UILabel!
    @IBOutlet weak var clickToEnterButton: UIButton!
    @IBOutlet weak var explicitSwitch: UISwitch!

    //    @IBAction func urlSwitch(_ sender: UISwitch) {
    //        performSegue(withIdentifier: "goToTableView", sender: explicitSwitch)
    //    }
    @IBAction func enterButton(_ sender: UIButton) {
        performSegue(withIdentifier: "goToTableView", sender: clickToEnterButton)

    }

    func explicitSwitchOff(){
        explicitSwitch.setOn(false, animated: true)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.destination is JokesTableViewController {
            let vc = segue.destination as? JokesTableViewController
            vc?.changeURL = explicitSwitch.isOn
            explicitSwitchOff()
        }
    }
}
</code>```

Ideally, I think I need to separate the value of the switch (true or false) from the UISwitch action. Then attach it to the UIButton action?

Any ideas are highly appreciated.

Thanks.

答:
Thanks, I have found the answer.

It turns out the UISwitch was still declared to a variable which wasn't there!

Lesson learnt.

Title: UISwitch Throwing Fault Swift

Body:
All.

I have had a look through, struggling to find an answer. For the life of me I know I can figure it out, however, I am struggling.

The below code executes and pushes changeURL to another view controller. This changeURL variable is set to an 'if' statement where true appends one string to the URL and false appends another.

The API works fine. Everything works as it should.

However, When I load the initial view below the UISwitch is already on. I hit enter and I get the return table view populated with content.

import UIKit

class DashboardViewController: UIViewController {

    @IBOutlet weak var warningLabel: UILabel!
    @IBOutlet weak var clickToEnterButton: UIButton!
    @IBOutlet weak var explicitSwitch: UISwitch!

    //    @IBAction func urlSwitch(_ sender: UISwitch) {
    //        performSegue(withIdentifier: "goToTableView", sender: explicitSwitch)
    //    }
    @IBAction func enterButton(_ sender: UIButton) {
        performSegue(withIdentifier: "goToTableView", sender: clickToEnterButton)

    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.destination is JokesTableViewController {
            let vc = segue.destination as? JokesTableViewController
            vc?.changeURL = explicitSwitch.isOn
        }
    }
}

If I then switch the UISwitch to the 'off' position it throws a fault.

'invalid mode 'kCFRunLoopCommonModes' provided to CFRunLoopRunSpecific - break on _CFRunLoopError_RunCalledWithInvalidMode to debug. This message will only appear once per execution.'

I know the switch is working because if I set the switch to false after accessing the view and then clicking enter again it presents me with the second API - code below.

import UIKit

class DashboardViewController: UIViewController {

    @IBOutlet weak var warningLabel: UILabel!
    @IBOutlet weak var clickToEnterButton: UIButton!
    @IBOutlet weak var explicitSwitch: UISwitch!

    //    @IBAction func urlSwitch(_ sender: UISwitch) {
    //        performSegue(withIdentifier: "goToTableView", sender: explicitSwitch)
    //    }
    @IBAction func enterButton(_ sender: UIButton) {
        performSegue(withIdentifier: "goToTableView", sender: clickToEnterButton)

    }

    func explicitSwitchOff(){
        explicitSwitch.setOn(false, animated: true)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.destination is JokesTableViewController {
            let vc = segue.destination as? JokesTableViewController
            vc?.changeURL = explicitSwitch.isOn
            explicitSwitchOff()
        }
    }
}

Ideally, I think I need to separate the value of the switch (true or false) from the UISwitch action. Then attach it to the UIButton action?

Any ideas are highly appreciated.

Thanks.


问:
Can I manually slot an input neuron into a hidden layer in Keras?
I have a CNN and I want to sneak in some extra information into one of the final layers.

Here's a simplified version of the code. Watch for the comment

```<code>def define_model():
    model = Sequential()
    model.add(Conv2D(32, (3,3))
    model.add(Conv2D(32, (3,3))
    model.add(MaxPooling2D((2,2))
    model.add(Conv2D(64, (3,3))
    model.add(Conv2D(64, (3,3))
    model.add(MaxPooling2D((2,2)))
    model.add(Flatten())
    # this next layer is where I want to sneak the neuron(s) in
    model.add(Dense(1024))
    model.add(Dropout(rate=0.4))
    model.add(Dense(168))
    model.compile()
    return model
</code>```

So I have some additional information about the input image which might be able to help the network. Think of it as a clue which may or may not deserve a reasonable amount of weighting.

The clue is in the form of an integer which technically is in [0, inf) but practically is probably in [0, 20].

So my questions are

What's the appropriate way to represent that hint speaking in terms of NN architecture in general.

How do I tweak the Keras model to make that happen in practice?

Bonus: If I wanted to, could I prevent the subsequent dropout from ever dropping out this added feature?

答:
This could work by using Keras' functional API:

```<code>def define_model():
    inputs = Input(input_shape=(...))
    hints = Input(input_shape=(...))

    x = Conv2D(32, (3,3))(inputs)
    x = Conv2D(32, (3,3))(x)
    x = MaxPooling2D((2,2))(x)
    x = Conv2D(64, (3,3))(x)
    x = Conv2D(64, (3,3))(x)
    x = MaxPooling2D((2,2))(x)
    x = Flatten()(x)

    x = Add()([x, hints])

    x = Dense(1024)(x)
    x = Dropout(rate=0.4)(x)
    outputs = Dense(168)(x)

    model = Model([inputs, hints], outputs)

    model.compile()
    return model
</code>```

I don't know about protecting it from the dropout using Keras though.

Body:
I have a CNN and I want to sneak in some extra information into one of the final layers.

Here's a simplified version of the code. Watch for the comment

def define_model():
    model = Sequential()
    model.add(Conv2D(32, (3,3))
    model.add(Conv2D(32, (3,3))
    model.add(MaxPooling2D((2,2))
    model.add(Conv2D(64, (3,3))
    model.add(Conv2D(64, (3,3))
    model.add(MaxPooling2D((2,2)))
    model.add(Flatten())
    # this next layer is where I want to sneak the neuron(s) in
    model.add(Dense(1024))
    model.add(Dropout(rate=0.4))
    model.add(Dense(168))
    model.compile()
    return model

So I have some additional information about the input image which might be able to help the network. Think of it as a clue which may or may not deserve a reasonable amount of weighting.

The clue is in the form of an integer which technically is in [0, inf) but practically is probably in [0, 20].

So my questions are

What's the appropriate way to represent that hint speaking in terms of NN architecture in general.

How do I tweak the Keras model to make that happen in practice?

Bonus: If I wanted to, could I prevent the subsequent dropout from ever dropping out this added feature?

Body:
This could work by using Keras' functional API:

def define_model():
    inputs = Input(input_shape=(...))
    hints = Input(input_shape=(...))

    x = Conv2D(32, (3,3))(inputs)
    x = Conv2D(32, (3,3))(x)
    x = MaxPooling2D((2,2))(x)
    x = Conv2D(64, (3,3))(x)
    x = Conv2D(64, (3,3))(x)
    x = MaxPooling2D((2,2))(x)
    x = Flatten()(x)

    x = Add()([x, hints])

    x = Dense(1024)(x)
    x = Dropout(rate=0.4)(x)
    outputs = Dense(168)(x)

    model = Model([inputs, hints], outputs)

    model.compile()
    return model

I don't know about protecting it from the dropout using Keras though.


问:
how to click the multiple checkboxes in selenium webdriver?
As i want to click the multiple checkboxes in selenium webdriver, so that im using the 'id' webelement to click but what problem i'm facing means all the checkboxes id's are same in my HTML
so is there anyway to click multiple checkboxes?

Here im posting my HTML code:
first check box:

```<code><tbody role="rowgroup">
<tr data-uid="6adb7eb4-7169-4ab8-aef4-cc8b2774beac" role="row" class="k-state-selected" aria-selected="true"><td style="text-align:left" role="gridcell">Order</td><td style="text-align:left" role="gridcell">55</td><td style="text-align:left" role="gridcell">ORD55</td><td style="text-align:right" role="gridcell">2,400.00</td><td style="text-align:right" role="gridcell">2,400.00</td><td style="text-align:center" role="gridcell" id="GridPayRecp_active_cell" class="" aria-describedby="c7c68ce1-edc3-4958-a6c1-2611999356b0 GridPayRecp_active_cell"><input type="checkBox" id="chkSelect" onclick="EditchkSelect()" height="15px;" width="15px;" checked=""></td><td style="text-align:right" role="gridcell">2,400.00</td></tr><tr class="k-alt" data-uid="3f3d1588-6f42-4c22-bdda-28c090ece58b" role="row"><td style="text-align:left" role="gridcell">Order</td><td style="text-align:left" role="gridcell">57</td><td style="text-align:left" role="gridcell">ORD57</td><td style="text-align:right" role="gridcell">3,600.00</td><td style="text-align:right" role="gridcell">3,597.00</td><td style="text-align:center" role="gridcell"><input type="checkBox" id="chkSelect" onclick="EditchkSelect()" height="15px;" width="15px;"></td><td style="text-align:right" role="gridcell">0.00</td></tr><tr data-uid="1ab110de-fbe6-4954-b612-39c3cb7fc8ba" role="row"><td style="text-align:left" role="gridcell">Proforma</td><td style="text-align:left" role="gridcell">90</td><td style="text-align:left" role="gridcell">PRO90</td><td style="text-align:right" role="gridcell">3,600.00</td><td style="text-align:right" role="gridcell">3,366.00</td><td style="text-align:center" role="gridcell"><input type="checkBox" id="chkSelect" onclick="EditchkSelect()" height="15px;" width="15px;"></td><td style="text-align:right" role="gridcell">0.00</td></tr>
</tbody>
</code>```

second checkbox:

```<code><tbody role="rowgroup">
<tr data-uid="6adb7eb4-7169-4ab8-aef4-cc8b2774beac" role="row" class="k-state-selected" aria-selected="true"><td style="text-align:left" role="gridcell">Order</td><td style="text-align:left" role="gridcell">55</td><td style="text-align:left" role="gridcell">ORD55</td><td style="text-align:right" role="gridcell">2,400.00</td><td style="text-align:right" role="gridcell">2,400.00</td><td style="text-align:center" role="gridcell" id="GridPayRecp_active_cell" class="" aria-describedby="c7c68ce1-edc3-4958-a6c1-2611999356b0 GridPayRecp_active_cell"><input type="checkBox" id="chkSelect" onclick="EditchkSelect()" height="15px;" width="15px;" checked=""></td><td style="text-align:right" role="gridcell">2,400.00</td></tr><tr class="k-alt" data-uid="3f3d1588-6f42-4c22-bdda-28c090ece58b" role="row"><td style="text-align:left" role="gridcell">Order</td><td style="text-align:left" role="gridcell">57</td><td style="text-align:left" role="gridcell">ORD57</td><td style="text-align:right" role="gridcell">3,600.00</td><td style="text-align:right" role="gridcell">3,597.00</td><td style="text-align:center" role="gridcell"><input type="checkBox" id="chkSelect" onclick="EditchkSelect()" height="15px;" width="15px;"></td><td style="text-align:right" role="gridcell">0.00</td></tr><tr data-uid="1ab110de-fbe6-4954-b612-39c3cb7fc8ba" role="row"><td style="text-align:left" role="gridcell">Proforma</td><td style="text-align:left" role="gridcell">90</td><td style="text-align:left" role="gridcell">PRO90</td><td style="text-align:right" role="gridcell">3,600.00</td><td style="text-align:right" role="gridcell">3,366.00</td><td style="text-align:center" role="gridcell"><input type="checkBox" id="chkSelect" onclick="EditchkSelect()" height="15px;" width="15px;"></td><td style="text-align:right" role="gridcell">0.00</td></tr></tbody>
</code>```

third checkbox:

```<code></tbody>
</code>```

答:
```<code>Wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div[2]/section[2]/section/div/div[2]/div/div/form/div/div/div/div[2]/div[1]/div/div[1]/div[2]/table/tbody/tr[1]/td[6]/input")));
Wait.until(ExpectedConditions.elementToBeClickable(By.xpath("/html/body/div[1]/div[2]/section[2]/section/div/div[2]/div/div/form/div/div/div/div[2]/div[1]/div/div[1]/div[2]/table/tbody/tr[1]/td[6]/input"))).click(); Wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div[2]/section[2]/section/div/div[2]/div/div/form/div/div/div/div[2]/div[1]/div/div[1]/div[2]/table/tbody/tr[2]/td[6]/input")));
Wait.until(ExpectedConditions.elementToBeClickable(By.xpath("/html/body/div[1]/div[2]/section[2]/section/div/div[2]/div/div/form/div/div/div/div[2]/div[1]/div/div[1]/div[2]/table/tbody/tr[2]/td[6]/input"))).click();
</code>```

i used the xpath like this to select particular checkboxes, but i dont know whether can we use the xpath like this or not?
is there any other good way to write the xpath?

Body:
As i want to click the multiple checkboxes in selenium webdriver, so that im using the 'id' webelement to click but what problem i'm facing means all the checkboxes id's are same in my HTML
so is there anyway to click multiple checkboxes?

Here im posting my HTML code:
first check box:

Order	55	ORD55	2,400.00	2,400.00	<input type="checkBox" id="chkSelect" onclick="EditchkSelect()" height="15px;" width="15px;" checked="">	2,400.00

Order	57	ORD57	3,600.00	3,597.00	<input type="checkBox" id="chkSelect" onclick="EditchkSelect()" height="15px;" width="15px;">	0.00

Proforma	90	PRO90	3,600.00	3,366.00	<input type="checkBox" id="chkSelect" onclick="EditchkSelect()" height="15px;" width="15px;">	0.00

second checkbox:

Order	55	ORD55	2,400.00	2,400.00	<input type="checkBox" id="chkSelect" onclick="EditchkSelect()" height="15px;" width="15px;" checked="">	2,400.00

Order	57	ORD57	3,600.00	3,597.00	<input type="checkBox" id="chkSelect" onclick="EditchkSelect()" height="15px;" width="15px;">	0.00

Proforma	90	PRO90	3,600.00	3,366.00	<input type="checkBox" id="chkSelect" onclick="EditchkSelect()" height="15px;" width="15px;">	0.00

third checkbox:

Body:
Wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div[2]/section[2]/section/div/div[2]/div/div/form/div/div/div/div[2]/div[1]/div/div[1]/div[2]/table/tbody/tr[1]/td[6]/input")));
Wait.until(ExpectedConditions.elementToBeClickable(By.xpath("/html/body/div[1]/div[2]/section[2]/section/div/div[2]/div/div/form/div/div/div/div[2]/div[1]/div/div[1]/div[2]/table/tbody/tr[1]/td[6]/input"))).click(); Wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/div[2]/section[2]/section/div/div[2]/div/div/form/div/div/div/div[2]/div[1]/div/div[1]/div[2]/table/tbody/tr[2]/td[6]/input")));
Wait.until(ExpectedConditions.elementToBeClickable(By.xpath("/html/body/div[1]/div[2]/section[2]/section/div/div[2]/div/div/form/div/div/div/div[2]/div[1]/div/div[1]/div[2]/table/tbody/tr[2]/td[6]/input"))).click();

i used the xpath like this to select particular checkboxes, but i dont know whether can we use the xpath like this or not?
is there any other good way to write the xpath?


问:
How can I clear the terminal in Visual Studio Code?
I need to clean the contents of the terminal in Visual Studio Code.

Every time I use Maven, the output of the terminal is attached to the previous build, which is confusing me.

How do I clear the terminal window with some command or keyboard shortcut?

cls doesn't work; it only hides the text.

答:
The accepted answer should be the following which was unmultimedio's comment to one of the answers above:

Cmd+K will work, you just need to set again in the Keyboard Shortcuts
  the workbench.action.terminal.clear to Cmd+K, so it shows as Source:
  User instead of Source: Default – unmultimedio Mar 12 '19 at 1:13


问:
THROW statement in catch block
I need to return error details in calling application using SQL stored procedure output parameter. If I use throw in catch block that time in case if procedure not execute successfully then output parameter will not not set with error details and if I ignore throw then it will work.

```<code>SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[pt44]
(
    @a int,
    @b int,
    @Msg varchar(2000) output
)
as
begin
    DECLARE @c int
    begin try
        set @c= (@a+@b)
        print 'C Value :' +@c--cast(@c as varchar(20))  error is here
    end try
    begin catch
        set @Msg='Error No. '+CAST(ERROR_NUMBER() AS VARCHAR(200))+'Error Line. '+CAST(ERROR_LINE() AS VARCHAR(200))+' Error Message.'+ERROR_MESSAGE()
        --;throw
    end catch
end
</code>```

Please tell me the best way how I can pass error to calling application and also want to use throw in SQL Server catch block.

答:
Without structured error handling in VB 6, one can use On Error to execute error handling code and capture SQL error details. See the VB6 documentation (no longer maintained) for more information and examples.

```<code>On Error GoTo ErrorHandler

' execute proc here
oCmd.Execute

' happy path code here
GoTo Done

:ErrorHandler
' this will show SQL error
MsgBox Err.Description

:Done
</code>```

This is the boiler plate T-SQL catch block code I normally use:

```<code>BEGIN CATCH
    IF @@TRANCOUNT > 0 ROLLBACK;
    THROW;
END;
</code>```

Title: THROW statement in catch block

Body:
I need to return error details in calling application using SQL stored procedure output parameter. If I use throw in catch block that time in case if procedure not execute successfully then output parameter will not not set with error details and if I ignore throw then it will work.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[pt44]
(
    @a int,
    @b int,
    @Msg varchar(2000) output
)
as
begin
    DECLARE @c int
    begin try
        set @c= (@a+@b)
        print 'C Value :' +@c--cast(@c as varchar(20))  error is here
    end try
    begin catch
        set @Msg='Error No. '+CAST(ERROR_NUMBER() AS VARCHAR(200))+'Error Line. '+CAST(ERROR_LINE() AS VARCHAR(200))+' Error Message.'+ERROR_MESSAGE()
        --;throw
    end catch
end

Please tell me the best way how I can pass error to calling application and also want to use throw in SQL Server catch block.

Body:
Without structured error handling in VB 6, one can use On Error to execute error handling code and capture SQL error details. See the VB6 documentation (no longer maintained) for more information and examples.

On Error GoTo ErrorHandler

' execute proc here
oCmd.Execute

' happy path code here
GoTo Done

:ErrorHandler
' this will show SQL error
MsgBox Err.Description

:Done

This is the boiler plate T-SQL catch block code I normally use:

BEGIN CATCH
    IF @@TRANCOUNT > 0 ROLLBACK;
    THROW;
END;


问:
Unit testing Angular with Karma/Jasmine:
I have inserted an if-else condition in my component so that after login I will be forwarded to a specific URL. However, my unit test now fails with the following error:

1) should create

AnotherComponent

```<code> Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'testroute'
</code>```

Without the if else condition everything is working fine, so I'm sure that this is the cause of my problem. The funny thing is, that I'm not testing anything that is related to the code inside my ngOnInit() lifecycle. More funny is, that not the test for MyComponent is failing but the test for another Component.

My Component (MyComponent) looks like this:

```<code>export class MyComponent implements OnInit {

  routes = Constants.routes;

  constructor(private router: Router,
    private myService: MyService) {
  }

  ngOnInit() {
    if (this.myService.context === 'TEST') {
      this.router.navigate([routes.testroute + this.myService.context]);
    } else {
      this.router.navigate([routes.testroute]);
    }
  }
}
</code>```

The Template looks like this:

```<code><router-outlet></router-outlet>
</code>```

The unit test of the failing component looks like this:

```<code>  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        CommonModule,
        RouterTestingModule.withRoutes([]),
      ],
      providers: [
        PathLocationStrategy
      ],
      declarations: [AnotherComponent],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AnotherComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
</code>```

答:
You need to configure the route when you import the router testing module. I generally set routes up with dummy components.</p>

```<code>TestBed.configureTestingModule({
  imports: [
    CommonModule,
    RouterTestingModule.withRoutes([
      // add routes here
      { path: 'testroute', component: DummyComponent }
    ]),
 ],
 providers: [
    PathLocationStrategy
  ],
 declarations: [AnotherComponent],
}).compileComponents();
</code>```

```<code>@Component({ template: '' })
class DummyComponent { }
</code>```

Body:
I have inserted an if-else condition in my component so that after login I will be forwarded to a specific URL. However, my unit test now fails with the following error:

1) should create

AnotherComponent

 Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'testroute'

Without the if else condition everything is working fine, so I'm sure that this is the cause of my problem. The funny thing is, that I'm not testing anything that is related to the code inside my ngOnInit() lifecycle. More funny is, that not the test for MyComponent is failing but the test for another Component.

My Component (MyComponent) looks like this:

export class MyComponent implements OnInit {

  routes = Constants.routes;

  constructor(private router: Router,
    private myService: MyService) {
  }

  ngOnInit() {
    if (this.myService.context === 'TEST') {
      this.router.navigate([routes.testroute + this.myService.context]);
    } else {
      this.router.navigate([routes.testroute]);
    }
  }
}

The Template looks like this:

<router-outlet></router-outlet>

The unit test of the failing component looks like this:

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        CommonModule,
        RouterTestingModule.withRoutes([]),
      ],
      providers: [
        PathLocationStrategy
      ],
      declarations: [AnotherComponent],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AnotherComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

Body:
You need to configure the route when you import the router testing module. I generally set routes up with dummy components.

TestBed.configureTestingModule({
  imports: [
    CommonModule,
    RouterTestingModule.withRoutes([
      // add routes here
      { path: 'testroute', component: DummyComponent }
    ]),
 ],
 providers: [
    PathLocationStrategy
  ],
 declarations: [AnotherComponent],
}).compileComponents();

@Component({ template: '' })
class DummyComponent { }


问:
Excel formula position of minimum value
EDIT: Likely an easy question, basically I have three values, let's say 9, 4 and 7 in different cells (not in a table), I want to find the minimum in an order then return its relative position, for example: 9,4,7 would return 2 as 4 is the minimum and is positioned second.

What is the correct excel formula to do so? Thanks .

Solution: Thanks all for your help, I didn't think excel could do if it wasn't continuous. I've ended up using a series of nested IF statements, an AND statement and < signs, to get the job done :)

答:
Here's an array formula that should work. It assumes the values are in A1, C3, and B4.

=MAX(IF(CHOOSE(TRANSPOSE({1,2,3}),$A$1,$C$3,$B$4)=MIN($A$1,$C$3,$B$4),TRANSPOSE({1,2,3}),0))

Title: Excel formula position of minimum value


问:
Could not connect to Twilio: open failed
In a Node.js project I use Twilio for video connections, sometimes I am getting the error message when I trigger the call. It says in the log Could not connect to Twilio: open failed, also I monitored the network in logs, it says can not be opened and it's still not connected. Anyone had this issue? What was the solution?

```<code> // Join the Room with the token from the server and the
          // LocalParticipant's Tracks.
          Video.connect(resdata.token, connectOptions).then(roomJoined, function (error) {
              log('Could not connect to Twilio: ' + error.message);
          });
        });
</code>```

答: An incident is reported for group rooms, you can wait until it is fixed. Check the status: https://status.twilio.com/incidents/2t0jh1jkxp39</p>

Body:
In a Node.js project I use Twilio for video connections, sometimes I am getting the error message when I trigger the call. It says in the log Could not connect to Twilio: open failed, also I monitored the network in logs, it says can not be opened and it's still not connected. Anyone had this issue? What was the solution?

 // Join the Room with the token from the server and the
          // LocalParticipant's Tracks.
          Video.connect(resdata.token, connectOptions).then(roomJoined, function (error) {
              log('Could not connect to Twilio: ' + error.message);
          });
        });


问:
Bootstrap 4 font size em differs in Mozilla Firefox and Google Chrome
I'm using Angular 8 with bootstrap v4.4.1 (package.json -> "@ng-bootstrap/ng-bootstrap": "^5.2.1",). My requirements:

support responsive design (accomplished with bootstrap)

make browsers render all elements consistently

I thought that the second point is solved by bootstrap as well. The problem is this:

```<code><button type="button" class="btn btn-outline-dark menu-item">
  <i class="fas fa-align-center"></i>
</button>
</code>```

Chrome shows button twice as large as Mozilla Firefox. I then added Bootstrap Reboot (as a normalizes, but it doesn't change anything)

This is my whole global styles.scss:

```<code>@import "~bootstrap/dist/css/bootstrap-reboot.css";
@import "~bootstrap/dist/css/bootstrap.min.css";
@import "~@fortawesome/fontawesome-free/css/all.css";
@import "variables.scss";

html,
body {
  height: 100%;
  background-color: $gray-light;
}

.menu-item {
  font-size: 1.5em;
}
</code>```

How do I get that font size renders equally in Firefox and Chrome. Specifying px works, but latest trends go to em or rem. Doesn't Reboot overrides the em?

Setting this works, but not really sure this is the best approach:

```<code>html,
body {
  height: 100%;
  background-color: $gray-light;
  font-size: 16px;
}
</code>```

答:
In your styles.scss:

```<code>html,
body {
  height: 100%;
  font-size:100%;
  background-color: $gray-light;
}
</code>```

Make sure that none of the browsers are zoomed in Ctrl+0 to reset zoom. Font sizes in different browsers are different a little bit but they shouldn't be too different.

Body:
I'm using Angular 8 with bootstrap v4.4.1 (package.json -> "@ng-bootstrap/ng-bootstrap": "^5.2.1",). My requirements:

support responsive design (accomplished with bootstrap)

make browsers render all elements consistently

I thought that the second point is solved by bootstrap as well. The problem is this:

<button type="button" class="btn btn-outline-dark menu-item">

</button>

Chrome shows button twice as large as Mozilla Firefox. I then added Bootstrap Reboot (as a normalizes, but it doesn't change anything)

This is my whole global styles.scss:

@import "~bootstrap/dist/css/bootstrap-reboot.css";
@import "~bootstrap/dist/css/bootstrap.min.css";
@import "~@fortawesome/fontawesome-free/css/all.css";
@import "variables.scss";

html,
body {
  height: 100%;
  background-color: $gray-light;
}

.menu-item {
  font-size: 1.5em;
}

How do I get that font size renders equally in Firefox and Chrome. Specifying px works, but latest trends go to em or rem. Doesn't Reboot overrides the em?

Setting this works, but not really sure this is the best approach:

html,
body {
  height: 100%;
  background-color: $gray-light;
  font-size: 16px;
}

Body:
In your styles.scss:

html,
body {
  height: 100%;
  font-size:100%;
  background-color: $gray-light;
}

Make sure that none of the browsers are zoomed in Ctrl+0 to reset zoom. Font sizes in different browsers are different a little bit but they shouldn't be too different.


问:
ImportError: No module named 'tensorflow.core'
After installing tensorflow-gpu using pip3, I am getting the following error when trying to import tensorflow as tf

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/dlpda/.local/lib/python3.5/site-packages/tensorflow/__init__.py", line 22, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "/home/dlpda/.local/lib/python3.5/site-packages/tensorflow/python/__init__.py", line 52, in <module>
    from tensorflow.core.framework.graph_pb2 import *
ImportError: No module named 'tensorflow.core'
</code>```

Although I am able to import successfully in a virtualenv, but not outside.

How should I resolve this problem to be able to import tensorflow?

答:
I was facing the same issue in tensorflow 1.15 with django 2.1.0 and python 3.7.4

It was working fine with tensorflow 1.14 with django 2.1.0 and python 3.7.4.

There is some issue in latest version of tensorflow(2.0/1.15) with previous version of django. same issue is observed with previous version of flask also.

https://github.com/tensorflow/tensorflow/issues/34607

Proposed solution is to update your django version from 2.1.0 > 2.2.5 , it works for me.

Body:
After installing tensorflow-gpu using pip3, I am getting the following error when trying to import tensorflow as tf

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/dlpda/.local/lib/python3.5/site-packages/tensorflow/__init__.py", line 22, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "/home/dlpda/.local/lib/python3.5/site-packages/tensorflow/python/__init__.py", line 52, in <module>
    from tensorflow.core.framework.graph_pb2 import *
ImportError: No module named 'tensorflow.core'

Although I am able to import successfully in a virtualenv, but not outside.

How should I resolve this problem to be able to import tensorflow?