问:
docker container seems to have failing /etc/hosts until an _interactive_ docker start
If I "docker-compose start service" in an interactive terminal (not -it, but a bash running on the host interactively), my service initializes happily.

But if I put that same command in a shell script, it fails.

I suspect the problem is name resolution via /etc/hosts; it seems to work interactively but not in a script for some reason.  I want the containers to be able to see the names defined in the host's /etc/hosts.  And although I am on Linux Mint 19.1 I need it to work on Windows, Mac and Linux.

Things I've tried that didn't work:

Adding sleeps - as long as 10 minutes

Checking for environment variable differences

Running the command under tcsh instead of bash

Running the command in a pseudo-tty using /usr/bin/script -c

But if I throw a /bin/bash -i in my script, with an echo that says what command to type, it works!

I'm using:

```<code>docker version 18.09.6, build 481bc77
docker-compose version 1.24.0, build 0aa59064
</code>```

I'd have to get an OK from my management to share more than small snippets of code.

I want the service to start via docker-compose up -d or at least docker-compose start - in a script, for the sake of automation.

The error message inside the container (from docker logs -f service) looks like:
elasticsearch.exceptions.ConnectionTimeout: ConnectionTimeout caused by - ReadTimeoutError(HTTPConnectionPool(host=u'elasticsearch', port=9200): Read timed out. (read timeout=10))

I sometimes see a high load in elasticsearch, which seems a bit odd.  By high I mean as high as 490% on an 8 core (probably counting hyperthreading).  More commonly it's down around 5-15%.

Here's an SSCCE:

```<code>#!/bin/bash

set -eu
set -o pipefail
set -x

docker stop elasticsearch || true
docker-compose start elasticsearch

# Give elasticsearch some time to come up.
# Normally I use a small REST client that calls ES until it starts responding - but that wouldn't be self-contained.
sleep 120

docker stop service || true
docker-compose start service
</code>```

The script itself runs to completion fine, but then "service" exits before it should.

Thanks!

答:
If I understood correctly, you want the elasticsearch container to serve your service container (i.e. both container to contact each other) hence, the service container needs to know the elasticsearch's IP address.

In that case, docker-compose will manage the containers addresses, what you will need to do is to store that information in the service container as an environment variable. The plus side of it, is that you can start both container with the same command (just docker-compose up -d). For example:

```<code>services:
  elasticsearch:
      image: YOUR_ELASTICSEARCH_IMAGE
      ports:
        - 9200:9200
  service:
      image: YOUR_SERVICE_IMAGE
      environment:
          - ELASTICSEARCH_HOST=elasticsearch
</code>```

If there is a dependency between containers and the elasticsearch container needs some time to startup, then you can either put a sleep statement in the service at startup or use the solution in 31746182

Body:
If I "docker-compose start service" in an interactive terminal (not -it, but a bash running on the host interactively), my service initializes happily.

But if I put that same command in a shell script, it fails.

I suspect the problem is name resolution via /etc/hosts; it seems to work interactively but not in a script for some reason.  I want the containers to be able to see the names defined in the host's /etc/hosts.  And although I am on Linux Mint 19.1 I need it to work on Windows, Mac and Linux.

Things I've tried that didn't work:

Adding sleeps - as long as 10 minutes

Checking for environment variable differences

Running the command under tcsh instead of bash

Running the command in a pseudo-tty using /usr/bin/script -c

But if I throw a /bin/bash -i in my script, with an echo that says what command to type, it works!

I'm using:

docker version 18.09.6, build 481bc77
docker-compose version 1.24.0, build 0aa59064

I'd have to get an OK from my management to share more than small snippets of code.

I want the service to start via docker-compose up -d or at least docker-compose start - in a script, for the sake of automation.

The error message inside the container (from docker logs -f service) looks like:
elasticsearch.exceptions.ConnectionTimeout: ConnectionTimeout caused by - ReadTimeoutError(HTTPConnectionPool(host=u'elasticsearch', port=9200): Read timed out. (read timeout=10))

I sometimes see a high load in elasticsearch, which seems a bit odd.  By high I mean as high as 490% on an 8 core (probably counting hyperthreading).  More commonly it's down around 5-15%.

Here's an SSCCE:

#!/bin/bash

set -eu
set -o pipefail
set -x

docker stop elasticsearch || true
docker-compose start elasticsearch

# Give elasticsearch some time to come up.
# Normally I use a small REST client that calls ES until it starts responding - but that wouldn't be self-contained.
sleep 120

docker stop service || true
docker-compose start service

The script itself runs to completion fine, but then "service" exits before it should.

Thanks!

Body:
If I understood correctly, you want the elasticsearch container to serve your service container (i.e. both container to contact each other) hence, the service container needs to know the elasticsearch's IP address.

In that case, docker-compose will manage the containers addresses, what you will need to do is to store that information in the service container as an environment variable. The plus side of it, is that you can start both container with the same command (just docker-compose up -d). For example:

services:
  elasticsearch:
      image: YOUR_ELASTICSEARCH_IMAGE
      ports:
        - 9200:9200
  service:
      image: YOUR_SERVICE_IMAGE
      environment:
          - ELASTICSEARCH_HOST=elasticsearch

If there is a dependency between containers and the elasticsearch container needs some time to startup, then you can either put a sleep statement in the service at startup or use the solution in 31746182


来源: stackexchange

问:
How do I keep my Dropdown open on highlight input, drag, release?
I'm using the react bootstrap Dropdown component. I'm noticing specific behavior I don't like. Best to explain with pictures.

I have a dropdown with an input filter box and a list.

When the user types text into the input box, goes to highlight that text, drags mouse to the left, and releases the mouse outside of the dropdown, the dropdown closes.

This is annoying behavior for the user who like to be able to select the text to delete it, and re-enter new search text.

Now please don't think the behavior I want is to not close the dropdown when the user clicks outside. I still do. The difference is I don't want the dropdown to close when the user clicks inside the dropdown -> drags mouse to outside boundary -> releases.

I've researched this a lot already but I'm struggling with knowing what to look for. I just need to be pointed in the right direction. I'm new to using React, and not sure how to get into the weeds when custom behavior is required. I would prefer to do this with React, I do not want to use jQuery.

Anyway, I will appreciate any help someone can give me. Thank you!

答:
This is happening because the <Dropdown.Menu/> listens for click and mousedown events. So, when you select, drag and release the mouse it will be considered as a click. This will close the popup.

To fix this make the dropdown listen to only mousedown with rootCloseEvent="mousedown"

```<code>    <Dropdown.Menu rootCloseEvent="mousedown">
      <Dropdown.Item eventKey="1">Red</Dropdown.Item>
      <Dropdown.Item eventKey="2">Blue</Dropdown.Item>
      <Dropdown.Item eventKey="3" active>Orange</Dropdown.Item>
      <Dropdown.Item eventKey="1">Red-Orange</Dropdown.Item>
    </Dropdown.Menu>

</code>```

Hope this helps!

ContentLicense: CC BY-SA 4.0

Body:
This is happening because the <Dropdown.Menu/> listens for click and mousedown events. So, when you select, drag and release the mouse it will be considered as a click. This will close the popup.

To fix this make the dropdown listen to only mousedown with rootCloseEvent="mousedown"

    <Dropdown.Menu rootCloseEvent="mousedown">
      <Dropdown.Item eventKey="1">Red</Dropdown.Item>
      <Dropdown.Item eventKey="2">Blue</Dropdown.Item>
      <Dropdown.Item eventKey="3" active>Orange</Dropdown.Item>
      <Dropdown.Item eventKey="1">Red-Orange</Dropdown.Item>
    </Dropdown.Menu>

Hope this helps!


问:
Reporting Services 2005 Subscriptions
I am trying to send reports from Reporting Services 2005 by to an FTP location but this does not seem to be an option within the subscription settings. Is this possible to have done?</p>

答:
You can code your own custom extension to SSRS to "send" reports directly to file or even to a printer from a subscription. The are samples provided by MS that show you how to do both if you don't mind getting into some code (I think they have examples for VB and C#) and XML config files.

I've implemented the printing extension before, very handy.

Sorry it's taken so long for my suggestion, been in other kinds of development lately.

HTH

OwnerDisplayName: JR Bell

ContentLicense: CC BY-SA 2.5

Title: Reporting Services 2005 Subscriptions

ContentLicense: CC BY-SA 3.0


问:
How to Encrypt/decrypt data in a Waves Keeper Web App?
currently developing a new feature on my Web App i'm having a question:

I encrypted some data because i dont want it public in the blockchain but i  have some concern about this, ideally the encrypt/decrypt password should be the privatekey of the keeper connected user but since we don't have access to this info in Waves Keeper, what would be the best practice ?

How can we encrypt/decrypt data in a decentralized manner with Waves Keeper?

im currently using a password predefined by me as an environment variable on the server side but this is far from ideal and definitelly centralized aside of having several downside.

Of course there is few backup options like:

1) Simply avoid put any non public data in the blockchain

2) Add an encrypt/decrypt field in the App requiring user to enter his password everytime

Both would work but are just getting around the problem and not ideal, would like to know if there is any good solution first :)

答:
There are two methods in Waves Keeper API to encrypt/decrypt data. You can find details on the github.
https://github.com/wavesplatform/waveskeeper</p>


问:
NAudio and Xamarin Android
I would like to use Naudio library to record audio, add some effects and play the audio with android. I have a xamarin android app which I would like to add this feature. I saw WaveOut (and WaveIn) is for Windows only right?, So, should I need to implement an IWavePlayer using the android audio player? Is this another way to use naudio with xamarin android?
thanks.</p>

答:
This can be recorded and played back:

https://github.com/NateRickard/Plugin.AudioRecorder

Page:

```<code><StackLayout Orientation="Horizontal">
    <Switch x:Name="TimeoutSwitch" IsToggled="True" />
    <Label Text="Timeout after silence?" />
</StackLayout>
<Button x:Name="RecordButton"
        Clicked="Record_Clicked" FontSize="24" HorizontalOptions="FillAndExpand"
        Text="Record" />
<Button x:Name="PlayButton"
        Clicked="Play_Clicked" FontSize="24" HorizontalOptions="FillAndExpand"
        IsEnabled="False" Text="Play" />
</code>```

CS:

```<code>AudioRecorderService recorder;
AudioPlayer player;

public AudioPlayPage()
{
    InitializeComponent();

    recorder = new AudioRecorderService
    {
        StopRecordingAfterTimeout = true,
        TotalAudioTimeout = TimeSpan.FromSeconds(15),
        AudioSilenceTimeout = TimeSpan.FromSeconds(2)
    };

    player = new AudioPlayer();
    player.FinishedPlaying += Player_FinishedPlaying;
}

private void Player_FinishedPlaying(object sender, EventArgs e)
{
    PlayButton.IsEnabled = true;
    RecordButton.IsEnabled = true;
}

private async void Record_Clicked(object sender, EventArgs e)
{
    try
    {
        if (!recorder.IsRecording)
        {
            recorder.StopRecordingOnSilence = TimeoutSwitch.IsToggled;

            RecordButton.IsEnabled = false;
            PlayButton.IsEnabled = false;

            var audioRecordTask = await recorder.StartRecording();

            RecordButton.Text = "Stop Recording";
            RecordButton.IsEnabled = true;

            await audioRecordTask;

            RecordButton.Text = "Record";
            PlayButton.IsEnabled = true;
        }
        else
        {
            RecordButton.IsEnabled = false;
            await recorder.StopRecording();
            RecordButton.IsEnabled = true;
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

private void Play_Clicked(object sender, EventArgs e)
{
    try
    {
        var filePath = recorder.GetAudioFilePath();

        if (filePath != null)
        {
            PlayButton.IsEnabled = false;
            RecordButton.IsEnabled = false;

            player.Play(filePath);
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}
</code>```

Title: NAudio and Xamarin Android

Body:
This can be recorded and played back:

https://github.com/NateRickard/Plugin.AudioRecorder

Page:

<StackLayout Orientation="Horizontal">
    <Switch x:Name="TimeoutSwitch" IsToggled="True" />
    <Label Text="Timeout after silence?" />
</StackLayout>
<Button x:Name="RecordButton"
        Clicked="Record_Clicked" FontSize="24" HorizontalOptions="FillAndExpand"
        Text="Record" />
<Button x:Name="PlayButton"
        Clicked="Play_Clicked" FontSize="24" HorizontalOptions="FillAndExpand"
        IsEnabled="False" Text="Play" />

CS:

AudioRecorderService recorder;
AudioPlayer player;

public AudioPlayPage()
{
    InitializeComponent();

    recorder = new AudioRecorderService
    {
        StopRecordingAfterTimeout = true,
        TotalAudioTimeout = TimeSpan.FromSeconds(15),
        AudioSilenceTimeout = TimeSpan.FromSeconds(2)
    };

    player = new AudioPlayer();
    player.FinishedPlaying += Player_FinishedPlaying;
}

private void Player_FinishedPlaying(object sender, EventArgs e)
{
    PlayButton.IsEnabled = true;
    RecordButton.IsEnabled = true;
}

private async void Record_Clicked(object sender, EventArgs e)
{
    try
    {
        if (!recorder.IsRecording)
        {
            recorder.StopRecordingOnSilence = TimeoutSwitch.IsToggled;

            RecordButton.IsEnabled = false;
            PlayButton.IsEnabled = false;

            var audioRecordTask = await recorder.StartRecording();

            RecordButton.Text = "Stop Recording";
            RecordButton.IsEnabled = true;

            await audioRecordTask;

            RecordButton.Text = "Record";
            PlayButton.IsEnabled = true;
        }
        else
        {
            RecordButton.IsEnabled = false;
            await recorder.StopRecording();
            RecordButton.IsEnabled = true;
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

private void Play_Clicked(object sender, EventArgs e)
{
    try
    {
        var filePath = recorder.GetAudioFilePath();

        if (filePath != null)
        {
            PlayButton.IsEnabled = false;
            RecordButton.IsEnabled = false;

            player.Play(filePath);
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}


问:
Python Translation to .NET C#
I want help translating finding the equivalent code for the C# version. </p>

<p>Mainly, I don't understand the BeautifulSoup and html.parser the most.
 Which libraries would I use in C# I ask for demonstration  of  code example. Thanks for all the help. </p>

```<code>import urllib.parse
import time
from bs4 import BeautifulSoup

def check_acc(user,password):
    POST = 'POST'
    GET = 'GET'
    data = "userLoginId={}&password={}&STAYIN=false&flow=websiteSignUp&mode=login&action=loginAction&withFields=STAYIN%2CnextPage%2CuserLoginId%2Cpassword%2CcountryCode%2CcountryIsoCode&authURL=authURL%2FEcpWPKhtag%3D&nextPage=&showPassword=&countryCode=%2B33&countryIsoCode=USA".format(email, password).encode("utf-8")

    request_login = urllib.request.Request("https://www.mywebsitetest:8080/Admin",
    data = data,
    headers ={
    'Host': 'www.mywebsitetest.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'fr-FR',
    'Accept-Encoding': 'gzip, deflate, br',
    'Referer': 'https://www.mywebsitetest/USA/Login',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': 330},
    unverifiable = True,
    method = 'POST')

    resfused_msg = "Wrong combination</a>.".format('<a href="/">')
    try:
        response = urllib.request.urlopen(request_login)
        readed = response.read()
        soup = BeautifulSoup(readed, "html.parser")
        IsTrue = str(soup.findAll("div", attrs={"class" : "ui-message-contents"}).text)
        if IsTrue == resfused_msg:
            print("Refused => ({}:{})".format(user, password))
        else:
            print("Accepted => ({}:{})".format(user, password))
            result_file = open(result, "a")
            result_file.write(user + ":" + password)
    except Exception as e:
        print(f"[-] Sorry an error as occured.\n=> {e}\n")
        print("[+]Closing program.\n")
        time.sleep(2)
        exit()

combo = "working.txt"
try:
    combo_file = open(combo, "r")
    line = list(combo)
    print("[+]Combolist loaded.\n")
    for line in combo_file:
        user = line.split(":")[0]
        password = line.split(":")[1]
        check_acc(user,password)
except FileNotFoundError:
    print("[-]NOthing found.")

print("[+]Bye!...\n")
time.sleep(20)
exit()```
</code>```

答:
The Html Agility Pack is one of the most common HTML parsing packages used in C#. It is available via direct download or from the NuGet package feed. The documentation is available here. You should also get the CssSelectors nuget package to allow you to use CSS Selectors to extract elements from the DOM.

To get your div with the ui-message-contents class you will do something like:

```<code>// You will need to pass in/configure the headers and other fields for your request before you call GetResponse
HttpWebRequest request= (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

HtmlDocument document = new HtmlAgilityPack.HtmlDocument();

document.Load(response.GetResponseStream());
IList<HtmlNode> elements = document.QuerySelectorAll("div.ui-message-contents");

// or if you're only expecting a single result
HtmlNode element = document.QuerySelector("div.ui-message-contents");
</code>```

Title: Python Translation to .NET C#

Body:
I want help translating finding the equivalent code for the C# version.

Mainly, I don't understand the BeautifulSoup and html.parser the most.
 Which libraries would I use in C# I ask for demonstration  of  code example. Thanks for all the help.

import urllib.parse
import time
from bs4 import BeautifulSoup

def check_acc(user,password):
    POST = 'POST'
    GET = 'GET'
    data = "userLoginId={}&password={}&STAYIN=false&flow=websiteSignUp&mode=login&action=loginAction&withFields=STAYIN%2CnextPage%2CuserLoginId%2Cpassword%2CcountryCode%2CcountryIsoCode&authURL=authURL%2FEcpWPKhtag%3D&nextPage=&showPassword=&countryCode=%2B33&countryIsoCode=USA".format(email, password).encode("utf-8")

    request_login = urllib.request.Request("https://www.mywebsitetest:8080/Admin",
    data = data,
    headers ={
    'Host': 'www.mywebsitetest.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'fr-FR',
    'Accept-Encoding': 'gzip, deflate, br',
    'Referer': 'https://www.mywebsitetest/USA/Login',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': 330},
    unverifiable = True,
    method = 'POST')

    resfused_msg = "Wrong combination.".format('')
    try:
        response = urllib.request.urlopen(request_login)
        readed = response.read()
        soup = BeautifulSoup(readed, "html.parser")
        IsTrue = str(soup.findAll("div", attrs={"class" : "ui-message-contents"}).text)
        if IsTrue == resfused_msg:
            print("Refused => ({}:{})".format(user, password))
        else:
            print("Accepted => ({}:{})".format(user, password))
            result_file = open(result, "a")
            result_file.write(user + ":" + password)
    except Exception as e:
        print(f"[-] Sorry an error as occured.\n=> {e}\n")
        print("[+]Closing program.\n")
        time.sleep(2)
        exit()

combo = "working.txt"
try:
    combo_file = open(combo, "r")
    line = list(combo)
    print("[+]Combolist loaded.\n")
    for line in combo_file:
        user = line.split(":")[0]
        password = line.split(":")[1]
        check_acc(user,password)
except FileNotFoundError:
    print("[-]NOthing found.")

print("[+]Bye!...\n")
time.sleep(20)
exit()```

Body:
The Html Agility Pack is one of the most common HTML parsing packages used in C#. It is available via direct download or from the NuGet package feed. The documentation is available here. You should also get the CssSelectors nuget package to allow you to use CSS Selectors to extract elements from the DOM.

To get your div with the ui-message-contents class you will do something like:

// You will need to pass in/configure the headers and other fields for your request before you call GetResponse
HttpWebRequest request= (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

HtmlDocument document = new HtmlAgilityPack.HtmlDocument();

document.Load(response.GetResponseStream());
IList<HtmlNode> elements = document.QuerySelectorAll("div.ui-message-contents");

// or if you're only expecting a single result
HtmlNode element = document.QuerySelector("div.ui-message-contents");


问:
Adjust div width according to child element
In this fiddle: https://jsfiddle.net/7d84Laxr/1/

```<code><div class="textCenter">
    <div class="wrapper">
        <input type="text" class="inputNoBorder">
        <p style="display: inline-block;">/Some Text.</p>
    </div>
</div>
</code>```

I want to underline (border-bottom) the input and p only. But as the width of parent div is same as window width, it draws a full line.

How can I reduce wrapper div's width to only contain two elements so that border will be only below those two elements?

I prefer no JavaScript.

答:
Add to .wrapper

```<code>width:fit-content;
margin: 0 auto;
</code>```

That way it conforms to the width of the input and paragraph and it's centered. Note the wrapper is still a block so it will not share space side-by-side with another element which an inline-block would do. BTW the input had display:inline-box it's fixed to inline-block.

.textCenter {
  text-align: center;
}

.inputNoBorder {
  border: 0px;
  display: inline-block;
  padding: 0px;
  margin: 0rem 0.2rem;
  width: 15rem;
}

.wrapper {
  border-bottom: 1px solid;
  width: fit-content;
  margin: 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="textCenter">
  <div class="wrapper">
    <input type="text" class="inputNoBorder">
    <p style="display: inline-block;">/DENSPRI, LLC.</p>
  </div>
</div></code>```

Body:
In this fiddle: https://jsfiddle.net/7d84Laxr/1/

        <input type="text" class="inputNoBorder">

/Some Text.

I want to underline (border-bottom) the input and p only. But as the width of parent div is same as window width, it draws a full line.

How can I reduce wrapper div's width to only contain two elements so that border will be only below those two elements?

I prefer no JavaScript.

Body:
Add to .wrapper

width:fit-content;
margin: 0 auto;

That way it conforms to the width of the input and paragraph and it's centered. Note the wrapper is still a block so it will not share space side-by-side with another element which an inline-block would do. BTW the input had display:inline-box it's fixed to inline-block.

.textCenter {
  text-align: center;
}

.inputNoBorder {
  border: 0px;
  display: inline-block;
  padding: 0px;
  margin: 0rem 0.2rem;
  width: 15rem;
}

.wrapper {
  border-bottom: 1px solid;
  width: fit-content;
  margin: 0 auto;
}

<div class="textCenter">
  <div class="wrapper">
    <input type="text" class="inputNoBorder">
    <p style="display: inline-block;">/DENSPRI, LLC.</p>
  </div>
</div>


问:
Interaction between restartBrowserBetweenTests with onPrepare()
I want each of my tests to run on clean browser (Firefox) so i use restartBrowserBetweenTests:true option. Because i use non-Angular demo app, in onPrepare() function i use browser.waitForAngularEnabled(false). It's works fine, when i run a single spec, but when i run 2 specs, i have error.

Angular could not be found on the page. If this is not an Angular application, you may need to turn off waiting for Angular.

How can i solve this? And in addition, how onPrepare works in this case - every time when browser starts or one time before all specs?

Here is my conf.js

```<code>const screenshotReporter = require('./screenshotCustomReporter')

exports.config = {
    capabilities: {
        browserName: 'firefox'
    },

    restartBrowserBetweenTests: true,

    framework: 'jasmine',
    directConnect: true,

    baseUrl: URL,

    specs: ['path/**/*Spec.js'],

    // Options to be passed to Jasmine.
    jasmineNodeOpts: {
        defaultTimeoutInterval: 30000,
        includeStackTrace: true
    },

    onPrepare: () => {
        require("@babel/register");

        jasmine.getEnv().addReporter(screenshotReporter)
        browser.waitForAngularEnabled(false)
    }
}

</code>```

You can recreate this issue using the following simple project:

conf.js

```<code>exports.config = {
    framework: 'jasmine',
    specs: ['./app.1.js', './app.2.js'],
    seleniumAddress: 'http://localhost:4444/wd/hub',
    restartBrowserBetweenTests:true,
    onPrepare:function(){
        browser.waitForAngularEnabled(false);
    },
}
</code>```

app.1.js

```<code>describe('second test', () => {
    it('should check is displayed successfully', () => {
        browser.driver.get("https://stackoverflow.com");
        browser.driver.sleep(5000);
        expect(element(by.linkText('Ask Question')).isDisplayed()).toBe(true);
    });
});
</code>```

app.2.js

```<code>describe('first test', () => {
    it('should check is displayed successfully', () => {
        browser.driver.get("https://stackoverflow.com");
        browser.driver.sleep(5000);
        expect(element(by.linkText('Ask Question')).isDisplayed()).toBe(true);
    });
});
</code>```

答:
OnPrepare is defined for all settings need to be executed for suite. It means it
is always one time operation irrespective of number of spec files.

One concept you need to understand is that whenever the new instance of
firefox browser is launched then WebdriverJs initialize the instance of webdriver.
and global object browser in protractor also gets initialized.

In your case First spec file start firefox browser, OnPrepare function is executed afterwards and
default setting of protractor is overriden by WaitForAngularEnabled.But when you run second spec file,
again firefox browser is launched with fresh instance of webdriver and protractor browser which expect
angular application and in that case test case gets failed.

The solution for this problem is to use before function in spec file

```<code>describe('first test', () => {
      before(() => {
                     browser.waitForAngularEnabled(false);
       });

    it('should check is displayed successfully', () => {
        browser.driver.get("https://stackoverflow.com");
        browser.driver.sleep(5000);
        expect(element(by.linkText('Ask Question')).isDisplayed()).toBe(true);
    });
});
</code>```

Note : If you are using restartBrowserBetweenTests: true then you will have to use beforeEach() function for waitForAngularEnabled because every time fresh instance of webdriver will be created.

Body:
I want each of my tests to run on clean browser (Firefox) so i use restartBrowserBetweenTests:true option. Because i use non-Angular demo app, in onPrepare() function i use browser.waitForAngularEnabled(false). It's works fine, when i run a single spec, but when i run 2 specs, i have error.

Angular could not be found on the page. If this is not an Angular application, you may need to turn off waiting for Angular.

How can i solve this? And in addition, how onPrepare works in this case - every time when browser starts or one time before all specs?

Here is my conf.js

const screenshotReporter = require('./screenshotCustomReporter')

exports.config = {
    capabilities: {
        browserName: 'firefox'
    },

    restartBrowserBetweenTests: true,

    framework: 'jasmine',
    directConnect: true,

    baseUrl: URL,

    specs: ['path/**/*Spec.js'],

    // Options to be passed to Jasmine.
    jasmineNodeOpts: {
        defaultTimeoutInterval: 30000,
        includeStackTrace: true
    },

    onPrepare: () => {
        require("@babel/register");

        jasmine.getEnv().addReporter(screenshotReporter)
        browser.waitForAngularEnabled(false)
    }
}

You can recreate this issue using the following simple project:

conf.js

exports.config = {
    framework: 'jasmine',
    specs: ['./app.1.js', './app.2.js'],
    seleniumAddress: 'http://localhost:4444/wd/hub',
    restartBrowserBetweenTests:true,
    onPrepare:function(){
        browser.waitForAngularEnabled(false);
    },
}

app.1.js

describe('second test', () => {
    it('should check is displayed successfully', () => {
        browser.driver.get("https://stackoverflow.com");
        browser.driver.sleep(5000);
        expect(element(by.linkText('Ask Question')).isDisplayed()).toBe(true);
    });
});

app.2.js

describe('first test', () => {
    it('should check is displayed successfully', () => {
        browser.driver.get("https://stackoverflow.com");
        browser.driver.sleep(5000);
        expect(element(by.linkText('Ask Question')).isDisplayed()).toBe(true);
    });
});

Body:
OnPrepare is defined for all settings need to be executed for suite. It means it
is always one time operation irrespective of number of spec files.

One concept you need to understand is that whenever the new instance of
firefox browser is launched then WebdriverJs initialize the instance of webdriver.
and global object browser in protractor also gets initialized.

In your case First spec file start firefox browser, OnPrepare function is executed afterwards and
default setting of protractor is overriden by WaitForAngularEnabled.But when you run second spec file,
again firefox browser is launched with fresh instance of webdriver and protractor browser which expect
angular application and in that case test case gets failed.

The solution for this problem is to use before function in spec file

describe('first test', () => {
      before(() => {
                     browser.waitForAngularEnabled(false);
       });

    it('should check is displayed successfully', () => {
        browser.driver.get("https://stackoverflow.com");
        browser.driver.sleep(5000);
        expect(element(by.linkText('Ask Question')).isDisplayed()).toBe(true);
    });
});

Note : If you are using restartBrowserBetweenTests: true then you will have to use beforeEach() function for waitForAngularEnabled because every time fresh instance of webdriver will be created.


问:
How can I manage my assets in hyperledger composer?
In my hyperledger composer project I have a medicine as an asset. There are different types of medicine, but all medicine need to be approved before they are allowed to be produced and distributed in the supply chain.

Can I store a list of allowed assets in the blockchain, a list which can grow or shrink? Or do I have to store it off-chain?

edit: grammar mistake fixed.

答:
Based on your reply to Riccardo Bonesi, I suggest something like this

```<code>asset AllowedMedicines identified by id {
  o String id
  o Medicines[] medicines
}

concept Medicines {
  o String medicineId
  o String medicineName
  o Participants[] allowedParticipants
}

concept Participants {
  o String participantId // either this is one below
  --> Participant somePerson
  // Any specific meta data you want to store
}
</code>```

Now in your .js files you can do something like this

```<code>const allowedMedicines = await registry.get(id);
const participant; // The person you are checking for
const medicineId; // The medicine against which you are checking
const medicines = allowedMedicines.medicines;
if (medicines.medicineId.contains(medicineId)) {
  // Medicine is in the list;
  let allowedParticipants = medicines.allowedParticipants;
  if (allowedParticipants.contains(participant) {
     // The participant is allowed access to the medicine
  };
};
</code>```

Now of course based on the composer version, some syntax may need to be tweaked, but is the general idea of how you can maintain a mapping.

Body:
Based on your reply to Riccardo Bonesi, I suggest something like this

asset AllowedMedicines identified by id {
  o String id
  o Medicines[] medicines
}

concept Medicines {
  o String medicineId
  o String medicineName
  o Participants[] allowedParticipants
}

concept Participants {
  o String participantId // either this is one below
  --> Participant somePerson
  // Any specific meta data you want to store
}

Now in your .js files you can do something like this

const allowedMedicines = await registry.get(id);
const participant; // The person you are checking for
const medicineId; // The medicine against which you are checking
const medicines = allowedMedicines.medicines;
if (medicines.medicineId.contains(medicineId)) {
  // Medicine is in the list;
  let allowedParticipants = medicines.allowedParticipants;
  if (allowedParticipants.contains(participant) {
     // The participant is allowed access to the medicine
  };
};

Now of course based on the composer version, some syntax may need to be tweaked, but is the general idea of how you can maintain a mapping.


问:
Xamarin.Forms Prism App.xaml can be binded to a ViewModel?
I am building a Xamarin.Forms application with Prism, it shows what Bluetooth devices are connected.

In this application, I need a footer in all the pages showing the connection status of the device.
To do that, I’ve made a static class called Pen with the property IsConnected updated from the BleService.

I also need a button in the footer that is visible when the Pen is disconnected and when it is pressed I can call the Connect method of the BleService.

For the footer, I’ve made a ControlTemplate in the App.xaml containing a button.

Now, I’m using Prism and I don’t know how to bind the button to a ViewModel (App.xaml does not have a ViewModel) in order to call the Connect Command of the BleService.

答:
I found a solution, but I'd like to know what do you think about.

In the App.Xaml, in the Control Template, I've binded the Command of the connection button as you can see below:

```<code><buttons:SfButton Grid.Column="0" Grid.Row="2"
    Command="{TemplateBinding Parent.BindingContext.ConnectCommand}"
    IsVisible="{Binding IsNotConnected, Source={x:Static local:Pen.Current}}"/>
</code>```

Then I've modified the class ViewModelBase, so any new View will inherit the link to Bluetooth Service and the Command Execution:

```<code>public class ViewModelBase : BindableBase, INavigationAware, IDestructible
{
    protected INavigationService NavigationService { get; private set; }
    protected IBLEService BLEService { get; private set; }

    private string _title;
    public string Title
    {
        get { return _title; }
        set { SetProperty(ref _title, value); }
}

public ViewModelBase(INavigationService nS,IBLEService bS)
{
    NavigationService = nS;
    BLEService = bS;
}

public virtual void Destroy()
{
}

private DelegateCommand connectCommand;
public DelegateCommand ConnectCommand => connectCommand ??
    (connectCommand = new DelegateCommand(ExecuteConnectCommand));

async void ExecuteConnectCommand()
{
    await BLEService.Connect();
}
</code>```

What do you think about?
Thanks a lot and have a nice day,
Andrea

Body:
I found a solution, but I'd like to know what do you think about.

In the App.Xaml, in the Control Template, I've binded the Command of the connection button as you can see below:

<buttons:SfButton Grid.Column="0" Grid.Row="2"
    Command="{TemplateBinding Parent.BindingContext.ConnectCommand}"
    IsVisible="{Binding IsNotConnected, Source={x:Static local:Pen.Current}}"/>

Then I've modified the class ViewModelBase, so any new View will inherit the link to Bluetooth Service and the Command Execution:

public class ViewModelBase : BindableBase, INavigationAware, IDestructible
{
    protected INavigationService NavigationService { get; private set; }
    protected IBLEService BLEService { get; private set; }

    private string _title;
    public string Title
    {
        get { return _title; }
        set { SetProperty(ref _title, value); }
}

public ViewModelBase(INavigationService nS,IBLEService bS)
{
    NavigationService = nS;
    BLEService = bS;
}

public virtual void Destroy()
{
}

private DelegateCommand connectCommand;
public DelegateCommand ConnectCommand => connectCommand ??
    (connectCommand = new DelegateCommand(ExecuteConnectCommand));

async void ExecuteConnectCommand()
{
    await BLEService.Connect();
}

What do you think about?
Thanks a lot and have a nice day,
Andrea


问:
How do I update npm on Windows?
When I install node 0.10.33 from the msi ( http://nodejs.org/download/ ), I get an old version of npm (1.4.28).  How can I upgrade npm on Windows?

npm install -g npm

does not work; I still have the old npm.

答:
all npm install commands were getting stuck and will throw error (behind proxy error) after sometime. setting up proxy was not helping. This is what I did.

Had 8.11 nodeJS

Uninstalled NodeJS from Programs & Features with the uninstaller.

Reboot (or you probably can get away with killing all node-related processes from Task Manager).

Look for these folders and remove them (and their contents) if any still exist. Depending on the version you installed, UAC settings, and CPU architecture, these may or may not exist:
•   C:\Program Files (x86)\Nodejs
•   C:\Program Files\Nodejs
•   C:\Users{User}\AppData\Roaming\npm (or %appdata%\npm)
•   C:\Users{User}\AppData\Roaming\npm-cache (or %appdata%\npm-cache)
•   C:\Users{User}.npmrc (and possibly check for that without the . prefix too)

Check your %PATH% environment variable to ensure no references to Nodejs or npm exist.

If it's still not uninstalled, type where node at the command prompt and you'll see where it resides -- delete that (and probably the parent directory) too.

Reboot, for good measure.

Installed 6.11 nodejs then it worked.

Title: How do I update npm on Windows?


问:
Will the UID of the user deleted from the Firebase be reused for the new user?
I know that the Uid of authenticated user on firebase is unique.

But, I can not be sure that uid of the deleted user will not be re used by the new user.

I could not find an explanation for this.

I need experience or information related to this.

答:
I think the uid will always be unique. It is actually based on the timestamp and other factors so it will be unique.

Info on how firebase generates it :
How does Firebase generate the Uid?

And about their uniqueness:
https://towardsdatascience.com/are-uuids-really-unique-57eb80fc2a87

If you still want to set your custom uid for a user for any analytics purpose :
https://firebase.google.com/docs/analytics/userid


问:
POST method is not supported for this route
First, I've checked other question topic, but couldn't find the solution.

when I try to post my form. I am getting this error.

The POST method is not supported for this route. Supported methods:
  GET, HEAD.

Form:

```<code><div class="card-body">
    <form action="{{route('profile.update', ['id' => $id])}}" method="post">
      @csrf
      @put

        <div class="form-group">
            <label for="location">Location</label>
            <input class="form-control" type="text" name="location" value="{{$info->location}}">
        </div>
        <div class="form-group">
            <label for="about">About</label>
            <textarea name="about" id="about" rows="10" cols="50" class="form-control">{{$info->about}}</textarea>
        </div>
        <div class="form-control">
            <p class="text-center">
                <button class="btn btn-primary btn-md" type="submit">Update Your Info</button>
            </p>
        </div>
    </form>
</div>
</code>```

Routes:

```<code>Route::group(["middleware" => "auth"], function(){
    route::get("/profile/edit", [
        "uses" => "ProfilesController@edit",
        "as" => "profile.edit"
    ]);
    route::get("/profile/{slug}", [
        "uses" => "ProfilesController@index",
        "as" => "profile"
    ]);
    route::put("/profile/update/{id}", [
        "uses" => "ProfilesController@update",
        "as" => "profile.update"
    ]);
});
</code>```

in controller:

```<code>public function update(Request $request, $id)
{

    dd($request->all());

}
</code>```

答:
From your question, i can understand that you're trying to update a profile using POST method or may be PUT method earlier. Since, the resource you are editing is unique, you're not passing any parameters for the controller to find that single resource so as to update it.

therefore modify your your route like

```<code> route::put("/profile/update/{id}", [
        "uses" => "ProfilesController@update",
        "as" => "profile.update"
    ]);
</code>```

And your form like

```<code><form action="{{route('profile.update', ['id' => $id])}}" method="post">
@csrf
@method('put')
</code>```

You'll need to pass the ID of the profile you want to update as parameter

then at the controller

```<code>public function update(Request $request, $id){
 //edit the profile with id = $id
}
</code>```

Body:
First, I've checked other question topic, but couldn't find the solution.

when I try to post my form. I am getting this error.

The POST method is not supported for this route. Supported methods:
  GET, HEAD.

Form:

    <form action="{{route('profile.update', ['id' => $id])}}" method="post">
      @csrf
      @put

            Location
            <input class="form-control" type="text" name="location" value="{{$info->location}}">

            About
            <textarea name="about" id="about" rows="10" cols="50" class="form-control">{{$info->about}}</textarea>

                <button class="btn btn-primary btn-md" type="submit">Update Your Info</button>

    </form>

Routes:

Route::group(["middleware" => "auth"], function(){
    route::get("/profile/edit", [
        "uses" => "ProfilesController@edit",
        "as" => "profile.edit"
    ]);
    route::get("/profile/{slug}", [
        "uses" => "ProfilesController@index",
        "as" => "profile"
    ]);
    route::put("/profile/update/{id}", [
        "uses" => "ProfilesController@update",
        "as" => "profile.update"
    ]);
});

in controller:

public function update(Request $request, $id)
{

    dd($request->all());

}

Body:
From your question, i can understand that you're trying to update a profile using POST method or may be PUT method earlier. Since, the resource you are editing is unique, you're not passing any parameters for the controller to find that single resource so as to update it.

therefore modify your your route like

 route::put("/profile/update/{id}", [
        "uses" => "ProfilesController@update",
        "as" => "profile.update"
    ]);

And your form like

<form action="{{route('profile.update', ['id' => $id])}}" method="post">
@csrf
@method('put')

You'll need to pass the ID of the profile you want to update as parameter

then at the controller

public function update(Request $request, $id){
 //edit the profile with id = $id
}


问:
How to use DatePickerComponent in a sharedModule
I have a DatePickerComponent works fine in AppModule.
I created a SharedModule to use the datePicker in different modules, i included the DatePickerComponent in it.
That's how my SharedModule looks like

here

Then i imported the ShareModule in AppModule.

@NgModule({
imports: [
SahredModuleModule, ...]
export class AppModule { }

I got this error

答:
Add the NgbModule as well to the exports array of your SharedModule. That's what will be required for the DatePicker to load.

Something like this:

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

import { NgbdDatepickerBasic } from '../datepicker-basic';

@NgModule({
  imports: [
    CommonModule,
    NgbModule,
    FormsModule
  ],
  declarations: [NgbdDatepickerBasic],
  exports: [
    NgbdDatepickerBasic,
    NgbModule /*THIS RIGHT HERE*/
  ]
})
export class SharedModule { }
</code>```

Here's a Working Sample StackBlitz for your ref.

Body:
Add the NgbModule as well to the exports array of your SharedModule. That's what will be required for the DatePicker to load.

Something like this:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

import { NgbdDatepickerBasic } from '../datepicker-basic';

@NgModule({
  imports: [
    CommonModule,
    NgbModule,
    FormsModule
  ],
  declarations: [NgbdDatepickerBasic],
  exports: [
    NgbdDatepickerBasic,
    NgbModule /*THIS RIGHT HERE*/
  ]
})
export class SharedModule { }

Here's a Working Sample StackBlitz for your ref.


问:
How to convert a string into an integer without white spaces?
I am trying to multiply complex numbers that is inputted by a user. Some example inputs would be :

Enter a complex number in the form ai + b: 2i + 8

Enter a complex number in the form ai + b: 11  i + 2

Enter a complex number in the form ai + b: 1i+6

I want these all to be valid inputs but am not sure how to make sure that scanf() ignores spaces and the characters so that I can just extract the integers.  I am trying to do this by having scanf() accepting the input as three strings with the first string containing ai, the second string containing the '+', and the third string containing b.  However, my code trying to turn my first string (with ai) into an integer (just a without 'i') is not successful.

```<code>int inta(char* ai){
  int i;
  int origa;
  int max;
  int a = 0;
  for(i = 0; i<strlen(ai); i++){
    if(ai[i] != "i" && ai[i] != ' ')
      continue;
    else
      break;
  }
  if(i > 1)
    for(max = i; max > 0; max--){
      origa = atoi(ai[max])*pow(10, max);
      a = origa + a;
    }
  else
    a = atoi(ai[0]);
  return a;
}
</code>```

答:
To extract a from a string ai+beven with a space between the value of a and the 'i' just use sscanf and check it returns 1 to verify you read an int

And finally to also extract the operator and b just do

```<code>sscanf(argv[1], "%d i %c %d", &a, &oper, &b)
</code>```

and check it returns 3 more oper is valid, for instance :

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

int main(int argc, char ** argv)
{
  int a, b;
  char oper;

  if (argc != 2)
    printf("Usage: %s <ai+b>\n", *argv);
  else if ((sscanf(argv[1], "%d i %c %d", &a, &oper, &b) == 3)
           && ((oper == '+') || (oper == '-')))
    printf("a=%d b=%d oper=%c\n", a, b, oper);
  else
    puts("invalid input");

  return 0;
}
</code>```

Compilation and executions :

```<code>pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out ai+2
invalid input
pi@raspberrypi:/tmp $ ./a.out 12i+3
a=12 b=3 oper=+
pi@raspberrypi:/tmp $ ./a.out "12i + 3"
a=12 b=3 oper=+
pi@raspberrypi:/tmp $ ./a.out "12 i + 3"
a=12 b=3 oper=+
pi@raspberrypi:/tmp $ ./a.out "12 i - 3"
a=12 b=3 oper=-
pi@raspberrypi:/tmp $ ./a.out "12i+-3"
a=12 b=-3 oper=+
pi@raspberrypi:/tmp $ ./a.out "-12i+-3"
a=-12 b=-3 oper=+
pi@raspberrypi:/tmp $ ./a.out "-12i*-3"
invalid input
pi@raspberrypi:/tmp $
</code>```

Note I allow to enter directly 1i-2 rather than to force to enter 1i+-2 less practical because I allow the operator to be '-', if you do not want to allow that simplified form :

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

int main(int argc, char ** argv)
{
  int a, b;

  if (argc != 2)
    printf("Usage: %s <ai+b>\n", *argv);
  else if (sscanf(argv[1], "%d i + %d", &a, &b) == 2)
    printf("a=%d b=%d\n", a, b);
  else
    puts("invalid input");

  return 0;
}
</code>```

Compilation and executions :

```<code>pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out ai+2
invalid input
pi@raspberrypi:/tmp $ ./a.out 12i+3
a=12 b=3 oper=+
pi@raspberrypi:/tmp $ ./a.out "12i + 3"
a=12 b=3 oper=+
pi@raspberrypi:/tmp $ ./a.out "12 i + 3"
a=12 b=3 oper=+
pi@raspberrypi:/tmp $ ./a.out "12 i - 3"
invalid input
pi@raspberrypi:/tmp $ ./a.out "12i+-3"
a=12 b=-3 oper=+
pi@raspberrypi:/tmp $ ./a.out "-12i+-3"
a=-12 b=-3 oper=+
pi@raspberrypi:/tmp $ ./a.out "-12i*-3"
invalid input
pi@raspberrypi:/tmp $ ./a.out "-12i++3"
a=-12 b=3 oper=+
pi@raspberrypi:/tmp $
</code>```

About your update, your input strings for sscanf are invalid because you give NULL pointers, you want something like that :

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

int main()
{
  char line[64];
  int a;
  int b;
  int c;
  int d;
  int finala;
  int finalb;

  printf("Enter the first complex number in the form ai + b: ");

  if ((fgets(line, sizeof(line), stdin) == NULL) ||
      (sscanf(line, "%d i + %d", &a, &b) != 2)) {
    puts("invalid form");
    return -1;
  }

  printf("Enter the second complex number in the form ai + b: ");
  if ((fgets(line, sizeof(line), stdin) == NULL) ||
      (sscanf(line, "%d i + %d", &c, &d) != 2)) {
    puts("invalid form");
    return -1;
  }

  finala = b*c + a*d;
  finalb = b*d + a*c*(-1);

  printf("(%di + %d) * (%di + %d) = %di + %d\n", a, b, c, d, finala, finalb);
}
</code>```

Compilation and execution :

```<code>pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out
Enter the first complex number in the form ai + b: 1i+2
Enter the second complex number in the form ai + b: -2i+6
(1i + 2) * (-2i + 6) = 2i + 14
pi@raspberrypi:/tmp $
</code>```

Body:
I am trying to multiply complex numbers that is inputted by a user. Some example inputs would be :

Enter a complex number in the form ai + b: 2i + 8

Enter a complex number in the form ai + b: 11  i + 2

Enter a complex number in the form ai + b: 1i+6

I want these all to be valid inputs but am not sure how to make sure that scanf() ignores spaces and the characters so that I can just extract the integers.  I am trying to do this by having scanf() accepting the input as three strings with the first string containing ai, the second string containing the '+', and the third string containing b.  However, my code trying to turn my first string (with ai) into an integer (just a without 'i') is not successful.

int inta(char* ai){
  int i;
  int origa;
  int max;
  int a = 0;
  for(i = 0; i<strlen(ai); i++){
    if(ai[i] != "i" && ai[i] != ' ')
      continue;
    else
      break;
  }
  if(i > 1)
    for(max = i; max > 0; max--){
      origa = atoi(ai[max])*pow(10, max);
      a = origa + a;
    }
  else
    a = atoi(ai[0]);
  return a;
}

Body:
To extract a from a string ai+beven with a space between the value of a and the 'i' just use sscanf and check it returns 1 to verify you read an int

And finally to also extract the operator and b just do

sscanf(argv[1], "%d i %c %d", &a, &oper, &b)

and check it returns 3 more oper is valid, for instance :

#include <stdio.h>

int main(int argc, char ** argv)
{
  int a, b;
  char oper;

  if (argc != 2)
    printf("Usage: %s <ai+b>\n", *argv);
  else if ((sscanf(argv[1], "%d i %c %d", &a, &oper, &b) == 3)
           && ((oper == '+') || (oper == '-')))
    printf("a=%d b=%d oper=%c\n", a, b, oper);
  else
    puts("invalid input");

  return 0;
}

Compilation and executions :

pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out ai+2
invalid input
pi@raspberrypi:/tmp $ ./a.out 12i+3
a=12 b=3 oper=+
pi@raspberrypi:/tmp $ ./a.out "12i + 3"
a=12 b=3 oper=+
pi@raspberrypi:/tmp $ ./a.out "12 i + 3"
a=12 b=3 oper=+
pi@raspberrypi:/tmp $ ./a.out "12 i - 3"
a=12 b=3 oper=-
pi@raspberrypi:/tmp $ ./a.out "12i+-3"
a=12 b=-3 oper=+
pi@raspberrypi:/tmp $ ./a.out "-12i+-3"
a=-12 b=-3 oper=+
pi@raspberrypi:/tmp $ ./a.out "-12i*-3"
invalid input
pi@raspberrypi:/tmp $

Note I allow to enter directly 1i-2 rather than to force to enter 1i+-2 less practical because I allow the operator to be '-', if you do not want to allow that simplified form :

#include <stdio.h>

int main(int argc, char ** argv)
{
  int a, b;

  if (argc != 2)
    printf("Usage: %s <ai+b>\n", *argv);
  else if (sscanf(argv[1], "%d i + %d", &a, &b) == 2)
    printf("a=%d b=%d\n", a, b);
  else
    puts("invalid input");

  return 0;
}

Compilation and executions :

pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out ai+2
invalid input
pi@raspberrypi:/tmp $ ./a.out 12i+3
a=12 b=3 oper=+
pi@raspberrypi:/tmp $ ./a.out "12i + 3"
a=12 b=3 oper=+
pi@raspberrypi:/tmp $ ./a.out "12 i + 3"
a=12 b=3 oper=+
pi@raspberrypi:/tmp $ ./a.out "12 i - 3"
invalid input
pi@raspberrypi:/tmp $ ./a.out "12i+-3"
a=12 b=-3 oper=+
pi@raspberrypi:/tmp $ ./a.out "-12i+-3"
a=-12 b=-3 oper=+
pi@raspberrypi:/tmp $ ./a.out "-12i*-3"
invalid input
pi@raspberrypi:/tmp $ ./a.out "-12i++3"
a=-12 b=3 oper=+
pi@raspberrypi:/tmp $

About your update, your input strings for sscanf are invalid because you give NULL pointers, you want something like that :

#include <stdio.h>

int main()
{
  char line[64];
  int a;
  int b;
  int c;
  int d;
  int finala;
  int finalb;

  printf("Enter the first complex number in the form ai + b: ");

  if ((fgets(line, sizeof(line), stdin) == NULL) ||
      (sscanf(line, "%d i + %d", &a, &b) != 2)) {
    puts("invalid form");
    return -1;
  }

  printf("Enter the second complex number in the form ai + b: ");
  if ((fgets(line, sizeof(line), stdin) == NULL) ||
      (sscanf(line, "%d i + %d", &c, &d) != 2)) {
    puts("invalid form");
    return -1;
  }

  finala = b*c + a*d;
  finalb = b*d + a*c*(-1);

  printf("(%di + %d) * (%di + %d) = %di + %d\n", a, b, c, d, finala, finalb);
}

Compilation and execution :

pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out
Enter the first complex number in the form ai + b: 1i+2
Enter the second complex number in the form ai + b: -2i+6
(1i + 2) * (-2i + 6) = 2i + 14
pi@raspberrypi:/tmp $


问:
Postman hangs while i make post request. Post request Working fine for registration but not for login
So i am implementing basic login/registration using passportJs JWT. Framework i am using is express of node.js. Problem is i am registering a user, it is working fine as it registers via Postman and i can see it in mongodb shell using db.users.find(). But when i am making a POST request to authenticate user means login it is giving me "User not Found" when i change JSON(application/json) to Text. Otherwise it hangs and after some time terminates.

app.js

```<code>   const app = express();

   const users = require('./routes/users');

   //port
   const port = 3000;

   //middleware
   app.use(cors());

   //Front
   app.use(express.static(path.join(__dirname,'public')));

   //middleware
   app.use(bodyParser.json());

   app.use(passport.initialize());
   app.use(passport.session());

   require('./config/passport')(passport);
</code>```

passport.js

```<code>module.exports = function(){
    let opts = {};
    opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt');
    opts.secretOrKey = 'secret';
    passport.use(new JwtStrategy(opts , (jwt_payload, done) => {
        User.getUserById(jwt_payload._id, (err, user) =>{
            if(err){
                return done(err, false);
            }
            if(user){
                return done(null, user);
            }
            else{
                return done(null, false);
            }
        })
    }));
}
</code>```

users.js

```<code>router.post('/authenticate', (req,res,next) =>{
    const email = req.body.email;
    const password = req.body.password;

    User.getUserByemail(email, (err, user) => {
        if(err) throw err;
        if(!user){
            return res.json({success: false,msg:'user Not Found'});
        }
        User.comparePassword(password,user.password, (err, isMatch) => {
            if(err){
                if(isMatch()){
                    const token = jwt.sign(user,'secret', {
                        expiresIn: 86400 // 1 Day
                    });
                    res.json({
                        success: true,
                        token: 'JWT ' +token,
                        user:{
                            id: user._id,
                            name: user.fname+ ' ' + user.lname,
                            email: user.email
                        }
                    });
                }
                else{
                    return res.json({success: false,msg:'Wrong Password'});
                }
            }
        });
    });
});
</code>```

user.js

```<code>module.exports.getUserByemail = function(email, callback){
    const query = {email: email}
    User.findOne(query,callback);
}
</code>```

答:
From what I see with your code, passport has nothing to do with your error since your /authenticate route is public (not using the passport middleware), so we can take this out of the equation.

I would suggest to double check/log the req.body and see if you are getting the right information in your API function, I'm pretty sure the data is wrong especially  since you are talking about the request format text/json.

Body:
So i am implementing basic login/registration using passportJs JWT. Framework i am using is express of node.js. Problem is i am registering a user, it is working fine as it registers via Postman and i can see it in mongodb shell using db.users.find(). But when i am making a POST request to authenticate user means login it is giving me "User not Found" when i change JSON(application/json) to Text. Otherwise it hangs and after some time terminates.

app.js

   const app = express();

   const users = require('./routes/users');

   //port
   const port = 3000;

   //middleware
   app.use(cors());

   //Front
   app.use(express.static(path.join(__dirname,'public')));

   //middleware
   app.use(bodyParser.json());

   app.use(passport.initialize());
   app.use(passport.session());

   require('./config/passport')(passport);

passport.js

module.exports = function(){
    let opts = {};
    opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt');
    opts.secretOrKey = 'secret';
    passport.use(new JwtStrategy(opts , (jwt_payload, done) => {
        User.getUserById(jwt_payload._id, (err, user) =>{
            if(err){
                return done(err, false);
            }
            if(user){
                return done(null, user);
            }
            else{
                return done(null, false);
            }
        })
    }));
}

users.js

router.post('/authenticate', (req,res,next) =>{
    const email = req.body.email;
    const password = req.body.password;

    User.getUserByemail(email, (err, user) => {
        if(err) throw err;
        if(!user){
            return res.json({success: false,msg:'user Not Found'});
        }
        User.comparePassword(password,user.password, (err, isMatch) => {
            if(err){
                if(isMatch()){
                    const token = jwt.sign(user,'secret', {
                        expiresIn: 86400 // 1 Day
                    });
                    res.json({
                        success: true,
                        token: 'JWT ' +token,
                        user:{
                            id: user._id,
                            name: user.fname+ ' ' + user.lname,
                            email: user.email
                        }
                    });
                }
                else{
                    return res.json({success: false,msg:'Wrong Password'});
                }
            }
        });
    });
});

user.js

module.exports.getUserByemail = function(email, callback){
    const query = {email: email}
    User.findOne(query,callback);
}


问:
C# if directive
Can I write in code to set the variable to true or false depending on a button I pressed? See example below.

If not, what other ways are there to achieve similar effects? I have already marked the codes for different modes using directives and only want developers to have the option of switching the modes, but now I wish to give the user the option of switching between the modes. The choice of the mode will only be given at the start of the program, and user is not allowed to switch the mode. To switch the mode, he can only restart the program again.

If cannot use directives, what is the fastest way can I use? (note: the statements are all around the solution)

In pseduocode of what I wish to achieve:

```<code>void button_click(...){
    if(!CONDITION)
        CONDITION = true;
    else
        CONDITION = false;
}

...
#if CONDITION
   //mode X with addtional steps
#endif
</code>```

答:
You are using a preprocessor directive and trying to set it from code which defeats the purpose, even if it were to be possible (I'm pretty sure you can't). Why not use a regular boolean field as a flag ?</p>

```<code>private bool Condition {get; set;}
</code>```

Title: C# if directive

Body:
Can I write in code to set the variable to true or false depending on a button I pressed? See example below.

If not, what other ways are there to achieve similar effects? I have already marked the codes for different modes using directives and only want developers to have the option of switching the modes, but now I wish to give the user the option of switching between the modes. The choice of the mode will only be given at the start of the program, and user is not allowed to switch the mode. To switch the mode, he can only restart the program again.

If cannot use directives, what is the fastest way can I use? (note: the statements are all around the solution)

In pseduocode of what I wish to achieve:

void button_click(...){
    if(!CONDITION)
        CONDITION = true;
    else
        CONDITION = false;
}

...
#if CONDITION
   //mode X with addtional steps
#endif

Body:
You are using a preprocessor directive and trying to set it from code which defeats the purpose, even if it were to be possible (I'm pretty sure you can't). Why not use a regular boolean field as a flag ?

private bool Condition {get; set;}


问:
AWS Java Lambda compressed JSON responses fails: "Execution failed due to configuration error: Malformed Lambda proxy response"
I am invoking a AWS Lambda function from the AWS API Gateway. The returned JSON needs to be zipped since it sometimes became too big (body size too large etc). However, I have some issues getting the response through the API Gateway. This is my Java code:

```<code>    @Override
    public JSONObject handleRequest(Object input, Context context) {
        String json_string = "";
        try {
            Gson gson = new Gson();
            json_string = gson.toJson(input, LinkedHashMap.class);
        } catch (ClassCastException ex) {
            json_string = (String) input;
        }

        GenerateJson generateJson = new GenerateJson ();
        String body = "";
        try {
            JSONParser parser = new JSONParser();
            Object jsonObj = parser.parse(json_string);
            JSONObject matchesobj = (JSONObject) jsonObj;

            if (matchesobj.containsKey("body")) {
                body = (String) matchesobj.get("body");
            } else {
                JSONObject error = new JSONObject();
                error.put("error", "No body with Base64 data in Request.");
                System.out.println(error.toJSONString());
                return error;
            }

        } catch (ParseException ex) {
            ex.printStackTrace();
        }

        byte[] decodedBytes = Base64.getDecoder().decode(body);
        String decodedString = new String(decodedBytes);
        // System.out.println(decodedString);

        JSONObject json = generateJson .getJson(decodedString, "", 2);

        JSONObject returnObject = new JSONObject();
        JSONObject headers = new JSONObject();
        returnObject.put("statusCode", 205);
        returnObject.put("isBase64Encoded", true);
        // returnObject.put("Content-Encoding", "gzip");

        returnObject.put("headers", headers);
        returnObject.put("body", compressStringAndReturnBase64(json.toString()));

        return (returnObject);
    }

    public static String compressStringAndReturnBase64(String srcTxt) {

        ByteArrayOutputStream rstBao = new ByteArrayOutputStream();
        GZIPOutputStream zos;
        try {
            zos = new GZIPOutputStream(rstBao);
            zos.write(srcTxt.getBytes());
            IOUtils.closeQuietly(zos);
            byte[] bytes = rstBao.toByteArray();
            String base64comp = Base64.getEncoder().encodeToString(bytes);
            System.out.println("Json String is " + srcTxt.toString().getBytes().length + " compressed " + bytes.length + " compressed Base64 " + base64comp.getBytes().length);

            return base64comp;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }
</code>```

I've checked the Base64 output and that seems to work fine (pasted it in https://www.base64decode.org/). In addition, when I check with Postman, I get a binary blob which can be unpacked with 7-zip if I save the response to something that ends with .gz.

Under settings, the API Gateway Binary Media Types has been set to /
But I'd like to have the client "see" that it is GZIPped and decode it on the fly. However, when I add the line

```<code>returnObject.put("Content-Encoding", "gzip");
</code>```

I get {"message": "Internal server error"} and in the AWS API logs: Execution failed due to configuration error: Malformed Lambda proxy response

The Lambda logs are fine, so it did execute successfully, just wasn't able to be returned.

I am thinking I need some more tweaking on the API Gateway side, any ideas?

答:
In your HTTP request add "Accept" header with payload content type.

Accept: application/gzip

Also in the HTTP response, there should be "Content-Type" header indicating response content type.

Content-Type: application/gzip

Your lambda returns Base64 encoded binary data to API Gateway. So in order to decode data your HTTP request's  Accept header and Response's Content-type headers should there.

Body:
I am invoking a AWS Lambda function from the AWS API Gateway. The returned JSON needs to be zipped since it sometimes became too big (body size too large etc). However, I have some issues getting the response through the API Gateway. This is my Java code:

    @Override
    public JSONObject handleRequest(Object input, Context context) {
        String json_string = "";
        try {
            Gson gson = new Gson();
            json_string = gson.toJson(input, LinkedHashMap.class);
        } catch (ClassCastException ex) {
            json_string = (String) input;
        }

        GenerateJson generateJson = new GenerateJson ();
        String body = "";
        try {
            JSONParser parser = new JSONParser();
            Object jsonObj = parser.parse(json_string);
            JSONObject matchesobj = (JSONObject) jsonObj;

            if (matchesobj.containsKey("body")) {
                body = (String) matchesobj.get("body");
            } else {
                JSONObject error = new JSONObject();
                error.put("error", "No body with Base64 data in Request.");
                System.out.println(error.toJSONString());
                return error;
            }

        } catch (ParseException ex) {
            ex.printStackTrace();
        }

        byte[] decodedBytes = Base64.getDecoder().decode(body);
        String decodedString = new String(decodedBytes);
        // System.out.println(decodedString);

        JSONObject json = generateJson .getJson(decodedString, "", 2);

        JSONObject returnObject = new JSONObject();
        JSONObject headers = new JSONObject();
        returnObject.put("statusCode", 205);
        returnObject.put("isBase64Encoded", true);
        // returnObject.put("Content-Encoding", "gzip");

        returnObject.put("headers", headers);
        returnObject.put("body", compressStringAndReturnBase64(json.toString()));

        return (returnObject);
    }

    public static String compressStringAndReturnBase64(String srcTxt) {

        ByteArrayOutputStream rstBao = new ByteArrayOutputStream();
        GZIPOutputStream zos;
        try {
            zos = new GZIPOutputStream(rstBao);
            zos.write(srcTxt.getBytes());
            IOUtils.closeQuietly(zos);
            byte[] bytes = rstBao.toByteArray();
            String base64comp = Base64.getEncoder().encodeToString(bytes);
            System.out.println("Json String is " + srcTxt.toString().getBytes().length + " compressed " + bytes.length + " compressed Base64 " + base64comp.getBytes().length);

            return base64comp;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }

I've checked the Base64 output and that seems to work fine (pasted it in https://www.base64decode.org/). In addition, when I check with Postman, I get a binary blob which can be unpacked with 7-zip if I save the response to something that ends with .gz.

Under settings, the API Gateway Binary Media Types has been set to /
But I'd like to have the client "see" that it is GZIPped and decode it on the fly. However, when I add the line

returnObject.put("Content-Encoding", "gzip");

I get {"message": "Internal server error"} and in the AWS API logs: Execution failed due to configuration error: Malformed Lambda proxy response

The Lambda logs are fine, so it did execute successfully, just wasn't able to be returned.

I am thinking I need some more tweaking on the API Gateway side, any ideas?


问:
How to have the same date format in mongo and react?
I'm facing a problem. I'm working on calendar app. The problem is that after populating mongo db collection with days of the whole year, everything seems to be fine, but after fetching the data to the react front i'm ending with wrong date format and timezone. I've tried to debug it, and while fetching data with Calendar.find({}, (err, calendar)) ... the calendar seems like parsed with wrong date timezone. More below.

Ok, so this is the controller that populates database with days of the year:

```<code>exports.generateCalendar = (req, res) => {
    let days = [];
    for(let i=1; i<366; i++) {

        const dayOfTheWeek = new Date(new Date().getFullYear(), 0, i).getDay();
        if(dayOfTheWeek === 0 || dayOfTheWeek === 6){
            days.push({day: new Date(new Date().getFullYear(), 0, i), offWork: true, description: ' '});
        }
        else{
            days.push({day: new Date(new Date().getFullYear(), 0, i), offWork: false, description: ' '});
        }
    }

    Calendar.insertMany(days, (err) => {
        res.json('done');
    });
};
</code>```

The output of this controller is collection of documents like that:

```<code>_id: 5cefc2e5c6db7f47401ba261
offWork: false
day: 2019-01-01T00:00:00.000+01:00
description: " "

_id: 5cefc2e5c6db7f47401ba262
offWork: false
day: 2019-01-02T00:00:00.000+01:00
description: " "

</code>```

The next step is fetching the whole collection and sending it to the front in this simple controller:

```<code>exports.getCalendar = (req, res) => {
    Calendar.find({}, (err, calendar) => {
        if(err){
            res.json('Error while fetching data');
        }else{
            res.json(calendar);
            }

    })
};
</code>```

However the output of fetching is:

```<code>{ offWork: false,
     _id: 5cefc2e5c6db7f47401ba261,
     day: 2018-12-31T23:00:00.000Z,
     description: ' ',
     __v: 0 },
   { offWork: false,
     _id: 5cefc2e5c6db7f47401ba262,
     day: 2019-01-01T23:00:00.000Z,
     description: ' ',
     __v: 0 },
   { offWork: false,
     _id: 5cefc2e5c6db7f47401ba263,
     day: 2019-01-02T23:00:00.000Z,
     description: ' ',
     __v: 0 },

</code>```

Which look like while fetching mongo is parsing the date including timezone offset.

I've created a for loop which pushes new date to a new array:

```<code>            let calendarArray = [];

                for(let i=0; i<calendar.length; i++){
                    calendarArray.push({day: calendar[i].day.toString(), offWork: calendar[i].offWork, description: calendar[i].description});
                }
                res.json(calendarArray);
</code>```

And the output of this is correct on front-end but in wrong format:

```<code>Tue Jan 01 2019 00:00:00 GMT+0100 (GMT+01:00)
Wed Jan 02 2019 00:00:00 GMT+0100 (GMT+01:00)
Thu Jan 03 2019 00:00:00 GMT+0100 (GMT+01:00)
</code>```

The perfect solution would be database in format YYYY-MM-DD or having the same date format in mongo and after fetching.

答:
Ok, What I've done is I've installed moment.js and used it while pushing dates to new array and sending them to the front:

```<code>
exports.getCalendar = (req, res) => {
    Calendar.find({}, (err, calendar) => {
        if(err){
            res.json('Error while fetching data');
        }else{
            let calendarArray = [];

                for(let i=0; i<calendar.length; i++){
                    calendarArray.push({_id: calendar[i]._id, day: moment(calendar[i].day).format("DD-MM-YYYY"), offWork: calendar[i].offWork, description: calendar[i].description, name: calendar[i].name});
                }

            res.json(calendarArray);
            }
    })
};
</code>```

Not a perfect solution, but apparently, it's working.
If you have any other ideas how to solve this, I'd be glad to hear them.

Body:
I'm facing a problem. I'm working on calendar app. The problem is that after populating mongo db collection with days of the whole year, everything seems to be fine, but after fetching the data to the react front i'm ending with wrong date format and timezone. I've tried to debug it, and while fetching data with Calendar.find({}, (err, calendar)) ... the calendar seems like parsed with wrong date timezone. More below.

Ok, so this is the controller that populates database with days of the year:

exports.generateCalendar = (req, res) => {
    let days = [];
    for(let i=1; i<366; i++) {

        const dayOfTheWeek = new Date(new Date().getFullYear(), 0, i).getDay();
        if(dayOfTheWeek === 0 || dayOfTheWeek === 6){
            days.push({day: new Date(new Date().getFullYear(), 0, i), offWork: true, description: ' '});
        }
        else{
            days.push({day: new Date(new Date().getFullYear(), 0, i), offWork: false, description: ' '});
        }
    }

    Calendar.insertMany(days, (err) => {
        res.json('done');
    });
};

The output of this controller is collection of documents like that:

_id: 5cefc2e5c6db7f47401ba261
offWork: false
day: 2019-01-01T00:00:00.000+01:00
description: " "

_id: 5cefc2e5c6db7f47401ba262
offWork: false
day: 2019-01-02T00:00:00.000+01:00
description: " "

The next step is fetching the whole collection and sending it to the front in this simple controller:

exports.getCalendar = (req, res) => {
    Calendar.find({}, (err, calendar) => {
        if(err){
            res.json('Error while fetching data');
        }else{
            res.json(calendar);
            }

    })
};

However the output of fetching is:

{ offWork: false,
     _id: 5cefc2e5c6db7f47401ba261,
     day: 2018-12-31T23:00:00.000Z,
     description: ' ',
     __v: 0 },
   { offWork: false,
     _id: 5cefc2e5c6db7f47401ba262,
     day: 2019-01-01T23:00:00.000Z,
     description: ' ',
     __v: 0 },
   { offWork: false,
     _id: 5cefc2e5c6db7f47401ba263,
     day: 2019-01-02T23:00:00.000Z,
     description: ' ',
     __v: 0 },

Which look like while fetching mongo is parsing the date including timezone offset.

I've created a for loop which pushes new date to a new array:

            let calendarArray = [];

                for(let i=0; i<calendar.length; i++){
                    calendarArray.push({day: calendar[i].day.toString(), offWork: calendar[i].offWork, description: calendar[i].description});
                }
                res.json(calendarArray);

And the output of this is correct on front-end but in wrong format:

Tue Jan 01 2019 00:00:00 GMT+0100 (GMT+01:00)
Wed Jan 02 2019 00:00:00 GMT+0100 (GMT+01:00)
Thu Jan 03 2019 00:00:00 GMT+0100 (GMT+01:00)

The perfect solution would be database in format YYYY-MM-DD or having the same date format in mongo and after fetching.

Body:
Ok, What I've done is I've installed moment.js and used it while pushing dates to new array and sending them to the front:

exports.getCalendar = (req, res) => {
    Calendar.find({}, (err, calendar) => {
        if(err){
            res.json('Error while fetching data');
        }else{
            let calendarArray = [];

                for(let i=0; i<calendar.length; i++){
                    calendarArray.push({_id: calendar[i]._id, day: moment(calendar[i].day).format("DD-MM-YYYY"), offWork: calendar[i].offWork, description: calendar[i].description, name: calendar[i].name});
                }

            res.json(calendarArray);
            }
    })
};

Not a perfect solution, but apparently, it's working.
If you have any other ideas how to solve this, I'd be glad to hear them.


问:
How to get data based on today date and time?
```<code>select * from hockey_stats where game_date between '11/3/2012 12:00:00' and '11/5/2012 15:00:00' order by game_date desc;
</code>```

How to get data based on today date and time between 12:00:00 to 15:00:00?

答:
How about:

```<code>game_date BETWEEN CONVERT(varchar(10),GETDATE(),121) + 'T12:00:00' AND CONVERT(varchar(10),GETDATE(),121) + 'T15:00:00'
</code>```

Note, however, I recommend using >= and < syntax when using times. I assume you wants all times after 12:00 and before 15:00, which would be:

```<code>WHERE game_date >= CONVERT(varchar(10),GETDATE(),121) + 'T12:00:00'
  AND game_date <= CONVERT(varchar(10),GETDATE(),121) + 'T15:00:00'
</code>```

This does assume that game_date is a datetime (or variant) datatype, and not a varchar; but then why would it not be?

Body:
select * from hockey_stats where game_date between '11/3/2012 12:00:00' and '11/5/2012 15:00:00' order by game_date desc;

How to get data based on today date and time between 12:00:00 to 15:00:00?

Body:
How about:

game_date BETWEEN CONVERT(varchar(10),GETDATE(),121) + 'T12:00:00' AND CONVERT(varchar(10),GETDATE(),121) + 'T15:00:00'

Note, however, I recommend using >= and < syntax when using times. I assume you wants all times after 12:00 and before 15:00, which would be:

WHERE game_date >= CONVERT(varchar(10),GETDATE(),121) + 'T12:00:00'
  AND game_date <= CONVERT(varchar(10),GETDATE(),121) + 'T15:00:00'

This does assume that game_date is a datetime (or variant) datatype, and not a varchar; but then why would it not be?


问:
Reading Waves Wallet Balance from waves testnet
How do I read my testnode waves wallet balance from my PHP program ?

which URL should be used for reading from testnet nodes

Able to read the balance in live mode.

For live waves balance checking, I use the following cURL code:

```<code>$opts = [
CURLOPT_URL =>
'https://nodes.wavesplatform.com/assets/balance/<<wallet address>>',
CURLOPT_RETURNTRANSFER => true,
];

$response = curl_exec($curl);
curl_close($curl);
$balance= json_decode($response, true);

echo "This account has ".$balance[balance]/100000000;
</code>```

答: You use nodes.wavesplatform.com, which is a nodes pool for MAINNET. URL for testnet is testnodes.wavesnodes.com</p>

Body:
How do I read my testnode waves wallet balance from my PHP program ?

which URL should be used for reading from testnet nodes

Able to read the balance in live mode.

For live waves balance checking, I use the following cURL code:

$opts = [
CURLOPT_URL =>
'https://nodes.wavesplatform.com/assets/balance/<<wallet address>>',
CURLOPT_RETURNTRANSFER => true,
];

$response = curl_exec($curl);
curl_close($curl);
$balance= json_decode($response, true);

echo "This account has ".$balance[balance]/100000000;


问:
What's the difference between a Docker image's Image ID and its Digest?
This has been surprisingly confusing for me. I thought Docker's Image ID is its SHA256 hash. However, apparently the result from docker image ls --digests (listed under the column header DIGEST) is different from the IMAGE ID of that image.

For example

```<code>docker image ls --digests alpine
REPOSITORY          TAG                 DIGEST                                                                    IMAGE ID            CREATED             SIZE
alpine              latest              sha256:769fddc7cc2f0a1c35abb2f91432e8beecf83916c421420e6a6da9f8975464b6   055936d39205        2 weeks ago         5.53MB
</code>```

while

```<code>docker image ls --no-trunc
REPOSITORY                                             TAG                 IMAGE ID                                                                  CREATED             SIZE
...
alpine                                                 latest              sha256:055936d3920576da37aa9bc460d70c5f212028bda1c08c0879aedf03d7a66ea1   2 weeks ago         5.53MB
</code>```

Clearly sha256:055936d3920576da37aa9bc460d70c5f212028bda1c08c0879aedf03d7a66ea1 (IMAGE ID) and sha256:769fddc7cc2f0a1c35abb2f91432e8beecf83916c421420e6a6da9f8975464b6 (DIGEST) are not the same value. But why? What's the purpose of having two different sha256 hashes of the same image. How are they calculated, respectively?

I was confused by this when reading the book Docker Deep Dive, and I haven't been able to find a clear answer either in the book or online.

答:
Thanks for michalk's comment. The short answer is:

The "digest" is a hash of the manifest, introduced in Docker registry v2.

The image ID is a hash of the local image JSON configuration.

Body:
This has been surprisingly confusing for me. I thought Docker's Image ID is its SHA256 hash. However, apparently the result from docker image ls --digests (listed under the column header DIGEST) is different from the IMAGE ID of that image.

For example

docker image ls --digests alpine
REPOSITORY          TAG                 DIGEST                                                                    IMAGE ID            CREATED             SIZE
alpine              latest              sha256:769fddc7cc2f0a1c35abb2f91432e8beecf83916c421420e6a6da9f8975464b6   055936d39205        2 weeks ago         5.53MB

while

docker image ls --no-trunc
REPOSITORY                                             TAG                 IMAGE ID                                                                  CREATED             SIZE
...
alpine                                                 latest              sha256:055936d3920576da37aa9bc460d70c5f212028bda1c08c0879aedf03d7a66ea1   2 weeks ago         5.53MB

Clearly sha256:055936d3920576da37aa9bc460d70c5f212028bda1c08c0879aedf03d7a66ea1 (IMAGE ID) and sha256:769fddc7cc2f0a1c35abb2f91432e8beecf83916c421420e6a6da9f8975464b6 (DIGEST) are not the same value. But why? What's the purpose of having two different sha256 hashes of the same image. How are they calculated, respectively?

I was confused by this when reading the book Docker Deep Dive, and I haven't been able to find a clear answer either in the book or online.


问:
Angular Material Dropdown with Create Option
I am using Angular material to create select Dropdown of Religion. But the options I provided might not cover all the religion of the world. But I want to give option for the user to enter his/her religion in the field if not found. So, What I want to do, give an option named 'other option' and when he clicks on the option, an input field will be given to the option which will be treated as the 'formcontrolName' value for the the field.

If you provide the code at Stackblitz, it would be great to see clearly.

答:
You can use text input after or before mat-option and you may need to fix its css.
Below code will insert text box in last of all mat-options.

Please don't forget to declare custom_religion as FormControl

```<code><mat-form-field fxFlex>
          <mat-select name="allowedValuesCriteria"
            [(ngModel)]="selectedReligion">
            <mat-option [value]="1">
              Religion 1
            </mat-option>
            <mat-option [value]="2">
              Religion 2
            </mat-option>
            <mat-form-field fxFlex>
              <input matInput [formControl]="custom_religion" name="custom_religion"
                (keydown)="$event.stopPropagation()">
            </mat-form-field>
            <small></small>
          </mat-select>
        </mat-form-field>
</code>```

Body:
You can use text input after or before mat-option and you may need to fix its css.
Below code will insert text box in last of all mat-options.

Please don't forget to declare custom_religion as FormControl

<mat-form-field fxFlex>
          <mat-select name="allowedValuesCriteria"
            [(ngModel)]="selectedReligion">
            <mat-option [value]="1">
              Religion 1
            </mat-option>
            <mat-option [value]="2">
              Religion 2
            </mat-option>
            <mat-form-field fxFlex>
              <input matInput [formControl]="custom_religion" name="custom_religion"
                (keydown)="$event.stopPropagation()">
            </mat-form-field>
            <small></small>
          </mat-select>
        </mat-form-field>


问:
How to use the promise return data outside the then in node js and sequelize?
I have the following code.

I get the data from db inside the .then .  i want to use the var data = data.get({ plain: true }) data outside the then.. how can i do this.

```<code>const datas = roleService.getRoleById(1)
      .then(data => {
        var data = data.get({ plain: true })
          console.log(data.get({ plain: true }))
        // return data.get({ plain: true })
        }
          )
      .catch((error) => res.status(400).send(error));
</code>```

Thanks in advance.

答:
There are several aproaches for this -

Define a variable at the top in the functional scope

```<code>let tempData;
const datas = roleService.getRoleById(1)
    .then(data => {
        var data = data.get({
            plain: true
        })
        console.log(data.get({
            plain: true
        }))
        tempData = data; //initializing variable
        // return data.get({ plain: true })
    })
    .catch((error) => res.status(400).send(error));
console.log('tempData is', tempData);
</code>```

You can use async-await which is the best approach suggested by Terry Lennox

```<code>async function fetchData () {
    return roleService.getRoleById(1);
}
const data = await fetchData();
const tempData = data.get({ plain: true })
</code>```

Body:
I have the following code.

I get the data from db inside the .then .  i want to use the var data = data.get({ plain: true }) data outside the then.. how can i do this.

const datas = roleService.getRoleById(1)
      .then(data => {
        var data = data.get({ plain: true })
          console.log(data.get({ plain: true }))
        // return data.get({ plain: true })
        }
          )
      .catch((error) => res.status(400).send(error));

Thanks in advance.

Body:
There are several aproaches for this -

Define a variable at the top in the functional scope

let tempData;
const datas = roleService.getRoleById(1)
    .then(data => {
        var data = data.get({
            plain: true
        })
        console.log(data.get({
            plain: true
        }))
        tempData = data; //initializing variable
        // return data.get({ plain: true })
    })
    .catch((error) => res.status(400).send(error));
console.log('tempData is', tempData);

You can use async-await which is the best approach suggested by Terry Lennox

async function fetchData () {
    return roleService.getRoleById(1);
}
const data = await fetchData();
const tempData = data.get({ plain: true })


问:
Accessing protobuf from different project .Net
I am trying to build out a large system using gRPC. I have a project where I define a .proto file. I create a second project that takes a reference to the first project. I want to be able to use a message defined in the first project's proto file in a message defined in the second project's proto file.  Is this possible?</p>

答:
In these cases I always place the proto files in their own repository. For example if you are using git you then use the repository with definition files in both of your projects as a submodule.

In the end you will have three repositories:

Message definitions

Project A

Project B

Project A and B will refer to the Message definitions repository.


问:
r leaflet popup not showing anything
I am ploting data via leaflet in R using

```<code>leaflet(data=a) %>%
addTiles() %>%
addMarkers(a$long, a$lat, popup=a[,4])
</code>```

which returns:

but when I have popup=rownames(a), it works:

Any ideas why? I have the same issue with label (works with rownames, not column values)

答:
it appears it needs to be type character:

popup = as.character(a[,4]) works

Title: r leaflet popup not showing anything

Body:
I am ploting data via leaflet in R using

leaflet(data=a) %>%
addTiles() %>%
addMarkers(a$long, a$lat, popup=a[,4])

which returns:

but when I have popup=rownames(a), it works:

Any ideas why? I have the same issue with label (works with rownames, not column values)


问:
Denormalized many-to-many mapping
In SQL Server 2008 R2 I have a table with the following structure

```<code>(
  Id     INT NOT NULL PRIMARY KEY,
  Left1  INT NOT NULL,
  Left2  INT NULL,
  Right1 NVARCHAR(128) NOT NULL,
  Right2 NVARCHAR(128) NOT NULL,
  Right3 NVARCHAR(128) NULL,
  Right4 NVARCHAR(128) NULL,
  Right5 NVARCHAR(128) NULL,
  Right6 NVARCHAR(128) NULL
)
</code>```

Which is used to map Left1 and Left2, coming from a system ("Left") into Right1-6, going to another system ("Right").

I need to ensure that the Left columns are unique, which I have done with a unique index, and that the Left-Right combinations are also unique.

I cannot use an index here because the maximum column size supported is 900 bytes. I need to avoid splitting the table in Left, Right and Left2Right - as it's way too tedious and error prone with my use cases.

What is the correct way of enforcing the uniqueness of the combination?

My requirements are:

In the whole table there MUST be no rows with the same values for Left1 and Left2 (solved)

In the whole table there MUST be no rows with the same values for Left1, Left2, Right1, Right2, Right3, Right4, Right5, Right6 (I need help here)

答:
It's completely unnecessary to add a second constraint.

Your unique constraint on

Left1, Left2

will prevent duplicate values of

Left1, Left2, Right1, Right2, Right3, Right4, Right5, Right6.

There is no way to duplicate all 8 of those fields without first duplicating the first 2.

Title: Denormalized many-to-many mapping

Body:
In SQL Server 2008 R2 I have a table with the following structure

(
  Id     INT NOT NULL PRIMARY KEY,
  Left1  INT NOT NULL,
  Left2  INT NULL,
  Right1 NVARCHAR(128) NOT NULL,
  Right2 NVARCHAR(128) NOT NULL,
  Right3 NVARCHAR(128) NULL,
  Right4 NVARCHAR(128) NULL,
  Right5 NVARCHAR(128) NULL,
  Right6 NVARCHAR(128) NULL
)

Which is used to map Left1 and Left2, coming from a system ("Left") into Right1-6, going to another system ("Right").

I need to ensure that the Left columns are unique, which I have done with a unique index, and that the Left-Right combinations are also unique.

I cannot use an index here because the maximum column size supported is 900 bytes. I need to avoid splitting the table in Left, Right and Left2Right - as it's way too tedious and error prone with my use cases.

What is the correct way of enforcing the uniqueness of the combination?

My requirements are:

In the whole table there MUST be no rows with the same values for Left1 and Left2 (solved)

In the whole table there MUST be no rows with the same values for Left1, Left2, Right1, Right2, Right3, Right4, Right5, Right6 (I need help here)