问:
Problem in uploading image to the server using XAMPP
I'm facing a problem while trying to upload image from the app to the server using xampp .

the thing is that when I write the image name($ImageName) manually on the PHP file it works fine but when I try with code it doesn't and show me this message ( the one on the bottom on the first click on the upload button and the other message on the second click and above ) .

enter image description here

this is the php file code

```<code><?php
require "connection.php";
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$DefaultId = 0;
$ImageData = $_POST['image_data'];
$ImageName =$_POST['image_tag'];  /* when I write here "stack" for example
it works and I find the image on the path with the name stack */

$ImagePath = "Documents/$ImageName.jpg";
$ServerURL = "192.168.1.5/$ImagePath";

$InsertSQL = "INSERT INTO imageupload (image_path,image_name) values('$ServerURL','$ImageName')";

if(mysqli_query($conn, $InsertSQL)){

file_put_contents($ImagePath,base64_decode($ImageData));

echo "Your Image Has Been Uploaded.";
}
mysqli_close($conn);
}else{
echo "Please Try Again";
}

?>
</code>```

and this is the java code (only the code in relation with the server )

```<code>public class MainActivity extends AppCompatActivity {

        class AsyncTaskUploadClass extends AsyncTask <Void,Void,String> {

            @Override
            protected void onPreExecute() {

                super.onPreExecute();

                progressDialog = ProgressDialog.show(MainActivity.this,"Image is Uploading","Please Wait",false,false);
            }

            @Override
            protected void onPostExecute(String string1) {

                super.onPostExecute(string1);

                progressDialog.dismiss();

                Toast.makeText(MainActivity.this,string1,Toast.LENGTH_LONG).show();

            }

            @Override
            protected String doInBackground(Void... params) {

                ImageProcessClass imageProcessClass = new ImageProcessClass();

                HashMap<String,String> HashMapParams = new HashMap<String,String>();

                HashMapParams.put("image_tag", GetImageNameFromEditText);

                HashMapParams.put("image_data", ConvertImage);

                String FinalData = imageProcessClass.ImageHttpRequest("http://192.168.1.5/documentupload.php", HashMapParams);

                return FinalData;
            }
        }
        AsyncTaskUploadClass AsyncTaskUploadClassOBJ = new AsyncTaskUploadClass();
        AsyncTaskUploadClassOBJ.execute();
    }

    public class ImageProcessClass{

        public String ImageHttpRequest(String requestURL,HashMap<String, String> PData) {

            StringBuilder stringBuilder = new StringBuilder();

            try {
                url = new URL(requestURL);

                httpURLConnection = (HttpURLConnection) url.openConnection();

                httpURLConnection.setReadTimeout(20000);

                httpURLConnection.setConnectTimeout(20000);

                httpURLConnection.setRequestMethod("POST");

                httpURLConnection.setDoInput(true);

                httpURLConnection.setDoOutput(true);

                outputStream = httpURLConnection.getOutputStream();

                bufferedWriter = new BufferedWriter(

                        new OutputStreamWriter(outputStream, "UTF-8"));

                bufferedWriter.write(bufferedWriterDataFN(PData));

                bufferedWriter.flush();

                bufferedWriter.close();

                outputStream.close();

                RC = httpURLConnection.getResponseCode();

                if (RC == HttpsURLConnection.HTTP_OK) {

                    bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));

                    stringBuilder = new StringBuilder();

                    String RC2;

                    while ((RC2 = bufferedReader.readLine()) != null){

                        stringBuilder.append(RC2);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return stringBuilder.toString();
        }

        private String bufferedWriterDataFN(HashMap<String, String> HashMapParams) throws UnsupportedEncodingException {

            stringBuilder = new StringBuilder();

            for (Map.Entry<String, String> KEY : HashMapParams.entrySet()) {
                if (check)
                    check = false;
                else
                    stringBuilder.append("&");

                stringBuilder.append(URLEncoder.encode(KEY.getKey(), "UTF-8"));

                stringBuilder.append("=");

                stringBuilder.append(URLEncoder.encode(KEY.getValue(), "UTF-8"));
            }

            return stringBuilder.toString();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 5) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Now user should be able to use camera

            }
            else {

                Toast.makeText(MainActivity.this, "Unable to use Camera..Please Allow us to use Camera", Toast.LENGTH_LONG).show();

            }
        }
    }
}
</code>```

and finally the XML code

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:visibility="visible"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="10dp"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"
    android:paddingTop="10dp"
    android:background="#E0E0E0"
    android:focusable="true"
    android:focusableInTouchMode="true">
    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:id="@+id/linearLayout">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Upload Image To Server"
                android:textSize="26dp"
                android:textColor="#000"
                android:fontFamily="sans-serif"
                android:paddingBottom="4dp"/>
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="1dp"
                android:background="#000"
                android:layout_marginBottom="10dp">
            </RelativeLayout>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Image Name"
                android:layout_marginTop="10dp"/>
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/imageName"/>
            <Button
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="Select Image"
                android:id="@+id/buttonSelect"
                android:background="#FFF"
                android:layout_margin="10dp"/>

            <ImageView
                android:layout_width="fill_parent"
                android:layout_height="270dp"
                android:id="@+id/imageView"/>
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="1dp"
                android:background="#000"
                android:layout_marginBottom="10dp"
                android:layout_marginTop="10dp">
            </RelativeLayout>

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:gravity="right">

                <Button
                    tools:visibility="visible"
                    android:layout_width="200dp"
                    android:layout_height="wrap_content"
                    android:text="Upload >>"
                    android:textColor="#FFF"
                    android:background="@color/colorPrimary"
                    android:id="@+id/buttonUpload"
                    android:visibility="gone"/>

            </LinearLayout>

        </LinearLayout>
    </ScrollView>

</RelativeLayout>
</code>```

答:
```<code>for (Map.Entry<String, String> KEY : HashMapParams.entrySet()) {
    if (check)
        check = false;
    else
        stringBuilder.append("&");//just give & symbol and remove amp;
    stringBuilder.append(URLEncoder.encode(KEY.getKey(), "UTF-8"));
    stringBuilder.append("=");
    stringBuilder.append(URLEncoder.encode(KEY.getValue(), "UTF-8"));
}
</code>```

Body:
I'm facing a problem while trying to upload image from the app to the server using xampp .

the thing is that when I write the image name($ImageName) manually on the PHP file it works fine but when I try with code it doesn't and show me this message ( the one on the bottom on the first click on the upload button and the other message on the second click and above ) .

enter image description here

this is the php file code

<?php
require "connection.php";
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$DefaultId = 0;
$ImageData = $_POST['image_data'];
$ImageName =$_POST['image_tag'];  /* when I write here "stack" for example
it works and I find the image on the path with the name stack */

$ImagePath = "Documents/$ImageName.jpg";
$ServerURL = "192.168.1.5/$ImagePath";

$InsertSQL = "INSERT INTO imageupload (image_path,image_name) values('$ServerURL','$ImageName')";

if(mysqli_query($conn, $InsertSQL)){

file_put_contents($ImagePath,base64_decode($ImageData));

echo "Your Image Has Been Uploaded.";
}
mysqli_close($conn);
}else{
echo "Please Try Again";
}

?>

and this is the java code (only the code in relation with the server )

public class MainActivity extends AppCompatActivity {

        class AsyncTaskUploadClass extends AsyncTask <Void,Void,String> {

            @Override
            protected void onPreExecute() {

                super.onPreExecute();

                progressDialog = ProgressDialog.show(MainActivity.this,"Image is Uploading","Please Wait",false,false);
            }

            @Override
            protected void onPostExecute(String string1) {

                super.onPostExecute(string1);

                progressDialog.dismiss();

                Toast.makeText(MainActivity.this,string1,Toast.LENGTH_LONG).show();

            }

            @Override
            protected String doInBackground(Void... params) {

                ImageProcessClass imageProcessClass = new ImageProcessClass();

                HashMap<String,String> HashMapParams = new HashMap<String,String>();

                HashMapParams.put("image_tag", GetImageNameFromEditText);

                HashMapParams.put("image_data", ConvertImage);

                String FinalData = imageProcessClass.ImageHttpRequest("http://192.168.1.5/documentupload.php", HashMapParams);

                return FinalData;
            }
        }
        AsyncTaskUploadClass AsyncTaskUploadClassOBJ = new AsyncTaskUploadClass();
        AsyncTaskUploadClassOBJ.execute();
    }

    public class ImageProcessClass{

        public String ImageHttpRequest(String requestURL,HashMap<String, String> PData) {

            StringBuilder stringBuilder = new StringBuilder();

            try {
                url = new URL(requestURL);

                httpURLConnection = (HttpURLConnection) url.openConnection();

                httpURLConnection.setReadTimeout(20000);

                httpURLConnection.setConnectTimeout(20000);

                httpURLConnection.setRequestMethod("POST");

                httpURLConnection.setDoInput(true);

                httpURLConnection.setDoOutput(true);

                outputStream = httpURLConnection.getOutputStream();

                bufferedWriter = new BufferedWriter(

                        new OutputStreamWriter(outputStream, "UTF-8"));

                bufferedWriter.write(bufferedWriterDataFN(PData));

                bufferedWriter.flush();

                bufferedWriter.close();

                outputStream.close();

                RC = httpURLConnection.getResponseCode();

                if (RC == HttpsURLConnection.HTTP_OK) {

                    bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));

                    stringBuilder = new StringBuilder();

                    String RC2;

                    while ((RC2 = bufferedReader.readLine()) != null){

                        stringBuilder.append(RC2);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return stringBuilder.toString();
        }

        private String bufferedWriterDataFN(HashMap<String, String> HashMapParams) throws UnsupportedEncodingException {

            stringBuilder = new StringBuilder();

            for (Map.Entry<String, String> KEY : HashMapParams.entrySet()) {
                if (check)
                    check = false;
                else
                    stringBuilder.append("&");

                stringBuilder.append(URLEncoder.encode(KEY.getKey(), "UTF-8"));

                stringBuilder.append("=");

                stringBuilder.append(URLEncoder.encode(KEY.getValue(), "UTF-8"));
            }

            return stringBuilder.toString();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 5) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Now user should be able to use camera

            }
            else {

                Toast.makeText(MainActivity.this, "Unable to use Camera..Please Allow us to use Camera", Toast.LENGTH_LONG).show();

            }
        }
    }
}

and finally the XML code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:visibility="visible"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="10dp"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"
    android:paddingTop="10dp"
    android:background="#E0E0E0"
    android:focusable="true"
    android:focusableInTouchMode="true">
    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:id="@+id/linearLayout">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Upload Image To Server"
                android:textSize="26dp"
                android:textColor="#000"
                android:fontFamily="sans-serif"
                android:paddingBottom="4dp"/>
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="1dp"
                android:background="#000"
                android:layout_marginBottom="10dp">
            </RelativeLayout>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Image Name"
                android:layout_marginTop="10dp"/>
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/imageName"/>
            <Button
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="Select Image"
                android:id="@+id/buttonSelect"
                android:background="#FFF"
                android:layout_margin="10dp"/>

            <ImageView
                android:layout_width="fill_parent"
                android:layout_height="270dp"
                android:id="@+id/imageView"/>
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="1dp"
                android:background="#000"
                android:layout_marginBottom="10dp"
                android:layout_marginTop="10dp">
            </RelativeLayout>

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:gravity="right">

                <Button
                    tools:visibility="visible"
                    android:layout_width="200dp"
                    android:layout_height="wrap_content"
                    android:text="Upload >>"
                    android:textColor="#FFF"
                    android:background="@color/colorPrimary"
                    android:id="@+id/buttonUpload"
                    android:visibility="gone"/>

            </LinearLayout>

        </LinearLayout>
    </ScrollView>

</RelativeLayout>


来源: stackexchange

问:
How Can I Modify/"Spoof" Standard Browser JS DOM Objects (Window.location) at Runtime?
I'd like to dynamically change some of the standard JS DOM objects from within a web browser.

For instance, when I execute:

```<code>var site = location;
</code>```

I want to specify a new value for my browser's "window.location" object other than the "correct" one (the URL used to access the requested page) at run time, either through a debugger-like interface or even programmatically if need be.

Although Firebug advertises the capability to do something similar via its "DOM Inspector," whenever I try to modify any of the DOM values while I've paused the Javascript via its debugger, it simply ignores the new value I enter.  After doing some research, it seems that this is a known issue according to this bug report: http://code.google.com/p/fbug/issues/detail?id=1707 .

Theoretically, I could write a program to simply open up an HTTP socket and emulate a browser "user agent," but this seems like a lot of trouble for my purposes.  While I'm asking, does anyone know a good Java/C# library with functions/objects that emulate HTTP headers and parse the received HTML/JS?  I've long dreamt about the existence of such a library but most of the ones I've tried (Java's Apache HttpClient, C#'s System.Net.HttpWebRequest) are far too low-level to make anything worthwhile with minimal planning and a short period of time.

Thanks in advance for recommendations and advice you can provide!

答:
Not sure if I understand you correctly, but if you want to change the loaded URL you can do that by setting window.location.href.
If your intent is to replace DOM buildins then you will be sad to hear, that most build-in objects (host objects) aren't regular JavaScript objects and their behaviour is not clearly defined. Some browsers may allow you to replace and/or extend some objects while in other browsers they won't be replaceable/extendable at all.

If you want to "script a browser" using JavaScript, you should definitly have a look at node.js and it's http module. There's also a thirdparty module called html5 that simulates the DOM in node.js and even allows the usage of jQuery.

ContentLicense: CC BY-SA 3.0

Body:
I'd like to dynamically change some of the standard JS DOM objects from within a web browser.

For instance, when I execute:

var site = location;

I want to specify a new value for my browser's "window.location" object other than the "correct" one (the URL used to access the requested page) at run time, either through a debugger-like interface or even programmatically if need be.

Although Firebug advertises the capability to do something similar via its "DOM Inspector," whenever I try to modify any of the DOM values while I've paused the Javascript via its debugger, it simply ignores the new value I enter.  After doing some research, it seems that this is a known issue according to this bug report: http://code.google.com/p/fbug/issues/detail?id=1707 .

Theoretically, I could write a program to simply open up an HTTP socket and emulate a browser "user agent," but this seems like a lot of trouble for my purposes.  While I'm asking, does anyone know a good Java/C# library with functions/objects that emulate HTTP headers and parse the received HTML/JS?  I've long dreamt about the existence of such a library but most of the ones I've tried (Java's Apache HttpClient, C#'s System.Net.HttpWebRequest) are far too low-level to make anything worthwhile with minimal planning and a short period of time.

Thanks in advance for recommendations and advice you can provide!


问:
how to compile fork() on windows [currently trying with cygwin]
I'm trying to translate a c-code written for linux to c-code for windows.
When trying 'make', it says

implicit declaration of function 'fork'

So I searched the internet, found this: What is the closest thing Windows has to fork()? Downloaded Cygwin and installed it and tried 'make' again, it spits out the same error-output. After that, I copied my c project into the cygwin folder, opened the 'cygwin-terminal'-program and run 'make' in it, still same error-output.
After that I copied 'cygwin1.dll' from cygwin bin folder into my project folder and changed my Makefile to

gcc -g -Wall -Wextra -Werror -o test_open cygwin1.dll main.c dictionary.c config.c tools.c

then start 'make' again in normal terminal, but it still spits out implicit declaration error.

Have you any suggestions, what I can try next to get fork() to compile?

Includes are:

```<code>#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<stdbool.h>
#include<stdarg.h>
#include<errno.h>
#include<signal.h>
</code>```

答:
Fork requires the header

```<code>#include <unistd.h>
</code>```

https://pubs.opengroup.org/onlinepubs/9699919799/functions/fork.html

that is contained in the cygwin-devel package

```<code>$ cygcheck -f /usr/include/unistd.h
cygwin-devel-3.1.4-1
</code>```

Using example code from
https://www.geeksforgeeks.org/fork-system-call/

```<code>#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{

    // make two process which run same
    // program after this instruction
    fork();

    printf("Hello world!\n");
    return 0;
}
</code>```

compiled and run with

```<code>$ gcc prova.c -o prova

$ ./prova
Hello world!
Hello world!
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to translate a c-code written for linux to c-code for windows.
When trying 'make', it says

implicit declaration of function 'fork'

So I searched the internet, found this: What is the closest thing Windows has to fork()? Downloaded Cygwin and installed it and tried 'make' again, it spits out the same error-output. After that, I copied my c project into the cygwin folder, opened the 'cygwin-terminal'-program and run 'make' in it, still same error-output.
After that I copied 'cygwin1.dll' from cygwin bin folder into my project folder and changed my Makefile to

gcc -g -Wall -Wextra -Werror -o test_open cygwin1.dll main.c dictionary.c config.c tools.c

then start 'make' again in normal terminal, but it still spits out implicit declaration error.

Have you any suggestions, what I can try next to get fork() to compile?

Includes are:

#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<stdbool.h>
#include<stdarg.h>
#include<errno.h>
#include<signal.h>

Body:
Fork requires the header

#include <unistd.h>

https://pubs.opengroup.org/onlinepubs/9699919799/functions/fork.html

that is contained in the cygwin-devel package

$ cygcheck -f /usr/include/unistd.h
cygwin-devel-3.1.4-1

Using example code from
https://www.geeksforgeeks.org/fork-system-call/

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{

    // make two process which run same
    // program after this instruction
    fork();

    printf("Hello world!\n");
    return 0;
}

compiled and run with

$ gcc prova.c -o prova

$ ./prova
Hello world!
Hello world!


问:
HTML onclick function not working for a button
So I'm making a website, and I have some buttons that scroll to certain parts of a page. I have 5 buttons, and all of them have the exact same code except for their names. One of the buttons is broken and doesn't do anything, even though its code is the same as the working ones.

Here is my HTML:

                About Us

```<code>    <div class = "OurMethodsBar">
        <button class = "OurMethodsButton" onclick = "ScrollTo(OurMethodsAnchor)">
            Our Methods
        </button>
    </div>
    <div class = "InvestBar">
        <button class = "InvestButton" onclick = "ScrollTo(InvestAnchor)">
                Invest
        </button>
    </div>
    <div class = "ContactUsBar">
        <button class = "ContactUsButton" onlclick = "ScrollTo(ContactUsAnchor)">
            Contact Us
        </button>
    </div>
    <div class = "MoreInformationBar">
        <button class = "MoreInformationButton" onclick = "ScrollTo(MoreInfoAnchor)">
            More Info
        </button>
    </div>
</code>```

Here is my JS:

var AboutUsAnchor = document.getElementById("AboutUsAnchor");

```<code>var OurMethodsAnchor = document.getElementById("OurMethodsAnchor");
var InvestAnchor = document.getElementById("InvestAnchor");
var ContactUsAnchor = document.getElementById("ContactUsAnchor");
var MoreInfoAnchor = document.getElementById("MoreInfoAnchor");

function ScrollTo(Element) {
    Element.scrollIntoView(true);
}

ScrollTo(AboutUsAnchor);
</code>```

The broken button is the ContactUsButton which is supposed to scroll to the ContactUsAnchor.
If I manually use my ScrollTo function and input the ContactUsAnchor, it still works, but when I try to hit the button, it doesn't work.

答:
I'd rather change approach and rewrite your function to get a string and get the element by ID later.

```<code>function ScrollTo(element) {
    document.getElementById(element).scrollIntoView(true);
}
</code>```

And then in your buttons just pass the string containing the ID in single quotes '

```<code>    <button class = "ContactUsButton" onclick = "ScrollTo('ContactUsAnchor')">
        Contact Us
    </button>
</code>```

And as others have pointed out, fix that onlclick :P

Body:
So I'm making a website, and I have some buttons that scroll to certain parts of a page. I have 5 buttons, and all of them have the exact same code except for their names. One of the buttons is broken and doesn't do anything, even though its code is the same as the working ones.

Here is my HTML:

                About Us

        <button class = "OurMethodsButton" onclick = "ScrollTo(OurMethodsAnchor)">
            Our Methods
        </button>

        <button class = "InvestButton" onclick = "ScrollTo(InvestAnchor)">
                Invest
        </button>

        <button class = "ContactUsButton" onlclick = "ScrollTo(ContactUsAnchor)">
            Contact Us
        </button>

        <button class = "MoreInformationButton" onclick = "ScrollTo(MoreInfoAnchor)">
            More Info
        </button>

Here is my JS:

var AboutUsAnchor = document.getElementById("AboutUsAnchor");

var OurMethodsAnchor = document.getElementById("OurMethodsAnchor");
var InvestAnchor = document.getElementById("InvestAnchor");
var ContactUsAnchor = document.getElementById("ContactUsAnchor");
var MoreInfoAnchor = document.getElementById("MoreInfoAnchor");

function ScrollTo(Element) {
    Element.scrollIntoView(true);
}

ScrollTo(AboutUsAnchor);

The broken button is the ContactUsButton which is supposed to scroll to the ContactUsAnchor.
If I manually use my ScrollTo function and input the ContactUsAnchor, it still works, but when I try to hit the button, it doesn't work.

Body:
I'd rather change approach and rewrite your function to get a string and get the element by ID later.

function ScrollTo(element) {
    document.getElementById(element).scrollIntoView(true);
}

And then in your buttons just pass the string containing the ID in single quotes '

    <button class = "ContactUsButton" onclick = "ScrollTo('ContactUsAnchor')">
        Contact Us
    </button>

And as others have pointed out, fix that onlclick :P


问:
Location of WAL in Spark Structured Streaming
I have enabled WAL for my Structured Streaming Application. Where do I find the location of WAL logs?
I am able to see WAL for my Spark streaming process in the prefix receivedBlockMetadata . But, I don't see any prefix created for Structured Streaming

答:
In Spark Structure Streaming, now WAL with every message from the receiver.
Only two logs with metadata for every batch: offset and commit logs.
You can find details of implementation in org.apache.spark.sql.execution.streaming.StreamExecution. ->

```<code>/**
   * A write-ahead-log that records the offsets that are present in each batch. In order to ensure
   * that a given batch will always consist of the same data, we write to this log *before* any
   * processing is done.  Thus, the Nth record in this log indicated data that is currently being
   * processed and the N-1th entry indicates which offsets have been durably committed to the sink.
   */
  val offsetLog = new OffsetSeqLog(sparkSession, checkpointFile("offsets"))

  /**
   * A log that records the batch ids that have completed. This is used to check if a batch was
   * fully processed, and its output was committed to the sink, hence no need to process it again.
   * This is used (for instance) during restart, to help identify which batch to run next.
   */
  val commitLog = new CommitLog(sparkSession, checkpointFile("commits"))
</code>```

Both of them available in a checkpointLocation in folder offsets and commits.
In Structure Streaming logs contain only offset information.

Body:
In Spark Structure Streaming, now WAL with every message from the receiver.
Only two logs with metadata for every batch: offset and commit logs.
You can find details of implementation in org.apache.spark.sql.execution.streaming.StreamExecution. ->

/**
   * A write-ahead-log that records the offsets that are present in each batch. In order to ensure
   * that a given batch will always consist of the same data, we write to this log *before* any
   * processing is done.  Thus, the Nth record in this log indicated data that is currently being
   * processed and the N-1th entry indicates which offsets have been durably committed to the sink.
   */
  val offsetLog = new OffsetSeqLog(sparkSession, checkpointFile("offsets"))

  /**
   * A log that records the batch ids that have completed. This is used to check if a batch was
   * fully processed, and its output was committed to the sink, hence no need to process it again.
   * This is used (for instance) during restart, to help identify which batch to run next.
   */
  val commitLog = new CommitLog(sparkSession, checkpointFile("commits"))

Both of them available in a checkpointLocation in folder offsets and commits.
In Structure Streaming logs contain only offset information.


问:
timer in thread problem
I have my application in which in three datagridview independently in three thread load data from wcf service. I execute in each thread timer which every second load this data.

My problem is that every time my thread go threw each thread but only like I show in method timerNowyYork_Elapsed

Any idea why this happens ? I bad lock thread?

this code :

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;

namespace Sprawdzanie_warunków_pogodowych
{
public partial class Form1 : Form
{
    PogodaEntities entity = new PogodaEntities();
    System.Timers.Timer timerKrakow = new System.Timers.Timer();
    System.Timers.Timer timerSzczecin = new System.Timers.Timer();
    System.Timers.Timer timerNowyYork = new System.Timers.Timer();
    KeyValuePair<string, string> krakowInfo;
    KeyValuePair<string, string> szczecinInfo;
    KeyValuePair<string, string> nowyYorkInfo;

    public Form1()
    {
        System.Net.ServicePointManager.Expect100Continue = false;
        InitializeComponent();
        List<MiastoContainer> miasta = (from miasto in entity.Miasta
                                        select new MiastoContainer()
                                   {
                                       MiastoName = miasto.Nazwa,
                                       Panstwo = miasto.Państwo
                                   }).ToList();
        krakowInfo = new KeyValuePair<string, string>(miasta[0].MiastoName, miasta[0].Panstwo);
        szczecinInfo = new KeyValuePair<string, string>(miasta[1].MiastoName, miasta[1].Panstwo);
        nowyYorkInfo = new KeyValuePair<string, string>(miasta[2].MiastoName, miasta[2].Panstwo);

        ParameterizedThreadStart ptsKrakow = new ParameterizedThreadStart(PobierzKrakow);
        Thread tKrakow = new Thread(ptsKrakow);
        tKrakow.Start(this.dataGridViewKrakow);

        ParameterizedThreadStart ptsSzczecin = new ParameterizedThreadStart(PobierzSzczecin);
        Thread tSzczecin = new Thread(ptsSzczecin);
        tSzczecin.Start(this.dataGridViewSzczecin);
    }

    private void oAutorzeToolStripMenuItem_Click(object sender, EventArgs e)
    {
        new AboutBox1().Show();
    }

    private void zapiszRaportToolStripMenuItem_Click(object sender, EventArgs e)
    {

    }

    public void PobierzKrakow(object parameters)
    {
        this.timerKrakow.Elapsed += new System.Timers.ElapsedEventHandler(timerKrakow_Elapsed);
        this.timerKrakow.Enabled = true;
        this.timerKrakow.Interval = 1000;
        this.timerKrakow.Start();
    }

    public void PobierzSzczecin(object parameters)
    {
        this.timerSzczecin.Elapsed += new System.Timers.ElapsedEventHandler(timerSzczecin_Elapsed);
        this.timerSzczecin.Enabled = true;
        this.timerSzczecin.Interval = 1000;
        this.timerSzczecin.Start();
    }

    public void PobierzNowyYork(object parameters)
    {
        this.timerNowyYork.Elapsed += new System.Timers.ElapsedEventHandler(timerNowyYork_Elapsed);
        this.timerNowyYork.Enabled = true;
        this.timerNowyYork.Interval = 1000;
        this.timerNowyYork.Start();
    }

    void timerNowyYork_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {  GlobalWeather.Weather weather = new GlobalWeather.Weather();
        lock (weather)
        {
            //thread always start from here
            List<object> weatherList = new List<object>();
            weatherList.Add(weather.GetTempreature(nowyYorkInfo.Key, nowyYorkInfo.Value));
           //and end here , never come any line further
            weatherList.Add(weather.GetPressure(nowyYorkInfo.Key, nowyYorkInfo.Value));
            weatherList.Add(weather.GetHumidity(nowyYorkInfo.Key, nowyYorkInfo.Value));
            weatherList.Add(weather.GetVisibility(nowyYorkInfo.Key, nowyYorkInfo.Value));
            entity.SaveChanges();

            WarunkiPogodowe warunki = new WarunkiPogodowe()
            {
                Temperatura = weatherList[0].ToString(),
                Ciśnienie = weatherList[1].ToString(),
                Wilgotność = weatherList[2].ToString(),
                Widoczność = weatherList[3].ToString(),
                DataSprawdzenia = DateTime.Now
            };
            entity.AddToWarunkiPogodowe(warunki);
            entity.SaveChanges();
            int miastoId = entity.Miasta.First(m => m.Nazwa == nowyYorkInfo.Key).id;
            Miasto_has_WarunkiPogodowe m_has_wp = new Miasto_has_WarunkiPogodowe()
            {
                idMiasto_FK = miastoId,
                idWarunkiPogodowe_FK = warunki.id
            };
            entity.AddToMiasto_has_WarunkiPogodowe(m_has_wp);
            entity.SaveChanges();

            this.dataGridViewNowyYork.Rows.Add(warunki);
        }
    }

    void timerSzczecin_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        GlobalWeather.Weather weather = new GlobalWeather.Weather();

        lock (weather)
        {
            List<object> weatherList = new List<object>();
            weatherList.Add(weather.GetTempreature(szczecinInfo.Key, szczecinInfo.Value));
            weatherList.Add(weather.GetPressure(szczecinInfo.Key, szczecinInfo.Value));
            weatherList.Add(weather.GetHumidity(szczecinInfo.Key, szczecinInfo.Value));
            weatherList.Add(weather.GetVisibility(szczecinInfo.Key, szczecinInfo.Value));
            entity.SaveChanges();

            WarunkiPogodowe warunki = new WarunkiPogodowe()
            {
                Temperatura = weatherList[0].ToString(),
                Ciśnienie = weatherList[1].ToString(),
                Wilgotność = weatherList[2].ToString(),
                Widoczność = weatherList[3].ToString(),
                DataSprawdzenia = DateTime.Now
            };
            entity.AddToWarunkiPogodowe(warunki);
            entity.SaveChanges();
            int miastoId = entity.Miasta.First(m => m.Nazwa == szczecinInfo.Key).id;
            Miasto_has_WarunkiPogodowe m_has_wp = new Miasto_has_WarunkiPogodowe()
            {
                idMiasto_FK = miastoId,
                idWarunkiPogodowe_FK = warunki.id
            };
            entity.AddToMiasto_has_WarunkiPogodowe(m_has_wp);
            entity.SaveChanges();

            this.dataGridViewSzczecin.Rows.Add(warunki);
        }
    }
    void timerKrakow_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        GlobalWeather.Weather weather = new GlobalWeather.Weather();

        lock (weather)
        {
            List<object> weatherList = new List<object>();
            weatherList.Add(weather.GetTempreature(krakowInfo.Key, krakowInfo.Value));
            weatherList.Add(weather.GetPressure(krakowInfo.Key, krakowInfo.Value));
            weatherList.Add(weather.GetHumidity(krakowInfo.Key, krakowInfo.Value));
            weatherList.Add(weather.GetVisibility(krakowInfo.Key, krakowInfo.Value));
            entity.SaveChanges();

            WarunkiPogodowe warunki = new WarunkiPogodowe()
            {
                Temperatura = weatherList[0].ToString(),
                Ciśnienie = weatherList[1].ToString(),
                Wilgotność = weatherList[2].ToString(),
                Widoczność = weatherList[3].ToString(),
                DataSprawdzenia = DateTime.Now
            };
            entity.AddToWarunkiPogodowe(warunki);
            entity.SaveChanges();
            int miastoId = entity.Miasta.First(m => m.Nazwa == krakowInfo.Key).id;
            Miasto_has_WarunkiPogodowe m_has_wp = new Miasto_has_WarunkiPogodowe()
            {
                idMiasto_FK = miastoId,
                idWarunkiPogodowe_FK = warunki.id
            };
            entity.AddToMiasto_has_WarunkiPogodowe(m_has_wp);
            entity.SaveChanges();

            this.dataGridViewKrakow.Rows.Add(warunki);
        }
    }
}

class MiastoContainer
{
    string miastoName;

    public string MiastoName
    {
        get { return miastoName; }
        set { miastoName = value; }
    }
    string panstwo;

    public string Panstwo
    {
        get { return panstwo; }
        set { panstwo = value; }
    }

    public MiastoContainer()
    { }

    public MiastoContainer(string miasto, string panstwo)
    {
        this.MiastoName = miasto;
        this.Panstwo = panstwo;
    }

    public void Add(MiastoContainer item)
    {
        ((ICollection<MiastoContainer>)this).Add(item);
    }

}
</code>```

}

答:
It seems to me that you are accessing DataGridView directly from another thread. You should not do that. UI controls must always be called from the UI thread. You can use the ISynchronizeInvoke interface to pass the data into correct thread.

```<code>this.dataGridViewNowyYork.Invoke(new Action(() => {
    this.dataGridViewNowyYork.Rows.Add(warunki);
}), null);
</code>```

Title: timer in thread problem

Body:
I have my application in which in three datagridview independently in three thread load data from wcf service. I execute in each thread timer which every second load this data.

My problem is that every time my thread go threw each thread but only like I show in method timerNowyYork_Elapsed

Any idea why this happens ? I bad lock thread?

this code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;

namespace Sprawdzanie_warunków_pogodowych
{
public partial class Form1 : Form
{
    PogodaEntities entity = new PogodaEntities();
    System.Timers.Timer timerKrakow = new System.Timers.Timer();
    System.Timers.Timer timerSzczecin = new System.Timers.Timer();
    System.Timers.Timer timerNowyYork = new System.Timers.Timer();
    KeyValuePair<string, string> krakowInfo;
    KeyValuePair<string, string> szczecinInfo;
    KeyValuePair<string, string> nowyYorkInfo;

    public Form1()
    {
        System.Net.ServicePointManager.Expect100Continue = false;
        InitializeComponent();
        List<MiastoContainer> miasta = (from miasto in entity.Miasta
                                        select new MiastoContainer()
                                   {
                                       MiastoName = miasto.Nazwa,
                                       Panstwo = miasto.Państwo
                                   }).ToList();
        krakowInfo = new KeyValuePair<string, string>(miasta[0].MiastoName, miasta[0].Panstwo);
        szczecinInfo = new KeyValuePair<string, string>(miasta[1].MiastoName, miasta[1].Panstwo);
        nowyYorkInfo = new KeyValuePair<string, string>(miasta[2].MiastoName, miasta[2].Panstwo);

        ParameterizedThreadStart ptsKrakow = new ParameterizedThreadStart(PobierzKrakow);
        Thread tKrakow = new Thread(ptsKrakow);
        tKrakow.Start(this.dataGridViewKrakow);

        ParameterizedThreadStart ptsSzczecin = new ParameterizedThreadStart(PobierzSzczecin);
        Thread tSzczecin = new Thread(ptsSzczecin);
        tSzczecin.Start(this.dataGridViewSzczecin);
    }

    private void oAutorzeToolStripMenuItem_Click(object sender, EventArgs e)
    {
        new AboutBox1().Show();
    }

    private void zapiszRaportToolStripMenuItem_Click(object sender, EventArgs e)
    {

    }

    public void PobierzKrakow(object parameters)
    {
        this.timerKrakow.Elapsed += new System.Timers.ElapsedEventHandler(timerKrakow_Elapsed);
        this.timerKrakow.Enabled = true;
        this.timerKrakow.Interval = 1000;
        this.timerKrakow.Start();
    }

    public void PobierzSzczecin(object parameters)
    {
        this.timerSzczecin.Elapsed += new System.Timers.ElapsedEventHandler(timerSzczecin_Elapsed);
        this.timerSzczecin.Enabled = true;
        this.timerSzczecin.Interval = 1000;
        this.timerSzczecin.Start();
    }

    public void PobierzNowyYork(object parameters)
    {
        this.timerNowyYork.Elapsed += new System.Timers.ElapsedEventHandler(timerNowyYork_Elapsed);
        this.timerNowyYork.Enabled = true;
        this.timerNowyYork.Interval = 1000;
        this.timerNowyYork.Start();
    }

    void timerNowyYork_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {  GlobalWeather.Weather weather = new GlobalWeather.Weather();
        lock (weather)
        {
            //thread always start from here
            List<object> weatherList = new List<object>();
            weatherList.Add(weather.GetTempreature(nowyYorkInfo.Key, nowyYorkInfo.Value));
           //and end here , never come any line further
            weatherList.Add(weather.GetPressure(nowyYorkInfo.Key, nowyYorkInfo.Value));
            weatherList.Add(weather.GetHumidity(nowyYorkInfo.Key, nowyYorkInfo.Value));
            weatherList.Add(weather.GetVisibility(nowyYorkInfo.Key, nowyYorkInfo.Value));
            entity.SaveChanges();

            WarunkiPogodowe warunki = new WarunkiPogodowe()
            {
                Temperatura = weatherList[0].ToString(),
                Ciśnienie = weatherList[1].ToString(),
                Wilgotność = weatherList[2].ToString(),
                Widoczność = weatherList[3].ToString(),
                DataSprawdzenia = DateTime.Now
            };
            entity.AddToWarunkiPogodowe(warunki);
            entity.SaveChanges();
            int miastoId = entity.Miasta.First(m => m.Nazwa == nowyYorkInfo.Key).id;
            Miasto_has_WarunkiPogodowe m_has_wp = new Miasto_has_WarunkiPogodowe()
            {
                idMiasto_FK = miastoId,
                idWarunkiPogodowe_FK = warunki.id
            };
            entity.AddToMiasto_has_WarunkiPogodowe(m_has_wp);
            entity.SaveChanges();

            this.dataGridViewNowyYork.Rows.Add(warunki);
        }
    }

    void timerSzczecin_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        GlobalWeather.Weather weather = new GlobalWeather.Weather();

        lock (weather)
        {
            List<object> weatherList = new List<object>();
            weatherList.Add(weather.GetTempreature(szczecinInfo.Key, szczecinInfo.Value));
            weatherList.Add(weather.GetPressure(szczecinInfo.Key, szczecinInfo.Value));
            weatherList.Add(weather.GetHumidity(szczecinInfo.Key, szczecinInfo.Value));
            weatherList.Add(weather.GetVisibility(szczecinInfo.Key, szczecinInfo.Value));
            entity.SaveChanges();

            WarunkiPogodowe warunki = new WarunkiPogodowe()
            {
                Temperatura = weatherList[0].ToString(),
                Ciśnienie = weatherList[1].ToString(),
                Wilgotność = weatherList[2].ToString(),
                Widoczność = weatherList[3].ToString(),
                DataSprawdzenia = DateTime.Now
            };
            entity.AddToWarunkiPogodowe(warunki);
            entity.SaveChanges();
            int miastoId = entity.Miasta.First(m => m.Nazwa == szczecinInfo.Key).id;
            Miasto_has_WarunkiPogodowe m_has_wp = new Miasto_has_WarunkiPogodowe()
            {
                idMiasto_FK = miastoId,
                idWarunkiPogodowe_FK = warunki.id
            };
            entity.AddToMiasto_has_WarunkiPogodowe(m_has_wp);
            entity.SaveChanges();

            this.dataGridViewSzczecin.Rows.Add(warunki);
        }
    }
    void timerKrakow_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        GlobalWeather.Weather weather = new GlobalWeather.Weather();

        lock (weather)
        {
            List<object> weatherList = new List<object>();
            weatherList.Add(weather.GetTempreature(krakowInfo.Key, krakowInfo.Value));
            weatherList.Add(weather.GetPressure(krakowInfo.Key, krakowInfo.Value));
            weatherList.Add(weather.GetHumidity(krakowInfo.Key, krakowInfo.Value));
            weatherList.Add(weather.GetVisibility(krakowInfo.Key, krakowInfo.Value));
            entity.SaveChanges();

            WarunkiPogodowe warunki = new WarunkiPogodowe()
            {
                Temperatura = weatherList[0].ToString(),
                Ciśnienie = weatherList[1].ToString(),
                Wilgotność = weatherList[2].ToString(),
                Widoczność = weatherList[3].ToString(),
                DataSprawdzenia = DateTime.Now
            };
            entity.AddToWarunkiPogodowe(warunki);
            entity.SaveChanges();
            int miastoId = entity.Miasta.First(m => m.Nazwa == krakowInfo.Key).id;
            Miasto_has_WarunkiPogodowe m_has_wp = new Miasto_has_WarunkiPogodowe()
            {
                idMiasto_FK = miastoId,
                idWarunkiPogodowe_FK = warunki.id
            };
            entity.AddToMiasto_has_WarunkiPogodowe(m_has_wp);
            entity.SaveChanges();

            this.dataGridViewKrakow.Rows.Add(warunki);
        }
    }
}

class MiastoContainer
{
    string miastoName;

    public string MiastoName
    {
        get { return miastoName; }
        set { miastoName = value; }
    }
    string panstwo;

    public string Panstwo
    {
        get { return panstwo; }
        set { panstwo = value; }
    }

    public MiastoContainer()
    { }

    public MiastoContainer(string miasto, string panstwo)
    {
        this.MiastoName = miasto;
        this.Panstwo = panstwo;
    }

    public void Add(MiastoContainer item)
    {
        ((ICollection<MiastoContainer>)this).Add(item);
    }

}

}

Body:
It seems to me that you are accessing DataGridView directly from another thread. You should not do that. UI controls must always be called from the UI thread. You can use the ISynchronizeInvoke interface to pass the data into correct thread.

this.dataGridViewNowyYork.Invoke(new Action(() => {
    this.dataGridViewNowyYork.Rows.Add(warunki);
}), null);


问:
Memory leak in hibernate5 typeconfiguration registry class
Recently we have integrated hibernate 5 with our application upgrading it from hibernate 3.

After few months we have started seeing memory leak in typeconfiguration registry class in hibernate 5.

https://github.com/hibernate/hibernate-orm/blob/master/hibernate-core/src/main/java/org/hibernate/type/internal/TypeConfigurationRegistry.java

Particularly while creating new concurrent hashmap in the registerTypeConfiguration method.

The heap dump clearly states there is a leak.

Contents of this file during bootstrap indicates it contains all the dao classes.

Going by this there should be single set of DAO classes that gets registered during boot time and deregisters during shutdown.

But it is leaking memory which is concerning during runtime. Are there duplicate copies of DAO classes??

We use spring's localSessionFactoryBean to integrate with hibernate transaction manager.

Going by the localSessionFactoryBean documentation it is compatible with hibernate 5 which pegs the question why there is a leak?

Dependencies:

```<code><dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>4.3.23.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.3.9.Final</version>
</dependency>
<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-jdbc</artifactId>
    <version>7.0.19</version>
</dependency>
</code>```

Configs:

```<code><bean id="sessionFactory"
      class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource"
          ref="dataSource"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.cache.region.factory_class">
                    <<>>
                </prop>
                <prop key="hibernate.dialect">
                    <<>>
                </prop>
            </props>
        </property>
    </bean>
<bean id="txManager"
      class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
</bean>
</code>```

答:
A few months back I faced a similar issue at work (leak from the same class but as part of a different hibernate workflow). Turns out that whenever Hibernate creates a TypeConfiguration it internally registers itself with the TypeConfigurationRegistry as shown in this file. The only place I see the de-registration happening is as part of session factory close callback as shown here.

We were using the SchemaExport Hibernate API along with the HBM XML syntax. Given that there was no "official" way to clear out the in-built Hibernate cache, we adopted a workaround to grab a reference to the internal state of TypeConfigurationRegistry and clear it out.

Not the best way to go about it, I know, but just wanted to put this out there in case someone is in a similar situation like us.

Body:
Recently we have integrated hibernate 5 with our application upgrading it from hibernate 3.

After few months we have started seeing memory leak in typeconfiguration registry class in hibernate 5.

https://github.com/hibernate/hibernate-orm/blob/master/hibernate-core/src/main/java/org/hibernate/type/internal/TypeConfigurationRegistry.java

Particularly while creating new concurrent hashmap in the registerTypeConfiguration method.

The heap dump clearly states there is a leak.

Contents of this file during bootstrap indicates it contains all the dao classes.

Going by this there should be single set of DAO classes that gets registered during boot time and deregisters during shutdown.

But it is leaking memory which is concerning during runtime. Are there duplicate copies of DAO classes??

We use spring's localSessionFactoryBean to integrate with hibernate transaction manager.

Going by the localSessionFactoryBean documentation it is compatible with hibernate 5 which pegs the question why there is a leak?

Dependencies:

<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>4.3.23.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.3.9.Final</version>
</dependency>
<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-jdbc</artifactId>
    <version>7.0.19</version>
</dependency>

Configs:

<bean id="sessionFactory"
      class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource"
          ref="dataSource"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.cache.region.factory_class">
                    <<>>
                </prop>
                <prop key="hibernate.dialect">
                    <<>>
                </prop>
            </props>
        </property>
    </bean>
<bean id="txManager"
      class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
</bean>


问:
Android Studio 3.6.1 error when i hook frame layout with autocomplete
Hello I just want to switch from a fragment to another using a button. Nothing difficult... the code works well but I have spent a lot of time because Android goesto error if I hook frameLayout with autocompile.
I'm explaining better:

```<code>package com.example.fragcookbook;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;

public class MainActivity extends AppCompatActivity {

    FragmentOne mFragmentOne;
    FragmentTwo mFragmentTwo;
    int showingFragment=0;

    @Override
    protected void onCreate ( Bundle savedInstanceState ) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.activity_main);
        mFragmentOne = new FragmentOne();
        mFragmentTwo = new FragmentTwo();
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.frameLayout, mFragmentOne);
        fragmentTransaction.commit();
        showingFragment=1;

    }
    public void switchFragment(View view) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        if (showingFragment==1) {
            fragmentTransaction.replace(R.id.frameLayout, mFragmentTwo);
            showingFragment = 2;
        } else {
            fragmentTransaction.replace(R.id.frameLayout, mFragmentOne);
            showingFragment=1;
        }
        fragmentTransaction.commit();
    }
</code>```

In all rows where you see R.id.frameLayout i have to handly write frameLayout..... Android colors it red but It works...

But if i choose the resource with autocompile...

...when i run app Android gives me this error....

Why? is not best practice use autocompile?
Thanks in advance

答:
Try this may will help you.Go to "File" -> "Invalidate Caches...", and select "Invalidate and Restart" option to fix this.

Or

Restar you android studio and emulator

Body:
Hello I just want to switch from a fragment to another using a button. Nothing difficult... the code works well but I have spent a lot of time because Android goesto error if I hook frameLayout with autocompile.
I'm explaining better:

package com.example.fragcookbook;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;

public class MainActivity extends AppCompatActivity {

    FragmentOne mFragmentOne;
    FragmentTwo mFragmentTwo;
    int showingFragment=0;

    @Override
    protected void onCreate ( Bundle savedInstanceState ) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.activity_main);
        mFragmentOne = new FragmentOne();
        mFragmentTwo = new FragmentTwo();
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.frameLayout, mFragmentOne);
        fragmentTransaction.commit();
        showingFragment=1;

    }
    public void switchFragment(View view) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        if (showingFragment==1) {
            fragmentTransaction.replace(R.id.frameLayout, mFragmentTwo);
            showingFragment = 2;
        } else {
            fragmentTransaction.replace(R.id.frameLayout, mFragmentOne);
            showingFragment=1;
        }
        fragmentTransaction.commit();
    }

In all rows where you see R.id.frameLayout i have to handly write frameLayout..... Android colors it red but It works...

But if i choose the resource with autocompile...

...when i run app Android gives me this error....

Why? is not best practice use autocompile?
Thanks in advance


问:
How to seed entity framework core data with related data
I have these two classes:

```<code>public class Item
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    public Store Location { get; set; }
}

public class Store
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }
}
</code>```

I want to seed some example data in my ASP.NET Core Entity Framework Core WebAPI Code First application.

So I saw I can use something like:

```<code>modelBuilder.Entity<Item>().HasData(new Item {<properties>});
</code>```

Two problems:

If I don't provide a value for "ID" I get an exception that it is required.

If I provide a value for Location like new Store{<etc.>} I get an error that no value was provided for LocationID which is the column in my database in table "Items" that is a foreign key linking that table with table "Stores".

How do I seed a new "Item" in my database when that class doesn't have a "LocationID" property? And must I first specifically add a "Store" before adding an "Item"? I was hoping there would be some sort of automatic cascade insert.

答:
About your questions:

You just provide Id since you are seeding initial data

You have to insert Stores, there is no such thing as "cascade insert", what would EF insert as Name in automatically generated Stores?

So you need also to seed your Stores like you are seeding Items:

```<code>modelBuilder.Entity<Store>().HasData(new Store {<properties>});
</code>```

What would I also do, is to change you models like this:

```<code>public class Item
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public int StoreId { get; set; } //or LocationId  if you prefer

    [Required]
    public Store Location { get; set; }
}

public class Store
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    public virtual ICollection<Item> Items { get; set; }
}
</code>```

and you need to set this as foreign key for your Location object:

```<code>modelBuilder.Entity<Item>().HasOne(e => e.Location)
                .WithMany(e => e.Items)
                .HasForeignKey(e => e.StoreId)
                .OnDelete(DeleteBehavior.Restrict);
</code>```

after that you can just adjust your seed method to:

```<code>modelBuilder.Entity<Item>().HasData(new Item { Id = 1, StoreId = 1 });
</code>```

Note that there is no need to instantiate Location object.

Body:
I have these two classes:

public class Item
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    public Store Location { get; set; }
}

public class Store
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }
}

I want to seed some example data in my ASP.NET Core Entity Framework Core WebAPI Code First application.

So I saw I can use something like:

modelBuilder.Entity<Item>().HasData(new Item {<properties>});

Two problems:

If I don't provide a value for "ID" I get an exception that it is required.

If I provide a value for Location like new Store{<etc.>} I get an error that no value was provided for LocationID which is the column in my database in table "Items" that is a foreign key linking that table with table "Stores".

How do I seed a new "Item" in my database when that class doesn't have a "LocationID" property? And must I first specifically add a "Store" before adding an "Item"? I was hoping there would be some sort of automatic cascade insert.

Body:
About your questions:

You just provide Id since you are seeding initial data

You have to insert Stores, there is no such thing as "cascade insert", what would EF insert as Name in automatically generated Stores?

So you need also to seed your Stores like you are seeding Items:

modelBuilder.Entity<Store>().HasData(new Store {<properties>});

What would I also do, is to change you models like this:

public class Item
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public int StoreId { get; set; } //or LocationId  if you prefer

    [Required]
    public Store Location { get; set; }
}

public class Store
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    public virtual ICollection<Item> Items { get; set; }
}

and you need to set this as foreign key for your Location object:

modelBuilder.Entity<Item>().HasOne(e => e.Location)
                .WithMany(e => e.Items)
                .HasForeignKey(e => e.StoreId)
                .OnDelete(DeleteBehavior.Restrict);

after that you can just adjust your seed method to:

modelBuilder.Entity<Item>().HasData(new Item { Id = 1, StoreId = 1 });

Note that there is no need to instantiate Location object.


问:
Is it possible to run a greater than query in AWS DynamoDB?
Let's say I have my DynamoDB table like this, with Order ID as the primary key. :

The Order ID increments by one, everytime I add/put a new item.

Now, I have one number, let's say 1000, and my user wants to get all the items which have Order ID > 1000.
So the items returned would be 1001, 1002, 1003, and so on till the last one.

My requirement is as simple as it seems - but is this thing possible to do with Query method of AWS DynamoDB?

Any help is appreciated :)
Thanks!

答:
No, because Query expects an exact key, and does not allow an expression for the partition key (it does however for the sort key).

What you could use however is a Scan with a FilterExpressions (see Filter Expressions for Scan
 and Condition Expressions for the syntax). This reads all records and filters afterwards, so it is not the most effective way.


问:
How to rename many dfs with digit-like column?
I have 5 dfs called:
control1,control2,control3,control4,control5.

All of these have a column name 1. This column name is int type.

How can i change this column name for each df to 'CODIGO' (str type).

I tried this:

```<code>for j in range(1,6):
   exec(f"control{j}=control{j}.rename(columns=lambda x: x.replace(1, 'CODIGO'))")
</code>```

But does not work. Can you help me please?

答:
Like this:</p>

```<code>l = [control1, control2, control3, control4, control5]

for df in l:
    df.rename(columns={1:'CODIGO'}, inplace=True)
</code>```

Body:
I have 5 dfs called:
control1,control2,control3,control4,control5.

All of these have a column name 1. This column name is int type.

How can i change this column name for each df to 'CODIGO' (str type).

I tried this:

for j in range(1,6):
   exec(f"control{j}=control{j}.rename(columns=lambda x: x.replace(1, 'CODIGO'))")

But does not work. Can you help me please?

Body:
Like this:

l = [control1, control2, control3, control4, control5]

for df in l:
    df.rename(columns={1:'CODIGO'}, inplace=True)


问:
SSIS consolidate and concatenate multiple rows into single rows without using SQL
I am trying to accomplish something that is pretty easy to do in SQL, but seemingly very challenging to do in SSIS without using SQL.  Basically, I need to consolidate and concatenate a field of a many-to-one relationship.

Given entities:  [Contract Item] (many) to (one) [Account]

There is a field [ari_productsummary] that contains the product listed on the Contract Item entity.  We want to write that value to the Account as [ari_activecontractitems].  However, an Account may have more than one Contract Item record associated to it, in which case, we want to concatenate those values.  We also only want the distinct values to be concatenated (distinct rows already solved within my data flow).

This can be accomplished by writing to a temporary table, and then using a query or view to obtain the summarized results as followed.  I created a SQL table called TESTTABLE that contains the [ari_productsummary] from the Contract Item entity along with the referring [accountid] to map it back to Account.  I then wrote the following query as a view:

```<code>SELECT distinct accountid,
        (SELECT TT2.ari_productsummary + '; '
                FROM TESTTABLE TT2
                WHERE TT2.accountid = TT.accountid
                FOR XML PATH ('')
            ) AS 'ari_activecontractitems'
FROM TESTTABLE TT
</code>```

Executing that Query provides me the results that I want, which I can then use for importing into the Account entity as shown below:

But how do I do this in a SSIS dataflow without writing to a SQL table as a temporary placeholder for the data??  I want to do the entire process inside one dataflow container, without using a temporary SQL table/view.  The whole summarization process needs to be done on the fly:

Does anyone have a solution that doesn't require a temporary SQL table/view/query, but is contained entirely within the data flow?

I am using VS 2017 and the KingswaySoft Dynamic CRM 365 ETL toolset to develop my solution/package.

答:
We have an upcoming release that comes with a component that does exactly what you are trying to achieve without the need of writing custom code. The feature is currently under preview, please reach out to us for private access to the feature. You can find our contact information on our website.

UPDATE - June 5, 2020, we have made the components available for public access at https://www.kingswaysoft.com/products/ssis-productivity-pack/ as a result of our 2020 Release Wave 1. We have two components available that serve this kind of purpose. The Composition component will take input values and transform into a composite value in a SSIS column. The Decomposition component does the opposite, it would take an input value and split it into multiple rows using either delimiter-based text splitting or XML/JSON array splitting.

Body:
I am trying to accomplish something that is pretty easy to do in SQL, but seemingly very challenging to do in SSIS without using SQL.  Basically, I need to consolidate and concatenate a field of a many-to-one relationship.

Given entities:  [Contract Item] (many) to (one) [Account]

There is a field [ari_productsummary] that contains the product listed on the Contract Item entity.  We want to write that value to the Account as [ari_activecontractitems].  However, an Account may have more than one Contract Item record associated to it, in which case, we want to concatenate those values.  We also only want the distinct values to be concatenated (distinct rows already solved within my data flow).

This can be accomplished by writing to a temporary table, and then using a query or view to obtain the summarized results as followed.  I created a SQL table called TESTTABLE that contains the [ari_productsummary] from the Contract Item entity along with the referring [accountid] to map it back to Account.  I then wrote the following query as a view:

SELECT distinct accountid,
        (SELECT TT2.ari_productsummary + '; '
                FROM TESTTABLE TT2
                WHERE TT2.accountid = TT.accountid
                FOR XML PATH ('')
            ) AS 'ari_activecontractitems'
FROM TESTTABLE TT

Executing that Query provides me the results that I want, which I can then use for importing into the Account entity as shown below:

But how do I do this in a SSIS dataflow without writing to a SQL table as a temporary placeholder for the data??  I want to do the entire process inside one dataflow container, without using a temporary SQL table/view.  The whole summarization process needs to be done on the fly:

Does anyone have a solution that doesn't require a temporary SQL table/view/query, but is contained entirely within the data flow?

I am using VS 2017 and the KingswaySoft Dynamic CRM 365 ETL toolset to develop my solution/package.


问:
arrays to store 20 numbers, then display the highest, lowest, total of the numbers and the average
How do I write an array that stores 20 numbers and then displays the following data: the lowest number in the array, the highest, the total of the numbers and the average of them?</p>

答:
Using java programing language </p>

```<code>int myArray[] = {15,25,85,32,74,15,3,25,63,32,2,1,9,4,54,25,0,65,74};

int max = myArray[0];
int min = myArray[0];
int sum = 0;

for (int i=0 ; i< myArray.length() ; i++){
    if(myArray[i] > max){
        max=myArray[i];
    }

    if(myArray[i] < min){
        min=myArray[i];
    }

    sum += myArray[i];
}
int average = sum / myArray.length();
</code>```

Body:
Using java programing language

int myArray[] = {15,25,85,32,74,15,3,25,63,32,2,1,9,4,54,25,0,65,74};

int max = myArray[0];
int min = myArray[0];
int sum = 0;

for (int i=0 ; i< myArray.length() ; i++){
    if(myArray[i] > max){
        max=myArray[i];
    }

    if(myArray[i] < min){
        min=myArray[i];
    }

    sum += myArray[i];
}
int average = sum / myArray.length();


问:
Grid System in CSS
I would like to display 3 white blocks in a blue container. Each with a 10px margin between.

Currently I have this:

                    <t class="f30 helv grey">Create Group</t>

                    <t class="f30 helv-b grey">Group Name</t>

                    <input class="gen-input helv-b">

                    <t class="f30 helv-b grey">Array Type</t>

                    <select class="gen-input helv txtind-10">
                      <option>Option 1</option>
                      <option>Option 2</option>
                    </select>

                    <button class="b_next">Next</button>

```

<pre class="lang-css prettyprint-override"><code>.wbg-create{
    position: absolute;
    width: 84%;
    background-color: #f3fbff;
    border-radius: 50px;
    height: 98vh;
    margin-top: 0px;
    text-align: center;
}
.f30{
    font-size: 30px;
}
.helv{
    font-family: Helvetica Neue;
}
.helv-b{
    font-family: Helvetica Neue;
    font-weight: bold;
}
.grey{
    color: #545454;
}
.gen-input{
    background-color: #e3e8ed;
    height: 50px;
    width: 300px;
    border-radius: 30px;
    border-color: transparent;
    text-align: center;
    font-size: 20px;
}
.txtind-10{
    text-indent: 10px;
}
.full-create{
    margin: 10px;
}
.white-create{
    left: 50%;
    width: 33%;
    background-color: white;
    border-radius: 50px;
    height: 96vh;
}
.b_next{
    border-radius: 50px;
    height: 45px;
    text-align: center;
    width: 100px;
    font-size: 20px;
    background-color: #cad2e7;
    color: #28284c;
    border-color: transparent;
    bottom: 30px;
}

.b_next:hover{
    border-radius: 50px;
    height: 45px;
    text-align: center;
    width: 100px;
    font-size: 20px;
    background-color: #dde7ff;
    color: #4e4e95;
    border-color: transparent;
}
.b_next:active{
    border-radius: 50px;
    height: 45px;
    text-align: center;
    width: 100px;
    font-size: 20px;
    background-color: #ffffff;
    color: #30a3f5;
    border-color: transparent;
}

</code>```

I know this is really messy, and I should be using margin and padding instead of
 but I find it a very long process. My web-app is only run in full-screen and cannot be resized, so it shouldn't be too much of a problem.

How do I get these containers to appear side-by-side?
Currently, there are side-by-side, but they appear below the previous one.

Like this:

```<code>[]-should be here-
  []
    []
</code>```

How can I fix this?

答:
Using grid.

```<code>.wbg-create {
display: grid;
grid-template-columns: repeat(3, 1fr)
grid-gap: 10px;
}
</code>```

Here's a pen with the working answer.
https://codepen.io/jorgeberen/pen/wvKVBNN

Using flex should do the trick too.

```<code>.wbg-create {
display: flex;
}
</code>```

Because display:flex displays the items within the container by default in a horizontal row, your three white blocks should be displayed side by side. For this case scenario it is simpler than using grid.

Title: Grid System in CSS

Body:
I would like to display 3 white blocks in a blue container. Each with a 10px margin between.

Currently I have this:

                    <t class="f30 helv grey">Create Group</t>

                    <t class="f30 helv-b grey">Group Name</t>

                    <input class="gen-input helv-b">

                    <t class="f30 helv-b grey">Array Type</t>

                    <select class="gen-input helv txtind-10">
                      <option>Option 1</option>
                      <option>Option 2</option>
                    </select>

                    <button class="b_next">Next</button>

.wbg-create{
    position: absolute;
    width: 84%;
    background-color: #f3fbff;
    border-radius: 50px;
    height: 98vh;
    margin-top: 0px;
    text-align: center;
}
.f30{
    font-size: 30px;
}
.helv{
    font-family: Helvetica Neue;
}
.helv-b{
    font-family: Helvetica Neue;
    font-weight: bold;
}
.grey{
    color: #545454;
}
.gen-input{
    background-color: #e3e8ed;
    height: 50px;
    width: 300px;
    border-radius: 30px;
    border-color: transparent;
    text-align: center;
    font-size: 20px;
}
.txtind-10{
    text-indent: 10px;
}
.full-create{
    margin: 10px;
}
.white-create{
    left: 50%;
    width: 33%;
    background-color: white;
    border-radius: 50px;
    height: 96vh;
}
.b_next{
    border-radius: 50px;
    height: 45px;
    text-align: center;
    width: 100px;
    font-size: 20px;
    background-color: #cad2e7;
    color: #28284c;
    border-color: transparent;
    bottom: 30px;
}

.b_next:hover{
    border-radius: 50px;
    height: 45px;
    text-align: center;
    width: 100px;
    font-size: 20px;
    background-color: #dde7ff;
    color: #4e4e95;
    border-color: transparent;
}
.b_next:active{
    border-radius: 50px;
    height: 45px;
    text-align: center;
    width: 100px;
    font-size: 20px;
    background-color: #ffffff;
    color: #30a3f5;
    border-color: transparent;
}

I know this is really messy, and I should be using margin and padding instead of
 but I find it a very long process. My web-app is only run in full-screen and cannot be resized, so it shouldn't be too much of a problem.

How do I get these containers to appear side-by-side?
Currently, there are side-by-side, but they appear below the previous one.

Like this:

[]-should be here-
  []
    []

How can I fix this?

Body:
Using grid.

.wbg-create {
display: grid;
grid-template-columns: repeat(3, 1fr)
grid-gap: 10px;
}

Here's a pen with the working answer.
https://codepen.io/jorgeberen/pen/wvKVBNN

Using flex should do the trick too.

.wbg-create {
display: flex;
}

Because display:flex displays the items within the container by default in a horizontal row, your three white blocks should be displayed side by side. For this case scenario it is simpler than using grid.


问:
PHP: How to modify working email script to run on own server (PHP mail server setup on LAMP server)
I am using lines like the below to send emails after submitting a form on my website.

So far everyhing works as intended.

Now I would like to set up my own server and would like to avoid setting up an email client on this server.

Can someone tell me what I have to add here to set this up to use a mailing server ?

Does this work using IP addresses or do I need an extra PHP file for this kind of set up ?

Note: My emails will only contain text and some basic HTML, no attachments.

I am pretty new to PHP and was hoping to get some help in getting started with this here.

My PHP (shortened):

```<code>// get submitted form data
$postData = $_POST;
// retrieve some post data to include in email

unset($postData);

// prepare email
$to = 'someone@mail.com';
$subject = 'Some text';

$emailBody = '<html><body>Some HTML text</body></html>';
$headers = 'From: Someone <someone@mail.com>' . PHP_EOL .
    'Cc: someoneelse@mail.com <someoneelse@mail.com>' . PHP_EOL .
    'Reply-To: noreply@mail.com <noreply@mail.com>' . PHP_EOL .
    'X-Mailer: PHP/' . phpversion();

// set content-type header for sending HTML email
$headers .= "\r\n". "MIME-Version: 1.0";
$headers .= "\r\n". "Content-type:text/html;charset=UTF-8";

// send email
$mail = mail($to, $subject, $emailBody, $headers);

if($mail) {
    header('Location: support.php?status=emailSent');
}
</code>```

Many thanks in advance,
Tom

答:
Open your php.ini file an look for "[mail function]".  You can specify your SMTP server/port/credentials there.

```<code>[mail function]
SMTP = smtp.example.com
smtp_port = 25
username = info@example.com
password = yourmailpassord
sendmail_from = info@example.com
</code>```

Here you can set it up like your email client on whatever machine you have email set up.

Body:
I am using lines like the below to send emails after submitting a form on my website.

So far everyhing works as intended.

Now I would like to set up my own server and would like to avoid setting up an email client on this server.

Can someone tell me what I have to add here to set this up to use a mailing server ?

Does this work using IP addresses or do I need an extra PHP file for this kind of set up ?

Note: My emails will only contain text and some basic HTML, no attachments.

I am pretty new to PHP and was hoping to get some help in getting started with this here.

My PHP (shortened):

// get submitted form data
$postData = $_POST;
// retrieve some post data to include in email

unset($postData);

// prepare email
$to = 'someone@mail.com';
$subject = 'Some text';

$emailBody = 'Some HTML text';
$headers = 'From: Someone <someone@mail.com>' . PHP_EOL .
    'Cc: someoneelse@mail.com <someoneelse@mail.com>' . PHP_EOL .
    'Reply-To: noreply@mail.com <noreply@mail.com>' . PHP_EOL .
    'X-Mailer: PHP/' . phpversion();

// set content-type header for sending HTML email
$headers .= "\r\n". "MIME-Version: 1.0";
$headers .= "\r\n". "Content-type:text/html;charset=UTF-8";

// send email
$mail = mail($to, $subject, $emailBody, $headers);

if($mail) {
    header('Location: support.php?status=emailSent');
}

Many thanks in advance,
Tom

Body:
Open your php.ini file an look for "[mail function]".  You can specify your SMTP server/port/credentials there.

[mail function]
SMTP = smtp.example.com
smtp_port = 25
username = info@example.com
password = yourmailpassord
sendmail_from = info@example.com

Here you can set it up like your email client on whatever machine you have email set up.


问:
How to restart Kestrel Hosted in Windows Service?
I want to restart Kestrel (asp.net core 3.1) via an authorized http request.
Kestrel is contained in a Windows service configured to restart itself automatically upon failure.
As far as i know the simplest way is to return an exit code different from 0, windows will do all the rest.

In light of that, the code I wrote is actually simple:

```<code>        public MaintenanceController(IHostApplicationLifetime hostLifetime)
        {
            this.HostLifetime = hostLifetime ?? throw new ArgumentNullException(nameof(hostLifetime));
        }

        [HttpPost]
        [Route("service/restart")]
        [Authorize("AdminOnly")]
        public ActionResult RestartService()
        {
                Program.IsRestart = true; //see below
                this.HostLifetime.StopApplication();

                //this does not work!
                if (HostLifetime is WindowsServiceLifetime lifetime)
                {
                    lifetime.ExitCode = 1;
                }
                //neither this!
                Environment.ExitCode = 1;

                return Ok();
        }
</code>```

The only way to make windows restarts the service is just actually call

```<code>Environment.Exit(1);
</code>```

without HostLifetime.StopApplication();

But the issue with Environment.Exit called alone is it causes a non graceful shutdown, something I want absolutely to avoid.

Another approach I tried, to force an exit code different from 0, which did not work, was to put in Startup.cs:

```<code>        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime applicationLifetime)
        {
            [...]

            applicationLifetime.ApplicationStopped.Register(() =>
            {
                //this can be set in the controller
                if (Program.IsRestart)
                {
                    Environment.Exit(1);
                }
            });
        }
</code>```

but, when called after ApplicationStopped, Environment.Exit(1) does apparently nothing, in fact even inside event viewer there is no trace of the services' shutdown with error, so windows does nothing.

UPDATE

Going back to classic, I changed the Main entry point to return an int and returned 1.
Still windows does not restart the service nor a failure entry is written to event viewer. It looks like is always stopped gracefully

答:
Everything is working like it should. You may want to consider writing a wrapper batch file or watcher process.

Your watcher would wait for the process to exit, and if a flag file (e.g. .staydown) is present, it would exit gracefully. If the file doesn't exist, it would then restart the process.

In your RestartService method, use Environment.Exit(0) which would be a graceful shutdown, but since the .staydown file doesn't exist, your watcher would then restart the server.  Your watcher would only stop running if the .staydown file exists and then the server is stopped, or the Windows Service itself is stopped.

When your app starts up, be sure to delete .staydown if present.

If you have node installed, you might be able to use a utility like forever in place of the watcher batch file.

Body:
I want to restart Kestrel (asp.net core 3.1) via an authorized http request.
Kestrel is contained in a Windows service configured to restart itself automatically upon failure.
As far as i know the simplest way is to return an exit code different from 0, windows will do all the rest.

In light of that, the code I wrote is actually simple:

        public MaintenanceController(IHostApplicationLifetime hostLifetime)
        {
            this.HostLifetime = hostLifetime ?? throw new ArgumentNullException(nameof(hostLifetime));
        }

        [HttpPost]
        [Route("service/restart")]
        [Authorize("AdminOnly")]
        public ActionResult RestartService()
        {
                Program.IsRestart = true; //see below
                this.HostLifetime.StopApplication();

                //this does not work!
                if (HostLifetime is WindowsServiceLifetime lifetime)
                {
                    lifetime.ExitCode = 1;
                }
                //neither this!
                Environment.ExitCode = 1;

                return Ok();
        }

The only way to make windows restarts the service is just actually call

Environment.Exit(1);

without HostLifetime.StopApplication();

But the issue with Environment.Exit called alone is it causes a non graceful shutdown, something I want absolutely to avoid.

Another approach I tried, to force an exit code different from 0, which did not work, was to put in Startup.cs:

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime applicationLifetime)
        {
            [...]

            applicationLifetime.ApplicationStopped.Register(() =>
            {
                //this can be set in the controller
                if (Program.IsRestart)
                {
                    Environment.Exit(1);
                }
            });
        }

but, when called after ApplicationStopped, Environment.Exit(1) does apparently nothing, in fact even inside event viewer there is no trace of the services' shutdown with error, so windows does nothing.

UPDATE

Going back to classic, I changed the Main entry point to return an int and returned 1.
Still windows does not restart the service nor a failure entry is written to event viewer. It looks like is always stopped gracefully


问:
Ionic Capacitor 404 eror - inappbrowser is not in the npm registry
I got an error 404 from running inappbrowser plugin

```<code>npm install @ionic-enterprise/inappbrowser

npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/@ionic-enterprise%2finappbrowser - Not found
npm ERR! 404
npm ERR! 404  '@ionic-enterprise/inappbrowser@latest' is not in the npm registry.
</code>```

I have also run npm config set registry https://registry.npmjs.org/  but still get the same error

答: If your using cordova this would do it:ionic cordova plugin add cordova-plugin-inappbrowser --save

Body:
I got an error 404 from running inappbrowser plugin

npm install @ionic-enterprise/inappbrowser

npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/@ionic-enterprise%2finappbrowser - Not found
npm ERR! 404
npm ERR! 404  '@ionic-enterprise/inappbrowser@latest' is not in the npm registry.

I have also run npm config set registry https://registry.npmjs.org/  but still get the same error


问:
Can't get background thread to work unless I use static methods. What are the alternatives?
I'm using Eclipse to develop an Android app to plot Bluetooth data. The primary components are a Bluetooth Activity, a background thread created by the Bluetooth Activity, and a Plotting Activity.

From Logcat I know for a fact that the background task continues to run and produce BluetoothData even after I switch the activity from Bluetooth Activity to Plotting activity.

I found the method in the background thread that writes BluetoothData to Logcat. So I decided to use this method to pass data data to the Plotting Activity's plotData() method as follows:

```<code>    PlottingActivity plottingActivity = new PlottingActivity();
    plottingActivity.plotData(BluetoothData);
</code>```

But it does't work with the call to plotData() being a regular instance method. Why?

It doesn't work because with this form (perhaps terrible form) of invoking plotData() the onCreate() method of the PlottingActivity activity does not get called. This results in at least in a null pointing exception for redraw() method so plot doesn't redrawn or drawn for that matter.

So that's why it doesn't work. But what makes it work? Interested? Making plotData() a static method. Works great. Clips right along in real-time. Looks like an Oscilloscope.

But I have received negative feedback about this solution (may it's not thread safe or something) I should now ask for alternative solutions. [NOT A DISCUSSION]. Just real, practical, sensible alternatives to using a background thread and an instance method.

答:
You can't transfer data from one activity to another, as only one activity can ever be active at a time. The reason it's working with static members is because the class definitions exist, but the objects created that were referenced by the activity no longer exist; they were garbage collected when the new activity came about.

You need to create a service that stays active no matter which activity is active.

Body:
I'm using Eclipse to develop an Android app to plot Bluetooth data. The primary components are a Bluetooth Activity, a background thread created by the Bluetooth Activity, and a Plotting Activity.

From Logcat I know for a fact that the background task continues to run and produce BluetoothData even after I switch the activity from Bluetooth Activity to Plotting activity.

I found the method in the background thread that writes BluetoothData to Logcat. So I decided to use this method to pass data data to the Plotting Activity's plotData() method as follows:

    PlottingActivity plottingActivity = new PlottingActivity();
    plottingActivity.plotData(BluetoothData);

But it does't work with the call to plotData() being a regular instance method. Why?

It doesn't work because with this form (perhaps terrible form) of invoking plotData() the onCreate() method of the PlottingActivity activity does not get called. This results in at least in a null pointing exception for redraw() method so plot doesn't redrawn or drawn for that matter.

So that's why it doesn't work. But what makes it work? Interested? Making plotData() a static method. Works great. Clips right along in real-time. Looks like an Oscilloscope.

But I have received negative feedback about this solution (may it's not thread safe or something) I should now ask for alternative solutions. [NOT A DISCUSSION]. Just real, practical, sensible alternatives to using a background thread and an instance method.


问:
How to verify that urls are redirected its respective page in Selenium?
I am trying to automate - verification of top nav links of https://www.zillow.com.

For that I am matching actual urls with expected urls. But in page class method this line retruns null. I don't get it why?

```<code>String urlp = locator.all_topnav_links.get(i).getAttribute("href");
</code>```

Method in page class:

```<code>public void verify_topnav_links() {
        System.out.println("Started");
        for (int i = 0; i < locator.all_topnav_links.size(); i++) {
            System.out.println(locator.all_topnav_links.size());
            if (locator.all_topnav_links.get(i).isDisplayed() == true) {
                String link=locator.all_topnav_links.get(i).getText();
                System.out.println(link);
                String urlp = locator.all_topnav_links.get(i).getAttribute("href");
                System.out.println("Links are : " + urlp);
                // now click link one by one
                locator.all_topnav_links.get(i).click();
                driver.navigate().back();
                // 2 verify before url with current opened url
                //Assert.assertEquals(urlp, driver.getCurrentUrl());

            }
</code>```

Locator in locator class:

```<code>@FindAll({@FindBy(xpath = "//ul[@data-zg-section='main']/li")})
    public List<WebElement> all_topnav_links;
</code>```

Test case in test class:

```<code>@Test
    public void verify_TopNav_links()
    {

        hpage.verify_topnav_links();
    }
</code>```

Also I am not sure whether this correct approach or not. Can anybody tell me the best approach to verify this scenario.

Note: This zillow.com will starts to display captcha if we open multiple times using selenium. To ignore it manually remove catpcha parameters from the url when test case is getting executed.

答:
It appears you need to use

```<code>//ul[@data-zg-section='main']/li/a
</code>```

here

```<code>@FindAll({@FindBy(xpath = "//ul[@data-zg-section='main']/li")})
    public List<WebElement> all_topnav_links;
</code>```

This xpath

```<code>//ul[@data-zg-section='main']/li
</code>```

Seems to contain multiple elements. But you're trying to access the href attribute directly. The li here doesn't have a href attribute.

Body:
I am trying to automate - verification of top nav links of https://www.zillow.com.

For that I am matching actual urls with expected urls. But in page class method this line retruns null. I don't get it why?

String urlp = locator.all_topnav_links.get(i).getAttribute("href");

Method in page class:

public void verify_topnav_links() {
        System.out.println("Started");
        for (int i = 0; i < locator.all_topnav_links.size(); i++) {
            System.out.println(locator.all_topnav_links.size());
            if (locator.all_topnav_links.get(i).isDisplayed() == true) {
                String link=locator.all_topnav_links.get(i).getText();
                System.out.println(link);
                String urlp = locator.all_topnav_links.get(i).getAttribute("href");
                System.out.println("Links are : " + urlp);
                // now click link one by one
                locator.all_topnav_links.get(i).click();
                driver.navigate().back();
                // 2 verify before url with current opened url
                //Assert.assertEquals(urlp, driver.getCurrentUrl());

            }

Locator in locator class:

@FindAll({@FindBy(xpath = "//ul[@data-zg-section='main']/li")})
    public List<WebElement> all_topnav_links;

Test case in test class:

@Test
    public void verify_TopNav_links()
    {

        hpage.verify_topnav_links();
    }

Also I am not sure whether this correct approach or not. Can anybody tell me the best approach to verify this scenario.

Note: This zillow.com will starts to display captcha if we open multiple times using selenium. To ignore it manually remove catpcha parameters from the url when test case is getting executed.

Body:
It appears you need to use

//ul[@data-zg-section='main']/li/a

here

@FindAll({@FindBy(xpath = "//ul[@data-zg-section='main']/li")})
    public List<WebElement> all_topnav_links;

This xpath

//ul[@data-zg-section='main']/li

Seems to contain multiple elements. But you're trying to access the href attribute directly. The li here doesn't have a href attribute.


问:
How do I use multiple classes in css module based on a const?
Currently my extraClassName const is never read and I would like the css module to follow what extraClassName is based on the if statements. Not sure how to go about doing this.   </p>

```<code>render() {
    const { isFinish, isStart } = this.props;
    const extraClassName = isFinish
      ? "node-finish"
      : isStart
      ? "node-start"
      : "";

    return <div className={`node ${styles.extraClassName}`}></div>;
  }```
</code>```

答:
extraClassName is just a variable in the local scope, it doesn't appear to be on a styles object.

So you should be able to just write:

```<code>return <div className={`node ${extraClassName}`}></div>;
</code>```

and it should work.

If you're doing a lot of this conditional class rendering, there are some useful npm packages such as classnames (https://www.npmjs.com/package/classnames) or clsx (https://www.npmjs.com/package/clsx), which make writing these conditional classes a little nicer.

Example

```<code>import clsx from 'clsx';

...

return <div className={clsx('node', {
  'node-finish': isFinish,
  'node-start': !isFinish &&isStart
})}></div>;
</code>```

If you're wary of npm packages for such a small utility, it's also pretty quick and easy to write a similar utility library for yourself.

Body:
Currently my extraClassName const is never read and I would like the css module to follow what extraClassName is based on the if statements. Not sure how to go about doing this.

render() {
    const { isFinish, isStart } = this.props;
    const extraClassName = isFinish
      ? "node-finish"
      : isStart
      ? "node-start"
      : "";

    return <div className={`node ${styles.extraClassName}`}>
;
  }```

Body:
extraClassName is just a variable in the local scope, it doesn't appear to be on a styles object.

So you should be able to just write:

return <div className={`node ${extraClassName}`}></div>;

and it should work.

If you're doing a lot of this conditional class rendering, there are some useful npm packages such as classnames (https://www.npmjs.com/package/classnames) or clsx (https://www.npmjs.com/package/clsx), which make writing these conditional classes a little nicer.

Example

import clsx from 'clsx';

...

return <div className={clsx('node', {
  'node-finish': isFinish,
  'node-start': !isFinish &&isStart
})}></div>;

If you're wary of npm packages for such a small utility, it's also pretty quick and easy to write a similar utility library for yourself.