问:
How to get Word Level Timestamps using Azure Speech to Text and the Python SDK?
My code currently is able to read an audio file and transcribe it using Azure Speech to Text, with help from an example that I found on GitHub. However, I need to include the timestamps for all the words in the transcription. According to the documentation, this functionality was added in version 1.5.0, and is accessed through the method request_word_level_timestamps(). But even when I have called it, I get the same response as before. I cannot figure out how to use it from the documentation. Does anyone know how it works?

I'm using Python SDK version 1.5.1.

```<code>import azure.cognitiveservices.speech as speechsdk
import time
from allennlp.predictors.predictor import Predictor
import json

inputPath = "(inputlocation)"
outputPath = "(outputlocation)"

# Creates an instance of a speech config with specified subscription     key and service region.
# Replace with your own subscription key and service region (e.g., "westus").
speech_key, service_region = "apikey", "region"
speech_config = speechsdk.SpeechConfig(subscription=speech_key,     region=service_region)
speech_config.request_word_level_timestamps()
speech_config.output_format=speechsdk.OutputFormat.Detailed
#print("VALUE: " +     speech_config.get_property(property_id=speechsdk.PropertyId.SpeechServic    eResponse_RequestWordLevelTimestamps))
filename = input("Enter filename: ")

print(speech_config)

try:
    audio_config = speechsdk.audio.AudioConfig(filename= inputPath +     filename)

    # Creates a recognizer with the given settings
    speech_recognizer =     speechsdk.SpeechRecognizer(speech_config=speech_config,     audio_config=audio_config)

def start():
    done = False
    #output = ""
    fileOpened = open(outputPath+ filename[0: len(filename) - 4] + "_MS_recognized.txt", "w+")
    fileOpened.truncate(0)
    fileOpened.close()

    def stop_callback(evt):
        print("Closing on {}".format(evt))
        speech_recognizer.stop_continuous_recognition()
        nonlocal done
        done = True

    def add_to_res(evt):
        #nonlocal output
        #print("Recognized: {}".format(evt.result.text))
        #output = output + evt.result.text + "\n"
        fileOpened = open( outputPath + filename[0: len(filename) - 4] + "_MS_recognized.txt", "a")
        fileOpened.write(evt.result.text + "\n")
        fileOpened.close()
        #print(output)

    # Connect callbacks to the events fired by the speech recognizer
    speech_recognizer.recognizing.connect(lambda evt: print('RECOGNIZING: {}'.format(evt)))
    speech_recognizer.recognized.connect(lambda evt: print('RECOGNIZED: {}'.format(evt)))
    speech_recognizer.recognized.connect(add_to_res)
    speech_recognizer.session_started.connect(lambda evt: print('SESSION STARTED: {}'.format(evt)))
    speech_recognizer.session_stopped.connect(lambda evt: print('SESSION STOPPED {}'.format(evt)))
    speech_recognizer.canceled.connect(lambda evt: print('CANCELED {}'.format(evt)))
    # stop continuous recognition on either session stopped or canceled events
    speech_recognizer.session_stopped.connect(stop_callback)
    speech_recognizer.canceled.connect(stop_callback)

    # Start continuous speech recognition
    speech_recognizer.start_continuous_recognition()
    while not done:
        time.sleep(.5)
    # </SpeechContinuousRecognitionWithFile>

    # Starts speech recognition, and returns after a single utterance is recognized. The end of a
    # single utterance is determined by listening for silence at the end or until a maximum of 15
    # seconds of audio is processed.  The task returns the recognition text as result.
    # Note: Since recognize_once() returns only a single utterance, it is suitable only for single
    # shot recognition like command or query.
    # For long-running multi-utterance recognition, use start_continuous_recognition() instead.

start()

except Exception as e:
    print("File does not exist")
    #print(e)
</code>```

The results only contain session_id and a result object which includes result_id, text and reason.

答:
Setting

```<code>speech_config.request_word_level_timestamps()
</code>```

in the speech config of azure sdk will allow you to get the transcripts along with the timestamps for each word.

```<code>speech_config.output_format = speechsdk.OutputFormat(1)
</code>```

This statement would allow you get the detailed json object from the azure sdk.

Below is a sample code. Make sure you replace the keys. Some error handling might be needed at places where speech to text could fail.

```<code>def process(self):
    logger.debug("Speech to text request received")

    speechapi_settings =  SpeechAPIConf()
    audio_filepath = <PATH_TO_AUDIO_FILE>
    locale = "en-US" # Change as per requirement

    logger.debug(audio_filepath)
    audio_config = speechsdk.audio.AudioConfig(filename=audio_filepath)
    speech_config = speechsdk.SpeechConfig(subscription=<SUBSCRIPTION_KEY>, region=<SERVICE_REGION>)
    speech_config.request_word_level_timestamps()
    speech_config.speech_recognition_language = locale
    speech_config.output_format = speechsdk.OutputFormat(1)

    # Creates a recognizer with the given settings
    speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config, audio_config=audio_config)

    # Variable to monitor status
    done = False

    # Service callback for recognition text
    transcript_display_list = []
    transcript_ITN_list = []
    confidence_list = []
    words = []
    def parse_azure_result(evt):
        import json
        response = json.loads(evt.result.json)
        transcript_display_list.append(response['DisplayText'])
        confidence_list_temp = [item.get('Confidence') for item in response['NBest']]
        max_confidence_index = confidence_list_temp.index(max(confidence_list_temp))
        confidence_list.append(response['NBest'][max_confidence_index]['Confidence'])
        transcript_ITN_list.append(response['NBest'][max_confidence_index]['ITN'])
        words.extend(response['NBest'][max_confidence_index]['Words'])
        logger.debug(evt)

    # Service callback that stops continuous recognition upon receiving an event `evt`
    def stop_cb(evt):
        print('CLOSING on {}'.format(evt))
        speech_recognizer.stop_continuous_recognition()
        nonlocal done
        done = True

        # Do something with the combined responses
        print(transcript_display_list)
        print(confidence_list)
        print(words)

    # Connect callbacks to the events fired by the speech recognizer
    speech_recognizer.recognizing.connect(lambda evt: logger.debug('RECOGNIZING: {}'.format(evt)))
    speech_recognizer.recognized.connect(parse_azure_result)
    speech_recognizer.session_started.connect(lambda evt: logger.debug('SESSION STARTED: {}'.format(evt)))
    speech_recognizer.session_stopped.connect(lambda evt: logger.debug('SESSION STOPPED {}'.format(evt)))
    speech_recognizer.canceled.connect(lambda evt: logger.debug('CANCELED {}'.format(evt)))
    # stop continuous recognition on either session stopped or canceled events
    speech_recognizer.session_stopped.connect(stop_cb)
    speech_recognizer.canceled.connect(stop_cb)

    # Start continuous speech recognition
    logger.debug("Initiating speech to text")
    speech_recognizer.start_continuous_recognition()
    while not done:
        time.sleep(.5)
</code>```

Body:
My code currently is able to read an audio file and transcribe it using Azure Speech to Text, with help from an example that I found on GitHub. However, I need to include the timestamps for all the words in the transcription. According to the documentation, this functionality was added in version 1.5.0, and is accessed through the method request_word_level_timestamps(). But even when I have called it, I get the same response as before. I cannot figure out how to use it from the documentation. Does anyone know how it works?

I'm using Python SDK version 1.5.1.

import azure.cognitiveservices.speech as speechsdk
import time
from allennlp.predictors.predictor import Predictor
import json

inputPath = "(inputlocation)"
outputPath = "(outputlocation)"

# Creates an instance of a speech config with specified subscription     key and service region.
# Replace with your own subscription key and service region (e.g., "westus").
speech_key, service_region = "apikey", "region"
speech_config = speechsdk.SpeechConfig(subscription=speech_key,     region=service_region)
speech_config.request_word_level_timestamps()
speech_config.output_format=speechsdk.OutputFormat.Detailed
#print("VALUE: " +     speech_config.get_property(property_id=speechsdk.PropertyId.SpeechServic    eResponse_RequestWordLevelTimestamps))
filename = input("Enter filename: ")

print(speech_config)

try:
    audio_config = speechsdk.audio.AudioConfig(filename= inputPath +     filename)

    # Creates a recognizer with the given settings
    speech_recognizer =     speechsdk.SpeechRecognizer(speech_config=speech_config,     audio_config=audio_config)

def start():
    done = False
    #output = ""
    fileOpened = open(outputPath+ filename[0: len(filename) - 4] + "_MS_recognized.txt", "w+")
    fileOpened.truncate(0)
    fileOpened.close()

    def stop_callback(evt):
        print("Closing on {}".format(evt))
        speech_recognizer.stop_continuous_recognition()
        nonlocal done
        done = True

    def add_to_res(evt):
        #nonlocal output
        #print("Recognized: {}".format(evt.result.text))
        #output = output + evt.result.text + "\n"
        fileOpened = open( outputPath + filename[0: len(filename) - 4] + "_MS_recognized.txt", "a")
        fileOpened.write(evt.result.text + "\n")
        fileOpened.close()
        #print(output)

    # Connect callbacks to the events fired by the speech recognizer
    speech_recognizer.recognizing.connect(lambda evt: print('RECOGNIZING: {}'.format(evt)))
    speech_recognizer.recognized.connect(lambda evt: print('RECOGNIZED: {}'.format(evt)))
    speech_recognizer.recognized.connect(add_to_res)
    speech_recognizer.session_started.connect(lambda evt: print('SESSION STARTED: {}'.format(evt)))
    speech_recognizer.session_stopped.connect(lambda evt: print('SESSION STOPPED {}'.format(evt)))
    speech_recognizer.canceled.connect(lambda evt: print('CANCELED {}'.format(evt)))
    # stop continuous recognition on either session stopped or canceled events
    speech_recognizer.session_stopped.connect(stop_callback)
    speech_recognizer.canceled.connect(stop_callback)

    # Start continuous speech recognition
    speech_recognizer.start_continuous_recognition()
    while not done:
        time.sleep(.5)
    # </SpeechContinuousRecognitionWithFile>

    # Starts speech recognition, and returns after a single utterance is recognized. The end of a
    # single utterance is determined by listening for silence at the end or until a maximum of 15
    # seconds of audio is processed.  The task returns the recognition text as result.
    # Note: Since recognize_once() returns only a single utterance, it is suitable only for single
    # shot recognition like command or query.
    # For long-running multi-utterance recognition, use start_continuous_recognition() instead.

start()

except Exception as e:
    print("File does not exist")
    #print(e)

The results only contain session_id and a result object which includes result_id, text and reason.

Body:
Setting

speech_config.request_word_level_timestamps()

in the speech config of azure sdk will allow you to get the transcripts along with the timestamps for each word.

speech_config.output_format = speechsdk.OutputFormat(1)

This statement would allow you get the detailed json object from the azure sdk.

Below is a sample code. Make sure you replace the keys. Some error handling might be needed at places where speech to text could fail.

def process(self):
    logger.debug("Speech to text request received")

    speechapi_settings =  SpeechAPIConf()
    audio_filepath = <PATH_TO_AUDIO_FILE>
    locale = "en-US" # Change as per requirement

    logger.debug(audio_filepath)
    audio_config = speechsdk.audio.AudioConfig(filename=audio_filepath)
    speech_config = speechsdk.SpeechConfig(subscription=<SUBSCRIPTION_KEY>, region=<SERVICE_REGION>)
    speech_config.request_word_level_timestamps()
    speech_config.speech_recognition_language = locale
    speech_config.output_format = speechsdk.OutputFormat(1)

    # Creates a recognizer with the given settings
    speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config, audio_config=audio_config)

    # Variable to monitor status
    done = False

    # Service callback for recognition text
    transcript_display_list = []
    transcript_ITN_list = []
    confidence_list = []
    words = []
    def parse_azure_result(evt):
        import json
        response = json.loads(evt.result.json)
        transcript_display_list.append(response['DisplayText'])
        confidence_list_temp = [item.get('Confidence') for item in response['NBest']]
        max_confidence_index = confidence_list_temp.index(max(confidence_list_temp))
        confidence_list.append(response['NBest'][max_confidence_index]['Confidence'])
        transcript_ITN_list.append(response['NBest'][max_confidence_index]['ITN'])
        words.extend(response['NBest'][max_confidence_index]['Words'])
        logger.debug(evt)

    # Service callback that stops continuous recognition upon receiving an event `evt`
    def stop_cb(evt):
        print('CLOSING on {}'.format(evt))
        speech_recognizer.stop_continuous_recognition()
        nonlocal done
        done = True

        # Do something with the combined responses
        print(transcript_display_list)
        print(confidence_list)
        print(words)

    # Connect callbacks to the events fired by the speech recognizer
    speech_recognizer.recognizing.connect(lambda evt: logger.debug('RECOGNIZING: {}'.format(evt)))
    speech_recognizer.recognized.connect(parse_azure_result)
    speech_recognizer.session_started.connect(lambda evt: logger.debug('SESSION STARTED: {}'.format(evt)))
    speech_recognizer.session_stopped.connect(lambda evt: logger.debug('SESSION STOPPED {}'.format(evt)))
    speech_recognizer.canceled.connect(lambda evt: logger.debug('CANCELED {}'.format(evt)))
    # stop continuous recognition on either session stopped or canceled events
    speech_recognizer.session_stopped.connect(stop_cb)
    speech_recognizer.canceled.connect(stop_cb)

    # Start continuous speech recognition
    logger.debug("Initiating speech to text")
    speech_recognizer.start_continuous_recognition()
    while not done:
        time.sleep(.5)


来源: stackexchange

问:
CSS rolling ball animation position
General info

I'm working on a Bingo game. Currently I'm trying to create a CSS rolling ball animation. The idea is to simulate a ball dropping from the wheel and making it roll from right to left.

The problem

The animation is working fine. But the "drop in" position is relative to the div. As a consequence of this, this position keeps moving right 75 pixels on each new ball dropping in.

Solutions I've tried

- Give the balls an absolute position. This solves the issue, but each ball will cover the previous balls due to the keyframe ending at left: 0%. This is not desirable.

- Lookup Javascript solutions to see if I can somehow change the keyframe to end with +75px on the previous ball. Unfortunately it seems impossible to manipulate animations this way, or I was unable to find a way to do it.

So now I'm hoping someone is able to help me find a solution to this problem.

Edit: I didn't tag jQuery because it's not used here, but solutions using jQuery are perfectly fine.

MCVE

const timer = setInterval(rollBall, 2000);
var ballNumber = 1;

function rollBall(){
 if(document.getElementById('ball-'+(ballNumber-1))){
   document.getElementById('ball-'+(ballNumber-1)).classList.remove('ball-animation');
  }
 let html = '
';
  html += '
';
  html += ballNumber;
  html += '

';

  document.getElementById('balls').innerHTML += html;

  ballNumber++;

  if(ballNumber > 10) {
   clearInterval(timer);
    document.getElementById('ball-'+(ballNumber-1)).classList.remove('ball-animation');
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.ball {
 display: block;
 position: relative;
 width: 75px;
 height: 75px;
 background: red;
 border-radius: 50%;
  background: -webkit-radial-gradient(25px 25px, circle, red, #000);
 background: -moz-radial-gradient(25px 25px, circle, red, #000);
 background: radial-gradient(25px 25px, circle, red, #000);
 /*position: absolute;*/
 float: left;
}

.ball-number {
 top: -34px;
 left: 25px;
 font-size: 45px;
 color: #fff;
 position: absolute;
}

.ball-animation {
 -webkit-animation: spin 1750ms linear infinite, moveRightToLeft 2s linear infinite;
 -moz-animation: spin 1750ms linear infinite, moveRightToLeft 2s linear infinite;
 -ms-animation: spin 1750ms linear infinite, moveRightToLeft 2s linear infinite;
 animation: spin 1750ms linear infinite, moveRightToLeft 2s linear;

 -webkit-transition: all 1.75s ease;
 transition: all 1.75s ease;
}

@keyframes spin {
 from { transform: rotate(360deg); }
 to { transform: rotate(0deg); }
}

@keyframes moveRightToLeft {
 0% { top: -50px; left: 200px; }
 10% { top: -40px; left: 180px; }
 20% { top: -25px; left: 150px; }
 30% { top: 0px; left: 100px; }
 100% { left: 0%; }
}</code>```

```

答:
This is a CSS only solution, using an intermediate div, zone to handle the ball movement .

Since this elements have varying sizes, you can set the keyframes on them to work in percentages, and adjust for a different ending point, while keeping the same origin point.

.container {
    width: 600px;
    height: 350px;
    border: solid 1px red;
    position: relative;
}

.zone {
    position: absolute;
    top: 0px;
    right: 0px;
    bottom: 40px;
    left: 40px;
    border: solid 1px green;
    animation: move 3s linear infinite;
}

.zone:nth-child(2) {
    left: calc(40px * 2);
}

.zone:nth-child(3) {
    left: calc(40px * 3);
}
.zone:nth-child(4) {
    left: calc(40px * 4);
}

.ball {
    width: 40px;
    height: 40px;
    border-radius: 100%;
    background-color: blue;
    right: 0px;
    position: absolute;
}

@keyframes move {
    from {transform: translate(0px, 0px);}
    50% {transform: translate(-100px, 100%);}
    to {transform: translate(-100%, 100%);}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="zone">
    <div class="ball">1</div>
  </div>
  <div class="zone">
    <div class="ball">2</div>
  </div>
  <div class="zone">
    <div class="ball">3</div>
  </div>
  <div class="zone">
    <div class="ball">4</div>
  </div>
</div></code>```

ContentLicense: CC BY-SA 4.0

Title: CSS rolling ball animation position

Body:
General info

I'm working on a Bingo game. Currently I'm trying to create a CSS rolling ball animation. The idea is to simulate a ball dropping from the wheel and making it roll from right to left.

The problem

The animation is working fine. But the "drop in" position is relative to the div. As a consequence of this, this position keeps moving right 75 pixels on each new ball dropping in.

Solutions I've tried

- Give the balls an absolute position. This solves the issue, but each ball will cover the previous balls due to the keyframe ending at left: 0%. This is not desirable.

- Lookup Javascript solutions to see if I can somehow change the keyframe to end with +75px on the previous ball. Unfortunately it seems impossible to manipulate animations this way, or I was unable to find a way to do it.

So now I'm hoping someone is able to help me find a solution to this problem.

Edit: I didn't tag jQuery because it's not used here, but solutions using jQuery are perfectly fine.

MCVE

const timer = setInterval(rollBall, 2000);
var ballNumber = 1;

function rollBall(){
 if(document.getElementById('ball-'+(ballNumber-1))){
   document.getElementById('ball-'+(ballNumber-1)).classList.remove('ball-animation');
  }
 let html = '
';
  html += '
';
  html += ballNumber;
  html += '

';

  document.getElementById('balls').innerHTML += html;

  ballNumber++;

  if(ballNumber > 10) {
   clearInterval(timer);
    document.getElementById('ball-'+(ballNumber-1)).classList.remove('ball-animation');
  }
}

.ball {
 display: block;
 position: relative;
 width: 75px;
 height: 75px;
 background: red;
 border-radius: 50%;
  background: -webkit-radial-gradient(25px 25px, circle, red, #000);
 background: -moz-radial-gradient(25px 25px, circle, red, #000);
 background: radial-gradient(25px 25px, circle, red, #000);
 /*position: absolute;*/
 float: left;
}

.ball-number {
 top: -34px;
 left: 25px;
 font-size: 45px;
 color: #fff;
 position: absolute;
}

.ball-animation {
 -webkit-animation: spin 1750ms linear infinite, moveRightToLeft 2s linear infinite;
 -moz-animation: spin 1750ms linear infinite, moveRightToLeft 2s linear infinite;
 -ms-animation: spin 1750ms linear infinite, moveRightToLeft 2s linear infinite;
 animation: spin 1750ms linear infinite, moveRightToLeft 2s linear;

 -webkit-transition: all 1.75s ease;
 transition: all 1.75s ease;
}

@keyframes spin {
 from { transform: rotate(360deg); }
 to { transform: rotate(0deg); }
}

@keyframes moveRightToLeft {
 0% { top: -50px; left: 200px; }
 10% { top: -40px; left: 180px; }
 20% { top: -25px; left: 150px; }
 30% { top: 0px; left: 100px; }
 100% { left: 0%; }
}

Body:
This is a CSS only solution, using an intermediate div, zone to handle the ball movement .

Since this elements have varying sizes, you can set the keyframes on them to work in percentages, and adjust for a different ending point, while keeping the same origin point.

.container {
    width: 600px;
    height: 350px;
    border: solid 1px red;
    position: relative;
}

.zone {
    position: absolute;
    top: 0px;
    right: 0px;
    bottom: 40px;
    left: 40px;
    border: solid 1px green;
    animation: move 3s linear infinite;
}

.zone:nth-child(2) {
    left: calc(40px * 2);
}

.zone:nth-child(3) {
    left: calc(40px * 3);
}
.zone:nth-child(4) {
    left: calc(40px * 4);
}

.ball {
    width: 40px;
    height: 40px;
    border-radius: 100%;
    background-color: blue;
    right: 0px;
    position: absolute;
}

@keyframes move {
    from {transform: translate(0px, 0px);}
    50% {transform: translate(-100px, 100%);}
    to {transform: translate(-100%, 100%);}
}

<div class="container">
  <div class="zone">
    <div class="ball">1</div>
  </div>
  <div class="zone">
    <div class="ball">2</div>
  </div>
  <div class="zone">
    <div class="ball">3</div>
  </div>
  <div class="zone">
    <div class="ball">4</div>
  </div>
</div>


问:
Is it possible to keep a ScrollView scrolled to the bottom?
For a chat-like app, I want to keep a ScrollView component scrolled to the bottom, because newest messages appear under the older ones. Can we adjust the scroll position of a ScrollView?

答:
In case anyone in 2020 or later is wondering how to achieve this with functional components. This is how I did:</p>

```<code>ref={ref => scrollView = ref }
onContentSizeChange={() => scrollView.scrollToEnd({ animated: true })}>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In case anyone in 2020 or later is wondering how to achieve this with functional components. This is how I did:

ref={ref => scrollView = ref }
onContentSizeChange={() => scrollView.scrollToEnd({ animated: true })}>


问:
cannot convert from 'ListMapColor.MyContainer' to 'System.Drawing.Color'
Im tryin to add a list with Hashset.

what im tryin to do? Im Tryin to mapping Haset Color some piece of image

Why ? Because i wanna to Compare Hashset list Colors in Real time and i need my own libary to gain process fast in real time for compare image's

Did u Research on Internet? Yes, but I didnt find something about usin hashset colors with ADD.

I did example to someone can help please.

```<code>public class ListMapColor
{

    public class MyContainer
    {
        public Color Number { get; set; }
        public Color Name { get; set; }
        public MyContainer(Color number, Color name)
        {
            Number = number;
            Name = name;
        }
    }

    public HashSet<Color> Battle(HashSet<Color> colors)
    {

        return colors.Add( new MyContainer (Color.FromArgb(255, 47, 47, 47), Color.FromName("ff2f2f2f") );

    }

}
</code>```

答:
In the original code posted you have a type error, which is exactly what the exception is telling you. It's expecting a Color object and you are giving it a MyContainer object and there is no way to convert between the two.

My comment suggested changing your code to the following:

```<code>public class ListMapColor
{

   public class MyContainer
   {
       public Color Number { get; set; }
       public Color Name { get; set; }
       public MyContainer(Color number, Color name)
       {
           Number = number;
           Name = name;
       }
   }

   public HashSet<MyContainer> Battle(HashSet<MyContainer> colors)
   {

       return colors.Add( new MyContainer (Color.FromArgb(255, 47, 47, 47), Color.FromName("ff2f2f2f") );

   }

}
</code>```

That will fix the type Error. If you want a HashSet of Color objects you need to be adding Color objects, not MyContainer objects.

I'm not sure why you'd want to do that though.

Seems you may want something along the lines of:

```<code>    HashSet<Color> myColors = new HashSet<Color>();

    myColors.Add(Color.FromArgb(255,47,47,47));
    myColors.Add(Color.FromName("ff2f2f2f"));
    myColors.Add(Color.FromName("AliceBlue"));
</code>```

Then you can access all the Color methods you may need:

```<code>    foreach(Color color in myColors)
    {
        Console.WriteLine(color.Name);
        Console.WriteLine(color.IsKnownColor);
        Console.WriteLine(color.ToArgb());
        Console.WriteLine(color.IsNamedColor());
    }
</code>```

Body:
Im tryin to add a list with Hashset.

what im tryin to do? Im Tryin to mapping Haset Color some piece of image

Why ? Because i wanna to Compare Hashset list Colors in Real time and i need my own libary to gain process fast in real time for compare image's

Did u Research on Internet? Yes, but I didnt find something about usin hashset colors with ADD.

I did example to someone can help please.

public class ListMapColor
{

    public class MyContainer
    {
        public Color Number { get; set; }
        public Color Name { get; set; }
        public MyContainer(Color number, Color name)
        {
            Number = number;
            Name = name;
        }
    }

    public HashSet<Color> Battle(HashSet<Color> colors)
    {

        return colors.Add( new MyContainer (Color.FromArgb(255, 47, 47, 47), Color.FromName("ff2f2f2f") );

    }

}

Body:
In the original code posted you have a type error, which is exactly what the exception is telling you. It's expecting a Color object and you are giving it a MyContainer object and there is no way to convert between the two.

My comment suggested changing your code to the following:

public class ListMapColor
{

   public class MyContainer
   {
       public Color Number { get; set; }
       public Color Name { get; set; }
       public MyContainer(Color number, Color name)
       {
           Number = number;
           Name = name;
       }
   }

   public HashSet<MyContainer> Battle(HashSet<MyContainer> colors)
   {

       return colors.Add( new MyContainer (Color.FromArgb(255, 47, 47, 47), Color.FromName("ff2f2f2f") );

   }

}

That will fix the type Error. If you want a HashSet of Color objects you need to be adding Color objects, not MyContainer objects.

I'm not sure why you'd want to do that though.

Seems you may want something along the lines of:

    HashSet<Color> myColors = new HashSet<Color>();

    myColors.Add(Color.FromArgb(255,47,47,47));
    myColors.Add(Color.FromName("ff2f2f2f"));
    myColors.Add(Color.FromName("AliceBlue"));

Then you can access all the Color methods you may need:

    foreach(Color color in myColors)
    {
        Console.WriteLine(color.Name);
        Console.WriteLine(color.IsKnownColor);
        Console.WriteLine(color.ToArgb());
        Console.WriteLine(color.IsNamedColor());
    }


问:
Create Variable from SELECT QUERY Results
```<code>SELECT DISTINCT
[State_IDs]

FROM [Database].[dbo].[enrollment]
WHERE [Market_State] = 'CO'
</code>```

I'm trying to figure out how I can declare a variable from a SELECT Query... with multiple returns/rows.

I want to use it like an array(?)... I want to pull that list of State IDs, declare it as a variable so I can use it later in my code when I'm pulling data from a different table where I don't have these filter options.

The code below throws me the 'subquery returned more than 1 value' error:

```<code>DECLARE @CO_IDS VARCHAR(25)
SET @CO_IDS =
    (
        SELECT DISTINCT
        [State_IDs]

        FROM [Database].[dbo].[enrollment]
        WHERE [Market_State] = 'CO'
    )
</code>```

Any help would be much appreciated.

答:
You can define a table type variable</p>

```<code>DECLARE @CO_IDS table(CO_ID VARCHAR(25));

Insert Into @CO_IDS (CO_ID)
SELECT DISTINCT [State_IDs]
FROM [Database].[dbo].[enrollment]
WHERE [Market_State] = 'CO'

Select CO_ID from @CO_IDS
</code>```

Body:
SELECT DISTINCT
[State_IDs]

FROM [Database].[dbo].[enrollment]
WHERE [Market_State] = 'CO'

I'm trying to figure out how I can declare a variable from a SELECT Query... with multiple returns/rows.

I want to use it like an array(?)... I want to pull that list of State IDs, declare it as a variable so I can use it later in my code when I'm pulling data from a different table where I don't have these filter options.

The code below throws me the 'subquery returned more than 1 value' error:

DECLARE @CO_IDS VARCHAR(25)
SET @CO_IDS =
    (
        SELECT DISTINCT
        [State_IDs]

        FROM [Database].[dbo].[enrollment]
        WHERE [Market_State] = 'CO'
    )

Any help would be much appreciated.

Body:
You can define a table type variable

DECLARE @CO_IDS table(CO_ID VARCHAR(25));

Insert Into @CO_IDS (CO_ID)
SELECT DISTINCT [State_IDs]
FROM [Database].[dbo].[enrollment]
WHERE [Market_State] = 'CO'

Select CO_ID from @CO_IDS


问:
Is it possible to create a custom notification with controls such as buttons in Android? How?
According to the Android Developers' Guide, it is possible to create a custom notification view.  However, is it possible to create one with controls such as buttons and text views?  If yes, how?

Note that I think it has something to do with PendingIntent.

答: Create a RemoteViews object -- like you would for an app widget -- and put it in the contentView public data member of the Notification.


问:
Removing multiple keys from a dictionary safely
I know how to remove an entry, 'key' from my dictionary d, safely. You do:

```<code>if d.has_key('key'):
    del d['key']
</code>```

However, I need to remove multiple entries from a dictionary safely.  I was thinking of defining the entries in a tuple as I will need to do this more than once.

```<code>entities_to_remove = ('a', 'b', 'c')
for x in entities_to_remove:
    if x in d:
        del d[x]
</code>```

However, I was wondering if there is a smarter way to do this?

答:
It would be nice to have full support for set methods for dictionaries (and not the unholy mess we're getting with Python 3.9) so that you could simply "remove" a set of keys. However, as long as that's not the case, and you have a large dictionary with potentially a large number of keys to remove, you might want to know about the performance. So, I've created some code that creates something large enough for meaningful comparisons: a 100,000 x 1000 matrix, so 10,000,00 items in total.

```<code>from itertools import product
from time import perf_counter

# make a complete worksheet 100000 * 1000
start = perf_counter()
prod = product(range(1, 100000), range(1, 1000))
cells = {(x,y):x for x,y in prod}
print(len(cells))

print(f"Create time {perf_counter()-start:.2f}s")
clock = perf_counter()
# remove everything above row 50,000

keys = product(range(50000, 100000), range(1, 100))

# for x,y in keys:
#     del cells[x, y]

for n in map(cells.pop, keys):
    pass

print(len(cells))
stop = perf_counter()
print(f"Removal time {stop-clock:.2f}s")
</code>```

10 million items or more is not unusual in some settings. Comparing the two methods on my local machine I see a slight improvement when using map and pop, presumably because of fewer function calls, but both take around 2.5s on my machine. But this pales in comparison to the time required to create the dictionary in the first place (55s), or including checks within the loop. If this is likely then its best to create a set that is a intersection of the dictionary keys and your filter:

keys = cells.keys() & keys

In summary: del is already heavily optimised, so don't worry about using it.

Body:
I know how to remove an entry, 'key' from my dictionary d, safely. You do:

if d.has_key('key'):
    del d['key']

However, I need to remove multiple entries from a dictionary safely.  I was thinking of defining the entries in a tuple as I will need to do this more than once.

entities_to_remove = ('a', 'b', 'c')
for x in entities_to_remove:
    if x in d:
        del d[x]

However, I was wondering if there is a smarter way to do this?

Body:
It would be nice to have full support for set methods for dictionaries (and not the unholy mess we're getting with Python 3.9) so that you could simply "remove" a set of keys. However, as long as that's not the case, and you have a large dictionary with potentially a large number of keys to remove, you might want to know about the performance. So, I've created some code that creates something large enough for meaningful comparisons: a 100,000 x 1000 matrix, so 10,000,00 items in total.

from itertools import product
from time import perf_counter

# make a complete worksheet 100000 * 1000
start = perf_counter()
prod = product(range(1, 100000), range(1, 1000))
cells = {(x,y):x for x,y in prod}
print(len(cells))

print(f"Create time {perf_counter()-start:.2f}s")
clock = perf_counter()
# remove everything above row 50,000

keys = product(range(50000, 100000), range(1, 100))

# for x,y in keys:
#     del cells[x, y]

for n in map(cells.pop, keys):
    pass

print(len(cells))
stop = perf_counter()
print(f"Removal time {stop-clock:.2f}s")

10 million items or more is not unusual in some settings. Comparing the two methods on my local machine I see a slight improvement when using map and pop, presumably because of fewer function calls, but both take around 2.5s on my machine. But this pales in comparison to the time required to create the dictionary in the first place (55s), or including checks within the loop. If this is likely then its best to create a set that is a intersection of the dictionary keys and your filter:

keys = cells.keys() & keys

In summary: del is already heavily optimised, so don't worry about using it.


问:
Python: Remove character only from end of string if character is ="/"
I add different Values to the Houdini Variables with Python.

Some of these Variables are file pathes and end with an "/" - others are just names and do not end with an "/".

In my current code I use [:-1] to remove the last character of the filepath, so I dont have the "/".
The problem is, that if I add a Value like "Var_ABC", the result will be "Var_AB" since it also removes the last character.

How can i remove the last character only if the last character is a "/"?

Thats what I have and it works so far:

```<code>def set_vars():

count = hou.evalParm('vars_names')
user_name = hou.evalParm('user_name')

for idx in range( 1,count+1):
    output = hou.evalParm('vars_' + str(idx))
    vars_path_out = hou.evalParm('vars_path_' + str(idx))
    vars_path = vars_path_out[:-1]

    hou.hscript("setenv -g " + output + "=" + vars_path)

    final_vars = hou.hscript("setenv -g " + output + "=" + vars_path)

    hou.ui.displayMessage(user_name +", " + "all variables are set.")
</code>```

Thank you

答:
As @jasonharper mentioned in the comments, you should probably use rstrip here. It is built-in and IMO more readable than the contitional one-liner:

vars_path_out.rstrip('/')
```

This will strip out those strings which end with / and return without that ending. Otherwise it will return your string as-is.

Body:
I add different Values to the Houdini Variables with Python.

Some of these Variables are file pathes and end with an "/" - others are just names and do not end with an "/".

In my current code I use [:-1] to remove the last character of the filepath, so I dont have the "/".
The problem is, that if I add a Value like "Var_ABC", the result will be "Var_AB" since it also removes the last character.

How can i remove the last character only if the last character is a "/"?

Thats what I have and it works so far:

def set_vars():

count = hou.evalParm('vars_names')
user_name = hou.evalParm('user_name')

for idx in range( 1,count+1):
    output = hou.evalParm('vars_' + str(idx))
    vars_path_out = hou.evalParm('vars_path_' + str(idx))
    vars_path = vars_path_out[:-1]

    hou.hscript("setenv -g " + output + "=" + vars_path)

    final_vars = hou.hscript("setenv -g " + output + "=" + vars_path)

    hou.ui.displayMessage(user_name +", " + "all variables are set.")

Thank you

Body:
As @jasonharper mentioned in the comments, you should probably use rstrip here. It is built-in and IMO more readable than the contitional one-liner:

vars_path_out.rstrip('/')

This will strip out those strings which end with / and return without that ending. Otherwise it will return your string as-is.


问:
How to run infinite loop and keep getting updates in telegram bot
I'm writing telegram-bot using Go (go-telegram-bot-api). It constantly parses a website and notifies about changes (every minute). Today I added simple keyboard and now can't make them work together.

The problem is that webpage parsing is in the infinite loop and program when it enters the loop ignores updates coming from the "client".

I've tried putting everything in a single loop, changing orders, etc. Maybe there is another or proper way of doing this?

Sample code:

```<code>    u := tgbotapi.NewUpdate(0)
    u.Timeout = 60

    updates, err := bot.GetUpdatesChan(u)

    for update := range updates {
            if update.Message != nil {

                  switch update.Message.Text {
                        case "Show Keyboard":
                              Keyboard is sent
                        case "OptionsForParsing":
                              options.applied
                        case "StartParsing":
                              search bool = true
                        case "StopParsing":
                              search bool = false
                   }
            }

            if search == true{
            for{
                 time.Sleep(1 * time.Minute)
                 AreThereChanges?()
                 if yes{
                         msg := tgbotapi.NewMessage(update.Message.Chat.ID, "help please")
                         bot.Send(msg)
                 }
            }}
     }
</code>```

答:
If I understood everything right you should start parsing loop inside of separated goroutine so updates cycle will keep working.

Try to do something like this:

// you can use cancel to stop running parsing goroutine
ctx, cancel := context.WithCancel(context.Background())

go func() {
  ticker := time.NewTicker(5 * time.Second)
  defer ticker.Stop()

  for {
    select {
      case <-ctx.Done():
        return
      case <-ticker.C:
        AreThereChanges?()
        if yes {
          msg := tgbotapi.NewMessage(update.Message.Chat.ID, "help please")
          bot.Send(msg)
        }
      }
  }
}()
```

Writing from the top of my brain, so do not expect it to compile from the first attempt, but demonstrates the idea. Please, check out following links for more information regarding Ticker and contexts with cancellation: click, click.

Body:
I'm writing telegram-bot using Go (go-telegram-bot-api). It constantly parses a website and notifies about changes (every minute). Today I added simple keyboard and now can't make them work together.

The problem is that webpage parsing is in the infinite loop and program when it enters the loop ignores updates coming from the "client".

I've tried putting everything in a single loop, changing orders, etc. Maybe there is another or proper way of doing this?

Sample code:

    u := tgbotapi.NewUpdate(0)
    u.Timeout = 60

    updates, err := bot.GetUpdatesChan(u)

    for update := range updates {
            if update.Message != nil {

                  switch update.Message.Text {
                        case "Show Keyboard":
                              Keyboard is sent
                        case "OptionsForParsing":
                              options.applied
                        case "StartParsing":
                              search bool = true
                        case "StopParsing":
                              search bool = false
                   }
            }

            if search == true{
            for{
                 time.Sleep(1 * time.Minute)
                 AreThereChanges?()
                 if yes{
                         msg := tgbotapi.NewMessage(update.Message.Chat.ID, "help please")
                         bot.Send(msg)
                 }
            }}
     }

Body:
If I understood everything right you should start parsing loop inside of separated goroutine so updates cycle will keep working.

Try to do something like this:

// you can use cancel to stop running parsing goroutine
ctx, cancel := context.WithCancel(context.Background())

go func() {
  ticker := time.NewTicker(5 * time.Second)
  defer ticker.Stop()

  for {
    select {
      case <-ctx.Done():
        return
      case <-ticker.C:
        AreThereChanges?()
        if yes {
          msg := tgbotapi.NewMessage(update.Message.Chat.ID, "help please")
          bot.Send(msg)
        }
      }
  }
}()

Writing from the top of my brain, so do not expect it to compile from the first attempt, but demonstrates the idea. Please, check out following links for more information regarding Ticker and contexts with cancellation: click, click.


问:
How to use bulk insert condition for particular number of records inside for loop
I want to use the bulk insert concept in C# once count reach 20.if we have 40 numbers no issue. but if we get 39 records got a problem, based on if the condition. how we able to avoid this problem. here below I added a simple program for reference.</p>

```<code>var numbers = 39  // not static numbers
int count = 0;
for(int i=0; i<=numbers; i++)
{

 count++;
 if (count == 20)
   {
      //Logic
      count = 0;
   }

}
</code>```

答:
No need of count variable, you can use modulo operator inside for loop

Like

```<code>for(int i = 0; i <= numbers; i++)
{
    //i != 0 to avoid bulk process at first
    if(i != 0 && i % 20 == 0)
    {
       //Your bulk operation
    }

}
</code>```

I recommend you to use Console.WriteLine() to print value of i and counter in each iteration so that you will understand bug in your code.

```<code>var numbers = 39  // not static numbers
int count = 0;
for(int i=0; i<=numbers; i++)
{

 count++;

 //Print values to understand flow of program
 Console.WriteLine($"For i = {i}, value of count is {count}");

 if (count == 20)
   {
      Console.WriteLine("Time to reset count variable");
      //Logic
      count = 0;

   }

}
</code>```

You can use Linq .Skip() and .Take(), to do batches

```<code>var batchSize = 20;
var batchCount = files.Count() / batchSize;
for (int i = 0; i < batchCount; i++)
{
  var bulkFiles = files.Skip(i * batchSize).Take(batchSize);
}
</code>```

Body:
I want to use the bulk insert concept in C# once count reach 20.if we have 40 numbers no issue. but if we get 39 records got a problem, based on if the condition. how we able to avoid this problem. here below I added a simple program for reference.

var numbers = 39  // not static numbers
int count = 0;
for(int i=0; i<=numbers; i++)
{

 count++;
 if (count == 20)
   {
      //Logic
      count = 0;
   }

}

Body:
No need of count variable, you can use modulo operator inside for loop

Like

for(int i = 0; i <= numbers; i++)
{
    //i != 0 to avoid bulk process at first
    if(i != 0 && i % 20 == 0)
    {
       //Your bulk operation
    }

}

I recommend you to use Console.WriteLine() to print value of i and counter in each iteration so that you will understand bug in your code.

var numbers = 39  // not static numbers
int count = 0;
for(int i=0; i<=numbers; i++)
{

 count++;

 //Print values to understand flow of program
 Console.WriteLine($"For i = {i}, value of count is {count}");

 if (count == 20)
   {
      Console.WriteLine("Time to reset count variable");
      //Logic
      count = 0;

   }

}

You can use Linq .Skip() and .Take(), to do batches

var batchSize = 20;
var batchCount = files.Count() / batchSize;
for (int i = 0; i < batchCount; i++)
{
  var bulkFiles = files.Skip(i * batchSize).Take(batchSize);
}


问:
Adding a splash screen to Flutter apps
How would you approach adding a splash screen to Flutter apps? It should load and display before any other content. Currently, there is a brief flash of color before the Scaffold(home:X) widget loads.</p>

答:
Here are the steps for configuring the splash screen in both IOS and Android platforms for your Flutter app.

IOS Platform

All apps submitted to the Apple App Store must use an Xcode storyboard to provide the app’s launch screen. Let’s do this in 3 steps:-

Step 1: Open ios/Runner.xcworkspace from the root of your app directory.

Step 2: Select Runner/Assets.xcassets from the Project Navigator and drag your launch images of all sizes (2x, 3x, etc.). You can also generate different sizes of images from https://appicon.co/#image-sets

Step 3: You can see the LaunchScreen.storyboard file is showing the provided image, here you can also change the position of the image by simply dragging the image. For more information please see official documentation https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/launch-screen/

Android Platform

In Android, a launch screen is shown while your Android app initializes. Let’s set this launch screen in 3 steps:-

Step 1: Open android/app/src/main/res/drawable/launch_background.xml file.

Step 2: At line number 4 you can select the desired colour:-

```<code><item android:drawable="@android:color/white" />
</code>```

Step 3: At line number 10 you can change the image:-

```<code>android:src="@mipmap/launch_image"
</code>```

That's all, you are done! Happy Coding :)

Title: Adding a splash screen to Flutter apps

Body:
Here are the steps for configuring the splash screen in both IOS and Android platforms for your Flutter app.

IOS Platform

All apps submitted to the Apple App Store must use an Xcode storyboard to provide the app’s launch screen. Let’s do this in 3 steps:-

Step 1: Open ios/Runner.xcworkspace from the root of your app directory.

Step 2: Select Runner/Assets.xcassets from the Project Navigator and drag your launch images of all sizes (2x, 3x, etc.). You can also generate different sizes of images from https://appicon.co/#image-sets

Step 3: You can see the LaunchScreen.storyboard file is showing the provided image, here you can also change the position of the image by simply dragging the image. For more information please see official documentation https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/launch-screen/

Android Platform

In Android, a launch screen is shown while your Android app initializes. Let’s set this launch screen in 3 steps:-

Step 1: Open android/app/src/main/res/drawable/launch_background.xml file.

Step 2: At line number 4 you can select the desired colour:-

<item android:drawable="@android:color/white" />

Step 3: At line number 10 you can change the image:-

android:src="@mipmap/launch_image"

That's all, you are done! Happy Coding :)


问:
When trying to test laravel auth for the register rout
I'm trying check out the auth scaffolding for laravel in my project. After creating my database and migrating, I get this error when i want to test the register auth.

Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'updated_at' in 'field list' (SQL: insert into users (name, email, password, updated_at, created_at) values (jonas, jokansey@gmail.com, $2y$10$9yqGB0hk0O5npBcsq1ImGeRYfTvkJe6ftC5QQ.nmezckbROw6CR06, 2020-05-28 16:18:49, 2020-05-28 16:18:49))
http://todaybusiness.test/register

答:
Your table is missing "updated_at" and mostly it missing "created_at" too, then you have to create it using migration, follow the following steps:

Create migration file using terminal:

```<code>php artisan make:migration update_users_add_timestamps
</code>```

Past the following code in your migration file:

```<code><?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class updateUsersAddTimestamps extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
          $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('users', function (Blueprint $table) {
          $table-> dropTimestamps();
    });
}
</code>```

}

Then run the following terminal command:

```<code>php artisan migrate
</code>```

Body:
Your table is missing "updated_at" and mostly it missing "created_at" too, then you have to create it using migration, follow the following steps:

Create migration file using terminal:

php artisan make:migration update_users_add_timestamps

Past the following code in your migration file:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class updateUsersAddTimestamps extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
          $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('users', function (Blueprint $table) {
          $table-> dropTimestamps();
    });
}

}

Then run the following terminal command:

php artisan migrate


问:
Which Rust data structures are non deterministic
When writing smart contracts it's important to make sure that all data structures used are deterministic.

Specifically, if HashMap or HashSet are used - is there a possible non determinism coming from Rust standard library?

答: To add to what @evgeny-kuzyakov said, the only sources of non-determinism are OS-level features, like threads, clock, OS randomness, networking, devices, file system, etc. If contract is compiled with the code that tries to access these features it will not be executed on our blockchain (though one can deploy it, because one can deploy any sequence of bytes as a contract) and will fail with an error before the execution starts.</p>


问:
Error while installing Django-channels on Python 3.5 on Windows
I'm also getting the same error while installing Twisted.

Here's version info:

Django : 1.9

Python : 3.5

Trying to install latest version of Django-channels

Command used : pip install channels

The error :

running build_ext

   building 'twisted.test.raiser' extension error:
  [WinError 2] The system cannot find the file specified

(Almost) full error message

```<code>.......pip install channels
Collecting channels
  Using cached channels-1.1.8-py2.py3-none-any.whl
Collecting daphne~=1.3 (from channels)
  Using cached daphne-1.3.0-py2.py3-none-any.whl
Requirement already satisfied: asgiref~=1.1 in g:\django\projectChat\venv\lib\site-packages (from channels
)
Requirement already satisfied: Django>=1.8 in g:\django\projectChat\venv\lib\site-packages (from channels)

Requirement already satisfied: autobahn>=0.18 in g:\django\projectChat\venv\lib\site-packages (from daphne
~=1.3->channels)
Collecting twisted>=17.1 (from daphne~=1.3->channels)
  Using cached Twisted-17.9.0.tar.bz2
Requirement already satisfied: six in g:\django\projectChat\venv\lib\site-packages (from asgiref~=1.1->cha
nnels)
Requirement already satisfied: txaio>=2.7.0 in g:\django\projectChat\venv\lib\site-packages (from autobahn
>=0.18->daphne~=1.3->channels)
Requirement already satisfied: zope.interface>=4.0.2 in g:\django\projectChat\venv\lib\site-packages (from
 twisted>=17.1->daphne~=1.3->channels)
Requirement already satisfied: constantly>=15.1 in g:\django\projectChat\venv\lib\site-packages (from twis
ted>=17.1->daphne~=1.3->channels)
Requirement already satisfied: incremental>=16.10.1 in g:\django\projectChat\venv\lib\site-packages (from
twisted>=17.1->daphne~=1.3->channels)
Requirement already satisfied: Automat>=0.3.0 in g:\django\projectChat\venv\lib\site-packages (from twiste
d>=17.1->daphne~=1.3->channels)
Requirement already satisfied: hyperlink>=17.1.1 in g:\django\projectChat\venv\lib\site-packages (from twi
sted>=17.1->daphne~=1.3->channels)
Requirement already satisfied: setuptools in g:\django\projectChat\venv\lib\site-packages (from zope.inter
face>=4.0.2->twisted>=17.1->daphne~=1.3->channels)
Requirement already satisfied: attrs in g:\django\projectChat\venv\lib\site-packages (from Automat>=0.3.0-
>twisted>=17.1->daphne~=1.3->channels)
Installing collected packages: twisted, daphne, channels
  Running setup.py install for twisted ... error
    Complete output from command G:\django\projectChat\venv\Scripts\python.exe -u -c "import setuptools, t
okenize;__file__='C:\\Users\\Mike\\AppData\\Local\\Temp\\pip-build-ngnwgsvg\\twisted\\setup.py';f=getattr(tokenize, 'open'
, open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Use
rs\Mike\AppData\Local\Temp\pip-y5sbi03u-record\install-record.txt --single-version-externally-managed --compile --install-
headers G:\django\projectChat\venv\include\site\python3.5\twisted:
    running install
    running build
    running build_py
    creating build
    creating build\lib.win-amd64-3.5
    creating build\lib.win-amd64-3.5\twisted
    copying src\twisted\copyright.py -> build\lib.win-amd64-3.5\twisted
    copying src\twisted\plugin.py -> build\lib.win-amd64-3.5\twisted
    copying src\twisted\_version.py -> build\lib.win-amd64-3.5\twisted
    copying src\twisted\__init__.py -> build\lib.win-amd64-3.5\twisted
    copying src\twisted\__main__.py -> build\lib.win-amd64-3.5\twisted
    creating build\lib.win-amd64-3.5\twisted\application
    copying src\twisted\application\app.py -> build\lib.win-amd64-3.5\twisted\application
    copying src\twisted\application\internet.py -> build\lib.win-amd64-3.5\twisted\application
    copying src\twisted\application\reactors.py -> build\lib.win-amd64-3.5\twisted\application
    copying src\twisted\application\service.py -> build\lib.win-amd64-3.5\twisted\application
    copying src\twisted\application\strports.py -> build\lib.win-amd64-3.5\twisted\application
    copying src\twisted\application\__init__.py -> build\lib.win-amd64-3.5\twisted\application
    creating build\lib.win-amd64-3.5\twisted\conch
    copying src\twisted\conch\avatar.py -> build\lib.win-amd64-3.5\twisted\conch
    [...]
    creating build\lib.win-amd64-3.5\twisted\_threads\test
    copying src\twisted\_threads\test\test_convenience.py -> build\lib.win-amd64-3.5\twisted\_threads\test
    copying src\twisted\_threads\test\test_memory.py -> build\lib.win-amd64-3.5\twisted\_threads\test
    copying src\twisted\_threads\test\test_team.py -> build\lib.win-amd64-3.5\twisted\_threads\test
    copying src\twisted\_threads\test\test_threadworker.py -> build\lib.win-amd64-3.5\twisted\_threads\test
    copying src\twisted\_threads\test\__init__.py -> build\lib.win-amd64-3.5\twisted\_threads\test
    running egg_info
    writing dependency_links to src\Twisted.egg-info\dependency_links.txt
    writing entry points to src\Twisted.egg-info\entry_points.txt
    writing src\Twisted.egg-info\PKG-INFO
    writing top-level names to src\Twisted.egg-info\top_level.txt
    writing requirements to src\Twisted.egg-info\requires.txt
    reading manifest file 'src\Twisted.egg-info\SOURCES.txt'
    reading manifest template 'MANIFEST.in'
    warning: no previously-included files matching '*.misc' found under directory 'src\twisted'
    warning: no previously-included files matching '*.bugfix' found under directory 'src\twisted'
    warning: no previously-included files matching '*.doc' found under directory 'src\twisted'
    warning: no previously-included files matching '*.feature' found under directory 'src\twisted'
    warning: no previously-included files matching '*.removal' found under directory 'src\twisted'
    warning: no previously-included files matching 'NEWS' found under directory 'src\twisted'
    warning: no previously-included files matching 'README' found under directory 'src\twisted'
    warning: no previously-included files matching 'newsfragments' found under directory 'src\twisted'
    warning: no previously-included files found matching 'src\twisted\topfiles\CREDITS'
    warning: no previously-included files found matching 'src\twisted\topfiles\ChangeLog.Old'
    warning: no previously-included files found matching 'pyproject.toml'
    warning: no previously-included files found matching 'codecov.yml'
    warning: no previously-included files found matching 'appveyor.yml'
    no previously-included directories found matching 'bin'
    no previously-included directories found matching 'admin'
    no previously-included directories found matching '.travis'
    warning: no previously-included files found matching 'docs\historic\2003'
    warning: no previously-included files matching '*' found under directory 'docs\historic\2003'
    writing manifest file 'src\Twisted.egg-info\SOURCES.txt'
    copying src\twisted\python\_sendmsg.c -> build\lib.win-amd64-3.5\twisted\python
    copying src\twisted\python\twisted-completion.zsh -> build\lib.win-amd64-3.5\twisted\python
    creating build\lib.win-amd64-3.5\twisted\python\_pydoctortemplates
    copying src\twisted\python\_pydoctortemplates\common.html -> build\lib.win-amd64-3.5\twisted\python\_pydoctortemplates
    copying src\twisted\python\_pydoctortemplates\index.html -> build\lib.win-amd64-3.5\twisted\python\_pydoctortemplates
    copying src\twisted\python\_pydoctortemplates\summary.html -> build\lib.win-amd64-3.5\twisted\python\_pydoctortemplates
    copying src\twisted\test\cert.pem.no_trailing_newline -> build\lib.win-amd64-3.5\twisted\test
    copying src\twisted\test\key.pem.no_trailing_newline -> build\lib.win-amd64-3.5\twisted\test
    copying src\twisted\test\raiser.c -> build\lib.win-amd64-3.5\twisted\test
    copying src\twisted\test\raiser.pyx -> build\lib.win-amd64-3.5\twisted\test
    copying src\twisted\test\server.pem -> build\lib.win-amd64-3.5\twisted\test
    copying src\twisted\internet\iocpreactor\build.bat -> build\lib.win-amd64-3.5\twisted\internet\iocpreactor
    copying src\twisted\internet\iocpreactor\notes.txt -> build\lib.win-amd64-3.5\twisted\internet\iocpreactor
    creating build\lib.win-amd64-3.5\twisted\internet\iocpreactor\iocpsupport
    copying src\twisted\internet\iocpreactor\iocpsupport\acceptex.pxi -> build\lib.win-amd64-3.5\twisted\internet\iocpreactor\
iocpsupport
    copying src\twisted\internet\iocpreactor\iocpsupport\connectex.pxi -> build\lib.win-amd64-3.5\twisted\internet\iocpreactor
\iocpsupport
    copying src\twisted\internet\iocpreactor\iocpsupport\iocpsupport.c -> build\lib.win-amd64-3.5\twisted\internet\iocpreactor
\iocpsupport
    copying src\twisted\internet\iocpreactor\iocpsupport\iocpsupport.pyx -> build\lib.win-amd64-3.5\twisted\internet\iocpreact
or\iocpsupport
    copying src\twisted\internet\iocpreactor\iocpsupport\winsock_pointers.c -> build\lib.win-amd64-3.5\twisted\internet\iocpre
actor\iocpsupport
    copying src\twisted\internet\iocpreactor\iocpsupport\winsock_pointers.h -> build\lib.win-amd64-3.5\twisted\internet\iocpre
actor\iocpsupport
    copying src\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi -> build\lib.win-amd64-3.5\twisted\internet\iocpreactor\i
ocpsupport
    copying src\twisted\internet\iocpreactor\iocpsupport\wsasend.pxi -> build\lib.win-amd64-3.5\twisted\internet\iocpreactor\i
ocpsupport
    copying src\twisted\internet\test\_awaittests.py.3only -> build\lib.win-amd64-3.5\twisted\internet\test
    copying src\twisted\internet\test\_yieldfromtests.py.3only -> build\lib.win-amd64-3.5\twisted\internet\test
    creating build\lib.win-amd64-3.5\twisted\internet\test\fake_CAs
    copying src\twisted\internet\test\fake_CAs\chain.pem -> build\lib.win-amd64-3.5\twisted\internet\test\fake_CAs
    copying src\twisted\internet\test\fake_CAs\not-a-certificate -> build\lib.win-amd64-3.5\twisted\internet\test\fake_CAs
    copying src\twisted\internet\test\fake_CAs\thing1.pem -> build\lib.win-amd64-3.5\twisted\internet\test\fake_CAs
    copying src\twisted\internet\test\fake_CAs\thing2-duplicate.pem -> build\lib.win-amd64-3.5\twisted\internet\test\fake_CAs
    copying src\twisted\internet\test\fake_CAs\thing2.pem -> build\lib.win-amd64-3.5\twisted\internet\test\fake_CAs
    copying src\twisted\mail\test\rfc822.message -> build\lib.win-amd64-3.5\twisted\mail\test
    copying src\twisted\python\test\_deprecatetests.py.3only -> build\lib.win-amd64-3.5\twisted\python\test
    copying src\twisted\words\im\instancemessenger.glade -> build\lib.win-amd64-3.5\twisted\words\im
    copying src\twisted\words\xish\xpathparser.g -> build\lib.win-amd64-3.5\twisted\words\xish
    running build_ext
    building 'twisted.test.raiser' extension
    error: [WinError 2] The system cannot find the file specified

    ----------------------------------------
Command "G:\django\projectChat\venv\Scripts\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Us
ers\\Mike\\AppData\\Local\\Temp\\pip-build-ngnwgsvg\\twisted\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f
.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Mike\AppData\Loca
l\Temp\pip-y5sbi03u-record\install-record.txt --single-version-externally-managed --compile --install-headers G:\django\projectChat\venv\include\site\python3.5\twisted" failed with error code 1 in C:\Users\Mike\AppData\Local\Tem
p\pip-build-ngnwgsvg\twisted\
</code>```

I don't know what i'm missing, could someone help me please, thanks.

答:
The problem is not regarding the need for Visual C++ 14.0 or whatsoever. It is concerned with the installation of Twisted. I was able to fix this problem after trying for weeks together.
To install the correct version of Twisted visit this link. (Found this on a similar question's answer, I'm not sure of the writer to give rightful credits).
The above-mentioned link displays several versions of Twisted. You should download the one corresponding to your python version. For instance, if your python version is 3.5, you should proceed with downloading cp35m-win32.whl (For Windows only) and so forth.
Further, open Command prompt, go to the downloaded path activate your virtual environment and pip install the downloaded file.
This shall fix your issue.

Body:
I'm also getting the same error while installing Twisted.

Here's version info:

Django : 1.9

Python : 3.5

Trying to install latest version of Django-channels

Command used : pip install channels

The error :

running build_ext

   building 'twisted.test.raiser' extension error:
  [WinError 2] The system cannot find the file specified

(Almost) full error message

.......pip install channels
Collecting channels
  Using cached channels-1.1.8-py2.py3-none-any.whl
Collecting daphne~=1.3 (from channels)
  Using cached daphne-1.3.0-py2.py3-none-any.whl
Requirement already satisfied: asgiref~=1.1 in g:\django\projectChat\venv\lib\site-packages (from channels
)
Requirement already satisfied: Django>=1.8 in g:\django\projectChat\venv\lib\site-packages (from channels)

Requirement already satisfied: autobahn>=0.18 in g:\django\projectChat\venv\lib\site-packages (from daphne
~=1.3->channels)
Collecting twisted>=17.1 (from daphne~=1.3->channels)
  Using cached Twisted-17.9.0.tar.bz2
Requirement already satisfied: six in g:\django\projectChat\venv\lib\site-packages (from asgiref~=1.1->cha
nnels)
Requirement already satisfied: txaio>=2.7.0 in g:\django\projectChat\venv\lib\site-packages (from autobahn
>=0.18->daphne~=1.3->channels)
Requirement already satisfied: zope.interface>=4.0.2 in g:\django\projectChat\venv\lib\site-packages (from
 twisted>=17.1->daphne~=1.3->channels)
Requirement already satisfied: constantly>=15.1 in g:\django\projectChat\venv\lib\site-packages (from twis
ted>=17.1->daphne~=1.3->channels)
Requirement already satisfied: incremental>=16.10.1 in g:\django\projectChat\venv\lib\site-packages (from
twisted>=17.1->daphne~=1.3->channels)
Requirement already satisfied: Automat>=0.3.0 in g:\django\projectChat\venv\lib\site-packages (from twiste
d>=17.1->daphne~=1.3->channels)
Requirement already satisfied: hyperlink>=17.1.1 in g:\django\projectChat\venv\lib\site-packages (from twi
sted>=17.1->daphne~=1.3->channels)
Requirement already satisfied: setuptools in g:\django\projectChat\venv\lib\site-packages (from zope.inter
face>=4.0.2->twisted>=17.1->daphne~=1.3->channels)
Requirement already satisfied: attrs in g:\django\projectChat\venv\lib\site-packages (from Automat>=0.3.0-
>twisted>=17.1->daphne~=1.3->channels)
Installing collected packages: twisted, daphne, channels
  Running setup.py install for twisted ... error
    Complete output from command G:\django\projectChat\venv\Scripts\python.exe -u -c "import setuptools, t
okenize;__file__='C:\\Users\\Mike\\AppData\\Local\\Temp\\pip-build-ngnwgsvg\\twisted\\setup.py';f=getattr(tokenize, 'open'
, open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Use
rs\Mike\AppData\Local\Temp\pip-y5sbi03u-record\install-record.txt --single-version-externally-managed --compile --install-
headers G:\django\projectChat\venv\include\site\python3.5\twisted:
    running install
    running build
    running build_py
    creating build
    creating build\lib.win-amd64-3.5
    creating build\lib.win-amd64-3.5\twisted
    copying src\twisted\copyright.py -> build\lib.win-amd64-3.5\twisted
    copying src\twisted\plugin.py -> build\lib.win-amd64-3.5\twisted
    copying src\twisted\_version.py -> build\lib.win-amd64-3.5\twisted
    copying src\twisted\__init__.py -> build\lib.win-amd64-3.5\twisted
    copying src\twisted\__main__.py -> build\lib.win-amd64-3.5\twisted
    creating build\lib.win-amd64-3.5\twisted\application
    copying src\twisted\application\app.py -> build\lib.win-amd64-3.5\twisted\application
    copying src\twisted\application\internet.py -> build\lib.win-amd64-3.5\twisted\application
    copying src\twisted\application\reactors.py -> build\lib.win-amd64-3.5\twisted\application
    copying src\twisted\application\service.py -> build\lib.win-amd64-3.5\twisted\application
    copying src\twisted\application\strports.py -> build\lib.win-amd64-3.5\twisted\application
    copying src\twisted\application\__init__.py -> build\lib.win-amd64-3.5\twisted\application
    creating build\lib.win-amd64-3.5\twisted\conch
    copying src\twisted\conch\avatar.py -> build\lib.win-amd64-3.5\twisted\conch
    [...]
    creating build\lib.win-amd64-3.5\twisted\_threads\test
    copying src\twisted\_threads\test\test_convenience.py -> build\lib.win-amd64-3.5\twisted\_threads\test
    copying src\twisted\_threads\test\test_memory.py -> build\lib.win-amd64-3.5\twisted\_threads\test
    copying src\twisted\_threads\test\test_team.py -> build\lib.win-amd64-3.5\twisted\_threads\test
    copying src\twisted\_threads\test\test_threadworker.py -> build\lib.win-amd64-3.5\twisted\_threads\test
    copying src\twisted\_threads\test\__init__.py -> build\lib.win-amd64-3.5\twisted\_threads\test
    running egg_info
    writing dependency_links to src\Twisted.egg-info\dependency_links.txt
    writing entry points to src\Twisted.egg-info\entry_points.txt
    writing src\Twisted.egg-info\PKG-INFO
    writing top-level names to src\Twisted.egg-info\top_level.txt
    writing requirements to src\Twisted.egg-info\requires.txt
    reading manifest file 'src\Twisted.egg-info\SOURCES.txt'
    reading manifest template 'MANIFEST.in'
    warning: no previously-included files matching '*.misc' found under directory 'src\twisted'
    warning: no previously-included files matching '*.bugfix' found under directory 'src\twisted'
    warning: no previously-included files matching '*.doc' found under directory 'src\twisted'
    warning: no previously-included files matching '*.feature' found under directory 'src\twisted'
    warning: no previously-included files matching '*.removal' found under directory 'src\twisted'
    warning: no previously-included files matching 'NEWS' found under directory 'src\twisted'
    warning: no previously-included files matching 'README' found under directory 'src\twisted'
    warning: no previously-included files matching 'newsfragments' found under directory 'src\twisted'
    warning: no previously-included files found matching 'src\twisted\topfiles\CREDITS'
    warning: no previously-included files found matching 'src\twisted\topfiles\ChangeLog.Old'
    warning: no previously-included files found matching 'pyproject.toml'
    warning: no previously-included files found matching 'codecov.yml'
    warning: no previously-included files found matching 'appveyor.yml'
    no previously-included directories found matching 'bin'
    no previously-included directories found matching 'admin'
    no previously-included directories found matching '.travis'
    warning: no previously-included files found matching 'docs\historic\2003'
    warning: no previously-included files matching '*' found under directory 'docs\historic\2003'
    writing manifest file 'src\Twisted.egg-info\SOURCES.txt'
    copying src\twisted\python\_sendmsg.c -> build\lib.win-amd64-3.5\twisted\python
    copying src\twisted\python\twisted-completion.zsh -> build\lib.win-amd64-3.5\twisted\python
    creating build\lib.win-amd64-3.5\twisted\python\_pydoctortemplates
    copying src\twisted\python\_pydoctortemplates\common.html -> build\lib.win-amd64-3.5\twisted\python\_pydoctortemplates
    copying src\twisted\python\_pydoctortemplates\index.html -> build\lib.win-amd64-3.5\twisted\python\_pydoctortemplates
    copying src\twisted\python\_pydoctortemplates\summary.html -> build\lib.win-amd64-3.5\twisted\python\_pydoctortemplates
    copying src\twisted\test\cert.pem.no_trailing_newline -> build\lib.win-amd64-3.5\twisted\test
    copying src\twisted\test\key.pem.no_trailing_newline -> build\lib.win-amd64-3.5\twisted\test
    copying src\twisted\test\raiser.c -> build\lib.win-amd64-3.5\twisted\test
    copying src\twisted\test\raiser.pyx -> build\lib.win-amd64-3.5\twisted\test
    copying src\twisted\test\server.pem -> build\lib.win-amd64-3.5\twisted\test
    copying src\twisted\internet\iocpreactor\build.bat -> build\lib.win-amd64-3.5\twisted\internet\iocpreactor
    copying src\twisted\internet\iocpreactor\notes.txt -> build\lib.win-amd64-3.5\twisted\internet\iocpreactor
    creating build\lib.win-amd64-3.5\twisted\internet\iocpreactor\iocpsupport
    copying src\twisted\internet\iocpreactor\iocpsupport\acceptex.pxi -> build\lib.win-amd64-3.5\twisted\internet\iocpreactor\
iocpsupport
    copying src\twisted\internet\iocpreactor\iocpsupport\connectex.pxi -> build\lib.win-amd64-3.5\twisted\internet\iocpreactor
\iocpsupport
    copying src\twisted\internet\iocpreactor\iocpsupport\iocpsupport.c -> build\lib.win-amd64-3.5\twisted\internet\iocpreactor
\iocpsupport
    copying src\twisted\internet\iocpreactor\iocpsupport\iocpsupport.pyx -> build\lib.win-amd64-3.5\twisted\internet\iocpreact
or\iocpsupport
    copying src\twisted\internet\iocpreactor\iocpsupport\winsock_pointers.c -> build\lib.win-amd64-3.5\twisted\internet\iocpre
actor\iocpsupport
    copying src\twisted\internet\iocpreactor\iocpsupport\winsock_pointers.h -> build\lib.win-amd64-3.5\twisted\internet\iocpre
actor\iocpsupport
    copying src\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi -> build\lib.win-amd64-3.5\twisted\internet\iocpreactor\i
ocpsupport
    copying src\twisted\internet\iocpreactor\iocpsupport\wsasend.pxi -> build\lib.win-amd64-3.5\twisted\internet\iocpreactor\i
ocpsupport
    copying src\twisted\internet\test\_awaittests.py.3only -> build\lib.win-amd64-3.5\twisted\internet\test
    copying src\twisted\internet\test\_yieldfromtests.py.3only -> build\lib.win-amd64-3.5\twisted\internet\test
    creating build\lib.win-amd64-3.5\twisted\internet\test\fake_CAs
    copying src\twisted\internet\test\fake_CAs\chain.pem -> build\lib.win-amd64-3.5\twisted\internet\test\fake_CAs
    copying src\twisted\internet\test\fake_CAs\not-a-certificate -> build\lib.win-amd64-3.5\twisted\internet\test\fake_CAs
    copying src\twisted\internet\test\fake_CAs\thing1.pem -> build\lib.win-amd64-3.5\twisted\internet\test\fake_CAs
    copying src\twisted\internet\test\fake_CAs\thing2-duplicate.pem -> build\lib.win-amd64-3.5\twisted\internet\test\fake_CAs
    copying src\twisted\internet\test\fake_CAs\thing2.pem -> build\lib.win-amd64-3.5\twisted\internet\test\fake_CAs
    copying src\twisted\mail\test\rfc822.message -> build\lib.win-amd64-3.5\twisted\mail\test
    copying src\twisted\python\test\_deprecatetests.py.3only -> build\lib.win-amd64-3.5\twisted\python\test
    copying src\twisted\words\im\instancemessenger.glade -> build\lib.win-amd64-3.5\twisted\words\im
    copying src\twisted\words\xish\xpathparser.g -> build\lib.win-amd64-3.5\twisted\words\xish
    running build_ext
    building 'twisted.test.raiser' extension
    error: [WinError 2] The system cannot find the file specified

    ----------------------------------------
Command "G:\django\projectChat\venv\Scripts\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Us
ers\\Mike\\AppData\\Local\\Temp\\pip-build-ngnwgsvg\\twisted\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f
.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Mike\AppData\Loca
l\Temp\pip-y5sbi03u-record\install-record.txt --single-version-externally-managed --compile --install-headers G:\django\projectChat\venv\include\site\python3.5\twisted" failed with error code 1 in C:\Users\Mike\AppData\Local\Tem
p\pip-build-ngnwgsvg\twisted\

I don't know what i'm missing, could someone help me please, thanks.


问:
Facebook Inbound replies through Nexmo API in PHP
Am working on a facebook chat bot using Nexmos facebook message API with PHP. I succeeded in sending a message in sandbox to facebook. However, get a reply when through the inbound webhook call back is a hard nut now.

NEXMO documentation is not that well detailed to help me get done with the TASK.
Any Help on how i can the reply message when a user on facebook replies to the page's chat?

```<code>function inbound() {
        $this->load_model("Api_model")->save_inbound_prod_message($_POST);
    }
</code>```

In that above code, i expected to have some data sent to me through $_POST however, the variable is empty.

THank you for your help

答:
I had not mastered the art of PHP wit JSON data.
So this was solved by these simple lines of code

```<code>$input = file_get_contents('php://input');
        //error_log($input);
        $input = json_decode($input);
        $psid = $input->from->id;
</code>```

as you can see in the question, i expected the reply to be in $_POST variable which wasn't the case.

Body:
Am working on a facebook chat bot using Nexmos facebook message API with PHP. I succeeded in sending a message in sandbox to facebook. However, get a reply when through the inbound webhook call back is a hard nut now.

NEXMO documentation is not that well detailed to help me get done with the TASK.
Any Help on how i can the reply message when a user on facebook replies to the page's chat?

function inbound() {
        $this->load_model("Api_model")->save_inbound_prod_message($_POST);
    }

In that above code, i expected to have some data sent to me through $_POST however, the variable is empty.

THank you for your help

Body:
I had not mastered the art of PHP wit JSON data.
So this was solved by these simple lines of code

$input = file_get_contents('php://input');
        //error_log($input);
        $input = json_decode($input);
        $psid = $input->from->id;

as you can see in the question, i expected the reply to be in $_POST variable which wasn't the case.


问:
Uploading file to onedrive using microsoft graph api
I am trying to uploading a video file to onedrive using the microsoft graph api with the php sdk implementation in laravel.

Code details as below

```<code>// Get the access token from the cache
    $tokenCache = new TokenCache();
    $accessToken = $tokenCache->getAccessToken();

    $file_name = 'new_video.mp4';
    $media_path = storage_path('video.mp4');

    // Create a Graph client
    $graph = new Graph();
    $graph->setAccessToken($accessToken);

          //create post request
    $postData = json_encode([ 'items' =>
                    [
                        "@odata.type" => "microsoft.graph.driveItemUploadableProperties",
                        "@microsoft.graph.conflictBehavior" => "rename",
                        "name" => $file_name
                    ]
                ]);
    //dd(json_encode($postData));

    try {
        $post = $graph->createRequest('POST', '/drive/root/:{item-path}:/createUploadSession')->attachBody($postData)->upload($media_path);

    } catch (\Illuminate\Http\Client\RequestException $e) {
        dd($e);
    }
</code>```

Not sure what should go into the item path too, i tried using the folder name but got error and i also tried excluding the item path but still got an error.

This is the error I am getting

```<code>Client error: `POST https://graph.microsoft.com/v1.0/drive/root/createUploadSession` resulted in a `400 Bad Request` response: {
 "error": {
 "code": "BadRequest",
 "message": "Unable to read JSON request payload. Please ensure Content-T (truncated...)
</code>```

Json Encode of the request data is also as below and I cant figure out the problem...

```<code>{"items":
  {
    "@odata.type":"microsoft.graph.driveItemUploadableProperties",
    "@microsoft.graph.conflictBehavior":"rename",
    "name":"new_video.mp4"
 }
}
</code>```

答:
According to this example given on msgraph-sdk-php repository you don't need to json_econde your body data. The sdk will do it for you.

So your code should looks like this:

```<code>    // Get the access token from the cache
    $tokenCache = new TokenCache();
    $accessToken = $tokenCache->getAccessToken();

    $file_name = 'new_video.mp4';
    $media_path = storage_path('video.mp4');

    // Create a Graph client
    $graph = new Graph();
    $graph->setAccessToken($accessToken);

          //create post request
    $postData = [ 'items' =>
                    [
                        "@odata.type" => "microsoft.graph.driveItemUploadableProperties",
                        "@microsoft.graph.conflictBehavior" => "rename",
                        "name" => $file_name
                    ]
                ];

    try {
        $post = $graph->createRequest('POST', '/drive/root/:{item-path}:/createUploadSession')->attachBody($postData)->upload($media_path);

    } catch (\Illuminate\Http\Client\RequestException $e) {
        dd($e);
    }
</code>```

Body:
I am trying to uploading a video file to onedrive using the microsoft graph api with the php sdk implementation in laravel.

Code details as below

// Get the access token from the cache
    $tokenCache = new TokenCache();
    $accessToken = $tokenCache->getAccessToken();

    $file_name = 'new_video.mp4';
    $media_path = storage_path('video.mp4');

    // Create a Graph client
    $graph = new Graph();
    $graph->setAccessToken($accessToken);

          //create post request
    $postData = json_encode([ 'items' =>
                    [
                        "@odata.type" => "microsoft.graph.driveItemUploadableProperties",
                        "@microsoft.graph.conflictBehavior" => "rename",
                        "name" => $file_name
                    ]
                ]);
    //dd(json_encode($postData));

    try {
        $post = $graph->createRequest('POST', '/drive/root/:{item-path}:/createUploadSession')->attachBody($postData)->upload($media_path);

    } catch (\Illuminate\Http\Client\RequestException $e) {
        dd($e);
    }

Not sure what should go into the item path too, i tried using the folder name but got error and i also tried excluding the item path but still got an error.

This is the error I am getting

Client error: `POST https://graph.microsoft.com/v1.0/drive/root/createUploadSession` resulted in a `400 Bad Request` response: {
 "error": {
 "code": "BadRequest",
 "message": "Unable to read JSON request payload. Please ensure Content-T (truncated...)

Json Encode of the request data is also as below and I cant figure out the problem...

{"items":
  {
    "@odata.type":"microsoft.graph.driveItemUploadableProperties",
    "@microsoft.graph.conflictBehavior":"rename",
    "name":"new_video.mp4"
 }
}

Body:
According to this example given on msgraph-sdk-php repository you don't need to json_econde your body data. The sdk will do it for you.

So your code should looks like this:

    // Get the access token from the cache
    $tokenCache = new TokenCache();
    $accessToken = $tokenCache->getAccessToken();

    $file_name = 'new_video.mp4';
    $media_path = storage_path('video.mp4');

    // Create a Graph client
    $graph = new Graph();
    $graph->setAccessToken($accessToken);

          //create post request
    $postData = [ 'items' =>
                    [
                        "@odata.type" => "microsoft.graph.driveItemUploadableProperties",
                        "@microsoft.graph.conflictBehavior" => "rename",
                        "name" => $file_name
                    ]
                ];

    try {
        $post = $graph->createRequest('POST', '/drive/root/:{item-path}:/createUploadSession')->attachBody($postData)->upload($media_path);

    } catch (\Illuminate\Http\Client\RequestException $e) {
        dd($e);
    }


问:
Any chance to get full autocompletion for Tensorflow 2.0 in PyCharm?
I have upgraded to tensorflow-gpu==2.0 and now I have very limited autocompletion in PyCharm (e.g. can't view a method signature). There seems to be some lazy loading mechanism that I'm not familiar with. Is there a way to have a full autocompletion working as in older TF versions?</p>

答:
Providing the answer here for the community even if the solution is present in the comment section.

Install PyCharm to latest version (2020.1 as of today) EAP jetbrains.com/pycharm/nextversion

It comes with a relevant fix for TensorFlow completion. In the meantime, PyCharm relies on some hardcoded data to provide the completion for TensorFlow as it's too dynamic to be statically parsable.

 If you have any issues with the latest EAP - report them directly to youtrack.jetbrains.com/issues/PY


问:
storing n+1 objects in a solr document
I'm struggling to work out how the best way to store n+1 object in a solr document.

I am storing a CV/resume document in a solr document.  I am looking at storing two different data types "education" and "employment"

If we look at education the object looks like this:

```<code>{
 "establishment" => 'Oxford',
 "Subject" => 'Computing',
 "Type" => 'Degree',
 "Grade" => '2:1'
}
</code>```

A CV can have n+1 of these objects depending on the contents of the CV.  The search needs to be able to see that when I search for CV with Establishment = Oxford & Subject = Computing & Grade = 2:1 that it matches this object not a different establishment with the same subject and grade.

A multivalue I don't think would help or is possible to store n+1 of these types of objects.

My question is how to set up solr to be able to store this type of data against one "CV" Solr document so that it is search able as part of a general search of the index?

答:
You essentially want to turn Solr into a relational database. I.e. you want to enforce some structure on your documents rather than having them just be a bag of words.

If you need relations, then you need relations. The only way I can think of accomplishing this is to index education objects separately, and then have a "foreign key" from the resume.

Alternatively, it seems likely that your "n" will be pretty small. So you could just include each resume in the index multiple times, once with each education listing. This might throw off scoring a bit, but ymmv.

Title: storing n+1 objects in a solr document

Body:
I'm struggling to work out how the best way to store n+1 object in a solr document.

I am storing a CV/resume document in a solr document.  I am looking at storing two different data types "education" and "employment"

If we look at education the object looks like this:

{
 "establishment" => 'Oxford',
 "Subject" => 'Computing',
 "Type" => 'Degree',
 "Grade" => '2:1'
}

A CV can have n+1 of these objects depending on the contents of the CV.  The search needs to be able to see that when I search for CV with Establishment = Oxford & Subject = Computing & Grade = 2:1 that it matches this object not a different establishment with the same subject and grade.

A multivalue I don't think would help or is possible to store n+1 of these types of objects.

My question is how to set up solr to be able to store this type of data against one "CV" Solr document so that it is search able as part of a general search of the index?


问:
Prevent input type=“number” from getting more than one dot in its value and limit decimals numbers
Inbefore: I know this question has been asked more than once on this forum. I know I could post my answer on these other posts. My issue is that the users who asked those questions did it 3 - 4 years ago, and looking at their autors profile, they do not seem very active and I beleive the questions would never be marked as solved.

So I've been looking around every where to find help on doing exactly that, with no simple solutions allowing to limit the user from typing more than one dot in an input type=“number”. It is important to keep the input type="number" as it may affect the keyboard on certain mobile devices.

I know it might seem limitative to prevent a keyboard event, and some might argue that the field should only be evaluated on submit or on change or on blur. I say the input type="number" already limits the effects of certain keypresses that are anything but numbers or "e" or ".", and that happens on the fly.

On top of it, some solutions made it impossible to limit the amount of floats allowed.

答:
You can find very detailed explainations in this Codepen

This solution is simple and will only allow one dot in the number field. It doesn't prevent from clicking back in the number and adding numbers before the ".". It doesn't prevent from executing browser keyboard shortcuts like refresh, copy and pasting (as long as the pasted value is a valid number) and others. It will allow to add "." withing the body of the number, but will remove any exceeding floats over the set limit.

The only behavior that I still can't prevent is if you press the dot key at the end of the input repeatedly, the dot will blink on and off. This happens because a typed value of "13." is a valid number and returns "13" and a typed value of "13.." is not and returns "". In my solution, if a value returns "" without the press of backspace or delete, it gets rolled back to the last valid value, wich is "13", obtained from the typed value "13.".

I've tried solutions where if a dot was pressed once, it was prevented to be triggered a second time, but every time I managed to get stuck with pressing the dot right after an already existing dot followed by nothing and then get stuck with not being able to type a dot unless I pressed any other key first.

I think the blinking on multiple press is the best solution for ther's no way a user would type a dot and nothing happens.

let lastValidInputValue;
let selectedDot = false;

const onKeypress = (e) => {
  if (e.key === "." && e.target.value.indexOf(".") !== -1 && !selectedDot) e.preventDefault();
  selectedDot = false;

  if (e.key === "e") e.preventDefault();
};

const onInput = (e) => {
  if (
    e.target.value.indexOf(".") < e.target.value.length - e.target.getAttribute("data-toFixed") - 1 &&
    e.target.value.indexOf(".") !== -1
  ) {
    let newValue;
    newValue = e.target.value.slice(
      0,
      e.target.value.indexOf(".") +
        parseInt(e.target.getAttribute("data-toFixed")) +
        1
    );
    newValue = parseFloat(newValue);
    e.target.value = newValue;
  }
  if (e.target.value !== "") {
    lastValidInputValue = e.target.value;
  } else if (e.inputType.match(/delete/g)) {
    lastValidInputValue = "";
  } else {
    e.target.value = lastValidInputValue;
  }
};

 const onSelect = (e) => {
   if(window.getSelection().toString().indexOf(".") > -1) selectedDot = true;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" id="myNumber" name="myNumber" data-toFixed="2" step="any" onkeypress="onKeypress(event)" oninput="onInput(event)" onselect="onSelect(event)"></code>```

Body:
You can find very detailed explainations in this Codepen

This solution is simple and will only allow one dot in the number field. It doesn't prevent from clicking back in the number and adding numbers before the ".". It doesn't prevent from executing browser keyboard shortcuts like refresh, copy and pasting (as long as the pasted value is a valid number) and others. It will allow to add "." withing the body of the number, but will remove any exceeding floats over the set limit.

The only behavior that I still can't prevent is if you press the dot key at the end of the input repeatedly, the dot will blink on and off. This happens because a typed value of "13." is a valid number and returns "13" and a typed value of "13.." is not and returns "". In my solution, if a value returns "" without the press of backspace or delete, it gets rolled back to the last valid value, wich is "13", obtained from the typed value "13.".

I've tried solutions where if a dot was pressed once, it was prevented to be triggered a second time, but every time I managed to get stuck with pressing the dot right after an already existing dot followed by nothing and then get stuck with not being able to type a dot unless I pressed any other key first.

I think the blinking on multiple press is the best solution for ther's no way a user would type a dot and nothing happens.

let lastValidInputValue;
let selectedDot = false;

const onKeypress = (e) => {
  if (e.key === "." && e.target.value.indexOf(".") !== -1 && !selectedDot) e.preventDefault();
  selectedDot = false;

  if (e.key === "e") e.preventDefault();
};

const onInput = (e) => {
  if (
    e.target.value.indexOf(".") < e.target.value.length - e.target.getAttribute("data-toFixed") - 1 &&
    e.target.value.indexOf(".") !== -1
  ) {
    let newValue;
    newValue = e.target.value.slice(
      0,
      e.target.value.indexOf(".") +
        parseInt(e.target.getAttribute("data-toFixed")) +
        1
    );
    newValue = parseFloat(newValue);
    e.target.value = newValue;
  }
  if (e.target.value !== "") {
    lastValidInputValue = e.target.value;
  } else if (e.inputType.match(/delete/g)) {
    lastValidInputValue = "";
  } else {
    e.target.value = lastValidInputValue;
  }
};

 const onSelect = (e) => {
   if(window.getSelection().toString().indexOf(".") > -1) selectedDot = true;
 }

<input type="number" id="myNumber" name="myNumber" data-toFixed="2" step="any" onkeypress="onKeypress(event)" oninput="onInput(event)" onselect="onSelect(event)">