问:
What is the difference between a theme and a template?
I am trying to migrate my site to Drupal and I am confused about themes and templates. The look and feel of the pages in my current site are completely controlled by template files and CSS. How does it work in Drupal?</p>

答:
A theme is made up of a collection of template files. block.tpl.php, node.tpl.php, page.tpl.php are all template files which when combined with your CSS, JS and images produces a theme. In addition a themes can be inherited. A theme can be created with just CSS and no additional template files by inheriting from an existing theme, in which case the template files from the parent theme are used.

Another way to look at it is a theme is what you see and the template files are responsible for generating the markup.

I hope this makes it a little bit clearer.

OwnerDisplayName: Joana

LastEditorDisplayName: Eddie

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: canen


来源: stackexchange

问:
Data type for large amounts of text?
I'm developing a Java package that makes basic HTTP requests (GET, POST, PUT, and DELETE). Right now, I'm having it just print the output of the request. I would like to store it in a field, but I'm not sure if String supports large amounts of text. Is there a data type for large amounts of text, or is there a reasonable alternative to it? Right now, because I'm just printing it, I can't do anything with the data that is returned (like parse it, if it's JSON).

Any ideas would be helpful.

Edit: The code is online on GitHub.

答: I see that you use BufferedReader in your code. You can just leave the string in there and pass that reader to your JSON parser for instance. Would be more efficient than first creating a String out of it.

ContentLicense: CC BY-SA 3.0

Title: Data type for large amounts of text?


问:
Running a SavedModel in TensorFlow 2 with inputs of a specific type
I'm trying to run an object detection model I have prepared in SavedModel format in TensorFlow 2.

The model takes inputs in the format of a byte-encoded JPEG, PNG, or GIF as encoded_image_string_tensor:0 and outputs the typical detection_scores:0, detection_boxes:0, etc.

In TensorFlow 1.15, I can do the following operations:

with tf.Session(graph=tf.Graph()) as sess:
    tf.saved_model.loader.load(sess, ["serve"], path_to_model)
    cap = cv2.VideoCapture(camera_id)
    ret, frame = cap.read()
    ret, encoded = cv2.imencode(".jpg", frame)
    inferred = sess.run(["detection_scores:0", "detection_boxes:0"], feed_dict={
        "encoded_image_string_tensor:0": [encoded.tobytes(),]
    })
    # Use the outputs from here
```

<p>I've been trying to convert this code to use TensorFlow 2's new APIs instead of the compatibility libraries, but I keep running into roadblocks. Here's the code I have been trying to use with TensorFlow 2:</p>

<pre class="lang-py prettyprint-override"><code>loaded = tf.saved_model.load(path_to_model)
infer = loaded.signatures["serving_default"]
# `encoded` is the same as the prior example,
# and TF2 is always requesting "image_bytes" and "key" as inputs
prediction = infer(image_bytes=encoded.tobytes(), key="")
"""
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py", line 1551, in __call__
    return self._call_impl(args, kwargs)
  File "venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py", line 1591, in _call_impl
    return self._call_flat(args, self.captured_inputs, cancellation_manager)
  File "venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py", line 1684, in _call_flat
    "Tensor." % (self._func_graph.name, i, str(arg)))
ValueError: All inputs to `ConcreteFunction`s must be Tensors; on invocation of pruned, the 0-th input (b'...') was not a Tensor.
"""
</code>```

Is there a functional TensorFlow 2.x equivalent to the TensorFlow 1.x code that doesn't use the compatibility libraries, or am I approaching this the completely wrong way?

I've been referencing the SavedModel documentation from TensorFlow, available here: https://www.tensorflow.org/guide/saved_model.

答:
The immediate problem seems to be:

```<code>All inputs to `ConcreteFunction`s must be Tensors...
</code>```

So instead of passing in encoded.tobytes() maybe try passing in tf.convert_to_tensor(encoded.tobytes()).

Alternatively, check out the documentation for tf.io.encode_jpeg, which seems to provide image-specific tensor convertion.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to run an object detection model I have prepared in SavedModel format in TensorFlow 2.

The model takes inputs in the format of a byte-encoded JPEG, PNG, or GIF as encoded_image_string_tensor:0 and outputs the typical detection_scores:0, detection_boxes:0, etc.

In TensorFlow 1.15, I can do the following operations:

with tf.Session(graph=tf.Graph()) as sess:
    tf.saved_model.loader.load(sess, ["serve"], path_to_model)
    cap = cv2.VideoCapture(camera_id)
    ret, frame = cap.read()
    ret, encoded = cv2.imencode(".jpg", frame)
    inferred = sess.run(["detection_scores:0", "detection_boxes:0"], feed_dict={
        "encoded_image_string_tensor:0": [encoded.tobytes(),]
    })
    # Use the outputs from here

I've been trying to convert this code to use TensorFlow 2's new APIs instead of the compatibility libraries, but I keep running into roadblocks. Here's the code I have been trying to use with TensorFlow 2:

loaded = tf.saved_model.load(path_to_model)
infer = loaded.signatures["serving_default"]
# `encoded` is the same as the prior example,
# and TF2 is always requesting "image_bytes" and "key" as inputs
prediction = infer(image_bytes=encoded.tobytes(), key="")
"""
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py", line 1551, in __call__
    return self._call_impl(args, kwargs)
  File "venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py", line 1591, in _call_impl
    return self._call_flat(args, self.captured_inputs, cancellation_manager)
  File "venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py", line 1684, in _call_flat
    "Tensor." % (self._func_graph.name, i, str(arg)))
ValueError: All inputs to `ConcreteFunction`s must be Tensors; on invocation of pruned, the 0-th input (b'...') was not a Tensor.
"""

Is there a functional TensorFlow 2.x equivalent to the TensorFlow 1.x code that doesn't use the compatibility libraries, or am I approaching this the completely wrong way?

I've been referencing the SavedModel documentation from TensorFlow, available here: https://www.tensorflow.org/guide/saved_model.

Body:
The immediate problem seems to be:

All inputs to `ConcreteFunction`s must be Tensors...

So instead of passing in encoded.tobytes() maybe try passing in tf.convert_to_tensor(encoded.tobytes()).

Alternatively, check out the documentation for tf.io.encode_jpeg, which seems to provide image-specific tensor convertion.


问:
Concatenate strings from array in PHP ignoring blanks
Similar to this question but for PHP.  I want to concatenate an array of strings but ignore blanks.

For instance, suppose I want to build a full_name attribute in Laravel using $this->title, $this->first_name, and $this->last_name, each separated by single space.  The simplest thought I had was to put them all into an array and pass it into implode() as in below:

implode(' ', [$this->title, $this->first_name, $this->last_name]);
```

<p>However I don't know whether those values are actually going to be set or not.  And if they are set, I don't want empty strings to pollute the output with multiple spaces between non-empty elements.  Is there a built-in function or at least a simpler/shorter way to do the below?</p>

<pre class="lang-php prettyprint-override"><code>public function concatenateStringsFromArray($glue = ' ', $arrayOfStrings)
{
    $result = '';
    foreach($arrayOfStrings as $piece)
        $result .= isset($piece) ? $piece . $glue : '';
    return $result;
}
</code>```

答:
array_filter() should do the trick.
Simply calling implode($glue,array_filter($array)) should give you what you want, by filtering out all elements of the given array which resolve to false (0, null and '' among others). If you need 0 or other values which resolve to boolean false as valid values you can use a custom callback:

```<code>array_filter($array, function($value) { return !is_null($value) && $value !== ''; })
</code>```

Body:
Similar to this question but for PHP.  I want to concatenate an array of strings but ignore blanks.

For instance, suppose I want to build a full_name attribute in Laravel using $this->title, $this->first_name, and $this->last_name, each separated by single space.  The simplest thought I had was to put them all into an array and pass it into implode() as in below:

implode(' ', [$this->title, $this->first_name, $this->last_name]);

However I don't know whether those values are actually going to be set or not.  And if they are set, I don't want empty strings to pollute the output with multiple spaces between non-empty elements.  Is there a built-in function or at least a simpler/shorter way to do the below?

public function concatenateStringsFromArray($glue = ' ', $arrayOfStrings)
{
    $result = '';
    foreach($arrayOfStrings as $piece)
        $result .= isset($piece) ? $piece . $glue : '';
    return $result;
}

Body:
array_filter() should do the trick.
Simply calling implode($glue,array_filter($array)) should give you what you want, by filtering out all elements of the given array which resolve to false (0, null and '' among others). If you need 0 or other values which resolve to boolean false as valid values you can use a custom callback:

array_filter($array, function($value) { return !is_null($value) && $value !== ''; })


问:
Has it occured to you that a GitLab repository that had deletion pending was not deleted after deadline passed?
According to new GitLab rules, if you delete a repo, this deletion is executed with some delay ( one week ), the deletion deadline is shown in the repo head ( you can revert this decision up to the deadline ).

My repo was to be deleted on 18th February. Now it is 19th February and the repo is still there, and still says it will be deleted on 18th February. ( An other repo of mine that had deletion pending on 18th February, was deleted in due course. ) Is this a common thing? Has this happened to you?

答:
Check first if it is a timezone issue, meaning if it is supposed to be deleted at an UTC hour which would mean:

it is still the 18th

even though it is already 19th in your zone

If not, check the logs for any error message regarding that repository.

The OP sbtpr adds in the comments:

I waited patiently, out of curiosity, to see what happens, and voila, after almost an other week passed, on 24th February, my repo was deleted.

So I'd better factor in that with GitLab deleting a repo may take 2 weeks.

Note that a pending deletion status can also be canceled.

See GitLab 14.9 (March 2022)

Users can recover projects pending deletion

In previous versions of GitLab, only Administrators could see projects that were pending deletion.

With GitLab 14.9, all users can now view the Pending deletion tab.

Project and group owners can view and recover projects that were accidentally deleted and
have not yet been permanently removed from disk. This means users can recover their own accidentally deleted projects without needing to direct all recovery requests to an Administrator.

To see the tab, on the top bar, select Menu > Projects > Pending deletion.

See Documentation and Issue.


问:
Android Nougat PopupWindow showAsDropDown(...) Gravity not working
I have this code.

```<code>PopupWindow popUp = new PopupWindow();
popUp.setFocusable(true);
popUp.setOutsideTouchable(true);
popUp.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
popUp.setHeight(600);

popUp.setContentView(anchorView);
popUp.showAsDropDown(anchorView);
popUp.update();
</code>```

And its perfectly works on Android Version < Android Nougat. But in Android Nougat, the popup is being displayed at the top of the screen instead of relative to the anchor view.

答:
In Android API 29, I fixed by replacing popup width and height as WRAP_CONTENT. As in my code in Kotlin.

```<code>private fun createSpinnerLikePopUp() {
        val inflater = context?.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        val vw = inflater.inflate(R.layout.dialog_window, null, false)
            popUp = PopupWindow(context).apply {
            isFocusable = true
            width = WindowManager.LayoutParams.WRAP_CONTENT
            height = WindowManager.LayoutParams.WRAP_CONTENT
            contentView = vw
            setBackgroundDrawable(null)
        }
        vw!!.recyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = RecyclerAdapter(context, myArray)
        }
    }
</code>```

And button click as follows:

```<code>displayPopupBtn.setOnClickListener { view ->
            if (popUp != null) {
                if (popUp.isShowing) {
                    popUp.dismiss()
                } else {
                    popUp.showAsDropDown(view)
                }
            }
        }
</code>```

Body:
I have this code.

PopupWindow popUp = new PopupWindow();
popUp.setFocusable(true);
popUp.setOutsideTouchable(true);
popUp.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
popUp.setHeight(600);

popUp.setContentView(anchorView);
popUp.showAsDropDown(anchorView);
popUp.update();

And its perfectly works on Android Version < Android Nougat. But in Android Nougat, the popup is being displayed at the top of the screen instead of relative to the anchor view.

Body:
In Android API 29, I fixed by replacing popup width and height as WRAP_CONTENT. As in my code in Kotlin.

private fun createSpinnerLikePopUp() {
        val inflater = context?.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        val vw = inflater.inflate(R.layout.dialog_window, null, false)
            popUp = PopupWindow(context).apply {
            isFocusable = true
            width = WindowManager.LayoutParams.WRAP_CONTENT
            height = WindowManager.LayoutParams.WRAP_CONTENT
            contentView = vw
            setBackgroundDrawable(null)
        }
        vw!!.recyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = RecyclerAdapter(context, myArray)
        }
    }

And button click as follows:

displayPopupBtn.setOnClickListener { view ->
            if (popUp != null) {
                if (popUp.isShowing) {
                    popUp.dismiss()
                } else {
                    popUp.showAsDropDown(view)
                }
            }
        }


问:
Dependency Property: Getting but not Setting
```<code>public static readonly DependencyProperty SingleGridLengthProperty = DependencyProperty.Register("SingleGridLength", typeof(double), typeof(MapConverter));

public class MapConverter : DependencyObject, INotifyPropertyChanged, IMultiValueConverter
{
    public double SingleGridLength
    {
        get { return (double)GetValue(MapConverter.SingleGridLengthProperty); }
        set
        {
            SetValue(MapConverter.SingleGridLengthProperty, value);
            OnNotifyPropertyChanged("SingleGridLength");
        }
    }

<local:MapConverter x:Key="MapConverter"
SingleGridLength="{Binding SingleGridLength, RelativeSource={RelativeSource Self}}" />
</code>```

I have a converter with a set of dependency properties bound in the .xaml

The problem I am having is each property is "getting" and returning the value but it never "sets" the value. Am I allowed to use dependency properties in converters? Or should I be approaching this a different way? Thanks in advance!

答:
First, your binding is invalid. You are binding the SingleGridLength property to itself. You would need to bind it to another property/object.

Second, you shouldn't raise the OnNotifyPropertyChanged in the setter for your SingleGridLength property. You only need to do that for regular CLR properties. Dependency properties have a built in change notification system that Binding hooks into.

Body:
public static readonly DependencyProperty SingleGridLengthProperty = DependencyProperty.Register("SingleGridLength", typeof(double), typeof(MapConverter));

public class MapConverter : DependencyObject, INotifyPropertyChanged, IMultiValueConverter
{
    public double SingleGridLength
    {
        get { return (double)GetValue(MapConverter.SingleGridLengthProperty); }
        set
        {
            SetValue(MapConverter.SingleGridLengthProperty, value);
            OnNotifyPropertyChanged("SingleGridLength");
        }
    }

<local:MapConverter x:Key="MapConverter"
SingleGridLength="{Binding SingleGridLength, RelativeSource={RelativeSource Self}}" />

I have a converter with a set of dependency properties bound in the .xaml

The problem I am having is each property is "getting" and returning the value but it never "sets" the value. Am I allowed to use dependency properties in converters? Or should I be approaching this a different way? Thanks in advance!


问:
Error while uploading a file in wordpress "Unable to create directory wp-content/uploads. Is its parent directory writable by the server?"
I am using wordpress 5.3.2 , while uploading any media ,plugin or theme file I am getting error

"Unable to create directory wp-content/uploads. Is its parent directory writable by the server?"

I had check all the permission of parent folder and permission is 755.

Still I am getting the same error.

答:
It must be issue of File Permission Follow The Following Steps.

1.To give all permissions to a folder give chmod -R 777:

```<code>sudo chmod 755 -R /path/to/directory
</code>```

or
    sudo chmod a+rwx /path/to/directory

or
Yo Can Also Give Permission Via Filezilla Parent Directory Recursively.

2.In wp-config.php
Add Code Before require_once(ABSPATH . 'wp-settings.php');

```<code>define( 'UPLOADS', 'wp-content/uploads' );
define('FS_METHOD', 'direct');
</code>```

Hope This Will Be Helpful.
https://wp-me.com/fix-unable-to-create-directory-wp-content-uploads-is-its-parent-directory-writable-by-the-server/

Body:
It must be issue of File Permission Follow The Following Steps.

1.To give all permissions to a folder give chmod -R 777:

sudo chmod 755 -R /path/to/directory

or
    sudo chmod a+rwx /path/to/directory

or
Yo Can Also Give Permission Via Filezilla Parent Directory Recursively.

2.In wp-config.php
Add Code Before require_once(ABSPATH . 'wp-settings.php');

define( 'UPLOADS', 'wp-content/uploads' );
define('FS_METHOD', 'direct');

Hope This Will Be Helpful.
https://wp-me.com/fix-unable-to-create-directory-wp-content-uploads-is-its-parent-directory-writable-by-the-server/


问:
chrome browser is not opening with robot framework
getting error :     WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally.   (unknown error: DevToolsActivePort file doesn't exist)   (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed

getting above error while running a robot script:
It is a simple code to open you tube in chrome browser.
it looks like this:

```<code>*** Settings ***
Library  SeleniumLibrary

*** Variables ***
${Browser}  Chrome
${URL}  https://www.youtube.com/

*** Test Cases ***
TC1
    Open Browser  ${URL}  ${Browser}
    Input Text  name:search_query  ted talk
    Click Button  id:search-icon-legacy
</code>```

It is on ubuntu
using python2.7

robotframework==3.0.2

robotframework-mqttlibrary==0.7.0

robotframework-selenium2library==1.8.0

robotframework-seleniumlibrary==4.3.0

ChromeDriver 80.0.3987.106

I tried updating chrome and chrome driver also.
I don't know what am i doing wrong,
please help.

答:
You are trying with robotframework-seleniumlibrary==4.3.0 & robotframework==3.0.2

Update the robotframework-seleniumlibrary 4.3.0 to 3.0.1

pip install robotframework-seleniumlibrary==3.0.1

Add capabilities

```<code>${chrome_options}=    Evaluate    sys.modules['selenium.webdriver'].ChromeOptions()    sys, selenium.webdriver

Call Method    ${chrome_options}    add_experimental_option    w3c    ${False}
Call Method    ${chrome_options}    add_argument    no-sandbox
Call Method    ${chrome_options}    add_argument    disable-setuid-sandbox
Call Method    ${chrome_options}    add_argument    disable-dev-shm-usage
Call Method    ${chrome_options}    add_argument    disable-single-click-autofill

Wait Until Keyword Succeeds    2x    1s
...    Create WebDriver    Chrome    alias=${Browser}    chrome_options=${chrome_options}

Go To    ${URL}
Input Text  name:search_query  ted talk
Click Button  id:search-icon-legacy
</code>```

Body:
getting error :     WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally.   (unknown error: DevToolsActivePort file doesn't exist)   (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed

getting above error while running a robot script:
It is a simple code to open you tube in chrome browser.
it looks like this:

*** Settings ***
Library  SeleniumLibrary

*** Variables ***
${Browser}  Chrome
${URL}  https://www.youtube.com/

*** Test Cases ***
TC1
    Open Browser  ${URL}  ${Browser}
    Input Text  name:search_query  ted talk
    Click Button  id:search-icon-legacy

It is on ubuntu
using python2.7

robotframework==3.0.2

robotframework-mqttlibrary==0.7.0

robotframework-selenium2library==1.8.0

robotframework-seleniumlibrary==4.3.0

ChromeDriver 80.0.3987.106

I tried updating chrome and chrome driver also.
I don't know what am i doing wrong,
please help.

Body:
You are trying with robotframework-seleniumlibrary==4.3.0 & robotframework==3.0.2

Update the robotframework-seleniumlibrary 4.3.0 to 3.0.1

pip install robotframework-seleniumlibrary==3.0.1

Add capabilities

${chrome_options}=    Evaluate    sys.modules['selenium.webdriver'].ChromeOptions()    sys, selenium.webdriver

Call Method    ${chrome_options}    add_experimental_option    w3c    ${False}
Call Method    ${chrome_options}    add_argument    no-sandbox
Call Method    ${chrome_options}    add_argument    disable-setuid-sandbox
Call Method    ${chrome_options}    add_argument    disable-dev-shm-usage
Call Method    ${chrome_options}    add_argument    disable-single-click-autofill

Wait Until Keyword Succeeds    2x    1s
...    Create WebDriver    Chrome    alias=${Browser}    chrome_options=${chrome_options}

Go To    ${URL}
Input Text  name:search_query  ted talk
Click Button  id:search-icon-legacy


问:
Jupyter Notebook not saving: '_xsrf' argument missing from post
I've been running a script on jupyter notebooks for about 26 hour; I haven't really been using my computer for anything else, but it needs to run this program that will take ~30 hours to complete. At about 21 hours in, it stopped saving and my terminal had this:

```<code>403 PUT /api/contents/[file.ipynb] (::1): '_xsrf' argument missing from POST
</code>```

where [file.ipynb] is the location of my jupyter notebook. It also says:

```<code>'_xsrf' argument missing from post
</code>```

in the top right part of the notebook again. The program is still running and I don't want to restart jupyter notebook and have to run the program again, as I have a deadline, is there anything else I can do?

I'm using google chrome, but I don't have the LastPass extension or any '%' characters in my code, as another post suggested.

Thanks for any help!

答:
This is the easiest way.

I did not need to open a new notebook. Instead, I reopened the tree, and reconnected the kernel. At some point I also restarted the kernel. – user650654 Oct 9 '19 at 0:17

Body:
I've been running a script on jupyter notebooks for about 26 hour; I haven't really been using my computer for anything else, but it needs to run this program that will take ~30 hours to complete. At about 21 hours in, it stopped saving and my terminal had this:

403 PUT /api/contents/[file.ipynb] (::1): '_xsrf' argument missing from POST

where [file.ipynb] is the location of my jupyter notebook. It also says:

'_xsrf' argument missing from post

in the top right part of the notebook again. The program is still running and I don't want to restart jupyter notebook and have to run the program again, as I have a deadline, is there anything else I can do?

I'm using google chrome, but I don't have the LastPass extension or any '%' characters in my code, as another post suggested.

Thanks for any help!


问:
Base64 PDF data IE and Edge does not show up
I have a PDF whose content is encrypted as a base64 string. I am trying to display it in an embed element. It works fine in Chrome and other browsers except Microsoft Edge and Internet Explorer.

```<code>success: function (data, textStatus, xhr) {
  $("#url").html("");
  $("#url").append("<embed src=\"" + data.encodeUrl + "\" class=\"iframe\"></embed>");
  $("#cameraLink").modal('show');
}
</code>```

答:
The Data Protocol are supported only for the following elements and/or attributes:

object (images only)

img

input type=image,

Link

CSS declarations that accept a URL, such as background, backgroundImage, and so on.

As far as I know, Internet Explorer and the legacy version of Microsoft Edge does not support the use of DATA URIs as the source of iframe or embed .

As an alternative workaround, in the IE browser and the legacy version of Microsoft Edge, I suggest you could download the PDF file first, then, using browser to display the PDF file.

You could refer to the following code:

```<code>function myfunction() {
    var data = "[encoded data, 5336 characters]";

    var fileName = "test.pdf";
    //For IE and the legacy version of Microsoft Edge, use atob convert base64 encoded data to byte array
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        var byteCharacters = window.atob(data);
        var byteNumbers = new Array(byteCharacters.length);
        for (var i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        var byteArray = new Uint8Array(byteNumbers);
        var blob = new Blob([byteArray], { type: 'application/pdf' });
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else {
        // Directly use base 64 encoded data for rest browsers (not IE and the legacy version of Microsoft Edge )
        var base64EncodedPDF = data;
        //var pdfWindow = window.open();
        //pdfWindow.document.write('<iframe src="data:application/pdf;base64,' + base64EncodedPDF+'" style="width: 100%; height: 100%;" frameborder="0" scrolling="no"></iframe>');
        var iframe = document.createElement('iframe');
        iframe.src="data:application/pdf;base64," + base64EncodedPDF;
        iframe.style ="width: 100%; height: 100%;";
        document.getElementById("content").append(iframe);
    }
}
</code>```

Body:
I have a PDF whose content is encrypted as a base64 string. I am trying to display it in an embed element. It works fine in Chrome and other browsers except Microsoft Edge and Internet Explorer.

success: function (data, textStatus, xhr) {
  $("#url").html("");
  $("#url").append("<embed src=\"" + data.encodeUrl + "\" class=\"iframe\"></embed>");
  $("#cameraLink").modal('show');
}

Body:
The Data Protocol are supported only for the following elements and/or attributes:

object (images only)

img

input type=image,

Link

CSS declarations that accept a URL, such as background, backgroundImage, and so on.

As far as I know, Internet Explorer and the legacy version of Microsoft Edge does not support the use of DATA URIs as the source of iframe or embed .

As an alternative workaround, in the IE browser and the legacy version of Microsoft Edge, I suggest you could download the PDF file first, then, using browser to display the PDF file.

You could refer to the following code:

function myfunction() {
    var data = "[encoded data, 5336 characters]";

    var fileName = "test.pdf";
    //For IE and the legacy version of Microsoft Edge, use atob convert base64 encoded data to byte array
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        var byteCharacters = window.atob(data);
        var byteNumbers = new Array(byteCharacters.length);
        for (var i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        var byteArray = new Uint8Array(byteNumbers);
        var blob = new Blob([byteArray], { type: 'application/pdf' });
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else {
        // Directly use base 64 encoded data for rest browsers (not IE and the legacy version of Microsoft Edge )
        var base64EncodedPDF = data;
        //var pdfWindow = window.open();
        //pdfWindow.document.write('<iframe src="data:application/pdf;base64,' + base64EncodedPDF+'" style="width: 100%; height: 100%;" frameborder="0" scrolling="no"></iframe>');
        var iframe = document.createElement('iframe');
        iframe.src="data:application/pdf;base64," + base64EncodedPDF;
        iframe.style ="width: 100%; height: 100%;";
        document.getElementById("content").append(iframe);
    }
}


问:
Enable submit button with validation
Here is my code.
The problem I encountered is how do I make the submit button work only when it is 10?

```<code><input type="text" name="qty>
<input type="submit" name="proceedbtn" value="PROCEED" id="button">

<script>
   $(document).ready(function(){
        $('input[id="button"]').attr('disabled',true);
        $('input[id="qty"]').on('keyup',function(){
            if($(this).val() == 10)
            $('input[id="button"]').attr('disabled',false);
    });
});
</script>
</code>```

How do i fix it?

答:
I have made some editions on your code and IT WORKS PERFECTLY!

$(document).ready(function() {
        $('#button').attr('disabled', true);
        $('input[name="qty"]').on('keyup', function () {
            if ($(this).val() == 10) {
                $('#button').attr('disabled', false);
            }else {
                $('#button').attr('disabled', true);
            }
        });
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" name="qty">
<input type="submit" name="proceedbtn" value="PROCEED" id="button">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

Title: Enable submit button with validation

Body:
Here is my code.
The problem I encountered is how do I make the submit button work only when it is 10?

<input type="text" name="qty>
<input type="submit" name="proceedbtn" value="PROCEED" id="button">

How do i fix it?

Body:
I have made some editions on your code and IT WORKS PERFECTLY!

$(document).ready(function() {
        $('#button').attr('disabled', true);
        $('input[name="qty"]').on('keyup', function () {
            if ($(this).val() == 10) {
                $('#button').attr('disabled', false);
            }else {
                $('#button').attr('disabled', true);
            }
        });
    });

<input type="text" name="qty">
<input type="submit" name="proceedbtn" value="PROCEED" id="button">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


问:
How to focus on Electron window when it opens after focussing on another program
I'm creating an Electron app that should show itself when a global shortcut key is pressed. For the shortcut key, I'm using iohook and that part works well.
If I allow the window to be shown as normally during startup of the app, Windows focusses on it (my test is pressing alt to see which menu bar is activated).

The problem is that if I start the program with visible: false or do not generate the Electron.BrowserWindow yet, and then call win.show() or create the window when I press the shortcut key, it opens the window in the foreground but the focus is still on the app that I was on before pressing the shortcut.

I have fixed this in the past with Autohotkey but I want to make this app cross-platorm and preferably contain as much of my code as possible within NodeJS.

答:
Turns out there is a delay in the OS before the window can be focussed on. Calling focus() immediately after show() does nothing (or may in some cases if it wins the race conditions). Using the show event to trigger the focus solves this.

```<code>win.on('show', () => { win.focus(); });
win.show();
</code>```

EDIT: There still seems to be a race condition on the OS level that sometimes causes the window not to be focussed so I still have to add the timeout:

```<code>win.on('show', () => {
  setTimeout(() => {
    win.focus();
  }, 200);
});
</code>```

Body:
Turns out there is a delay in the OS before the window can be focussed on. Calling focus() immediately after show() does nothing (or may in some cases if it wins the race conditions). Using the show event to trigger the focus solves this.

win.on('show', () => { win.focus(); });
win.show();

EDIT: There still seems to be a race condition on the OS level that sometimes causes the window not to be focussed so I still have to add the timeout:

win.on('show', () => {
  setTimeout(() => {
    win.focus();
  }, 200);
});


问:
Get fields from through table in Django
I have two models, organization and vendor, which are connected by a 'relational' or 'through' table, VendorOrganization. There is a field description in my through table, which I am trying to access, but do not know. How should I configure my view, query and serializer to be able to access fields from the through table? Thanks for any help!

// models.py

```<code>class Organization(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=20, unique=True, validators=[alphanumeric_plus_underscore, MinLengthValidator(4)])
    vendors = models.ManyToManyField("thirdparty.Vendor", through="thirdparty.VendorOrganization")

class Vendor(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=60, blank=False, null=False)

class VendorOrganization(models.Model):
    vendor = models.ForeignKey(Vendor, blank=False, null=False, on_delete=models.CASCADE)
    organization = models.ForeignKey(Organization, blank=True, null=False, on_delete=models.DO_NOTHING)
    created_at = models.DateTimeField(_('created at'), auto_now_add=True, null=True)
    created_by_user = models.ForeignKey(User, blank=False, null=False, on_delete=models.DO_NOTHING)
    description = models.CharField(max_length=300, blank=True, null=False)
</code>```

// serializers.py (this does not work to get the 'description' field)

```<code>class VendorSerializer(serializers.ModelSerializer):

class Meta:
    model = Vendor
    fields = ('id', 'name', 'created_at', 'created_by_user', 'description')
    extra_kwargs = {
        'id': {'read_only': True},
        'created_at': {'read_only': True},
    }
</code>```

// views.py

```<code>class VendorView(mixins.DestroyModelMixin, ListAPIView):
    authentication_classes = (TokenAuthentication,)

    def get(self, request):

        pagination_class = None
        current_org = Organization.objects.get(id=request.user.organization.id)
        queryset = current_org.vendors.select_related()
        vendors = VendorSerializer(queryset, many=True)
        return Response(vendors.data)
</code>```

答:
You can pass your organization_id with context to your serializer and in serializer, use SerializerMethodField(). Like that

in your views.py:

```<code>class VendorView(mixins.DestroyModelMixin, ListAPIView):
    #your other codes

     #add this method for pass data to your serializer
     def get_serializer_context(self):
         return {'organization_id': request.user.organization.id}
</code>```

in your serializers.py file

```<code>class VendorSerializer(serializers.ModelSerializer):
    description = serializers.SerializerMethodField()

    class Meta:
        model = Vendor
        fields = ('id', 'name', 'created_at', 'created_by_user', 'description')
        extra_kwargs = {
        'id': {'read_only': True},
        'created_at': {'read_only': True},
    }

    def get_description(self,obj):
        organization = Organization.objects.get(id=self.context['organization_id'])
        return obj.vendororganization_set.filter(organization=organization).first().description()
    #NOTE: You can have multiple vendororganization, so you must set a logic in here.Perhaps you can change your vendor model with OneToOneFieldAnd you must check whether your vendor organziation exists.
</code>```

Title: Get fields from through table in Django

Body:
I have two models, organization and vendor, which are connected by a 'relational' or 'through' table, VendorOrganization. There is a field description in my through table, which I am trying to access, but do not know. How should I configure my view, query and serializer to be able to access fields from the through table? Thanks for any help!

// models.py

class Organization(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=20, unique=True, validators=[alphanumeric_plus_underscore, MinLengthValidator(4)])
    vendors = models.ManyToManyField("thirdparty.Vendor", through="thirdparty.VendorOrganization")

class Vendor(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=60, blank=False, null=False)

class VendorOrganization(models.Model):
    vendor = models.ForeignKey(Vendor, blank=False, null=False, on_delete=models.CASCADE)
    organization = models.ForeignKey(Organization, blank=True, null=False, on_delete=models.DO_NOTHING)
    created_at = models.DateTimeField(_('created at'), auto_now_add=True, null=True)
    created_by_user = models.ForeignKey(User, blank=False, null=False, on_delete=models.DO_NOTHING)
    description = models.CharField(max_length=300, blank=True, null=False)

// serializers.py (this does not work to get the 'description' field)

class VendorSerializer(serializers.ModelSerializer):

class Meta:
    model = Vendor
    fields = ('id', 'name', 'created_at', 'created_by_user', 'description')
    extra_kwargs = {
        'id': {'read_only': True},
        'created_at': {'read_only': True},
    }

// views.py

class VendorView(mixins.DestroyModelMixin, ListAPIView):
    authentication_classes = (TokenAuthentication,)

    def get(self, request):

        pagination_class = None
        current_org = Organization.objects.get(id=request.user.organization.id)
        queryset = current_org.vendors.select_related()
        vendors = VendorSerializer(queryset, many=True)
        return Response(vendors.data)

Body:
You can pass your organization_id with context to your serializer and in serializer, use SerializerMethodField(). Like that

in your views.py:

class VendorView(mixins.DestroyModelMixin, ListAPIView):
    #your other codes

     #add this method for pass data to your serializer
     def get_serializer_context(self):
         return {'organization_id': request.user.organization.id}

in your serializers.py file

class VendorSerializer(serializers.ModelSerializer):
    description = serializers.SerializerMethodField()

    class Meta:
        model = Vendor
        fields = ('id', 'name', 'created_at', 'created_by_user', 'description')
        extra_kwargs = {
        'id': {'read_only': True},
        'created_at': {'read_only': True},
    }

    def get_description(self,obj):
        organization = Organization.objects.get(id=self.context['organization_id'])
        return obj.vendororganization_set.filter(organization=organization).first().description()
    #NOTE: You can have multiple vendororganization, so you must set a logic in here.Perhaps you can change your vendor model with OneToOneFieldAnd you must check whether your vendor organziation exists.


问:
How to create an interface for object and array of objects in Angular 8 and type script?
I'm trying to create an interface for Object, objects, and array of objects.

Sample interface

```<code>export interface ErateColumn {
  categories:{
    [key:string]:column[]
  }
}

interface column {
  label:string
  value:string
}
</code>```

Sample API response like this

```<code>{
"categories": {
    "Basic Information": [
        { label: "Applicant Type", value: "ApplicantType" },
        { label: "Organization Name", value: "OrganizationName" },
    ],
    "FRN Lineitem": [
        { label: "Monthly_Cost", value: "Monthly_Cost" },
        ],
    "FRN status": [
        { label: "Purpose Type", value: "PurposeType" },

    ]
}
}
</code>```

答:
Hope this helps...</p>

```<code>interface User {
   name: string;
   phone: string;
}

const user: User ==> Object

const usersList: User[] ===> Array of Objects
</code>```

Body:
I'm trying to create an interface for Object, objects, and array of objects.

Sample interface

export interface ErateColumn {
  categories:{
    [key:string]:column[]
  }
}

interface column {
  label:string
  value:string
}

Sample API response like this

{
"categories": {
    "Basic Information": [
        { label: "Applicant Type", value: "ApplicantType" },
        { label: "Organization Name", value: "OrganizationName" },
    ],
    "FRN Lineitem": [
        { label: "Monthly_Cost", value: "Monthly_Cost" },
        ],
    "FRN status": [
        { label: "Purpose Type", value: "PurposeType" },

    ]
}
}

Body:
Hope this helps...

interface User {
   name: string;
   phone: string;
}

const user: User ==> Object

const usersList: User[] ===> Array of Objects


问:
Silverlight 4 launch a trusted application into the browser?
I just lost 5 hours looking for a answer which i haven't been able to find :p

First, I'd like to force a trusted application (i need to access the file system) to display into the browser. Based on what i found on google a trusted application must be installed and launched as a desktop application (also called out-of-browser application).

So, i want to have an installed application on the client side but meanwhile, the user must also be able to start this same application into a browser window when he goes on my web site. Is this possible ?

Second, I'd like to give to the user the possibility to start the application from the browser. To be clear, the application is installed on the client computer but i want a button on my web site which starts the desktop application. How can i do that ?

Thanks

答: Yes, it is possbile since Silverlight 5, see my answer on silverlight-4-elevated-permission-inside-the-browser</p>


问:
KNN model (using PCA) outputs same accuracy over each iteration of k
I am fairly new to machine learning techniques and I'm trying to wrap my head around the implementation of PCA and KNN to classify different outputs.

I am using a dataset of handwritten numbers from 0 to 9. The training set has shape of (60000,784) and the testing set has shape of (10000,784). I use PCA to reduce the dimensionality to the first 6 principal components, so now my training set has shape of (60000,6) and testing set has (10000,6). I attempt to perform an iteration over different k values, ranging from 1 to 17, to extract the best possible k value for my application. However, when I do this I keep getting 0.2023 for my accuracy. I feel this is incorrect and was wondering what I could possibly be doing wrong.

Here is my code, where I perform the PCA and my attempt at extracting the optimal K value:

```<code>from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn import metrics
from sklearn.decomposition import PCA

pca = PCA(n_components=6)
train_projected = pca.fit_transform(X_train_norm)
test_projected = pca.fit_transform(X_test_norm)
</code>```

For my normalized arrays, I just divided them by 255 as that is the max possible value.

```<code>k_range = range(1,17)
scores = {};
scores_list = [];
for i in k_range:
    knn = KNeighborsClassifier(n_neighbors=k)
    knn.fit(train_projected,y_train)
    pred = knn.predict(test_projected)
    scores[i] = metrics.accuracy_score(y_test,pred)
    scores_list.append(metrics.accuracy_score(y_test,pred))

print('Scores ', scores,'\n')
print('Scores List ',scores_list,'\n')

Scores  {1: 0.2023, 2: 0.2023, 3: 0.2023, 4: 0.2023, 5: 0.2023, 6: 0.2023, 7: 0.2023, 8: 0.2023, 9: 0.2023, 10: 0.2023, 11: 0.2023, 12: 0.2023, 13: 0.2023, 14: 0.2023, 15: 0.2023, 16: 0.2023, 17: 0.2023, 18: 0.2023, 19: 0.2023, 20: 0.2023, 21: 0.2023, 22: 0.2023, 23: 0.2023, 24: 0.2023, 25: 0.2023, 26: 0.2023}

Scores List  [0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023]
</code>```

答:
Simple mistake!

In this code:

```<code>for i in k_range:
    knn = KNeighborsClassifier(n_neighbors=k)
</code>```

You are setting n_neighbors=k for each iteration. It should be n_neighbors=i

Body:
I am fairly new to machine learning techniques and I'm trying to wrap my head around the implementation of PCA and KNN to classify different outputs.

I am using a dataset of handwritten numbers from 0 to 9. The training set has shape of (60000,784) and the testing set has shape of (10000,784). I use PCA to reduce the dimensionality to the first 6 principal components, so now my training set has shape of (60000,6) and testing set has (10000,6). I attempt to perform an iteration over different k values, ranging from 1 to 17, to extract the best possible k value for my application. However, when I do this I keep getting 0.2023 for my accuracy. I feel this is incorrect and was wondering what I could possibly be doing wrong.

Here is my code, where I perform the PCA and my attempt at extracting the optimal K value:

from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn import metrics
from sklearn.decomposition import PCA

pca = PCA(n_components=6)
train_projected = pca.fit_transform(X_train_norm)
test_projected = pca.fit_transform(X_test_norm)

For my normalized arrays, I just divided them by 255 as that is the max possible value.

k_range = range(1,17)
scores = {};
scores_list = [];
for i in k_range:
    knn = KNeighborsClassifier(n_neighbors=k)
    knn.fit(train_projected,y_train)
    pred = knn.predict(test_projected)
    scores[i] = metrics.accuracy_score(y_test,pred)
    scores_list.append(metrics.accuracy_score(y_test,pred))

print('Scores ', scores,'\n')
print('Scores List ',scores_list,'\n')

Scores  {1: 0.2023, 2: 0.2023, 3: 0.2023, 4: 0.2023, 5: 0.2023, 6: 0.2023, 7: 0.2023, 8: 0.2023, 9: 0.2023, 10: 0.2023, 11: 0.2023, 12: 0.2023, 13: 0.2023, 14: 0.2023, 15: 0.2023, 16: 0.2023, 17: 0.2023, 18: 0.2023, 19: 0.2023, 20: 0.2023, 21: 0.2023, 22: 0.2023, 23: 0.2023, 24: 0.2023, 25: 0.2023, 26: 0.2023}

Scores List  [0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023, 0.2023]

Body:
Simple mistake!

In this code:

for i in k_range:
    knn = KNeighborsClassifier(n_neighbors=k)

You are setting n_neighbors=k for each iteration. It should be n_neighbors=i


问:
Is there a way to toggle/fix a menu while scrolling?
I want to build a Windows Forms App that has a menu (several labels) on it's left side which is toggled. On the right side there should be some columns i can scroll through. Jst like Excel with it's fixed rownumbers.

Is there a way to do this? Preferably an easy one.

答:
I think you can use two panels to make the form like the picture you provided.

The following code is a code example and you can refer to it.

```<code> public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        ScrollBar hScrollBar1 = new HScrollBar();
        private void Form1_Load(object sender, EventArgs e)
        {
            panel1.BorderStyle = BorderStyle.FixedSingle;
            panel1.Dock = DockStyle.Left;
            panel2.BorderStyle = BorderStyle.FixedSingle;
            panel2.Dock = DockStyle.Fill;
            hScrollBar1.Dock = DockStyle.Bottom;
            hScrollBar1.Scroll += new ScrollEventHandler(hScroller_Scroll);
            panel2.Controls.Add(hScrollBar1);
            panel2.HorizontalScroll.Visible = false;
            panel2.HorizontalScroll.Enabled = true;
        }
        private void hScroller_Scroll(object sender, ScrollEventArgs e)
        {
            panel2.HorizontalScroll.Value = e.NewValue;
        }
    }
</code>```

The specific result:

Body:
I think you can use two panels to make the form like the picture you provided.

The following code is a code example and you can refer to it.

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        ScrollBar hScrollBar1 = new HScrollBar();
        private void Form1_Load(object sender, EventArgs e)
        {
            panel1.BorderStyle = BorderStyle.FixedSingle;
            panel1.Dock = DockStyle.Left;
            panel2.BorderStyle = BorderStyle.FixedSingle;
            panel2.Dock = DockStyle.Fill;
            hScrollBar1.Dock = DockStyle.Bottom;
            hScrollBar1.Scroll += new ScrollEventHandler(hScroller_Scroll);
            panel2.Controls.Add(hScrollBar1);
            panel2.HorizontalScroll.Visible = false;
            panel2.HorizontalScroll.Enabled = true;
        }
        private void hScroller_Scroll(object sender, ScrollEventArgs e)
        {
            panel2.HorizontalScroll.Value = e.NewValue;
        }
    }

The specific result:


问:
Triggering a specific action when the app enters foreground from a local notification in iOS? (using swift)
I am building an iOS app using the new language Swift. Now it is an HTML5 app, that displays HTML content using the UIWebView. The app has local notifications, and what i want to do is trigger a specific javascript method in the UIWebView when the app enters foreground by clicking (touching) the local notification.

I have had a look at this question, but it does not seem to solve my problem. I have also come across this question which tells me about using UIApplicationState, which is good as that would help me know the the app enters foreground from a notification. But when the app resumes and how do i invoke a method in the viewController of the view that gets displayed when the app resumes?

What i would like to do is get an instance of my ViewController and set a property in it to true. Something as follows

```<code>class FirstViewController: UIViewController,UIWebViewDelegate {
  var execute:Bool = false;
  @IBOutlet var tasksView: UIWebView!
}
</code>```

And in my AppDelegate i have the method

```<code>func applicationWillEnterForeground(application: UIApplication!) {
    let viewController = self.window!.rootViewController;
    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

    var setViewController = mainStoryboard.instantiateViewControllerWithIdentifier("FirstView") as FirstViewController
    setViewController.execute = true;

}
</code>```

so what i would like to do is when the app enters foreground again, i want to look at the execute variable and run the method as follows,

```<code>if execute{
 tasksView.stringByEvaluatingJavaScriptFromString("document.getElementById('sample').click()");
}
</code>```

Where should i put the code for the logic to trigger the javascript from the webview? would it be on viewDidLoad method, or one of the webView delegate methods? i have tried to put that code in the viewDidLoad method but the value of the boolean execute is set to its initial value and not the value set in the delegate when the app enters foreground.

答:
Add Below Code in ViewController</p>

```<code>override func viewDidLoad() {
super.viewDidLoad()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector:#selector(appMovedToForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
   }

  @objc func appMovedToForeground() {
  print("App moved to foreground!")
  }
</code>```

Body:
I am building an iOS app using the new language Swift. Now it is an HTML5 app, that displays HTML content using the UIWebView. The app has local notifications, and what i want to do is trigger a specific javascript method in the UIWebView when the app enters foreground by clicking (touching) the local notification.

I have had a look at this question, but it does not seem to solve my problem. I have also come across this question which tells me about using UIApplicationState, which is good as that would help me know the the app enters foreground from a notification. But when the app resumes and how do i invoke a method in the viewController of the view that gets displayed when the app resumes?

What i would like to do is get an instance of my ViewController and set a property in it to true. Something as follows

class FirstViewController: UIViewController,UIWebViewDelegate {
  var execute:Bool = false;
  @IBOutlet var tasksView: UIWebView!
}

And in my AppDelegate i have the method

func applicationWillEnterForeground(application: UIApplication!) {
    let viewController = self.window!.rootViewController;
    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

    var setViewController = mainStoryboard.instantiateViewControllerWithIdentifier("FirstView") as FirstViewController
    setViewController.execute = true;

}

so what i would like to do is when the app enters foreground again, i want to look at the execute variable and run the method as follows,

if execute{
 tasksView.stringByEvaluatingJavaScriptFromString("document.getElementById('sample').click()");
}

Where should i put the code for the logic to trigger the javascript from the webview? would it be on viewDidLoad method, or one of the webView delegate methods? i have tried to put that code in the viewDidLoad method but the value of the boolean execute is set to its initial value and not the value set in the delegate when the app enters foreground.

Body:
Add Below Code in ViewController

override func viewDidLoad() {
super.viewDidLoad()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector:#selector(appMovedToForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
   }

  @objc func appMovedToForeground() {
  print("App moved to foreground!")
  }


问:
Running instances of a particular class on network (python)
So, I have a class SomeCode.py (daemon) running on multiple hosts in my network.
I need to scan the network and find the number of running instances of the class.

I am working on Windows10

EDIT 1:
Sample content for SomeCode.py

```<code>import time
class SomeCode(object):
    def something(self):
        while(True):
           time.sleep(10)
           print("SomeCode Running")
if __name__ == '__main__':
    obj = SomeCode()
    obj.something()
</code>```

I have already tried this:

```<code>import gc
for obj in gc.get_objects():
    if isinstance(obj, MyClass):
        print obj.name
</code>```

Brute Force approach - Works for my PC but how to implement on network

答:
@vidya marathe:You can use Python Socket programming to achieve this...one machine run code that acts as a socket server and remaining clients will connect over socket to this server and can emit events after successful deployment...

1)Run Socket server
2)Create 10 socket clients that will connect to socket server
3)Send event to socket server after execution of your calls...etc

refer below:
https://realpython.com/python-sockets/

Body:
So, I have a class SomeCode.py (daemon) running on multiple hosts in my network.
I need to scan the network and find the number of running instances of the class.

I am working on Windows10

EDIT 1:
Sample content for SomeCode.py

import time
class SomeCode(object):
    def something(self):
        while(True):
           time.sleep(10)
           print("SomeCode Running")
if __name__ == '__main__':
    obj = SomeCode()
    obj.something()

I have already tried this:

import gc
for obj in gc.get_objects():
    if isinstance(obj, MyClass):
        print obj.name

Brute Force approach - Works for my PC but how to implement on network


问:
Kafka Topic And Offset
I have a question,Suppose there is a TOPIC T1 and there are two Consumer C1 and C2 belongs to two different groups and current offset is 0.We know that Kafka maintains the Offset for consumer.So if C1 consume the message and Offset becomes 1 then what will happen if C2 consume the message will it start from 1 offset or it will start consume the message from 0 offset?. Means how offset will be maintains for two different consumer Group?.

Thanks

答:
when consumers belong to different consumer groups they are supposed to consume the same messages as in a publish/subscribe pattern. when they are in the same consumer group, they are "competing" and reading on different partitions of the topic (assigned on subscription) so they don't get same messages.
The consumer offset is saved in an internal __consumer_offset topic and the messages have the following format:

key = [group, topic, partition]
value = offset

so as you can see, for different group(s) but same topic/partition, there is a different offset saved there.

Title: Kafka Topic And Offset


问:
How to INDEX this MySQL table for use with GEO data?
My table currently stands like this:

```<code>CREATE TABLE IF NOT EXISTS `x_geodata` (
  `post_id` int(11) NOT NULL,
  `post_type` varchar(20) NOT NULL,
  `lat` float(10,6) NOT NULL,
  `lng` float(10,6) NOT NULL,
  PRIMARY KEY  (`post_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
</code>```

How do I correctly and efficiently INDEX this table?

The only query ran on this table is as follows:

```<code>if(!empty($_SESSION['s_property_radius'])) {$dist = $_SESSION['s_property_radius'];}else{$dist = 50;}
$orig_lat = $_SESSION['s_property_address_lat'];
$orig_lon = $_SESSION['s_property_address_lng'];
$lon1 = $orig_lon - $dist / abs( cos( deg2rad( $orig_lat ) ) * 69 );
$lon2 = $orig_lon + $dist / abs( cos( deg2rad( $orig_lat ) ) * 69 );
$lat1 = $orig_lat - ( $dist / 69 );
$lat2 = $orig_lat + ( $dist / 69 );

$sql = "

SELECT `t`.`post_id`, 3956 * 2 * ASIN( SQRT( POWER( SIN( ( ".$orig_lat." - `t`.`lat` ) * pi() / 180 / 2), 2 ) + COS( ".$orig_lat." * pi() / 180) * COS( `t`.`lat` * pi() / 180 ) * POWER( SIN( ( ".$orig_lon." - `t`.`lng` ) * pi() / 180 / 2 ), 2 ) ) ) AS `distance` FROM (
    SELECT `post_id`, `lat`, `lng` FROM `x_geodata` WHERE `post_type` = 'some post type' AND `lng` BETWEEN '".$lon1."' AND '".$lon2."' AND `lat` BETWEEN '".$lat1."' AND '".$lat2."'
) AS `t` HAVING `distance` <= ".$dist."

";
</code>```

The query checks to make sure we are looking at the correct post type and then does a square radius check on the lat and lng. The returned results are then run through a circular radius check.

What I'm looking for is updated CREATE TABLE SQL or UPDATE TABLE SQL to get this INDEXED correctly.

Any help is greatly appreciated.

EDIT:
Did an EXPLAIN on my query based on arnep answer and I got this:

```<code>id    select_type    table    type    possible_keys    key    key_len    ref    rows    Extra
1    PRIMARY    <derived2>    ALL    NULL    NULL    NULL    NULL    3
2    DERIVED    zch_geodatastore    range    post_type    post_type    70    NULL    3    Using where
</code>```

No idea what it means though...

答:
As your inner SELECT uses post_type, lat and lon in WHERE clause I would recommend to put an index on those.

Use EXPLAIN [QUERY] to see if the index is used and what benefit you get from it.

Body:
My table currently stands like this:

CREATE TABLE IF NOT EXISTS `x_geodata` (
  `post_id` int(11) NOT NULL,
  `post_type` varchar(20) NOT NULL,
  `lat` float(10,6) NOT NULL,
  `lng` float(10,6) NOT NULL,
  PRIMARY KEY  (`post_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

How do I correctly and efficiently INDEX this table?

The only query ran on this table is as follows:

if(!empty($_SESSION['s_property_radius'])) {$dist = $_SESSION['s_property_radius'];}else{$dist = 50;}
$orig_lat = $_SESSION['s_property_address_lat'];
$orig_lon = $_SESSION['s_property_address_lng'];
$lon1 = $orig_lon - $dist / abs( cos( deg2rad( $orig_lat ) ) * 69 );
$lon2 = $orig_lon + $dist / abs( cos( deg2rad( $orig_lat ) ) * 69 );
$lat1 = $orig_lat - ( $dist / 69 );
$lat2 = $orig_lat + ( $dist / 69 );

$sql = "

SELECT `t`.`post_id`, 3956 * 2 * ASIN( SQRT( POWER( SIN( ( ".$orig_lat." - `t`.`lat` ) * pi() / 180 / 2), 2 ) + COS( ".$orig_lat." * pi() / 180) * COS( `t`.`lat` * pi() / 180 ) * POWER( SIN( ( ".$orig_lon." - `t`.`lng` ) * pi() / 180 / 2 ), 2 ) ) ) AS `distance` FROM (
    SELECT `post_id`, `lat`, `lng` FROM `x_geodata` WHERE `post_type` = 'some post type' AND `lng` BETWEEN '".$lon1."' AND '".$lon2."' AND `lat` BETWEEN '".$lat1."' AND '".$lat2."'
) AS `t` HAVING `distance` <= ".$dist."

";

The query checks to make sure we are looking at the correct post type and then does a square radius check on the lat and lng. The returned results are then run through a circular radius check.

What I'm looking for is updated CREATE TABLE SQL or UPDATE TABLE SQL to get this INDEXED correctly.

Any help is greatly appreciated.

EDIT:
Did an EXPLAIN on my query based on arnep answer and I got this:

id    select_type    table    type    possible_keys    key    key_len    ref    rows    Extra
1    PRIMARY    <derived2>    ALL    NULL    NULL    NULL    NULL    3
2    DERIVED    zch_geodatastore    range    post_type    post_type    70    NULL    3    Using where

No idea what it means though...


问:
Change profile picture in django
I'm trying to make a edit profile module , but it needs to change profile picture too.. I already try some code , but the picture isnt change when I press the submit button

Here's the views.py for update_profile

```<code>def update_profile(request):
    if request.method == 'POST':
        user_form = UserInfoForm(request.POST, instance=request.user )
        profile_form = UserProfileInfoForm(request.POST, instance=request.user.profile)
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            user.save()
            profile = profile_form.save(commit=False)
            profile.user = user
            if 'profile_pic' in request.FILES:
                profile.profile_pic = request.FILES['profile_pic']
            profile.save()
            return redirect('/profile/')
        else:
            messages.error(request, ('Please correct the error below.'))
    else:
        user_form = UserInfoForm(instance=request.user)
        profile_form = UserProfileInfoForm(instance=request.user.profile)
    return render(request, 'profile.html', {
        'user_form': user_form,
        'profile_form': profile_form
    })
</code>```

here's the form

```<code><form role="form" class="form-horizontal" method="post">

                          {% load staticfiles %}
                          {% block body_block %}

                                {% if registered %}
                                  <h1>Update Profile Success!</h1>
                                {% else %}
                                  <form class="cmxform form-horizontal style-form" id="commentForm" enctype="multipart/form-data" method="POST" action="">
                                    {% csrf_token %}
                                    {{ user_form.as_p }}
                                    {{ profile_form.as_p }}

                                    <input type="submit" name="" value="Update">
                                  </form>

                                {% endif %}

                          {% endblock %}

                        </form>
</code>```

urls.py (already add +static[]) from someone suggestion and still not working

```<code>app_name = 'polls'
urlpatterns = [
    path('profile/', views.update_profile, name='profile'),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

Hope someone can solve the problem, thank you.

答:
Add enctype in your HTML form.

```<code><form role="form" class="form-horizontal" method="post" <b>enctype="multipart/form-data"</b>>
    <!-- Your html elements -->
</form>
</code>```

also provide request.FILES to your form.

```<code>profile_form = UserProfileInfoForm(request.POST, <b>request.FILES,</b> instance=request.user.profile)
</code>```

remove these lines:

if 'profile_pic' in request.FILES:
    profile.profile_pic = request.FILES['profile_pic']
```

If you are passing the request.FILES to UserProfileInfoForm then you don't have to directly assign it to the profile.

Title: Change profile picture in django

Body:
I'm trying to make a edit profile module , but it needs to change profile picture too.. I already try some code , but the picture isnt change when I press the submit button

Here's the views.py for update_profile

def update_profile(request):
    if request.method == 'POST':
        user_form = UserInfoForm(request.POST, instance=request.user )
        profile_form = UserProfileInfoForm(request.POST, instance=request.user.profile)
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            user.save()
            profile = profile_form.save(commit=False)
            profile.user = user
            if 'profile_pic' in request.FILES:
                profile.profile_pic = request.FILES['profile_pic']
            profile.save()
            return redirect('/profile/')
        else:
            messages.error(request, ('Please correct the error below.'))
    else:
        user_form = UserInfoForm(instance=request.user)
        profile_form = UserProfileInfoForm(instance=request.user.profile)
    return render(request, 'profile.html', {
        'user_form': user_form,
        'profile_form': profile_form
    })

here's the form

<form role="form" class="form-horizontal" method="post">

                          {% load staticfiles %}
                          {% block body_block %}

                                {% if registered %}

Update Profile Success!

                                {% else %}
                                  <form class="cmxform form-horizontal style-form" id="commentForm" enctype="multipart/form-data" method="POST" action="">
                                    {% csrf_token %}
                                    {{ user_form.as_p }}
                                    {{ profile_form.as_p }}

                                    <input type="submit" name="" value="Update">
                                  </form>

                                {% endif %}

                          {% endblock %}

                        </form>

urls.py (already add +static[]) from someone suggestion and still not working

app_name = 'polls'
urlpatterns = [
    path('profile/', views.update_profile, name='profile'),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Hope someone can solve the problem, thank you.

Body:
Add enctype in your HTML form.

<form role="form" class="form-horizontal" method="post" enctype="multipart/form-data">
    <!-- Your html elements -->
</form>

also provide request.FILES to your form.

profile_form = UserProfileInfoForm(request.POST, request.FILES, instance=request.user.profile)

remove these lines:

if 'profile_pic' in request.FILES:
    profile.profile_pic = request.FILES['profile_pic']

If you are passing the request.FILES to UserProfileInfoForm then you don't have to directly assign it to the profile.


问:
How to reuse code from iPhone project for iPad project? Which way is the best?
I started a company project for about 1 year for iPhone devices. This year,  I will start the project for the Ipad device, the feature the same but different layout. My problem, how to reuse that code for Ipad? Which way is the best?

My workspace includes an iPhone project and Pod project.

Thank All.

答: If UI has major changes then create a new storyboard for the iPad and use the same outlets and classes, you don't need to re-write the code. Just design new ui and attach outlets.</p>


问:
Accessing request container (event_dispatcher) within a test client
I created a simple test case in Symfony.
So one client which should listen for an event which will be dispatched during an request.
But nothing happen because the request have an own scope or I dont know why Im not able to access the dispatcher in it.

```<code>$this->client = static::createClient();
self::$container = $this->client->getContainer();

$dispatcher = self::$container->get('event_dispatcher');

$dispatcher->addListener('example', function ($event) {
    // Never executed
});

$this->client->request('POST', $endpoint, $this->getNextRequestParameters($i), [$file], $this->requestHeaders);
$this->client->getResponse();
</code>```

The listener is never called.
When I debug it a bit I find out that the object hash via spl_object_hash($dispatcher) is different on the highest level than on within the request level.
So it seems that the request has an own world and ignores everything outside.

But then is the question how I can put my listener to this "world"?

答:
I think part of the problem is the mixing of testing styles. You have a WebTestCase which is intended for a very high level of testing (requests & responses). It should not really care about internals, i.e. which services or listeners are called. It only cares that given input x (your request) you will get output y (your response). This allows to ensure the basic functionality as perceived by your users is always met, without caring how it is done. Making these tests very flexible.

By looking into the container and the services you are going into a lower level of testing, which tests interconnected services. This is usually only done within the same process for the reasons you already found out. The higher level test has 2 separate lifecycles, one for the test itself and one for the simulated web request to your application, hence the different object ids.

The solution is either to emit something to the higher level, e.g. by setting headers or changing the output, so you can inspect the response body. You could also write into some log file and check the logs before/after the request for that message.

A different option would be to move the whole test into a lower level where you do not need the requests and instead only work with the services. For this you can use the KernelTestCase (instead of the WebTestCase) and instead of calling createClient() you call bootKernel. This will give you access to your container where you can modify the EventDispatcher. Rather than sending a request you can then either call the code directly, e.g. dispatch an event if you only want to test the listeners, or you can make your controller accessible as service and then manually create a request, call the action and then either check the response or whatever else you want to assert on. This could look roughly like this:

public function testActionFiresEvent()
{
    $kernel = static::bootKernel();

    $eventDispatcher = $kernel->getContainer()->get('event_dispatcher');

    // ...

    $request = Request::create();

    // This might not work when the controller
    // You can create a service configuration only used by tests,
    // e.g. "config/services_test.yaml" and provide the controller service there
    $controller = $kernel->getContainer()->get(MyController::class);

    $response = $controller->endpointAction($request);

    // ...Do assertions...
}
```

Body:
I created a simple test case in Symfony.
So one client which should listen for an event which will be dispatched during an request.
But nothing happen because the request have an own scope or I dont know why Im not able to access the dispatcher in it.

$this->client = static::createClient();
self::$container = $this->client->getContainer();

$dispatcher = self::$container->get('event_dispatcher');

$dispatcher->addListener('example', function ($event) {
    // Never executed
});

$this->client->request('POST', $endpoint, $this->getNextRequestParameters($i), [$file], $this->requestHeaders);
$this->client->getResponse();

The listener is never called.
When I debug it a bit I find out that the object hash via spl_object_hash($dispatcher) is different on the highest level than on within the request level.
So it seems that the request has an own world and ignores everything outside.

But then is the question how I can put my listener to this "world"?


问:
Replacing a checkbox element with icons
I want to customize the browser checkbox. When the status is checked, the icon checked.svg should be displayed instead of checkbox and the icon unchecked.svg otherwise.

Here is my code.
HTML:

```<code><div class="checkbox-custom">
   <input type="checkbox"/>
      <div class="checkmark">
          <img src="@/assets/images/icons/checkbox/unchecked.svg" class="unchecked"/>
          <img src="@/assets/images/icons/checkbox/checked.svg" class="checked"/>
    </div>
</div>
</code>```

SASS:

```<code>.checkbox-custom {
    position: absolute;
    width: 28px;
    height: 28px;
    left: 0;
    top: 0;

    // Hide default browser checkbox
    input[type=checkbox] {
                display: none;
            }

   input[type=checkbox] + .checkmark {
        position: absolute;
        left: 3.5px;
        top: 3.5px;
        right: 3.5px;
        bottom: 3.5px;

        display: inline-block;
        cursor: pointer;

        img {
            width: 21px;
            height: 21px;
        }

        .checked {
            display: none;
        }
    }

    input[type=checkbox]:checked + .checkmark {
        .checked {
            display: block;
        }

        .unchecked {
            display: none;
        }
    }
 }
</code>```

When i click on the checkbox, nothing happens. What could be the error?

答:
This can be accomplished without any javascript. Clicking the label element toggles the checkbox inside of it, so with some clever css, we can change the display based on the input's checked state.

input[type=checkbox] {
  display: none;
}
.label {
  border: 1px solid #000;
  display: inline-block;
  padding: 3px;
  /* background: url("unchecked.png") no-repeat left center; */
  /* padding-left: 15px; */
}
input[type=checkbox]:checked + .label {
  background: #f00;
  color: #fff;
  /* background-image: url("checked.png"); */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label><input type="checkbox"><span class="label">Check me</span></label></code>```

Change the .label styles to use background-image of your choice (and position it to the left of your text).

Title: Replacing a checkbox element with icons

Body:
I want to customize the browser checkbox. When the status is checked, the icon checked.svg should be displayed instead of checkbox and the icon unchecked.svg otherwise.

Here is my code.
HTML:

   <input type="checkbox"/>

SASS:

.checkbox-custom {
    position: absolute;
    width: 28px;
    height: 28px;
    left: 0;
    top: 0;

    // Hide default browser checkbox
    input[type=checkbox] {
                display: none;
            }

   input[type=checkbox] + .checkmark {
        position: absolute;
        left: 3.5px;
        top: 3.5px;
        right: 3.5px;
        bottom: 3.5px;

        display: inline-block;
        cursor: pointer;

        img {
            width: 21px;
            height: 21px;
        }

        .checked {
            display: none;
        }
    }

    input[type=checkbox]:checked + .checkmark {
        .checked {
            display: block;
        }

        .unchecked {
            display: none;
        }
    }
 }

When i click on the checkbox, nothing happens. What could be the error?

Body:
This can be accomplished without any javascript. Clicking the label element toggles the checkbox inside of it, so with some clever css, we can change the display based on the input's checked state.

input[type=checkbox] {
  display: none;
}
.label {
  border: 1px solid #000;
  display: inline-block;
  padding: 3px;
  /* background: url("unchecked.png") no-repeat left center; */
  /* padding-left: 15px; */
}
input[type=checkbox]:checked + .label {
  background: #f00;
  color: #fff;
  /* background-image: url("checked.png"); */
}

<label><input type="checkbox"><span class="label">Check me</span></label>

Change the .label styles to use background-image of your choice (and position it to the left of your text).


问:
Good books for WCF based SOA, Distributed and Server Side Programming?
I am basically a .NET GUI programmer and have worked on a lot of WPF, Winforms and also have used WCF. I joined a new job in a bank and we are currently writing a new software to replace existing trading apps. This involves lot of work based on WCF services and we need to use/implement a lot of SOA related concepts like message broker, pub-sub patterns, message bus etc. So, basically means a lot of server side and distributed programming in my way ahead ! We now use simple WCF services that does our job for our service layer but aiming to make this more scalable, robust, secure and reliable.

I have a basic WCF book but wondering if there is a more specialized SOA, Distributed Architecture based book (based on .NET, WCF or may be not) that can quickly help me to get through the curve of server side programming. Possibly that talks about CEP, EDA etc..

Many Thanks,
Mani

答:
Professional WCF 4: Windows Communication Foundation with .NET 4.
Pablo Cibraro; Kurt Claeys; Fabio Cozzolino; Johann Grabner

WCF 4.0 Multi-tier Services Development with LINQ to Entities.
Mike Liu

SOA Modeling Patterns for Service-Oriented Discovery and Analysis.
Michael Bell

Pro WCF: Practical Microsoft SOA Implementation.
Chris Peiris; Dennis Mulder

Thanks,
Sebastian


问:
How use image in api get by axios request in html tags in ReactJS?
I use axios to get data from the api, now I need to display the image in the td tag in HTML, the text response are working fine but the image is not displaying.

my request code is:

```<code>componentDidMount(){

      var headers = {
        "Content-Type":"application/json",
        "AccessToken":localStorage.TOKEN,
      }

      axios.get(window.$_APIurl+"myProviders/5e463d53e7179a2f011c4104", {headers: headers})
        .then((response) => {
          console.log(response.data[0].provider.image);
          const doctor = response.data[0].provider.image;
        if(response.data.length > 0)   this.setState({"listOfProviders": response.data});
      })
  }
</code>```

My html to use is:

```<code>  {this.state.listOfProviders.length > 0 ?
                      <tbody>
                        {this.state.listOfProviders.map((providerData,indx)=>
                          <tr>
                            <td className="font-weight-medium"> <img className="logo" src={doctor} alt="pam-logo" /> {providerData.provider.firstName} {providerData.provider.lastName} </td>
                            <td>{providerData.provider.email}</td>
                            <td>{providerData.provider.phoneNumber}</td>
                            <td>{(providerData.provider.specialities)}</td>
                            <td > {providerData.provider.qbid}</td>
                            <td> Mountain view,Ave </td>
                            <td><Icon icon={editIcon} width="20px"/>  <Icon icon={deleteIcon} width="20px"/></td>

                        </tr>
                        )}
                      </tbody>
</code>```

I need image in src tag.

答:
create a state variable in constructor

```<code>this.state = {
    doctor: ''
}
</code>```

after geting response update the image url using setState inside componentDidMount

```<code>this.setState({doctor: response.data[0].provider.image})
</code>```

Body:
I use axios to get data from the api, now I need to display the image in the td tag in HTML, the text response are working fine but the image is not displaying.

my request code is:

componentDidMount(){

      var headers = {
        "Content-Type":"application/json",
        "AccessToken":localStorage.TOKEN,
      }

      axios.get(window.$_APIurl+"myProviders/5e463d53e7179a2f011c4104", {headers: headers})
        .then((response) => {
          console.log(response.data[0].provider.image);
          const doctor = response.data[0].provider.image;
        if(response.data.length > 0)   this.setState({"listOfProviders": response.data});
      })
  }

My html to use is:

  {this.state.listOfProviders.length > 0 ?

                        {this.state.listOfProviders.map((providerData,indx)=>

                              {providerData.provider.firstName} {providerData.provider.lastName}
                            {providerData.provider.email}
                            {providerData.provider.phoneNumber}
                            {(providerData.provider.specialities)}
                             {providerData.provider.qbid}
                             Mountain view,Ave
                            <Icon icon={editIcon} width="20px"/>  <Icon icon={deleteIcon} width="20px"/>

                        )}

I need image in src tag.

Body:
create a state variable in constructor

this.state = {
    doctor: ''
}

after geting response update the image url using setState inside componentDidMount

this.setState({doctor: response.data[0].provider.image})


问:
What is the use of Assignment expressions in python 3.8
Bit to know new syntax := (the walrus operator) that assigns values. Anyone explain with brief example.

答:
Lets take the first example from the What's new in 3.8 documentation:

```<code>if (n := len(a)) > 10:
    print(f"List is too long ({n} elements, expected <= 10)")
</code>```

"Normal" assignment is a statement, it can't be used as part of expressions. Without the expression-assignment ("walrus") operator the above example would have to be something like

```<code>n = len(a)
if n > 10:
    print(f"List is too long ({n} elements, expected <= 10)")
</code>```

With the expression-assignment you can combine the assignment to n with the condition.

Body:
Lets take the first example from the What's new in 3.8 documentation:

if (n := len(a)) > 10:
    print(f"List is too long ({n} elements, expected <= 10)")

"Normal" assignment is a statement, it can't be used as part of expressions. Without the expression-assignment ("walrus") operator the above example would have to be something like

n = len(a)
if n > 10:
    print(f"List is too long ({n} elements, expected <= 10)")

With the expression-assignment you can combine the assignment to n with the condition.


问:
How can I revert or rollback the database changes made during testing using 'tap' after test is completed?
I am using tap framework for testing my node application. While running the test I am making some changes in the database.

I want to revert all the changes made in the database after testing. Can anyone help me out of this?

答:
No, you can't undo, rollback or reverse a commit.

Basically, restore from backup. If you can't, you might be able to recover with **pg_dirtyread**.

If you don't have backups, stop the whole server, take a disk image of the drive, and contact a $lots data recovery expert.

If you have committed the transaction, you cannot rollback or undo the update. Please find the detailed answer here.

There is one article about this pg_dirtyread here on medium.

Can I rollback a transaction I've already committed? (data loss)


问:
unable to clear my sharedPreferences using editor.clear().commit();
I am working on an android project where I have a scenario such as :

I used place picker.and data that place picker gave is sent to different activities using shared preference.and show this data in TextView.

but the problem is when I closed activity and again open that activity; my data still visible in TextView.

even when I cleared it in onDestroy().

here is my code for send data :

```<code> SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
 SharedPreferences.Editor editor = settings.edit();
 editor.putString("address", (String) Address);
 editor.commit();
 finish();
</code>```

here is my code to set and clear data:

```<code> @Override
protected void onResume() {

    super.onResume();
    SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
    String n = settings.getString("name", "");
    String a = settings.getString("address", "");
    name.setText(n);
    location.setText(a);
}

@Override
protected void onDestroy() {

    SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();
    editor.remove("address");
    editor.clear().commit();
    super.onDestroy();
}
</code>```

here is my preference manager class :

```<code>   public class PrefManager {

    SharedPreferences pref;
    SharedPreferences.Editor editor;
    Context _context;

    // shared pref mode
    int PRIVATE_MODE = 0;

    // Shared preferences file name
    private static final String PREF_NAME = "sara";

    private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";

    public PrefManager(Context context) {
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

    public void setFirstTimeLaunch(boolean isFirstTime) {
        editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
        editor.clear().commit();
    }

    public boolean isFirstTimeLaunch() {
        return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true);
    }
}
</code>```

And please don't mark this question as duplicate because I see every related questions and see answers. I tried every possible solutions but nothing worked for me. I am new to android so please help me.

答:
I'm not sure where you are using SharedPreference object to set data in it. But I guess this is the problem:

In this activity, you are clearing SharedPreferenece correctly.

You go back to previous Activity. And the previous activity, sets data to shared preference, again. So SharedPreference is not empty anymore.

You go to second activity (which you remove shared preference data in onDestroy()). As shared preference is not empty, you are seeing data again.

So check the code again and feel free to ask any questions.

Body:
I am working on an android project where I have a scenario such as :

I used place picker.and data that place picker gave is sent to different activities using shared preference.and show this data in TextView.

but the problem is when I closed activity and again open that activity; my data still visible in TextView.

even when I cleared it in onDestroy().

here is my code for send data :

 SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
 SharedPreferences.Editor editor = settings.edit();
 editor.putString("address", (String) Address);
 editor.commit();
 finish();

here is my code to set and clear data:

 @Override
protected void onResume() {

    super.onResume();
    SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
    String n = settings.getString("name", "");
    String a = settings.getString("address", "");
    name.setText(n);
    location.setText(a);
}

@Override
protected void onDestroy() {

    SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();
    editor.remove("address");
    editor.clear().commit();
    super.onDestroy();
}

here is my preference manager class :

   public class PrefManager {

    SharedPreferences pref;
    SharedPreferences.Editor editor;
    Context _context;

    // shared pref mode
    int PRIVATE_MODE = 0;

    // Shared preferences file name
    private static final String PREF_NAME = "sara";

    private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";

    public PrefManager(Context context) {
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

    public void setFirstTimeLaunch(boolean isFirstTime) {
        editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
        editor.clear().commit();
    }

    public boolean isFirstTimeLaunch() {
        return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true);
    }
}

And please don't mark this question as duplicate because I see every related questions and see answers. I tried every possible solutions but nothing worked for me. I am new to android so please help me.


问:
React - could not send a redux-thunk action with extra argument
I trying to working with typescript with redux-thunk and redux.
I would like to pass an object to any action (I am using dependency injection and I need to pass an object service or string)

i got this error;

```<code>  Overload 1 of 2, '(action: AnyAction): AnyAction', gave the following error.
    Argument of type '(dispatch: any, getState: AppState, extraArg: string) => Promise<any>' is not assignable to parameter of type 'AnyAction'.
</code>```

it's done as follows:

store.ts:

```<code>const middlewares = [
    routerMiddleware(history),
    thunkMiddleware.withExtraArgument('bar') as ThunkMiddleware<
      AppState,
      Actions,
      string
    >
  ];
  const middleWareEnhancer = applyMiddleware(...middlewares);

  const store = createStore(
    rootReducer(history),
    preloadState,
    composeWithDevTools(middleWareEnhancer)
  );
</code>```

my index.ts where I am trying to send action is :

```<code>(store.dispatch as ThunkDispatch<{}, void, AnyAction>)(getAll());
</code>```

my action file that working:

```<code>export const getall = () => async (dispatch: any) => {
  try {
    dispatch({ type: GETALL_REQUEST });
    return dispatch({ type: GETALL_SUCCESS, payload: null });
  } catch (e) {
    return dispatch({ type: GETALL_FAILURE, error: e });
  }
};
</code>```

my action (put part of it) that raises the error

```<code>export const getAll = () => async (
  dispatch: any,
  getState: AppState,
  extraArg: string
) => {....action logic}
</code>```

then I got the error on:

```<code>(store.dispatch as ThunkDispatch<{}, void, AnyAction>)(getAll());
</code>```

答:
The easiest way to correct the error:

```<code>(store.dispatch as ThunkDispatch<AppState, string, AnyAction>)(getAll());
</code>```

and

```<code>export const getAll = () => async (
  dispatch: any,
  getState: () => AppState,
  extraArg: string
) => {....action logic}
</code>```

ThunkDispatch accepts following type arguments: S - state, E - extended arg, A - action. So your use of ThunkDispatch should match types of your state and extended arg.

Thunk action is a function which accepts following arguments: dispatch is a function, getState is also a function which returns state and extraArg. So make sure, that getState is a function.

To avoid dispatch casting I suggest to properly type a store when creating. As you're using applyMiddleware which accepts an array, you should pass type argument to it. It accepts type of dispatch which will be used after applying Delawares.

```<code>const middlewares = [thunk.withExtraArgument("bar")];
const middleWareEnhancer = applyMiddleware<
  ThunkDispatch<AppState, string, Actions>
>(...middlewares);
</code>```

As a result, you'll get a store with properly typed dispatch function. And you'll be able to use it without casting.

```<code>store.dispatch(getAll());
</code>```

The working demo

Body:
I trying to working with typescript with redux-thunk and redux.
I would like to pass an object to any action (I am using dependency injection and I need to pass an object service or string)

i got this error;

  Overload 1 of 2, '(action: AnyAction): AnyAction', gave the following error.
    Argument of type '(dispatch: any, getState: AppState, extraArg: string) => Promise<any>' is not assignable to parameter of type 'AnyAction'.

it's done as follows:

store.ts:

const middlewares = [
    routerMiddleware(history),
    thunkMiddleware.withExtraArgument('bar') as ThunkMiddleware<
      AppState,
      Actions,
      string
    >
  ];
  const middleWareEnhancer = applyMiddleware(...middlewares);

  const store = createStore(
    rootReducer(history),
    preloadState,
    composeWithDevTools(middleWareEnhancer)
  );

my index.ts where I am trying to send action is :

(store.dispatch as ThunkDispatch<{}, void, AnyAction>)(getAll());

my action file that working:

export const getall = () => async (dispatch: any) => {
  try {
    dispatch({ type: GETALL_REQUEST });
    return dispatch({ type: GETALL_SUCCESS, payload: null });
  } catch (e) {
    return dispatch({ type: GETALL_FAILURE, error: e });
  }
};

my action (put part of it) that raises the error

export const getAll = () => async (
  dispatch: any,
  getState: AppState,
  extraArg: string
) => {....action logic}

then I got the error on:

(store.dispatch as ThunkDispatch<{}, void, AnyAction>)(getAll());

Body:
The easiest way to correct the error:

(store.dispatch as ThunkDispatch<AppState, string, AnyAction>)(getAll());

and

export const getAll = () => async (
  dispatch: any,
  getState: () => AppState,
  extraArg: string
) => {....action logic}

ThunkDispatch accepts following type arguments: S - state, E - extended arg, A - action. So your use of ThunkDispatch should match types of your state and extended arg.

Thunk action is a function which accepts following arguments: dispatch is a function, getState is also a function which returns state and extraArg. So make sure, that getState is a function.

To avoid dispatch casting I suggest to properly type a store when creating. As you're using applyMiddleware which accepts an array, you should pass type argument to it. It accepts type of dispatch which will be used after applying Delawares.

const middlewares = [thunk.withExtraArgument("bar")];
const middleWareEnhancer = applyMiddleware<
  ThunkDispatch<AppState, string, Actions>
>(...middlewares);

As a result, you'll get a store with properly typed dispatch function. And you'll be able to use it without casting.

store.dispatch(getAll());

The working demo