问:
How to find multiple indexes of a letter inside a word? (Python)
So I'm making a hanging man game and I have run into a problem regarding indexes. Basically, I want to find the index of a letter inside a secret word, the problem is that if the secret word includes two letters that are the same, for instance, "guacamole", where the letter a has the index of 2 and 4 but when I want to find the index of a, it only prints "2" and not "4". Is there a way around this? Thanks in advance!

Part of code where problem occurs:

```<code>for letter in secret_word:
    if user_guess == letter:
        current_word_index = secret_word.find(letter)
        print(current_word_index) #Not in full program, only to test errors.
</code>```

Full code:

```<code>#Hanging man

import string

space = "\v"

dbl_space = "\n"

secret_word = str(input("Enter a secret word: "))

guess_low = list(string.ascii_lowercase)

used_letters = []

user_errors = 0

user_errors_max = 1

secret_word_index = int(len(secret_word))

secret_word_placeholder = list(range(secret_word_index))

while user_errors != user_errors_max:
    user_guess = str(input("Enter a letter: "))
    if len(user_guess) != 1:
        print("You have to pick one letter")
    if user_guess in guess_low:
        guess_low.remove(user_guess)
        used_letters.extend(user_guess)
        print(used_letters)
    for letter in secret_word:
        if user_guess == letter:
            current_word_index = secret_word.find(letter)

if user_errors == user_errors_max:
    print("You lost the game, the secret word was: " + secret_word)
</code>```

答:
Python's string find accepts a start parameter that tells it where to start searching:

```<code>>>> "guacamole".find('a')
2
>>> "guacamole".find('a', 3)
4
</code>```

Use a loop, and use the index of the last hit you found + 1 as the start parameter for the next call.

Body:
So I'm making a hanging man game and I have run into a problem regarding indexes. Basically, I want to find the index of a letter inside a secret word, the problem is that if the secret word includes two letters that are the same, for instance, "guacamole", where the letter a has the index of 2 and 4 but when I want to find the index of a, it only prints "2" and not "4". Is there a way around this? Thanks in advance!

Part of code where problem occurs:

for letter in secret_word:
    if user_guess == letter:
        current_word_index = secret_word.find(letter)
        print(current_word_index) #Not in full program, only to test errors.

Full code:

#Hanging man

import string

space = "\v"

dbl_space = "\n"

secret_word = str(input("Enter a secret word: "))

guess_low = list(string.ascii_lowercase)

used_letters = []

user_errors = 0

user_errors_max = 1

secret_word_index = int(len(secret_word))

secret_word_placeholder = list(range(secret_word_index))

while user_errors != user_errors_max:
    user_guess = str(input("Enter a letter: "))
    if len(user_guess) != 1:
        print("You have to pick one letter")
    if user_guess in guess_low:
        guess_low.remove(user_guess)
        used_letters.extend(user_guess)
        print(used_letters)
    for letter in secret_word:
        if user_guess == letter:
            current_word_index = secret_word.find(letter)

if user_errors == user_errors_max:
    print("You lost the game, the secret word was: " + secret_word)

Body:
Python's string find accepts a start parameter that tells it where to start searching:

>>> "guacamole".find('a')
2
>>> "guacamole".find('a', 3)
4

Use a loop, and use the index of the last hit you found + 1 as the start parameter for the next call.


来源: stackexchange

问:
Wrong records when filtering date
I have strange problem when i filter in related models by date,
consider this code :

```<code>function applyDepositOnRangeFilter($query, $request)
{
    if ($request->has('deposit_at_from')) {
        $query->whereHas('deposits', function ($query) use ($request) {
            $query->whereDate('created_at', '>=', $request->input('deposit_at_from'));
        });
    }

    if ($request->has('deposit_at_to')) {
        $query->whereHas('deposits', function ($query) use ($request) {
            $query->whereDate('created_at', '<=', $request->input('deposit_at_to'));
        });
    }
}
</code>```

if I filtering yesterday date  17/02/20;  it returns results with today date 18/02/20 too
and if I filter 16/02/20 it returns 17 and 18 too,
its happens in all related model filtering only

答:
you are searching ranges, so it is logical you get multiple dates. also on input you need to have both dates set to limit lower and upper range limit. in your setup you need to send both 16/02/20 and 17/02/20 to receive records for 16/02/20.

so check that both values are available if you need to get a specific range.

```<code>if ($request->has('deposit_at_from') && $request->has('deposit_at_to') {
     $query->whereHas('deposits', function ($query) use ($request) {
            $query->whereDate('created_at', '>=', $request->input('deposit_at_from'));
     $query->whereHas('deposits', function ($query) use ($request) {
            $query->whereDate('created_at', '<=', $request->input('deposit_at_to'));

}
</code>```

or just use one field for date filtering of you want a single date result and do raw filter:

```<code>$query->where(DB::raw("DATE(created_at) = '".date('Y-m-d', $request->input('deposit_date')."'"));

</code>```

ContentLicense: CC BY-SA 4.0

Title: Wrong records when filtering date

Body:
I have strange problem when i filter in related models by date,
consider this code :

function applyDepositOnRangeFilter($query, $request)
{
    if ($request->has('deposit_at_from')) {
        $query->whereHas('deposits', function ($query) use ($request) {
            $query->whereDate('created_at', '>=', $request->input('deposit_at_from'));
        });
    }

    if ($request->has('deposit_at_to')) {
        $query->whereHas('deposits', function ($query) use ($request) {
            $query->whereDate('created_at', '<=', $request->input('deposit_at_to'));
        });
    }
}

if I filtering yesterday date  17/02/20;  it returns results with today date 18/02/20 too
and if I filter 16/02/20 it returns 17 and 18 too,
its happens in all related model filtering only

Body:
you are searching ranges, so it is logical you get multiple dates. also on input you need to have both dates set to limit lower and upper range limit. in your setup you need to send both 16/02/20 and 17/02/20 to receive records for 16/02/20.

so check that both values are available if you need to get a specific range.

if ($request->has('deposit_at_from') && $request->has('deposit_at_to') {
     $query->whereHas('deposits', function ($query) use ($request) {
            $query->whereDate('created_at', '>=', $request->input('deposit_at_from'));
     $query->whereHas('deposits', function ($query) use ($request) {
            $query->whereDate('created_at', '<=', $request->input('deposit_at_to'));

}

or just use one field for date filtering of you want a single date result and do raw filter:

$query->where(DB::raw("DATE(created_at) = '".date('Y-m-d', $request->input('deposit_date')."'"));


问:
Cordova: Cannot find plugin.xml
I am trying to remove this plugin from my coordova file and I am getting this issues

```<code>Error: Cannot find plugin.xml for plugin 'org.apache.cordova.file-transfer'. Please try adding it again.
</code>```

This is the cordova command to remove the plugin

```<code>cordova plugin rm cordova-plugin-file-transfer
</code>```

Please assist on why I cannot be able to remove this plugin. Thank you

答:
Faced the same issue when building out my app in Ionic 3. The steps I followed to clear this issue include:

Check what Cordova Plugins are already installed on the App using -cordova plugin list in your CLI

Delete any Plugin that are not listed in Step(1) from your Apps plugins folder in your applications directory ie.deleting folder of this plugin from plugins folder

Try and build again.

ContentLicense: CC BY-SA 3.0

Title: Cordova: Cannot find plugin.xml

Body:
I am trying to remove this plugin from my coordova file and I am getting this issues

Error: Cannot find plugin.xml for plugin 'org.apache.cordova.file-transfer'. Please try adding it again.

This is the cordova command to remove the plugin

cordova plugin rm cordova-plugin-file-transfer

Please assist on why I cannot be able to remove this plugin. Thank you


问:
Javascript float subtract
I was wondering how can I subtract two negative Floating-Point numbers in javascript. I tried:

```<code>alert(-0.2-0.1);
</code>```

and the result is -0.30000000000000004. Am I doing something wrong? What do I have to do to get -0.3 ?

答:
The reason of your problem is explained here:
Why does modulus operator return fractional number in javascript?

A possible solution could be:

```<code><script type="text/javascript">
var result = (-20-10)/100;
alert("My result is "+result);
</script>
</code>```

Title: Javascript float subtract

Body:
I was wondering how can I subtract two negative Floating-Point numbers in javascript. I tried:

alert(-0.2-0.1);

and the result is -0.30000000000000004. Am I doing something wrong? What do I have to do to get -0.3 ?

Body:
The reason of your problem is explained here:
Why does modulus operator return fractional number in javascript?

A possible solution could be:

<script type="text/javascript">
var result = (-20-10)/100;
alert("My result is "+result);
</script>


问:
why flutter test coverage does not cover assert statements?
I have a constructor for LoginPageBloc as shown below

```<code> LoginPageBloc(
  {@required this.dataRepository,
 })
  : assert(null != dataRepository);
</code>```

when I use flutter test --coverage, the assertion statements are excluded. why??

Then I checked on the dart-lang repo for any open issues, and I found this.

This coverall result also shows the same issue (found in that git repo issue).

But, that issue status is closed and I found the following message thereby @ZichangG.

VM uses function calls to determine. Callsites that have been executed will be considered as a hit.

If a variable is evaluated, like assert(mode == null), an implicit
  getter function will be called if it is not a local variable. For this
  case assert(callback != null), callback is a local variable and it is
  also not being called here.

When functions that has been executed are evaluated, we set the first
  token position of that function as a hit. That's probably the reason
  why a line like assert( () { will be marked as hit. Because the
  closure function starts in this line.

I having difficulty understanding the above message by @ZichangG.

Unfortunately, I am still experiencing the same problem.
Just because of these assertion statements, I am unable to reach 100% code coverage.

why flutter test coverage does not cover assert statements?

Could you please explain to me the reason behind this and what should I do to avoid this?

答:
You can wrap the assert call into a until function to by pass the issue.

See below,

Define a util function

```<code>  void assertNotNull(Object object) {
    assert(object != null);
    }
</code>```

Use it like

```<code> assertNotNull(dataRepository);
</code>```

Body:
I have a constructor for LoginPageBloc as shown below

 LoginPageBloc(
  {@required this.dataRepository,
 })
  : assert(null != dataRepository);

when I use flutter test --coverage, the assertion statements are excluded. why??

Then I checked on the dart-lang repo for any open issues, and I found this.

This coverall result also shows the same issue (found in that git repo issue).

But, that issue status is closed and I found the following message thereby @ZichangG.

VM uses function calls to determine. Callsites that have been executed will be considered as a hit.

If a variable is evaluated, like assert(mode == null), an implicit
  getter function will be called if it is not a local variable. For this
  case assert(callback != null), callback is a local variable and it is
  also not being called here.

When functions that has been executed are evaluated, we set the first
  token position of that function as a hit. That's probably the reason
  why a line like assert( () { will be marked as hit. Because the
  closure function starts in this line.

I having difficulty understanding the above message by @ZichangG.

Unfortunately, I am still experiencing the same problem.
Just because of these assertion statements, I am unable to reach 100% code coverage.

why flutter test coverage does not cover assert statements?

Could you please explain to me the reason behind this and what should I do to avoid this?

Body:
You can wrap the assert call into a until function to by pass the issue.

See below,

Define a util function

  void assertNotNull(Object object) {
    assert(object != null);
    }

Use it like

 assertNotNull(dataRepository);


问:
How can I implement onActivityResult and onNewIntent on FlutterActivity
I would like to implement onActivityResult and onNewIntent on my Android native side of flutter app.

For example, I would like to be able to run "startActivityForResult", and open my app using a deep link.

My main activity is flutter, but I have some work I need to do on the native part.

Is there a way to accomplish this without writing an external plugin?

```<code>package com.test.flutter_app

import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant

class MainActivity: FlutterActivity() {
    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine);
    }
}
</code>```

As I understand from the documentation, I need to use PluginRegistry.Registrar addActivityResultListener. But who is my Registrar? how can I get it/use it?
Code examples would be much appreciated.

答:
FlutterActivity is an activity so I guess you could add something like this:

```<code>Result mResult;

private void doStuff() {
    ...
    startActivityForResult(intent, INTENT_CODE);
}

@Override
public boolean onActivityResult(int requestCode, int resultCode, Intent intent) {
    ...
    mResult.success(null);
    return false;
}
</code>```

Now you can use doStuff using a platformchannel

```<code>    new MethodChannel(getFlutterView(), MY_CHANNEL).setMethodCallHandler(
            (call, result) -> {
                if (call.method.equals("my_method")) {
                    mResult = result;
                    doStuff();
                }
            });
</code>```

Body:
I would like to implement onActivityResult and onNewIntent on my Android native side of flutter app.

For example, I would like to be able to run "startActivityForResult", and open my app using a deep link.

My main activity is flutter, but I have some work I need to do on the native part.

Is there a way to accomplish this without writing an external plugin?

package com.test.flutter_app

import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant

class MainActivity: FlutterActivity() {
    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine);
    }
}

As I understand from the documentation, I need to use PluginRegistry.Registrar addActivityResultListener. But who is my Registrar? how can I get it/use it?
Code examples would be much appreciated.

Body:
FlutterActivity is an activity so I guess you could add something like this:

Result mResult;

private void doStuff() {
    ...
    startActivityForResult(intent, INTENT_CODE);
}

@Override
public boolean onActivityResult(int requestCode, int resultCode, Intent intent) {
    ...
    mResult.success(null);
    return false;
}

Now you can use doStuff using a platformchannel

    new MethodChannel(getFlutterView(), MY_CHANNEL).setMethodCallHandler(
            (call, result) -> {
                if (call.method.equals("my_method")) {
                    mResult = result;
                    doStuff();
                }
            });


问:
Pandas dataframe reverse increment dictionary in new column
I saved a dictionary with different keys in each row and all values equal to 0 in a new Dataframe column.

Starting from the end, and depending on the value of another column (same row), I would like to increment this dictionary, and store the view of this dictionary.

Incrementing is fine, but storing the view doesn't work. In the end I have the same dictionary in the whole column.

```<code>Before
col1    col_dict
1       {1:0, 2:0, 3:0}
2       {1:0, 2:0, 3:0}
3       {1:0, 2:0, 3:0}

What i want:

col1    col_dict
1       {1:1, 2:1, 3:1}
2       {1:0, 2:1, 3:1}
3       {1:0, 2:0, 3:1}

What I have:

col1    col_dict
1       {1:1, 2:1, 3:1}
2       {1:1, 2:1, 3:1}
3       {1:1, 2:1, 3:1}

</code>```

For example:

```<code>def function():
    for x in reversed(range(20)):
        #taking the value in the other column, and incrementing the value in the dictionary
        dataset["dict_column"][x][str(dataset.value[x])][0] += 1
</code>```

I have tried to pass to list format, same problem.
I think it's due to the process of pandas.

Thank you in advance.

Open to any solution to do the job

答:
Thanks to John Doe, I found a solution to my problem, may not be the best option, but as I don't need performances..

Here is my code, less efficient than his I guess, but for a beginner like me, might be more clear to understand (no offense).

```<code>import pandas as pd
import copy

def function():
    #to skip the copy for the first (last) row
    flag = 0
    for x in reversed(range(20)):
        if flag == 0:
            dataset["dict_column"][x][str(dataset.value[x])][0] += 1
            flag = 1
        else:
            dataset["dict_column"][x] = copy.deepcopy(dataset["dict_column"][x+1])
            dataset["dict_column"][x][str(dataset.value[x])][0] += 1

</code>```

Body:
I saved a dictionary with different keys in each row and all values equal to 0 in a new Dataframe column.

Starting from the end, and depending on the value of another column (same row), I would like to increment this dictionary, and store the view of this dictionary.

Incrementing is fine, but storing the view doesn't work. In the end I have the same dictionary in the whole column.

Before
col1    col_dict
1       {1:0, 2:0, 3:0}
2       {1:0, 2:0, 3:0}
3       {1:0, 2:0, 3:0}

What i want:

col1    col_dict
1       {1:1, 2:1, 3:1}
2       {1:0, 2:1, 3:1}
3       {1:0, 2:0, 3:1}

What I have:

col1    col_dict
1       {1:1, 2:1, 3:1}
2       {1:1, 2:1, 3:1}
3       {1:1, 2:1, 3:1}

For example:

def function():
    for x in reversed(range(20)):
        #taking the value in the other column, and incrementing the value in the dictionary
        dataset["dict_column"][x][str(dataset.value[x])][0] += 1

I have tried to pass to list format, same problem.
I think it's due to the process of pandas.

Thank you in advance.

Open to any solution to do the job

Body:
Thanks to John Doe, I found a solution to my problem, may not be the best option, but as I don't need performances..

Here is my code, less efficient than his I guess, but for a beginner like me, might be more clear to understand (no offense).

import pandas as pd
import copy

def function():
    #to skip the copy for the first (last) row
    flag = 0
    for x in reversed(range(20)):
        if flag == 0:
            dataset["dict_column"][x][str(dataset.value[x])][0] += 1
            flag = 1
        else:
            dataset["dict_column"][x] = copy.deepcopy(dataset["dict_column"][x+1])
            dataset["dict_column"][x][str(dataset.value[x])][0] += 1


问:
Push notifications not receiving/working for AppStore and TestFlight build
As one of our iOS applications is UNABLE to receive push/remote notifications for production/live build which installed from App Store/TestFlight but able to receive push/remote notifications in development environment and even in production environment also app is able to receive push/remote notifications from third party services like Gimbal (which is in sync with Urban Airship) but not receiving in app notifications which triggered from our servers using Java code base.

We have cross checked

Push notifications permissions in iOS devices

Device token registration/update in our databases.

All ports which are needed for APNS are open in our servers firewall restrictions.

All the .p12 certificates which we are using for development and production are not expired and even we are able to send/trigger these push/remote notifications manually from third party portals(like pushtry.com website, NWPusher) by using the same .p12 certificates even in production environment to live build installed from App Store/TestFlight.

Need help/suggestions in this issue???

Thanks

答:
I would suggest to check the host and port used in your server for production push notification.

I hope you are removing the sandbox from the host for production push notifications.


问:
I can't install Docker because containerd.io has no installation candidate
I tried to install Docker on Kubuntu 19.10.

I used these steps to install: https://docs.docker.com/install/linux/docker-ce/ubuntu/

During step 2, after added repository and key I got this message

```<code>Package containerd.io is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'containerd.io' has no installation candidate
</code>```

答:
It's not the cleanest way to do it I guess, but I had the same problem as you and I changed:

```<code>$ sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"
</code>```

to

```<code>$ sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   bionic \
   stable"
</code>```

because

```<code>$(lsb_release -cs)
</code>```

returns "eoan" (the name of the latest ubuntu version, currently 19.10) and it seems to cause problems.
Replacing this with "bionic" (ubuntu 18.10) worked perfectly for me, and I still have no problems 4 months later.

Don't forget to open "/etc/apt/sources.list" and comment-out/delete the line:

```<code>deb-src [arch=amd64] https://download.docker.com/linux/ubuntu eoan stable
</code>```

to avoid conflicts.
 (You added this with the first command you entered in this process.)

Body:
I tried to install Docker on Kubuntu 19.10.

I used these steps to install: https://docs.docker.com/install/linux/docker-ce/ubuntu/

During step 2, after added repository and key I got this message

Package containerd.io is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'containerd.io' has no installation candidate

Body:
It's not the cleanest way to do it I guess, but I had the same problem as you and I changed:

$ sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"

to

$ sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   bionic \
   stable"

because

$(lsb_release -cs)

returns "eoan" (the name of the latest ubuntu version, currently 19.10) and it seems to cause problems.
Replacing this with "bionic" (ubuntu 18.10) worked perfectly for me, and I still have no problems 4 months later.

Don't forget to open "/etc/apt/sources.list" and comment-out/delete the line:

deb-src [arch=amd64] https://download.docker.com/linux/ubuntu eoan stable

to avoid conflicts.
 (You added this with the first command you entered in this process.)


问:
How to browse through the full command history in RStudio
Occasionally I had not saved my source script, and its old version opened. I can find the new version which was executed during the previous session, but only like shreds: I search in history and it shows me a piece of code, but not all lines though they were executed simultaneously. Is there any way to access the complete history, which is definitely stored somewhere, but not shown as a whole? Thanks!

I am using R version 3.6.2 and RStudio Version 1.2.5033.

答:
Please, take a look at: https://support.rstudio.com/hc/en-us/articles/200526217-Command-History
use shortcut key Ctrl + 4 to put focus on history or Ctrl+Shift+4 to enlarge window of history. Let us know</p>


问:
How to integrate react-draft-wysiwyg custom component with React-Final-Form
I'm trying to learn how to use React-Final-Form (RFF in short).

I've learnt how to use <Field> component but now I need to add a custom component to use a WYSIWYG editor which is NOT provided by RFF.

So, I've chosen react-draft-wysiwyg.

Ok, first here my form:

```<code>const FormComponent = () => {

  const handleSubmitOnClick = () => ({
    news_title,
    news_subtitle,
    editor_content,
    image_url,
  }) => {

    const data = {
      "user": {
        news_title: news_title,
        news_subtitle: news_subtitle,
        editor_content: editor_content <- here the content from the WYSIWYG editor
        image_url: image_url
      }
    }

     // API call here ....
  }

  return (
    <>
      <h1>News Main Page</h1>

      <Form
        onSubmit={handleSubmitOnClick()}
      >
        {
          ({
            handleSubmit,
            values,
            submitting,
          }) => (
          <form onSubmit={handleSubmit} data-testid="form">
            <Field
              name='news_title'
              placeholder='News Title'
              validate={required}
            >
              {({ input, meta, placeholder }) => (
                <div className={meta.active ? 'active' : ''}>

                  <input {...input}
                    type='text'
                    placeholder={placeholder}

                  />
                </div>
              )}
            </Field>

            <Field
              name='news_subtitle'
              placeholder='News SubTitle'
              validate={required}
            >
              {({ input, meta, placeholder }) => (
                <div className={meta.active ? 'active' : ''}>

                  <input {...input}
                    type='text'
                    placeholder={placeholder}
                  />
                </div>
              )}
            </Field>

            <WYSIWYGEditor /> **** HERE THE ISSUE ****

            <MyDropzone />
            <button
              type="submit"
              className="signup-button"
              disabled={submitting}
            >
              Continue
            </button>

          </form>
        )}
      </Form>
    </>
  )
}

export default FormComponent;

</code>```

This is the Editor file:

```<code>import React, { useState } from 'react';

// Components
import { EditorState, convertToRaw } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';

// Hooks version of the Class below (done by me)
const WYSIWYGEditor = () => {
  const [editorState, setEditorState] = useState(EditorState.createEmpty());
  const onEditorStateChange = editorState => {
    return setEditorState(editorState)
  }

  return (
    <div className="editor">
      <Editor
        editorState={editorState}
        wrapperClassName="demo-wrapper"
        editorClassName="demo-editor"
        onEditorStateChange={onEditorStateChange}
      />
      {
        console.log('editorState => ', draftToHtml(convertToRaw(editorState.getCurrentContent())))
      }
    </div>
  )
}

export default WYSIWYGEditor

</code>```

The <WYSIWYGEditor /> returns the correct value, no prob there, but I don't how to integrate this component to the RFF flow by using name='editor_content' and when the form submit button is clicked.

Any help is much appreciated.

Joe

答:
OK, I found the solution myself by looking at the React-Final-Form website.

In order to use custom solution OR 3rd Party components with <Field> inside your RFF form, you need to add the following:

// main component file with RFF form

```<code>....

<Field
  name="editor_content"
  component={WYSIWYGEditor}
/>

etc...
</code>```

Please note: do not try to pass the component this way component={<WYSIWYGEditor />} otherwise it returns an error about not allowed to pass an Object
DO NOT forget to import the component :)

The example above will pass input and meta to the custom component to collect the data and use it in the form, and this is how:

// WYSIWYGEditor file

```<code>const WYSIWYGEditor = ({ input, meta }) => {
  const [editorState, setEditorState] = useState(EditorState.createEmpty());
  const onEditorStateChange = editorState => {
    setEditorState(editorState)
    return input.onChange(draftToHtml(convertToRaw(editorState.getCurrentContent())))

etc....
  }
</code>```

You'll notice that, in the onEditorStateChange function I have been able to use input from the props, and by using the onChange method I can pass back the returned value to the parent component (RFF form).

I hope this will help someone else.
Happy coding!

Body:
I'm trying to learn how to use React-Final-Form (RFF in short).

I've learnt how to use <Field> component but now I need to add a custom component to use a WYSIWYG editor which is NOT provided by RFF.

So, I've chosen react-draft-wysiwyg.

Ok, first here my form:

const FormComponent = () => {

  const handleSubmitOnClick = () => ({
    news_title,
    news_subtitle,
    editor_content,
    image_url,
  }) => {

    const data = {
      "user": {
        news_title: news_title,
        news_subtitle: news_subtitle,
        editor_content: editor_content <- here the content from the WYSIWYG editor
        image_url: image_url
      }
    }

     // API call here ....
  }

  return (
    <>

News Main Page

      <Form
        onSubmit={handleSubmitOnClick()}
      >
        {
          ({
            handleSubmit,
            values,
            submitting,
          }) => (
          <form onSubmit={handleSubmit} data-testid="form">
            <Field
              name='news_title'
              placeholder='News Title'
              validate={required}
            >
              {({ input, meta, placeholder }) => (

                  <input {...input}
                    type='text'
                    placeholder={placeholder}

                  />

              )}
            </Field>

            <Field
              name='news_subtitle'
              placeholder='News SubTitle'
              validate={required}
            >
              {({ input, meta, placeholder }) => (

                  <input {...input}
                    type='text'
                    placeholder={placeholder}
                  />

              )}
            </Field>

            <WYSIWYGEditor /> **** HERE THE ISSUE ****

            <MyDropzone />
            <button
              type="submit"
              className="signup-button"
              disabled={submitting}
            >
              Continue
            </button>

          </form>
        )}
      </Form>
    </>
  )
}

export default FormComponent;

This is the Editor file:

import React, { useState } from 'react';

// Components
import { EditorState, convertToRaw } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';

// Hooks version of the Class below (done by me)
const WYSIWYGEditor = () => {
  const [editorState, setEditorState] = useState(EditorState.createEmpty());
  const onEditorStateChange = editorState => {
    return setEditorState(editorState)
  }

  return (

      <Editor
        editorState={editorState}
        wrapperClassName="demo-wrapper"
        editorClassName="demo-editor"
        onEditorStateChange={onEditorStateChange}
      />
      {
        console.log('editorState => ', draftToHtml(convertToRaw(editorState.getCurrentContent())))
      }

  )
}

export default WYSIWYGEditor

The <WYSIWYGEditor /> returns the correct value, no prob there, but I don't how to integrate this component to the RFF flow by using name='editor_content' and when the form submit button is clicked.

Any help is much appreciated.

Joe

Body:
OK, I found the solution myself by looking at the React-Final-Form website.

In order to use custom solution OR 3rd Party components with <Field> inside your RFF form, you need to add the following:

// main component file with RFF form

....

<Field
  name="editor_content"
  component={WYSIWYGEditor}
/>

etc...

Please note: do not try to pass the component this way component={<WYSIWYGEditor />} otherwise it returns an error about not allowed to pass an Object
DO NOT forget to import the component :)

The example above will pass input and meta to the custom component to collect the data and use it in the form, and this is how:

// WYSIWYGEditor file

const WYSIWYGEditor = ({ input, meta }) => {
  const [editorState, setEditorState] = useState(EditorState.createEmpty());
  const onEditorStateChange = editorState => {
    setEditorState(editorState)
    return input.onChange(draftToHtml(convertToRaw(editorState.getCurrentContent())))

etc....
  }

You'll notice that, in the onEditorStateChange function I have been able to use input from the props, and by using the onChange method I can pass back the returned value to the parent component (RFF form).

I hope this will help someone else.
Happy coding!


问:
Find the next section by class name
How can I show the next div with class form_section by clicking .btn_next?

$(".form_section").hide();

$(document).on("click", ".btn_next", function(e) {
  $(this).next(".form_section").show();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row form_section">
  <div>
    <div></div>
    <div></div>
    <button class="btn btn-primary btn_next">SHOW NEXT SECTION</button>
  </div>
</div>
<div class="row form_section">
  <div>
    <div></div>
    <div></div>
    <button class="btn btn-primary btn_next">SHOW NEXT SECTION</button>
  </div>
</div>
<div class="row form_section">
  <div>
    <div></div>
    <div></div>
    <button class="btn btn-primary btn_next">SHOW NEXT SECTION</button>
  </div>
</div></code>```

答:
To achieve this you need to traverse the DOM to retrieve the nearest parent .form_section to the button which was clicked, hide it, then get the next .form_section to show.

To do that you can use a combination of closest(), hide(), next() and show(). Try this:

$(document).on("click", ".btn_next", function(e) {
  $(this).closest('.form_section').hide().next(".form_section").show();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.form_section { display: none; }
.form_section:nth-of-type(1) { display: block; }</code>```

1

    <button class="btn btn-primary btn_next">SHOW NEXT SECTION</button>

2

    <button class="btn btn-primary btn_next">SHOW NEXT SECTION</button>

3

    <button class="btn btn-primary btn_next">SHOW NEXT SECTION</button>

```

Note the use of CSS to hide/show the relevant elements when the page loads. This is a better approach than using JS as it avoids the FOUC.

Title: Find the next section by class name

Body:
How can I show the next div with class form_section by clicking .btn_next?

$(".form_section").hide();

$(document).on("click", ".btn_next", function(e) {
  $(this).next(".form_section").show();
});

    <button class="btn btn-primary btn_next">SHOW NEXT SECTION</button>

    <button class="btn btn-primary btn_next">SHOW NEXT SECTION</button>

    <button class="btn btn-primary btn_next">SHOW NEXT SECTION</button>

Body:
To achieve this you need to traverse the DOM to retrieve the nearest parent .form_section to the button which was clicked, hide it, then get the next .form_section to show.

To do that you can use a combination of closest(), hide(), next() and show(). Try this:

$(document).on("click", ".btn_next", function(e) {
  $(this).closest('.form_section').hide().next(".form_section").show();
});

.form_section { display: none; }
.form_section:nth-of-type(1) { display: block; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row form_section">
  <div>
    <div>1</div>
    <div></div>
    <button class="btn btn-primary btn_next">SHOW NEXT SECTION</button>
  </div>
</div>
<div class="row form_section">
  <div>
    <div>2</div>
    <div></div>
    <button class="btn btn-primary btn_next">SHOW NEXT SECTION</button>
  </div>
</div>
<div class="row form_section">
  <div>
    <div>3</div>
    <div></div>
    <button class="btn btn-primary btn_next">SHOW NEXT SECTION</button>
  </div>
</div>

Note the use of CSS to hide/show the relevant elements when the page loads. This is a better approach than using JS as it avoids the FOUC.


问:
Request goes through each line in dictionary: how to fix
```<code>geomap = {
    "UK": ["London", "Manchester", "Liverpool"],
    "Czech Republic": ["Prague", "Brno", "Ostrava"],
    "Slovak Republic": ["Bratislava", "Košice"],
    "USA": ["Washington", "New York", "Detroit"],
    "Germany": ["Berlin", "Hamburg", "Munich"]
}

search = input("Tell me city and I'll tell you country: ")

for country, cities in geomap.items():
  if search in cities:
    print(search, "found in", country)
  else:
    print(search, "not found")
</code>```

outcome:

```<code>London found in UK
London not found
London not found
London not found
London not found
</code>```

Looks like it goes through each line in geomap dictionary. Do you have some ideas how to fix this? Thank you!

desired outcome:

```<code>London -> London found in UK (when IN dictionary)
Paris -> Paris not found (when not)
</code>```

and no extra sentences

答:
You want to break out the loop as soon as you find a match (after printing) or print one single message at the end if the city has not been found:

```<code>geomap = {
    "UK": ["London", "Manchester", "Liverpool"],
    "Czech Republic": ["Prague", "Brno", "Ostrava"],
    "Slovak Republic": ["Bratislava", "Košice"],
    "USA": ["Washington", "New York", "Detroit"],
    "Germany": ["Berlin", "Hamburg", "Munich"]
}

search = input("Tell me city and I'll tell you country: ")

for country, cities in geomap.items():
  if search in cities:
    print(search, "found in", country)
    break
else:
    print(search, "not found")
</code>```

Notice that the else does not align with the if. It is a for/else construct: the else branch is executed only if the loop exits without triggering any break.

There are a few other improvements you can make to the code (e.g. variable naming, printing arguments, etc. but that's more for the CodeReview SE).

Body:
geomap = {
    "UK": ["London", "Manchester", "Liverpool"],
    "Czech Republic": ["Prague", "Brno", "Ostrava"],
    "Slovak Republic": ["Bratislava", "Košice"],
    "USA": ["Washington", "New York", "Detroit"],
    "Germany": ["Berlin", "Hamburg", "Munich"]
}

search = input("Tell me city and I'll tell you country: ")

for country, cities in geomap.items():
  if search in cities:
    print(search, "found in", country)
  else:
    print(search, "not found")

outcome:

London found in UK
London not found
London not found
London not found
London not found

Looks like it goes through each line in geomap dictionary. Do you have some ideas how to fix this? Thank you!

desired outcome:

London -> London found in UK (when IN dictionary)
Paris -> Paris not found (when not)

and no extra sentences

Body:
You want to break out the loop as soon as you find a match (after printing) or print one single message at the end if the city has not been found:

geomap = {
    "UK": ["London", "Manchester", "Liverpool"],
    "Czech Republic": ["Prague", "Brno", "Ostrava"],
    "Slovak Republic": ["Bratislava", "Košice"],
    "USA": ["Washington", "New York", "Detroit"],
    "Germany": ["Berlin", "Hamburg", "Munich"]
}

search = input("Tell me city and I'll tell you country: ")

for country, cities in geomap.items():
  if search in cities:
    print(search, "found in", country)
    break
else:
    print(search, "not found")

Notice that the else does not align with the if. It is a for/else construct: the else branch is executed only if the loop exits without triggering any break.

There are a few other improvements you can make to the code (e.g. variable naming, printing arguments, etc. but that's more for the CodeReview SE).


问:
How to consume api rest passing flink stream as parameter and return this stream transformed
I'm new in apache flink. I have one flink scala project that consume data from kafka cluster and I need to pass the stream result as parameter to consume api that return this stream transformed. Here is my code

```<code>class Testing {
  def main(args: Array[String]): Unit = {}
  def streamTest(): Unit = {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment
    val properties = new Properties()
    properties.setProperty("bootstrap.servers", "test1.server.local:9092,test2.server.local:9092,test3.server.local:9092")
    val consumer_test = new FlinkKafkaConsumer[String]("topic_test", new SimpleStringSchema(), properties)
    consumer_test.setStartFromEarliest()
    val stream =  env.addSource(consumer_test).setParallelism(5)
    val api_test = "http://api-test.server.local/test/?msg=%s"
    // Here I need pass stream as parameter to api and return transformed stream
    env.execute()
  }
}
</code>```

Any Help ?

答: You should use any http/rest library with which you are familiar and then use asyncIO.

Body:
I'm new in apache flink. I have one flink scala project that consume data from kafka cluster and I need to pass the stream result as parameter to consume api that return this stream transformed. Here is my code

class Testing {
  def main(args: Array[String]): Unit = {}
  def streamTest(): Unit = {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment
    val properties = new Properties()
    properties.setProperty("bootstrap.servers", "test1.server.local:9092,test2.server.local:9092,test3.server.local:9092")
    val consumer_test = new FlinkKafkaConsumer[String]("topic_test", new SimpleStringSchema(), properties)
    consumer_test.setStartFromEarliest()
    val stream =  env.addSource(consumer_test).setParallelism(5)
    val api_test = "http://api-test.server.local/test/?msg=%s"
    // Here I need pass stream as parameter to api and return transformed stream
    env.execute()
  }
}

Any Help ?


问:
Installing Snowflake JDBC driver
I am trying to install Snowflake JDBC driver according to instructions.

I have downloaded and installed Java from here, then downloaded snowflake-jdbc-3.6.9.jar file from here.   When I double-click the file, nothing happens. So I opened CMD and tried this:

```<code>java -jar snowflake-jdbc-3.6.9.jar
</code>```

I received *no main manifest attribute, in snowflake-jdbc-3.6.9.jar*.

When I open META-INF\MANIFEST.MF file, I do see:

```<code>*Manifest-Version: 1.0*

*Main-Class: net.snowflake.client.jdbc.SnowflakeDriver*
</code>```

I have gotten this far using suggestions from other StackOverflow topics, and don't know what else to try. I don't know much about Java, I just need to install this driver, so I could connect to Snowflake from a BI tool.  I would really appreciate your help.

答:
I presume you got it up and running by now.

But as mentioned by one of the other responders, by copying the .jar file to your computer you have already more or less installed the driver.

Different from OBDC drivers, there is no JDBC manager, which expects that JDBC drivers need always to be installed in a certain directory.

You have to point the used application to this driver to use this driver.

Let's take as an example dBeaver, a popular JDBC Query tool among Snowflaker users. (And available for Windows, Mac and Linux)

Before you can use this driver within dBeaver, dBeaver has to be made aware that this driver does exist and can be used.

So after starting up dBeaver you first point dBeaver to the location where you have put the Snowflake .jar file.

(Let's assume that you don't want to use the preconfigured Snowflake JDBC driver for the sake of usefulness of my answer)

So you select New and select 'create new driver'

Under the windows [Libraries] you can add a file or a folder.
Select [Add File] and point at your JDBC .jar file.

As of then you can use the JDBC driver.

For completeness are here the other details to use a different Snowflake JDBC driver than the provided one in dBeaver:

```<code>[Driver Type:] Snowflake
[Class Name:] net.snowflake.client.jdbc.SnowflakeDriver
[URL Template:] this contains the default connectstring format to use this JDBC driver (So how a connectstring should look like to make a successful connection to Snowflake)

[Default Port:] 443 (should have been preset)
</code>```

The rest should be self explanatory.

Title: Installing Snowflake JDBC driver

Body:
I am trying to install Snowflake JDBC driver according to instructions.

I have downloaded and installed Java from here, then downloaded snowflake-jdbc-3.6.9.jar file from here.   When I double-click the file, nothing happens. So I opened CMD and tried this:

java -jar snowflake-jdbc-3.6.9.jar

I received *no main manifest attribute, in snowflake-jdbc-3.6.9.jar*.

When I open META-INF\MANIFEST.MF file, I do see:

*Manifest-Version: 1.0*

*Main-Class: net.snowflake.client.jdbc.SnowflakeDriver*

I have gotten this far using suggestions from other StackOverflow topics, and don't know what else to try. I don't know much about Java, I just need to install this driver, so I could connect to Snowflake from a BI tool.  I would really appreciate your help.

Body:
I presume you got it up and running by now.

But as mentioned by one of the other responders, by copying the .jar file to your computer you have already more or less installed the driver.

Different from OBDC drivers, there is no JDBC manager, which expects that JDBC drivers need always to be installed in a certain directory.

You have to point the used application to this driver to use this driver.

Let's take as an example dBeaver, a popular JDBC Query tool among Snowflaker users. (And available for Windows, Mac and Linux)

Before you can use this driver within dBeaver, dBeaver has to be made aware that this driver does exist and can be used.

So after starting up dBeaver you first point dBeaver to the location where you have put the Snowflake .jar file.

(Let's assume that you don't want to use the preconfigured Snowflake JDBC driver for the sake of usefulness of my answer)

So you select New and select 'create new driver'

Under the windows [Libraries] you can add a file or a folder.
Select [Add File] and point at your JDBC .jar file.

As of then you can use the JDBC driver.

For completeness are here the other details to use a different Snowflake JDBC driver than the provided one in dBeaver:

[Driver Type:] Snowflake
[Class Name:] net.snowflake.client.jdbc.SnowflakeDriver
[URL Template:] this contains the default connectstring format to use this JDBC driver (So how a connectstring should look like to make a successful connection to Snowflake)

[Default Port:] 443 (should have been preset)

The rest should be self explanatory.


问:
C# 2captcha image post with Base64
C# 2captcha image post

```<code>         HttpClient client = new HttpClient();
         var bytes = File.ReadAllBytes("sample.jpg");

         var base64 =   Convert.ToBase64String(bytes);

         var secretKey = "8ffa...";
         var url = "https://2captcha.com/in.php?key=" + secretKey;

         using ( client = new HttpClient())
         {
             var content = new StringContent(base64);

             var response = await client.PostAsync(url , content);

             var stringResponse = await response.Content.ReadAsStringAsync();

             Console.WriteLine(stringResponse);
             Console.ReadLine();
</code>```

My every response is ERROR_ZERO_CAPTCHA_FILESIZE and i don't know what's the problem.

答:
ERROR_ZERO_CAPTCHA_FILESIZE means that image size is less than 100 bytes (NOT kilobytes). You need to check thoroughly if you're sending image correctly.
Here is the sample of a proper Base64 sample form:

```<code><form method="post" action="https://2captcha.com/in.php">
<input type="hidden" name="method" value="base64">
<input type="text" name="key" value="YOUR_APIKEY">
<textarea name="body">BASE64_FILE</textarea>
<input type="submit" value="Upload and get the ID">
</form>
</code>```

Maybe the problem is in your sample.jpg file. Try to encode to base64 a real captcha picture (you can take one on the 2captcha sign-in page actually).
Your base64 text string must have a weight of an image file, so it must be at least a few kilobytes.

Title: C# 2captcha image post with Base64

Body:
C# 2captcha image post

         HttpClient client = new HttpClient();
         var bytes = File.ReadAllBytes("sample.jpg");

         var base64 =   Convert.ToBase64String(bytes);

         var secretKey = "8ffa...";
         var url = "https://2captcha.com/in.php?key=" + secretKey;

         using ( client = new HttpClient())
         {
             var content = new StringContent(base64);

             var response = await client.PostAsync(url , content);

             var stringResponse = await response.Content.ReadAsStringAsync();

             Console.WriteLine(stringResponse);
             Console.ReadLine();

My every response is ERROR_ZERO_CAPTCHA_FILESIZE and i don't know what's the problem.

Body:
ERROR_ZERO_CAPTCHA_FILESIZE means that image size is less than 100 bytes (NOT kilobytes). You need to check thoroughly if you're sending image correctly.
Here is the sample of a proper Base64 sample form:

<form method="post" action="https://2captcha.com/in.php">
<input type="hidden" name="method" value="base64">
<input type="text" name="key" value="YOUR_APIKEY">
<textarea name="body">BASE64_FILE</textarea>
<input type="submit" value="Upload and get the ID">
</form>

Maybe the problem is in your sample.jpg file. Try to encode to base64 a real captcha picture (you can take one on the 2captcha sign-in page actually).
Your base64 text string must have a weight of an image file, so it must be at least a few kilobytes.


问:
How to mock clock.millis() in Java
I have a code where I calculate the difference between current clock time and time saved in my db
If difference between the two is greater than certain value then I return result accordingly.
For this case I am trying to write test but is facing problem to mock Clock.millis(). I have referred some answers but none worked for me can someone help me with that.

For my test I want to mock this clock.millis() function with a fixed value so that each time I run test it takes that value only.

答: You need to wrap Clockinto your own class, exposing Clock.millis() as a delegate. In your test you can then mock your wrapper and return whatever you like.

Title: How to mock clock.millis() in Java


问:
Find and replace with regex by defining beginning and end of string
How would I replace in PhpStorm (it is not important I guess) all occurrences of (selecting string which starts with {!! and ends with !!}):

{!! $arr['my.key.1234'] !!}
to {!! $arr('my.key.1234') !!}
(note change in braces)

I tried to select the key with this regex:
\{\!\! \$arr\[.*.] !!}  which works but how do I now replace it?

EDIT:

I only want to select array key which is variable so my regex doesn't work - it selects whole line.

答:
You can search like this with phpstorm:

(\{\!\!.+\$.+)(\[) replace by $1(

(])(.*\!\!}$) replace by )$2

Don't forget to check the box regex in search toolbar.


问:
How could i define a function at run-time in c
I am trying to define and call a function at run-time with c language in arm cpu(cortex a72). in order to do that, i implemented a code like below:

```<code>#include <stdio.h>
#include <sys/mman.h>

char* ibuf;
int   pbuf = 0;
#define ADD_BYTE(val) do{ibuf[pbuf] = val; pbuf++;} while(0)
void (*routine)(void);

void MakeRoutineSimpleFunc(void)
{
    //nop
    ADD_BYTE(0x00);
    ADD_BYTE(0xf0);
    ADD_BYTE(0x20);
    ADD_BYTE(0xe3);

    //bx lr
    ADD_BYTE(0x1e);
    ADD_BYTE(0xff);
    ADD_BYTE(0x2f);
    ADD_BYTE(0xe1);
}

int main(void)
{
    ibuf = (char*)mmap(NULL, 4 * 1024, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_POPULATE | MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
    MakeRoutineSimpleFunc();
    routine = (void(*)())(ibuf);
    routine();
}
</code>```

as you can see, in above code at first i allocate an executable memory region and assign address of that to ibuf, then i put some simple instruction in ibuf (a "nop" and "bx lr" that means return in arm) and then i try to call this function through a function pointer.

but when i want to call function through function pointer i got an "segmentation fault" error. BTW when i try to run the app with GDB debugger program run successfully without any error.

there is anything that i missed in above code that cause "segmentation fault"?

i want to add, when i add above instructions (a "nop" and "bx lr" that means return in arm) at compile-time to a function like below, function work without any error.

```<code>void f2(void)
{
    __asm__ volatile (".byte 0x00, 0xf0, 0x20, 0xe3");
    __asm__ volatile (".byte 0x1e, 0xff, 0x2f, 0xe1");
}
</code>```

EDIT1:
in order to check validity of run-time function, i have removed f2 prolog and epilogue with ghidra disassembler, so assembly code of f2 is like this:

```<code>**************************************************************
FUNCTION
**************************************************************
undefined FUN_0000083c()
undefined         r0:1           <RETURN>
undefined4        Stack[-0x4]:4  local_4
FUN_0000083c                                    XREF[1]: FUN_00000868:000008a4(c)
        0000083c 00 f0 20 e3     nop
        00000840 00 f0 20 e3     nop
        00000844 00 f0 20 e3     nop
        00000848 00 f0 20 e3     nop
        0000084c 00 f0 20 e3     nop
        00000850 00 f0 20 e3     nop
        00000854 1e ff 2f e1     bx         lr
        00000858 00 f0 20 e3     nop
        0000085c 00 f0 20 e3     nop
        00000860 00 f0 20 e3     nop
        00000864 00 f0 20 e3     nop
</code>```

and also it work again without problem.

EDIT2:
something that i want to add that may be helpful to solve the problem, as i saw in the assembler, compiler call "routine" function with "blx r3" instruction while it call other functions with "bl 'symbol name'". as i know blx can change processor state from ARM to Thumb or vise versa. could this point cause the problem?

EDIT3:
disassemble of main function is something like below:

```<code>**************************************************************
FUNCTION
**************************************************************
int __stdcall main(void)
int               r0:4           <RETURN>
undefined4        Stack[-0xc]:4  local_c                                 XREF[1]:     00010d44(W)
undefined4        Stack[-0x10]:4 local_10                                XREF[1]:     00010d4c(W)
                             main                                            XREF[4]:     Entry Point(*),
                                                                                _start:00010394(*), 000103a8(*),
                                                                                .debug_frame::000000a0(*)
        00010d34 00 48 2d e9     stmdb      sp!,{ r11 lr }
        00010d38 04 b0 8d e2     add        r11,sp,#0x4
        00010d3c 08 d0 4d e2     sub        sp,sp,#0x8
        00010d40 00 30 a0 e3     mov        r3,#0x0
        00010d44 04 30 8d e5     str        r3,[sp,#local_c]
        00010d48 00 30 e0 e3     mvn        r3,#0x0
        00010d4c 00 30 8d e5     str        r3,[sp,#0x0]=>local_10
        00010d50 22 30 a0 e3     mov        r3,#0x22
        00010d54 07 20 a0 e3     mov        r2,#0x7
        00010d58 01 1a a0 e3     mov        r1,#0x1000
        00010d5c 00 00 a0 e3     mov        r0,#0x0
        00010d60 7d fd ff eb     bl         mmap
        00010d64 00 20 a0 e1     cpy        r2,r0
        00010d68 50 30 9f e5     ldr        r3,[->ibuf]
        00010d6c 00 20 83 e5     str        r2,[r3,#0x0]=>ibuf
        00010d70 48 30 9f e5     ldr        r3,[->ibuf]
        00010d74 00 30 93 e5     ldr        r3,[r3,#0x0]=>ibuf
        00010d78 03 10 a0 e1     cpy        r1,r3
        00010d7c 40 00 9f e5     ldr        r0=>s_ibuf:_%x_00010e40,[PTR_s_ibuf:_%x_00010d
        00010d80 69 fd ff eb     bl         printf
        00010d84 ae fe ff eb     bl         MakeRoutineSimpleFunc
        00010d88 30 30 9f e5     ldr        r3,[->ibuf]
        00010d8c 00 30 93 e5     ldr        r3,[r3,#0x0]=>ibuf
        00010d90 03 20 a0 e1     cpy        r2,r3
        00010d94 2c 30 9f e5     ldr        r3,[->routine]
        00010d98 00 20 83 e5     str        r2,[r3,#0x0]=>routine
        00010d9c 24 30 9f e5     ldr        r3,[->routine]
        00010da0 00 30 93 e5     ldr        r3,[r3,#0x0]=>routine
        00010da4 33 ff 2f e1     blx        r3
        00010da8 1c 00 9f e5     ldr        r0=>DAT_00010e4c,
        00010dac 61 fd ff eb     bl         puts
        00010db0 00 30 a0 e3     mov        r3,#0x0
        00010db4 03 00 a0 e1     cpy        r0,r3
        00010db8 04 d0 4b e2     sub        sp,r11,#0x4
        00010dbc 00 88 bd e8     ldmia      sp!,{ r11 pc }
</code>```

as you can see, routine called with "blx r3" instruction at address "00010da4". and also i printed address of ibuf, it is was "0xb6ff8000".

答: I think, you can enter the opcodes directly in a string "binary-code" and execute the code using ((void*)STRING)().  However, you may want to read also about how gcc implements trampolines, because this is how gcc generates code that creates code on the stack and jumps the execution there.

Body:
I am trying to define and call a function at run-time with c language in arm cpu(cortex a72). in order to do that, i implemented a code like below:

#include <stdio.h>
#include <sys/mman.h>

char* ibuf;
int   pbuf = 0;
#define ADD_BYTE(val) do{ibuf[pbuf] = val; pbuf++;} while(0)
void (*routine)(void);

void MakeRoutineSimpleFunc(void)
{
    //nop
    ADD_BYTE(0x00);
    ADD_BYTE(0xf0);
    ADD_BYTE(0x20);
    ADD_BYTE(0xe3);

    //bx lr
    ADD_BYTE(0x1e);
    ADD_BYTE(0xff);
    ADD_BYTE(0x2f);
    ADD_BYTE(0xe1);
}

int main(void)
{
    ibuf = (char*)mmap(NULL, 4 * 1024, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_POPULATE | MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
    MakeRoutineSimpleFunc();
    routine = (void(*)())(ibuf);
    routine();
}

as you can see, in above code at first i allocate an executable memory region and assign address of that to ibuf, then i put some simple instruction in ibuf (a "nop" and "bx lr" that means return in arm) and then i try to call this function through a function pointer.

but when i want to call function through function pointer i got an "segmentation fault" error. BTW when i try to run the app with GDB debugger program run successfully without any error.

there is anything that i missed in above code that cause "segmentation fault"?

i want to add, when i add above instructions (a "nop" and "bx lr" that means return in arm) at compile-time to a function like below, function work without any error.

void f2(void)
{
    __asm__ volatile (".byte 0x00, 0xf0, 0x20, 0xe3");
    __asm__ volatile (".byte 0x1e, 0xff, 0x2f, 0xe1");
}

EDIT1:
in order to check validity of run-time function, i have removed f2 prolog and epilogue with ghidra disassembler, so assembly code of f2 is like this:

**************************************************************
FUNCTION
**************************************************************
undefined FUN_0000083c()
undefined         r0:1           <RETURN>
undefined4        Stack[-0x4]:4  local_4
FUN_0000083c                                    XREF[1]: FUN_00000868:000008a4(c)
        0000083c 00 f0 20 e3     nop
        00000840 00 f0 20 e3     nop
        00000844 00 f0 20 e3     nop
        00000848 00 f0 20 e3     nop
        0000084c 00 f0 20 e3     nop
        00000850 00 f0 20 e3     nop
        00000854 1e ff 2f e1     bx         lr
        00000858 00 f0 20 e3     nop
        0000085c 00 f0 20 e3     nop
        00000860 00 f0 20 e3     nop
        00000864 00 f0 20 e3     nop

and also it work again without problem.

EDIT2:
something that i want to add that may be helpful to solve the problem, as i saw in the assembler, compiler call "routine" function with "blx r3" instruction while it call other functions with "bl 'symbol name'". as i know blx can change processor state from ARM to Thumb or vise versa. could this point cause the problem?

EDIT3:
disassemble of main function is something like below:

**************************************************************
FUNCTION
**************************************************************
int __stdcall main(void)
int               r0:4           <RETURN>
undefined4        Stack[-0xc]:4  local_c                                 XREF[1]:     00010d44(W)
undefined4        Stack[-0x10]:4 local_10                                XREF[1]:     00010d4c(W)
                             main                                            XREF[4]:     Entry Point(*),
                                                                                _start:00010394(*), 000103a8(*),
                                                                                .debug_frame::000000a0(*)
        00010d34 00 48 2d e9     stmdb      sp!,{ r11 lr }
        00010d38 04 b0 8d e2     add        r11,sp,#0x4
        00010d3c 08 d0 4d e2     sub        sp,sp,#0x8
        00010d40 00 30 a0 e3     mov        r3,#0x0
        00010d44 04 30 8d e5     str        r3,[sp,#local_c]
        00010d48 00 30 e0 e3     mvn        r3,#0x0
        00010d4c 00 30 8d e5     str        r3,[sp,#0x0]=>local_10
        00010d50 22 30 a0 e3     mov        r3,#0x22
        00010d54 07 20 a0 e3     mov        r2,#0x7
        00010d58 01 1a a0 e3     mov        r1,#0x1000
        00010d5c 00 00 a0 e3     mov        r0,#0x0
        00010d60 7d fd ff eb     bl         mmap
        00010d64 00 20 a0 e1     cpy        r2,r0
        00010d68 50 30 9f e5     ldr        r3,[->ibuf]
        00010d6c 00 20 83 e5     str        r2,[r3,#0x0]=>ibuf
        00010d70 48 30 9f e5     ldr        r3,[->ibuf]
        00010d74 00 30 93 e5     ldr        r3,[r3,#0x0]=>ibuf
        00010d78 03 10 a0 e1     cpy        r1,r3
        00010d7c 40 00 9f e5     ldr        r0=>s_ibuf:_%x_00010e40,[PTR_s_ibuf:_%x_00010d
        00010d80 69 fd ff eb     bl         printf
        00010d84 ae fe ff eb     bl         MakeRoutineSimpleFunc
        00010d88 30 30 9f e5     ldr        r3,[->ibuf]
        00010d8c 00 30 93 e5     ldr        r3,[r3,#0x0]=>ibuf
        00010d90 03 20 a0 e1     cpy        r2,r3
        00010d94 2c 30 9f e5     ldr        r3,[->routine]
        00010d98 00 20 83 e5     str        r2,[r3,#0x0]=>routine
        00010d9c 24 30 9f e5     ldr        r3,[->routine]
        00010da0 00 30 93 e5     ldr        r3,[r3,#0x0]=>routine
        00010da4 33 ff 2f e1     blx        r3
        00010da8 1c 00 9f e5     ldr        r0=>DAT_00010e4c,
        00010dac 61 fd ff eb     bl         puts
        00010db0 00 30 a0 e3     mov        r3,#0x0
        00010db4 03 00 a0 e1     cpy        r0,r3
        00010db8 04 d0 4b e2     sub        sp,r11,#0x4
        00010dbc 00 88 bd e8     ldmia      sp!,{ r11 pc }

as you can see, routine called with "blx r3" instruction at address "00010da4". and also i printed address of ibuf, it is was "0xb6ff8000".


问:
How to find multiple indexes of a letter inside a word? (Python)
So I'm making a hanging man game and I have run into a problem regarding indexes. Basically, I want to find the index of a letter inside a secret word, the problem is that if the secret word includes two letters that are the same, for instance, "guacamole", where the letter a has the index of 2 and 4 but when I want to find the index of a, it only prints "2" and not "4". Is there a way around this? Thanks in advance!

Part of code where problem occurs:

```<code>for letter in secret_word:
    if user_guess == letter:
        current_word_index = secret_word.find(letter)
        print(current_word_index) #Not in full program, only to test errors.
</code>```

Full code:

```<code>#Hanging man

import string

space = "\v"

dbl_space = "\n"

secret_word = str(input("Enter a secret word: "))

guess_low = list(string.ascii_lowercase)

used_letters = []

user_errors = 0

user_errors_max = 1

secret_word_index = int(len(secret_word))

secret_word_placeholder = list(range(secret_word_index))

while user_errors != user_errors_max:
    user_guess = str(input("Enter a letter: "))
    if len(user_guess) != 1:
        print("You have to pick one letter")
    if user_guess in guess_low:
        guess_low.remove(user_guess)
        used_letters.extend(user_guess)
        print(used_letters)
    for letter in secret_word:
        if user_guess == letter:
            current_word_index = secret_word.find(letter)

if user_errors == user_errors_max:
    print("You lost the game, the secret word was: " + secret_word)
</code>```

答:
This is an example of what you are trying to achieve. use list comprehension.

```<code>string='hello'
letter='l'
[idx for idx,ch in enumerate(string) if ch==letter]
</code>```

Body:
So I'm making a hanging man game and I have run into a problem regarding indexes. Basically, I want to find the index of a letter inside a secret word, the problem is that if the secret word includes two letters that are the same, for instance, "guacamole", where the letter a has the index of 2 and 4 but when I want to find the index of a, it only prints "2" and not "4". Is there a way around this? Thanks in advance!

Part of code where problem occurs:

for letter in secret_word:
    if user_guess == letter:
        current_word_index = secret_word.find(letter)
        print(current_word_index) #Not in full program, only to test errors.

Full code:

#Hanging man

import string

space = "\v"

dbl_space = "\n"

secret_word = str(input("Enter a secret word: "))

guess_low = list(string.ascii_lowercase)

used_letters = []

user_errors = 0

user_errors_max = 1

secret_word_index = int(len(secret_word))

secret_word_placeholder = list(range(secret_word_index))

while user_errors != user_errors_max:
    user_guess = str(input("Enter a letter: "))
    if len(user_guess) != 1:
        print("You have to pick one letter")
    if user_guess in guess_low:
        guess_low.remove(user_guess)
        used_letters.extend(user_guess)
        print(used_letters)
    for letter in secret_word:
        if user_guess == letter:
            current_word_index = secret_word.find(letter)

if user_errors == user_errors_max:
    print("You lost the game, the secret word was: " + secret_word)

Body:
This is an example of what you are trying to achieve. use list comprehension.

string='hello'
letter='l'
[idx for idx,ch in enumerate(string) if ch==letter]


问:
How do I pass data from method _callLogs to body and print it?
I'm new to using flutter framework and I want to pass call logs to my app so I can print them. How do I do that?</p>

```<code>class _QuoteListState extends State<QuoteList> {

   Future<bool>_callLogs() async {
     Iterable<CallLogEntry> entries = await CallLog.get();

   }

 @override
 Widget build(BuildContext context) {
   return Scaffold(
     backgroundColor: Colors.grey[200],
     appBar: AppBar(
       title: Text('Calls Log'),
       centerTitle: true,
       backgroundColor: Colors.purple,
     ),
     body: ListView.builder(
       itemCount: entries.length,
       itemBuilder: (context, index){

       }
     )
   );
</code>```

答:
You can use Future Builder to achieve so.

Following minimal code simulate you conditions, so you can implement in your own code.

```<code>import 'package:flutter/material.dart';

class DeleteWidget extends StatefulWidget {
  const DeleteWidget({Key key}) : super(key: key);

  @override
  _DeleteWidgetState createState() => _DeleteWidgetState();
}

class _DeleteWidgetState extends State<DeleteWidget> {
  @override
  void initState() {
    super.initState();
  }

  List<int> _data;

  Future<bool> _callLogs() async {
    await Future.delayed(Duration(seconds: 4));
    _data = [6, 5, 4, 3, 2, 1];
    return true;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Center(
          child: FutureBuilder(
            future: _callLogs(),
            builder: (context, snapshot) {
              if (!snapshot.hasError) {
                if (snapshot.data == true) {
                  return ListView.builder(
                    itemCount: _data.length,
                    itemBuilder: (context, index) {
                      return Text(_data[index].toString());
                    },
                  );
                } else {
                  return Text("Whatever when it returns false");
                }
              } else {
                return Text("Something wents wrong");
              }
            },
          ),
        ),
      ),
    );
  }
}
</code>```

Body:
I'm new to using flutter framework and I want to pass call logs to my app so I can print them. How do I do that?

class _QuoteListState extends State<QuoteList> {

   Future<bool>_callLogs() async {
     Iterable<CallLogEntry> entries = await CallLog.get();

   }

 @override
 Widget build(BuildContext context) {
   return Scaffold(
     backgroundColor: Colors.grey[200],
     appBar: AppBar(
       title: Text('Calls Log'),
       centerTitle: true,
       backgroundColor: Colors.purple,
     ),
     body: ListView.builder(
       itemCount: entries.length,
       itemBuilder: (context, index){

       }
     )
   );

Body:
You can use Future Builder to achieve so.

Following minimal code simulate you conditions, so you can implement in your own code.

import 'package:flutter/material.dart';

class DeleteWidget extends StatefulWidget {
  const DeleteWidget({Key key}) : super(key: key);

  @override
  _DeleteWidgetState createState() => _DeleteWidgetState();
}

class _DeleteWidgetState extends State<DeleteWidget> {
  @override
  void initState() {
    super.initState();
  }

  List<int> _data;

  Future<bool> _callLogs() async {
    await Future.delayed(Duration(seconds: 4));
    _data = [6, 5, 4, 3, 2, 1];
    return true;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Center(
          child: FutureBuilder(
            future: _callLogs(),
            builder: (context, snapshot) {
              if (!snapshot.hasError) {
                if (snapshot.data == true) {
                  return ListView.builder(
                    itemCount: _data.length,
                    itemBuilder: (context, index) {
                      return Text(_data[index].toString());
                    },
                  );
                } else {
                  return Text("Whatever when it returns false");
                }
              } else {
                return Text("Something wents wrong");
              }
            },
          ),
        ),
      ),
    );
  }
}


问:
Receive webhook or other kind of ping from Sanity when a document is published?
I have a backend that stores data in Sanity.io, and I would like to configure Sanity to ping my app when a document is published, so that I can clear any cached data. This way I can greatly reduce traffic between my app and Sanity. Possible?</p>

答: Have you looked at the webhooks documentation?  https://www.sanity.io/docs/webhooks</p>


问:
How to display the activity indicator
After clicking the Login Button in the login screen i need to display a transparent View with activity indicator in the middle(spinning) and after some time that should disappear and the next view should be loaded.

please help me in this aspect

thanks
rizwan

答:
Place an Activity Indicator View in the middle of the view, selects its style so that it is visible (white or grey), select "hides when stopped", call:

```<code>[activity startAnimating];
</code>```

the activityView will be visible and animating. Then do whatever you want to do, call NSTimer or whatever and when the timer get triggered or your action is finished clal:

```<code>[activity stopAnimating];
</code>```

and the activity view will stop spinning and hide.

Other than using the stock Activity Indicator View you may find useful controls on www.cocoacontrols.com, for exmaple MBProgressHUD's screenshot looks like it were also a candidate for what you want to do.

Title: How to display the activity indicator

Body:
Place an Activity Indicator View in the middle of the view, selects its style so that it is visible (white or grey), select "hides when stopped", call:

[activity startAnimating];

the activityView will be visible and animating. Then do whatever you want to do, call NSTimer or whatever and when the timer get triggered or your action is finished clal:

[activity stopAnimating];

and the activity view will stop spinning and hide.

Other than using the stock Activity Indicator View you may find useful controls on www.cocoacontrols.com, for exmaple MBProgressHUD's screenshot looks like it were also a candidate for what you want to do.


问:
Delete a folder already exist php
I have created folder based on year and month (while I upload image), eg: if I upload an pdf on February 1 2018 then I have created folder 2018 and folder 2.

```<code> $filename = $_SERVER['DOCUMENT_ROOT'] . '/' . 'folder1/admin/slip' . '/' . $year . '';
                    $filename2 = $filename . '/' . $month;
                    if (file_exists($filename)) {
                        if (file_exists($filename2) == false) {
                            mkdir($filename2, 0777);
                        }
                    } else {
                        mkdir($filename, 0777);
                    }
</code>```

If I again upload an pdf in February, I want to delete this folder and create it again. I use the following code

```<code>rmdir($filename2)
</code>```

but its not working.

please help me

答:
Use this function for delete file.</p>

```<code>unlink( $filepath)
</code>```

Title: Delete a folder already exist php

Body:
I have created folder based on year and month (while I upload image), eg: if I upload an pdf on February 1 2018 then I have created folder 2018 and folder 2.

 $filename = $_SERVER['DOCUMENT_ROOT'] . '/' . 'folder1/admin/slip' . '/' . $year . '';
                    $filename2 = $filename . '/' . $month;
                    if (file_exists($filename)) {
                        if (file_exists($filename2) == false) {
                            mkdir($filename2, 0777);
                        }
                    } else {
                        mkdir($filename, 0777);
                    }

If I again upload an pdf in February, I want to delete this folder and create it again. I use the following code

rmdir($filename2)

but its not working.

please help me

Body:
Use this function for delete file.

unlink( $filepath)


问:
Cancellation token in Task constructor: why?
Certain System.Threading.Tasks.Task constructors take a CancellationToken as a parameter:

```<code>CancellationTokenSource source = new CancellationTokenSource();
Task t = new Task (/* method */, source.Token);
</code>```

What baffles me about this is that there is no way from inside the method body to actually get at the token passed in (e.g., nothing like Task.CurrentTask.CancellationToken). The token has to be provided through some other mechanism, such as the state object or captured  in a lambda.

So what purpose does providing the cancellation token in the constructor serve?

答:
Here is a code example that demonstrates the two points in the accepted answer by Max Galkin:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("*********************************************************************");
        Console.WriteLine("* Start canceled task, don't pass token to constructor");
        Console.WriteLine("*********************************************************************");
        StartCanceledTaskTest(false);
        Console.WriteLine();

        Console.WriteLine("*********************************************************************");
        Console.WriteLine("* Start canceled task, pass token to constructor");
        Console.WriteLine("*********************************************************************");
        StartCanceledTaskTest(true);
        Console.WriteLine();

        Console.WriteLine("*********************************************************************");
        Console.WriteLine("* Throw if cancellation requested, don't pass token to constructor");
        Console.WriteLine("*********************************************************************");
        ThrowIfCancellationRequestedTest(false);
        Console.WriteLine();

        Console.WriteLine("*********************************************************************");
        Console.WriteLine("* Throw if cancellation requested, pass token to constructor");
        Console.WriteLine("*********************************************************************");
        ThrowIfCancellationRequestedTest(true);
        Console.WriteLine();

        Console.WriteLine();
        Console.WriteLine("Test Completed!!!");
        Console.ReadKey();
    }

    static void StartCanceledTaskTest(bool passTokenToConstructor)
    {
        Console.WriteLine("Creating task");
        CancellationTokenSource tokenSource = new CancellationTokenSource();
        Task task = null;
        if (passTokenToConstructor)
        {
            task = new Task(() => TaskWork(tokenSource.Token, false), tokenSource.Token);

        }
        else
        {
            task = new Task(() => TaskWork(tokenSource.Token, false));
        }

        Console.WriteLine("Canceling task");
        tokenSource.Cancel();

        try
        {
            Console.WriteLine("Starting task");
            task.Start();
            task.Wait();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: {0}", ex.Message);
            if (ex.InnerException != null)
            {
                Console.WriteLine("InnerException: {0}", ex.InnerException.Message);
            }
        }

        Console.WriteLine("Task.Status: {0}", task.Status);
    }

    static void ThrowIfCancellationRequestedTest(bool passTokenToConstructor)
    {
        Console.WriteLine("Creating task");
        CancellationTokenSource tokenSource = new CancellationTokenSource();
        Task task = null;
        if (passTokenToConstructor)
        {
            task = new Task(() => TaskWork(tokenSource.Token, true), tokenSource.Token);

        }
        else
        {
            task = new Task(() => TaskWork(tokenSource.Token, true));
        }

        try
        {
            Console.WriteLine("Starting task");
            task.Start();
            Thread.Sleep(100);

            Console.WriteLine("Canceling task");
            tokenSource.Cancel();
            task.Wait();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: {0}", ex.Message);
            if (ex.InnerException != null)
            {
                Console.WriteLine("InnerException: {0}", ex.InnerException.Message);
            }
        }

        Console.WriteLine("Task.Status: {0}", task.Status);
    }

    static void TaskWork(CancellationToken token, bool throwException)
    {
        int loopCount = 0;

        while (true)
        {
            loopCount++;
            Console.WriteLine("Task: loop count {0}", loopCount);

            token.WaitHandle.WaitOne(50);
            if (token.IsCancellationRequested)
            {
                Console.WriteLine("Task: cancellation requested");
                if (throwException)
                {
                    token.ThrowIfCancellationRequested();
                }

                break;
            }
        }
    }
}
```
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>*********************************************************************
* Start canceled task, don't pass token to constructor
*********************************************************************
Creating task
Canceling task
Starting task
Task: loop count 1
Task: cancellation requested
Task.Status: RanToCompletion

*********************************************************************
* Start canceled task, pass token to constructor
*********************************************************************
Creating task
Canceling task
Starting task
Exception: Start may not be called on a task that has completed.
Task.Status: Canceled

*********************************************************************
* Throw if cancellation requested, don't pass token to constructor
*********************************************************************
Creating task
Starting task
Task: loop count 1
Task: loop count 2
Canceling task
Task: cancellation requested
Exception: One or more errors occurred.
InnerException: The operation was canceled.
Task.Status: Faulted

*********************************************************************
* Throw if cancellation requested, pass token to constructor
*********************************************************************
Creating task
Starting task
Task: loop count 1
Task: loop count 2
Canceling task
Task: cancellation requested
Exception: One or more errors occurred.
InnerException: A task was canceled.
Task.Status: Canceled

Test Completed!!!
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Certain System.Threading.Tasks.Task constructors take a CancellationToken as a parameter:

CancellationTokenSource source = new CancellationTokenSource();
Task t = new Task (/* method */, source.Token);

What baffles me about this is that there is no way from inside the method body to actually get at the token passed in (e.g., nothing like Task.CurrentTask.CancellationToken). The token has to be provided through some other mechanism, such as the state object or captured  in a lambda.

So what purpose does providing the cancellation token in the constructor serve?

Body:
Here is a code example that demonstrates the two points in the accepted answer by Max Galkin:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("*********************************************************************");
        Console.WriteLine("* Start canceled task, don't pass token to constructor");
        Console.WriteLine("*********************************************************************");
        StartCanceledTaskTest(false);
        Console.WriteLine();

        Console.WriteLine("*********************************************************************");
        Console.WriteLine("* Start canceled task, pass token to constructor");
        Console.WriteLine("*********************************************************************");
        StartCanceledTaskTest(true);
        Console.WriteLine();

        Console.WriteLine("*********************************************************************");
        Console.WriteLine("* Throw if cancellation requested, don't pass token to constructor");
        Console.WriteLine("*********************************************************************");
        ThrowIfCancellationRequestedTest(false);
        Console.WriteLine();

        Console.WriteLine("*********************************************************************");
        Console.WriteLine("* Throw if cancellation requested, pass token to constructor");
        Console.WriteLine("*********************************************************************");
        ThrowIfCancellationRequestedTest(true);
        Console.WriteLine();

        Console.WriteLine();
        Console.WriteLine("Test Completed!!!");
        Console.ReadKey();
    }

    static void StartCanceledTaskTest(bool passTokenToConstructor)
    {
        Console.WriteLine("Creating task");
        CancellationTokenSource tokenSource = new CancellationTokenSource();
        Task task = null;
        if (passTokenToConstructor)
        {
            task = new Task(() => TaskWork(tokenSource.Token, false), tokenSource.Token);

        }
        else
        {
            task = new Task(() => TaskWork(tokenSource.Token, false));
        }

        Console.WriteLine("Canceling task");
        tokenSource.Cancel();

        try
        {
            Console.WriteLine("Starting task");
            task.Start();
            task.Wait();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: {0}", ex.Message);
            if (ex.InnerException != null)
            {
                Console.WriteLine("InnerException: {0}", ex.InnerException.Message);
            }
        }

        Console.WriteLine("Task.Status: {0}", task.Status);
    }

    static void ThrowIfCancellationRequestedTest(bool passTokenToConstructor)
    {
        Console.WriteLine("Creating task");
        CancellationTokenSource tokenSource = new CancellationTokenSource();
        Task task = null;
        if (passTokenToConstructor)
        {
            task = new Task(() => TaskWork(tokenSource.Token, true), tokenSource.Token);

        }
        else
        {
            task = new Task(() => TaskWork(tokenSource.Token, true));
        }

        try
        {
            Console.WriteLine("Starting task");
            task.Start();
            Thread.Sleep(100);

            Console.WriteLine("Canceling task");
            tokenSource.Cancel();
            task.Wait();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: {0}", ex.Message);
            if (ex.InnerException != null)
            {
                Console.WriteLine("InnerException: {0}", ex.InnerException.Message);
            }
        }

        Console.WriteLine("Task.Status: {0}", task.Status);
    }

    static void TaskWork(CancellationToken token, bool throwException)
    {
        int loopCount = 0;

        while (true)
        {
            loopCount++;
            Console.WriteLine("Task: loop count {0}", loopCount);

            token.WaitHandle.WaitOne(50);
            if (token.IsCancellationRequested)
            {
                Console.WriteLine("Task: cancellation requested");
                if (throwException)
                {
                    token.ThrowIfCancellationRequested();
                }

                break;
            }
        }
    }
}

Output:

*********************************************************************
* Start canceled task, don't pass token to constructor
*********************************************************************
Creating task
Canceling task
Starting task
Task: loop count 1
Task: cancellation requested
Task.Status: RanToCompletion

*********************************************************************
* Start canceled task, pass token to constructor
*********************************************************************
Creating task
Canceling task
Starting task
Exception: Start may not be called on a task that has completed.
Task.Status: Canceled

*********************************************************************
* Throw if cancellation requested, don't pass token to constructor
*********************************************************************
Creating task
Starting task
Task: loop count 1
Task: loop count 2
Canceling task
Task: cancellation requested
Exception: One or more errors occurred.
InnerException: The operation was canceled.
Task.Status: Faulted

*********************************************************************
* Throw if cancellation requested, pass token to constructor
*********************************************************************
Creating task
Starting task
Task: loop count 1
Task: loop count 2
Canceling task
Task: cancellation requested
Exception: One or more errors occurred.
InnerException: A task was canceled.
Task.Status: Canceled

Test Completed!!!


问:
C++: Rotating point around origin, but output point is not correct by some margin
first time asking.
I want to rotate a point in 3d in c++ in the XY Plane and am using the following function for the task.

void rotateXY(double angle){
    //save the x and y and z coordinates in seperate variables
    double x = this->pos[0]; // value 1
    double y = this->pos[1]; // value 0
    double z = this->pos[2]; // value 0, but in the xy rotation it is not important
    double radian = angle*M_PI/180;

    this->pos[0] = cos(radian)*x - sin(radian)*y;
    this->pos[1] = sin(radian)*x + cos(radian)*y;
    this->pos[2] = 1*z;
};
```

<p>I got the matrix from https://gamedevelopment.tutsplus.com/tutorials/lets-build-a-3d-graphics-engine-linear-transformations--gamedev-7716</p>

<p>In this I am directly manipulating the coordinates of the point, hence the this->pos[0]</p>

<p>If I call another function called rotateXYP where I first substract a mathematical vector from the rotating point and add the same mathematical vector to it after the rotate I get the wanted results.</p>

<pre class="lang-cpp prettyprint-override"><code>void rotateXYP(double angle, eng::point originOfRotation){
    this->subVec(originOfRotation);
    this->rotateXY(angle);
    this->addVec(originOfRotation);
};

void rotateXY(double angle){
    //save x,y and z in seperate variables for manipulation
    double x = this->pos[0]; // value 1
    double y = this->pos[1]; // value 0
    double z = this->pos[2]; // value 0, but in the xy rotation it is not important
    //convert from degrees to radians because cmath requires it
    double radian = angle*M_PI/180;
    //apply the values according to a rotation matrix found on the internet
    this->pos[0] = cos(radian)*x - sin(radian)*y;
    this->pos[1] = sin(radian)*x + cos(radian)*y;
    this->pos[2] = 1*z;
};
</code>```

My Question

Why am I getting with the point (1|0|0) as an input to the function rotateXY(90) the follwing as an output.

```<code>(6.12323e-17|1|0)
</code>```

instead of

```<code>(0|1|0)
</code>```

and if I call the function rotateXYP(90, some point), I get the correct point, without the tiny number on the x-coordinate.
I suspect it has something to do with the cos and sin in the following line of code:

```<code>this->pos[0] = cos(radian)*x - sin(radian)*y;
</code>```

As I am too inexperienced with c++ I seek answeres and hope that this was not a bad question.

答:
Your implementation is correct. This is just the nature of floating point arithmetic. All numbers are represented as approximations. When translating the point you get a better numeric condition.

I might add that this effect will occur independent of the programming language and hardware used.

Body:
first time asking.
I want to rotate a point in 3d in c++ in the XY Plane and am using the following function for the task.

void rotateXY(double angle){
    //save the x and y and z coordinates in seperate variables
    double x = this->pos[0]; // value 1
    double y = this->pos[1]; // value 0
    double z = this->pos[2]; // value 0, but in the xy rotation it is not important
    double radian = angle*M_PI/180;

    this->pos[0] = cos(radian)*x - sin(radian)*y;
    this->pos[1] = sin(radian)*x + cos(radian)*y;
    this->pos[2] = 1*z;
};

I got the matrix from https://gamedevelopment.tutsplus.com/tutorials/lets-build-a-3d-graphics-engine-linear-transformations--gamedev-7716

In this I am directly manipulating the coordinates of the point, hence the this->pos[0]

If I call another function called rotateXYP where I first substract a mathematical vector from the rotating point and add the same mathematical vector to it after the rotate I get the wanted results.

void rotateXYP(double angle, eng::point originOfRotation){
    this->subVec(originOfRotation);
    this->rotateXY(angle);
    this->addVec(originOfRotation);
};

void rotateXY(double angle){
    //save x,y and z in seperate variables for manipulation
    double x = this->pos[0]; // value 1
    double y = this->pos[1]; // value 0
    double z = this->pos[2]; // value 0, but in the xy rotation it is not important
    //convert from degrees to radians because cmath requires it
    double radian = angle*M_PI/180;
    //apply the values according to a rotation matrix found on the internet
    this->pos[0] = cos(radian)*x - sin(radian)*y;
    this->pos[1] = sin(radian)*x + cos(radian)*y;
    this->pos[2] = 1*z;
};

My Question

Why am I getting with the point (1|0|0) as an input to the function rotateXY(90) the follwing as an output.

(6.12323e-17|1|0)

instead of

(0|1|0)

and if I call the function rotateXYP(90, some point), I get the correct point, without the tiny number on the x-coordinate.
I suspect it has something to do with the cos and sin in the following line of code:

this->pos[0] = cos(radian)*x - sin(radian)*y;

As I am too inexperienced with c++ I seek answeres and hope that this was not a bad question.


问:
UnknownHostException when trying to access oracle database server hosted locally from PCF
I have a spring boot JPA application that works fine locally by connecting to the oracle database which also running locally.

But when I deploy my application to pivotal cloud foundry it gives below exception  while connecting to local database server:

2020-02-08T15:13:27.499+05:30 [APP/PROC/WEB/0] [OUT] Caused by: java.net.UnknownHostException: DESKTOP-619LJLN: Name or service not known
2020-02-08T15:13:27.499+05:30 [APP/PROC/WEB/0] [OUT] at java.net.Inet4AddressImpl.lookupAllHostAddr(Native Method) ~[na:1.8.0_242]
2020-02-08T15:13:27.499+05:30 [APP/PROC/WEB/0] [OUT] at java.net.InetAddress$2.lookupAllHostAddr(InetAddress.java:929) ~[na:1.8.0_242]

application.properties as below:

```<code>spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
spring.jpa.hibernate.ddl-auto=update
security.require-ssl=false
spring.datasource.url=jdbc:oracle:thin:AVINASH_DB/oracle@DESKTOP-659FJUK:1522:xe
</code>```

I tried using cups in PCF but its not working.Kindly let me know how to connect local databse from PCF.
note: i dont want to use database services in pcf market place.trying to figureout how to connect external db from pcf.
Thanks in advance

答:
Add DNS information to the network at opsmanager dashboard-> bosh director tile to let PAS identify the host in the DB.
Temporarily you can use oracle DB's IP in your app.</p>

Body:
I have a spring boot JPA application that works fine locally by connecting to the oracle database which also running locally.

But when I deploy my application to pivotal cloud foundry it gives below exception  while connecting to local database server:

2020-02-08T15:13:27.499+05:30 [APP/PROC/WEB/0] [OUT] Caused by: java.net.UnknownHostException: DESKTOP-619LJLN: Name or service not known
2020-02-08T15:13:27.499+05:30 [APP/PROC/WEB/0] [OUT] at java.net.Inet4AddressImpl.lookupAllHostAddr(Native Method) ~[na:1.8.0_242]
2020-02-08T15:13:27.499+05:30 [APP/PROC/WEB/0] [OUT] at java.net.InetAddress$2.lookupAllHostAddr(InetAddress.java:929) ~[na:1.8.0_242]

application.properties as below:

spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
spring.jpa.hibernate.ddl-auto=update
security.require-ssl=false
spring.datasource.url=jdbc:oracle:thin:AVINASH_DB/oracle@DESKTOP-659FJUK:1522:xe

I tried using cups in PCF but its not working.Kindly let me know how to connect local databse from PCF.
note: i dont want to use database services in pcf market place.trying to figureout how to connect external db from pcf.
Thanks in advance


问:
Convert ODT to PDF file in C# ASP.NET (and adding content)
I was wondering what the best way is to convert an ODT file to a PDF while also adding content to that file.

I don't know what routes are possible (library-wise) to make this work:

ODT > edit > PDF

ODT > PDF > edit

ODT > HTML > edit > PDF

ODT > DOC(X) > edit > PDF

The API I'm building is using C# ASP.NET, version 3.1. I have been looking for multiple hours what the best way is to get started on this but I'm really struggling to find the right library. I never really used too many libraries before so I don't know where to look and what I exactly need. I tried looking on NuGet packages in Visual Studio 2019 but none seem to work with ODT but DOCX or HTML. Anyone that has experience with this and could tell me on what I should do?

答:
The solution I found is:

Convert my .odt files to .html files using cloudconvert. This can also be done in batches. However, you might have to do this manually.

Use Html Agility Pack to edit the .html files before making them .pdf files.

Use iText7 with the pdfHTML extension to generate my PDF files from the .html files.


问:
How can we center title of react-navigation header?
React-navigation docs are still young, and reading through the issues is not working quite much for me (changes on each version) does anyone have a working method to center title in Android using react-navigation in React Native?

答:
On React Navigation v5 the only way I managed to center a View was to use it like this:</p>

```<code> <MainStack.Navigator
  screenOptions={{
    headerTitleAlign: 'center',
  }}>

 ...

  <MainStack.Screen
    ...
    options={({navigation, route}) => ({
      headerTitle: () => <ViewButton />,
    ...
    })}
</code>```

Body:
On React Navigation v5 the only way I managed to center a View was to use it like this:

 <MainStack.Navigator
  screenOptions={{
    headerTitleAlign: 'center',
  }}>

 ...

  <MainStack.Screen
    ...
    options={({navigation, route}) => ({
      headerTitle: () => <ViewButton />,
    ...
    })}